<commit_before>/*

Copyright (c) 2009, Arvid Norberg
All rights reserved.

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

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

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

*/

#include "libtorrent/allocator.hpp"
#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"

#if defined TORRENT_BEOS
#include <kernel/OS.h>
#include <stdlib.h> // malloc/free
#else
#include <stdlib.h> // valloc/free
#include <unistd.h> // _SC_PAGESIZE
#endif

#if TORRENT_USE_MEMALIGN || TORRENT_USE_POSIX_MEMALIGN || defined TORRENT_WINDOWS
#include <malloc.h> // memalign and _aligned_malloc
#include <stdlib.h> // _aligned_malloc on mingw
#endif

#ifdef TORRENT_WINDOWS
// windows.h must be included after stdlib.h under mingw
#include <windows.h>
#endif

#ifdef TORRENT_MINGW
#define _aligned_malloc __mingw_aligned_malloc
#define _aligned_free __mingw_aligned_free
#endif

#ifdef TORRENT_DEBUG_BUFFERS
#include <sys/mman.h>
#include "libtorrent/size_type.hpp"

struct alloc_header
{
	libtorrent::size_type size;
	int magic;
	char stack[3072];
};

#endif

#if defined TORRENT_DEBUG_BUFFERS && (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050))
	void print_backtrace(char* out, int len);
#endif

namespace libtorrent
{

	int page_size()
	{
		static int s = 0;
		if (s != 0) return s;

#ifdef TORRENT_WINDOWS
		SYSTEM_INFO si;
		GetSystemInfo(&si);
		s = si.dwPageSize;
#elif defined TORRENT_BEOS
		s = B_PAGE_SIZE;
#else
		s = sysconf(_SC_PAGESIZE);
#endif
		// assume the page size is 4 kiB if we
		// fail to query it
		if (s <= 0) s = 4096;
		return s;
	}

	char* page_aligned_allocator::malloc(size_type bytes)
	{
		TORRENT_ASSERT(bytes >= page_size());
		TORRENT_ASSERT(bytes % page_size() == 0);
#ifdef TORRENT_DEBUG_BUFFERS
		int page = page_size();
		int num_pages = (bytes + (page-1)) / page + 2;
		char* ret = (char*)valloc(num_pages * page);
		// make the two surrounding pages non-readable and -writable
		alloc_header* h = (alloc_header*)ret;
		h->size = bytes;
		h->magic = 0x1337;
#if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)
		print_backtrace(h->stack, sizeof(h->stack));
#endif
		mprotect(ret, page, PROT_READ);
		mprotect(ret + (num_pages-1) * page, page, PROT_READ);
//		fprintf(stderr, "malloc: %p head: %p tail: %p size: %d\n", ret + page, ret, ret + page + bytes, int(bytes));

		return ret + page;
#endif

#if TORRENT_USE_POSIX_MEMALIGN
		void* ret;
		if (posix_memalign(&ret, page_size(), bytes) != 0) ret = 0;
		return (char*)ret;
#elif TORRENT_USE_MEMALIGN
		return (char*)memalign(page_size(), bytes);
#elif defined TORRENT_WINDOWS
		return (char*)_aligned_malloc(bytes, page_size());
#elif defined TORRENT_BEOS
		void* ret = 0;
		area_id id = create_area("", &ret, B_ANY_ADDRESS
			, (bytes + page_size() - 1) & (page_size()-1), B_NO_LOCK, B_READ_AREA | B_WRITE_AREA);
		if (id < B_OK) return 0;
		return (char*)ret;
#else
		return (char*)valloc(bytes);
#endif
	}

	void page_aligned_allocator::free(char* const block)
	{

#ifdef TORRENT_DEBUG_BUFFERS
		int page = page_size();
		// make the two surrounding pages non-readable and -writable
		mprotect(block - page, page, PROT_READ | PROT_WRITE);
		alloc_header* h = (alloc_header*)(block - page);
		int num_pages = (h->size + (page-1)) / page + 2;
		TORRENT_ASSERT(h->magic == 0x1337);
		mprotect(block + (num_pages-2) * page, page, PROT_READ | PROT_WRITE);
//		fprintf(stderr, "free: %p head: %p tail: %p size: %d\n", block, block - page, block + h->size, int(h->size));
		h->magic = 0;

#if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)
		print_backtrace(h->stack, sizeof(h->stack));
#endif
		::free(block - page);
		return;
#endif

#ifdef TORRENT_WINDOWS
		_aligned_free(block);
#elif defined TORRENT_BEOS
		area_id id = area_for(block);
		if (id < B_OK) return;
		delete_area(id);
#else
		::free(block);
#endif
	}

}

<commit_msg>fix msvc build again<commit_after>/*

Copyright (c) 2009, Arvid Norberg
All rights reserved.

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

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

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

*/

#include "libtorrent/allocator.hpp"
#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"

#if defined TORRENT_BEOS
#include <kernel/OS.h>
#include <stdlib.h> // malloc/free
#elif !defined TORRENT_WINDOWS
#include <stdlib.h> // valloc/free
#include <unistd.h> // _SC_PAGESIZE
#endif

#if TORRENT_USE_MEMALIGN || TORRENT_USE_POSIX_MEMALIGN || defined TORRENT_WINDOWS
#include <malloc.h> // memalign and _aligned_malloc
#include <stdlib.h> // _aligned_malloc on mingw
#endif

#ifdef TORRENT_WINDOWS
// windows.h must be included after stdlib.h under mingw
#include <windows.h>
#endif

#ifdef TORRENT_MINGW
#define _aligned_malloc __mingw_aligned_malloc
#define _aligned_free __mingw_aligned_free
#endif

#ifdef TORRENT_DEBUG_BUFFERS
#include <sys/mman.h>
#include "libtorrent/size_type.hpp"

struct alloc_header
{
	libtorrent::size_type size;
	int magic;
	char stack[3072];
};

#endif

#if defined TORRENT_DEBUG_BUFFERS && (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050))
	void print_backtrace(char* out, int len);
#endif

namespace libtorrent
{

	int page_size()
	{
		static int s = 0;
		if (s != 0) return s;

#ifdef TORRENT_WINDOWS
		SYSTEM_INFO si;
		GetSystemInfo(&si);
		s = si.dwPageSize;
#elif defined TORRENT_BEOS
		s = B_PAGE_SIZE;
#else
		s = sysconf(_SC_PAGESIZE);
#endif
		// assume the page size is 4 kiB if we
		// fail to query it
		if (s <= 0) s = 4096;
		return s;
	}

	char* page_aligned_allocator::malloc(size_type bytes)
	{
		TORRENT_ASSERT(bytes >= page_size());
		TORRENT_ASSERT(bytes % page_size() == 0);
#ifdef TORRENT_DEBUG_BUFFERS
		int page = page_size();
		int num_pages = (bytes + (page-1)) / page + 2;
		char* ret = (char*)valloc(num_pages * page);
		// make the two surrounding pages non-readable and -writable
		alloc_header* h = (alloc_header*)ret;
		h->size = bytes;
		h->magic = 0x1337;
#if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)
		print_backtrace(h->stack, sizeof(h->stack));
#endif
		mprotect(ret, page, PROT_READ);
		mprotect(ret + (num_pages-1) * page, page, PROT_READ);
//		fprintf(stderr, "malloc: %p head: %p tail: %p size: %d\n", ret + page, ret, ret + page + bytes, int(bytes));

		return ret + page;
#endif

#if TORRENT_USE_POSIX_MEMALIGN
		void* ret;
		if (posix_memalign(&ret, page_size(), bytes) != 0) ret = 0;
		return (char*)ret;
#elif TORRENT_USE_MEMALIGN
		return (char*)memalign(page_size(), bytes);
#elif defined TORRENT_WINDOWS
		return (char*)_aligned_malloc(bytes, page_size());
#elif defined TORRENT_BEOS
		void* ret = 0;
		area_id id = create_area("", &ret, B_ANY_ADDRESS
			, (bytes + page_size() - 1) & (page_size()-1), B_NO_LOCK, B_READ_AREA | B_WRITE_AREA);
		if (id < B_OK) return 0;
		return (char*)ret;
#else
		return (char*)valloc(bytes);
#endif
	}

	void page_aligned_allocator::free(char* const block)
	{

#ifdef TORRENT_DEBUG_BUFFERS
		int page = page_size();
		// make the two surrounding pages non-readable and -writable
		mprotect(block - page, page, PROT_READ | PROT_WRITE);
		alloc_header* h = (alloc_header*)(block - page);
		int num_pages = (h->size + (page-1)) / page + 2;
		TORRENT_ASSERT(h->magic == 0x1337);
		mprotect(block + (num_pages-2) * page, page, PROT_READ | PROT_WRITE);
//		fprintf(stderr, "free: %p head: %p tail: %p size: %d\n", block, block - page, block + h->size, int(h->size));
		h->magic = 0;

#if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)
		print_backtrace(h->stack, sizeof(h->stack));
#endif
		::free(block - page);
		return;
#endif

#ifdef TORRENT_WINDOWS
		_aligned_free(block);
#elif defined TORRENT_BEOS
		area_id id = area_for(block);
		if (id < B_OK) return;
		delete_area(id);
#else
		::free(block);
#endif
	}

}

<|endoftext|>


<commit_before>// kmfiltermgr.cpp

#include <kapp.h>
#include <kconfig.h>
#include <kdebug.h>

#include "kmglobal.h"
#include "kmfiltermgr.h"
#include "kmfoldermgr.h"
#include "kmfilter.h"
#include "kmfilterdlg.h"
#include "kmmessage.h"

//-----------------------------------------------------------------------------
KMFilterMgr::KMFilterMgr(): KMFilterMgrInherited()
{
  setAutoDelete(TRUE);
  mEditDialog = NULL;
}

//-----------------------------------------------------------------------------
KMFilterMgr::~KMFilterMgr()
{
  writeConfig(FALSE);
}

//-----------------------------------------------------------------------------
void KMFilterMgr::readConfig(void)
{
  KConfig* config = kapp->config();
  int i, numFilters;
  QString grpName;
  KMFilter* filter;

  clear();

  config->setGroup("General");
  numFilters = config->readNumEntry("filters",0);

  for (i=0; i<numFilters; i++)
  {
    grpName.sprintf("Filter #%d", i);
    config->setGroup(grpName);
    filter = new KMFilter(config);
    append(filter);
  }
}

//-----------------------------------------------------------------------------
void KMFilterMgr::writeConfig(bool withSync)
{
  KConfig* config = kapp->config();
  QString grpName;
  KMFilter* filter;
  int i;

  config->setGroup("General");
  config->writeEntry("filters", count());

  for (i=0, filter=first(); filter; filter=next(), i++)
  {
    grpName.sprintf("Filter #%d", i);
    config->setGroup(grpName);
    filter->writeConfig(config);
  }

  if (withSync) config->sync();
}

//-----------------------------------------------------------------------------
int KMFilterMgr::process(KMMessage* msg)
{
  KMFilter* filter;
  bool stopIt = FALSE;
  int status = -1;
  int result;

  for (filter=first(); !stopIt && filter; filter=next())
  {
    if (!filter->matches(msg)) continue;
    //    kdDebug() << "KMFilterMgr: filter " << filter->name().data() << " matches message " << //    msg->subject().data() << endl;
    //    if (status < 0)
    //      status = 0;
    result = filter->execActions(msg, stopIt);
    if (result == 2) { // Critical error
      status = 2;
      break;
    }
    else if (result == 1) // Message not saved
      status = 1;
    else if ((result == 0) && (status < 0))  // Message saved in a folder
      status = 0;
  }

  if (status < 0) // No filters matched, keep copy of message
    status = 1;

  return status;
}

//-----------------------------------------------------------------------------
void KMFilterMgr::cleanup(void)
{
  KMFolder* fld;

  kernel->folderMgr()->contentsChanged();

  for (fld=mOpenFolders.first(); fld; fld=mOpenFolders.next())
    if (fld) fld->close();

  mOpenFolders.clear();
}

//-----------------------------------------------------------------------------
int KMFilterMgr::tempOpenFolder(KMFolder* aFolder)
{
  assert(aFolder!=NULL);

  int rc = aFolder->open();
  if (rc) return rc;

  mOpenFolders.append(aFolder);
  return rc;
}

//-----------------------------------------------------------------------------
void KMFilterMgr::dialogDestroyed()
{
  mEditDialog = NULL;
}

//-----------------------------------------------------------------------------
void KMFilterMgr::openDialog( QWidget *parent )
{
  if( !mEditDialog )
  {
    //
    // We can't use the parent as long as the dialog is modeless
    // and there is one shared dialog for all top level windows.
    //
    (void)parent;
    mEditDialog = new KMFilterDlg( 0, "filterdialog" );
  }
  mEditDialog->show();
}

//-----------------------------------------------------------------------------
bool KMFilterMgr::folderRemoved(KMFolder* aFolder, KMFolder* aNewFolder)
{
  KMFilter* filter;
  bool rem = FALSE;

  for (filter=first(); filter; filter=next())
    if (filter->folderRemoved(aFolder, aNewFolder)) rem=TRUE;

  return rem;
}

//-----------------------------------------------------------------------------
void KMFilterMgr::dump(void)
{
  KMFilter* filter;
  int i;

  for (i=0, filter=first(); filter; filter=next(), i++)
  {
    kdDebug() << filter->asString() << endl;
  }
}
<commit_msg>This fixes an extremely difficult to track down problem that resulted in drag and drop crashes when the drag started before a mail check had finished and the drop was made after the mail check had ended.<commit_after>// kmfiltermgr.cpp

#include <kapp.h>
#include <kconfig.h>
#include <kdebug.h>

#include "kmglobal.h"
#include "kmfiltermgr.h"
#include "kmfoldermgr.h"
#include "kmfilter.h"
#include "kmfilterdlg.h"
#include "kmmessage.h"

//-----------------------------------------------------------------------------
KMFilterMgr::KMFilterMgr(): KMFilterMgrInherited()
{
  setAutoDelete(TRUE);
  mEditDialog = NULL;
}

//-----------------------------------------------------------------------------
KMFilterMgr::~KMFilterMgr()
{
  writeConfig(FALSE);
}

//-----------------------------------------------------------------------------
void KMFilterMgr::readConfig(void)
{
  KConfig* config = kapp->config();
  int i, numFilters;
  QString grpName;
  KMFilter* filter;

  clear();

  config->setGroup("General");
  numFilters = config->readNumEntry("filters",0);

  for (i=0; i<numFilters; i++)
  {
    grpName.sprintf("Filter #%d", i);
    config->setGroup(grpName);
    filter = new KMFilter(config);
    append(filter);
  }
}

//-----------------------------------------------------------------------------
void KMFilterMgr::writeConfig(bool withSync)
{
  KConfig* config = kapp->config();
  QString grpName;
  KMFilter* filter;
  int i;

  config->setGroup("General");
  config->writeEntry("filters", count());

  for (i=0, filter=first(); filter; filter=next(), i++)
  {
    grpName.sprintf("Filter #%d", i);
    config->setGroup(grpName);
    filter->writeConfig(config);
  }

  if (withSync) config->sync();
}

//-----------------------------------------------------------------------------
int KMFilterMgr::process(KMMessage* msg)
{
  KMFilter* filter;
  bool stopIt = FALSE;
  int status = -1;
  int result;

  for (filter=first(); !stopIt && filter; filter=next())
  {
    if (!filter->matches(msg)) continue;
    //    kdDebug() << "KMFilterMgr: filter " << filter->name().data() << " matches message " << //    msg->subject().data() << endl;
    //    if (status < 0)
    //      status = 0;
    result = filter->execActions(msg, stopIt);
    if (result == 2) { // Critical error
      status = 2;
      break;
    }
    else if (result == 1) // Message not saved
      status = 1;
    else if ((result == 0) && (status < 0))  // Message saved in a folder
      status = 0;
  }

  if (status < 0) // No filters matched, keep copy of message
    status = 1;

  return status;
}

//-----------------------------------------------------------------------------
void KMFilterMgr::cleanup(void)
{
  KMFolder* fld;

  for (fld=mOpenFolders.first(); fld; fld=mOpenFolders.next())
    if (fld) fld->close();

  mOpenFolders.clear();
}

//-----------------------------------------------------------------------------
int KMFilterMgr::tempOpenFolder(KMFolder* aFolder)
{
  assert(aFolder!=NULL);

  int rc = aFolder->open();
  if (rc) return rc;

  mOpenFolders.append(aFolder);
  return rc;
}

//-----------------------------------------------------------------------------
void KMFilterMgr::dialogDestroyed()
{
  mEditDialog = NULL;
}

//-----------------------------------------------------------------------------
void KMFilterMgr::openDialog( QWidget *parent )
{
  if( !mEditDialog )
  {
    //
    // We can't use the parent as long as the dialog is modeless
    // and there is one shared dialog for all top level windows.
    //
    (void)parent;
    mEditDialog = new KMFilterDlg( 0, "filterdialog" );
  }
  mEditDialog->show();
}

//-----------------------------------------------------------------------------
bool KMFilterMgr::folderRemoved(KMFolder* aFolder, KMFolder* aNewFolder)
{
  KMFilter* filter;
  bool rem = FALSE;

  for (filter=first(); filter; filter=next())
    if (filter->folderRemoved(aFolder, aNewFolder)) rem=TRUE;

  return rem;
}

//-----------------------------------------------------------------------------
void KMFilterMgr::dump(void)
{
  KMFilter* filter;
  int i;

  for (i=0, filter=first(); filter; filter=next(), i++)
  {
    kdDebug() << filter->asString() << endl;
  }
}
<|endoftext|>


<commit_before>#if defined(__cpp_constexpr) && __cpp_constexpr >= 201304

#include <benchmark/benchmark.h>

#define FMT_HEADER_ONLY
#include <cppformat/format.h>

#include <blackhole/extensions/format.hpp>

namespace blackhole {
namespace benchmark {

static
void
cpp14formatter(::benchmark::State& state) {
    while (state.KeepRunning()) {
        constexpr auto formatter = blackhole::detail::formatter<
            blackhole::detail::literal_count("{} - {} [{}] 'GET {} HTTP/1.0' {} {}")
        >("{} - {} [{}] 'GET {} HTTP/1.0' {} {}");

        fmt::MemoryWriter wr;
        formatter.format(wr, "[::]", "esafronov", "10/Oct/2000:13:55:36 -0700", "/porn.png", 200, 2326);
    }

    state.SetItemsProcessed(state.iterations());
}

BENCHMARK(cpp14formatter);

}  // namespace benchmark
}  // namespace blackhole

#endif
<commit_msg>fix(bench): fix broken include<commit_after>#if defined(__cpp_constexpr) && __cpp_constexpr >= 201304

#include <benchmark/benchmark.h>

#define FMT_HEADER_ONLY
#include <cppformat/format.h>

#include <blackhole/extensions/metaformat.hpp>

namespace blackhole {
namespace benchmark {

static
void
cpp14formatter(::benchmark::State& state) {
    while (state.KeepRunning()) {
        constexpr auto formatter = blackhole::detail::formatter<
            blackhole::detail::literal_count("{} - {} [{}] 'GET {} HTTP/1.0' {} {}")
        >("{} - {} [{}] 'GET {} HTTP/1.0' {} {}");

        fmt::MemoryWriter wr;
        formatter.format(wr, "[::]", "esafronov", "10/Oct/2000:13:55:36 -0700", "/porn.png", 200, 2326);
    }

    state.SetItemsProcessed(state.iterations());
}

BENCHMARK(cpp14formatter);

}  // namespace benchmark
}  // namespace blackhole

#endif
<|endoftext|>


<commit_before>// Qt includes
#include <QDebug>
#include <QStandardItemModel>
#include <QTimer>
#include <QTreeView>

// SlicerQt includes
#include "qSlicerOpenIGTLinkIFModuleWidget.h"
#include "ui_qSlicerOpenIGTLinkIFModule.h"

// qMRMLWidgets includes
#include <qMRMLNodeFactory.h>

// OpenIGTLinkIF Logic includes
#include "vtkSlicerOpenIGTLinkIFLogic.h"

// OpenIGTLinkIF MRML includes
#include "vtkMRMLIGTLConnectorNode.h"

//-----------------------------------------------------------------------------
/// \ingroup Slicer_QtModules_OpenIGTLinkIF
class qSlicerOpenIGTLinkIFModuleWidgetPrivate: public Ui_qSlicerOpenIGTLinkIFModule
{
  Q_DECLARE_PUBLIC(qSlicerOpenIGTLinkIFModuleWidget);
protected:
  qSlicerOpenIGTLinkIFModuleWidget* const q_ptr;
public:
  qSlicerOpenIGTLinkIFModuleWidgetPrivate(qSlicerOpenIGTLinkIFModuleWidget& object);

  vtkSlicerOpenIGTLinkIFLogic * logic();

  QTimer ImportDataAndEventsTimer;
};

//-----------------------------------------------------------------------------
// qSlicerOpenIGTLinkIFModuleWidgetPrivate methods

//-----------------------------------------------------------------------------
qSlicerOpenIGTLinkIFModuleWidgetPrivate::qSlicerOpenIGTLinkIFModuleWidgetPrivate(qSlicerOpenIGTLinkIFModuleWidget& object)
 : q_ptr(&object)
{
}

//-----------------------------------------------------------------------------
vtkSlicerOpenIGTLinkIFLogic * qSlicerOpenIGTLinkIFModuleWidgetPrivate::logic()
{
  Q_Q(qSlicerOpenIGTLinkIFModuleWidget);
  return vtkSlicerOpenIGTLinkIFLogic::SafeDownCast(q->logic());
}

//-----------------------------------------------------------------------------
// qSlicerOpenIGTLinkIFModuleWidget methods

//-----------------------------------------------------------------------------
qSlicerOpenIGTLinkIFModuleWidget::qSlicerOpenIGTLinkIFModuleWidget(QWidget* _parent)
  : Superclass( _parent )
  , d_ptr( new qSlicerOpenIGTLinkIFModuleWidgetPrivate(*this) )
{
}

//-----------------------------------------------------------------------------
qSlicerOpenIGTLinkIFModuleWidget::~qSlicerOpenIGTLinkIFModuleWidget()
{
}

//-----------------------------------------------------------------------------
void qSlicerOpenIGTLinkIFModuleWidget::setup()
{
  Q_D(qSlicerOpenIGTLinkIFModuleWidget);
  d->setupUi(this);
  this->Superclass::setup();

  // --------------------------------------------------
  // Connectors section
  //  Connector List View
  connect(d->ConnectorListView, SIGNAL(currentNodeChanged(vtkMRMLNode*)),
          d->ConnectorPropertyWidget, SLOT(setMRMLIGTLConnectorNode(vtkMRMLNode*)));
  d->ConnectorPropertyWidget->setMRMLIGTLConnectorNode(static_cast<vtkMRMLNode*>(0));

  //  Add(+) / Remove(-) Connector Buttons
  connect(d->AddConnectorButton, SIGNAL(clicked()), this,
          SLOT(onAddConnectorButtonClicked()));
  connect(d->RemoveConnectorButton, SIGNAL(clicked()), this,
          SLOT(onRemoveConnectorButtonClicked()));

  // --------------------------------------------------
  //  I/O COnfiguration Section
  connect(this, SIGNAL(mrmlSceneChanged(vtkMRMLScene*)),
          d->IGTIONodeSelectorWidget, SLOT(setMRMLScene(vtkMRMLScene*)));
  connect(d->IOTreeView, SIGNAL(ioTreeViewUpdated(int,vtkMRMLIGTLConnectorNode*,int)),
          d->IGTIONodeSelectorWidget, SLOT(updateEnabledStatus(int,vtkMRMLIGTLConnectorNode*,int)));

  // --------------------------------------------------
  //  Visualization Section
  connect(d->EnableLocatorDriverCheckBox, SIGNAL(toggled(bool)), this,
          SLOT(setLocatorDriverVisible(bool)));
  this->setLocatorDriverVisible(d->EnableLocatorDriverCheckBox->isChecked());

  // TODO We should probably listen for the logic and implement a onLogicModified() slot
  //      Doing so we would be able to update the UI if the locator is externally enabled.

  connect(&d->ImportDataAndEventsTimer, SIGNAL(timeout()),
          this, SLOT(importDataAndEvents()));
  d->ImportDataAndEventsTimer.start(5);

}

//-----------------------------------------------------------------------------
void qSlicerOpenIGTLinkIFModuleWidget::setMRMLScene(vtkMRMLScene* scene)
{
  Q_D(qSlicerOpenIGTLinkIFModuleWidget);

  this->Superclass::setMRMLScene(scene);
  if (scene == NULL)
    {
    return;
    }
  d->ConnectorListView->setMRMLScene(scene);
  d->IOTreeView->setMRMLScene(scene);
}

//-----------------------------------------------------------------------------
void qSlicerOpenIGTLinkIFModuleWidget::onAddConnectorButtonClicked()
{
  qMRMLNodeFactory::createNode(this->mrmlScene(), "vtkMRMLIGTLConnectorNode");
}

//-----------------------------------------------------------------------------
void qSlicerOpenIGTLinkIFModuleWidget::onRemoveConnectorButtonClicked()
{
  Q_D(qSlicerOpenIGTLinkIFModuleWidget);
  vtkMRMLNode * node = d->ConnectorListView->currentNode();
  if (!node)
    {
    return;
    }
  vtkMRMLIGTLConnectorNode * connectorNode = vtkMRMLIGTLConnectorNode::SafeDownCast(node);
  Q_ASSERT(connectorNode);
  connectorNode->Stop();
  this->mrmlScene()->RemoveNode(connectorNode);
}

//-----------------------------------------------------------------------------
void qSlicerOpenIGTLinkIFModuleWidget::setLocatorDriverVisible(bool visible)
{
  Q_D(qSlicerOpenIGTLinkIFModuleWidget);
  d->logic()->EnableLocatorDriver(visible);
}

//-----------------------------------------------------------------------------
void qSlicerOpenIGTLinkIFModuleWidget::importDataAndEvents()
{
  Q_D(qSlicerOpenIGTLinkIFModuleWidget);
  d->logic()->ImportEvents();
  d->logic()->ImportFromCircularBuffers();
}
<commit_msg>STYLE: fix misspell.<commit_after>// Qt includes
#include <QDebug>
#include <QStandardItemModel>
#include <QTimer>
#include <QTreeView>

// SlicerQt includes
#include "qSlicerOpenIGTLinkIFModuleWidget.h"
#include "ui_qSlicerOpenIGTLinkIFModule.h"

// qMRMLWidgets includes
#include <qMRMLNodeFactory.h>

// OpenIGTLinkIF Logic includes
#include "vtkSlicerOpenIGTLinkIFLogic.h"

// OpenIGTLinkIF MRML includes
#include "vtkMRMLIGTLConnectorNode.h"

//-----------------------------------------------------------------------------
/// \ingroup Slicer_QtModules_OpenIGTLinkIF
class qSlicerOpenIGTLinkIFModuleWidgetPrivate: public Ui_qSlicerOpenIGTLinkIFModule
{
  Q_DECLARE_PUBLIC(qSlicerOpenIGTLinkIFModuleWidget);
protected:
  qSlicerOpenIGTLinkIFModuleWidget* const q_ptr;
public:
  qSlicerOpenIGTLinkIFModuleWidgetPrivate(qSlicerOpenIGTLinkIFModuleWidget& object);

  vtkSlicerOpenIGTLinkIFLogic * logic();

  QTimer ImportDataAndEventsTimer;
};

//-----------------------------------------------------------------------------
// qSlicerOpenIGTLinkIFModuleWidgetPrivate methods

//-----------------------------------------------------------------------------
qSlicerOpenIGTLinkIFModuleWidgetPrivate::qSlicerOpenIGTLinkIFModuleWidgetPrivate(qSlicerOpenIGTLinkIFModuleWidget& object)
 : q_ptr(&object)
{
}

//-----------------------------------------------------------------------------
vtkSlicerOpenIGTLinkIFLogic * qSlicerOpenIGTLinkIFModuleWidgetPrivate::logic()
{
  Q_Q(qSlicerOpenIGTLinkIFModuleWidget);
  return vtkSlicerOpenIGTLinkIFLogic::SafeDownCast(q->logic());
}

//-----------------------------------------------------------------------------
// qSlicerOpenIGTLinkIFModuleWidget methods

//-----------------------------------------------------------------------------
qSlicerOpenIGTLinkIFModuleWidget::qSlicerOpenIGTLinkIFModuleWidget(QWidget* _parent)
  : Superclass( _parent )
  , d_ptr( new qSlicerOpenIGTLinkIFModuleWidgetPrivate(*this) )
{
}

//-----------------------------------------------------------------------------
qSlicerOpenIGTLinkIFModuleWidget::~qSlicerOpenIGTLinkIFModuleWidget()
{
}

//-----------------------------------------------------------------------------
void qSlicerOpenIGTLinkIFModuleWidget::setup()
{
  Q_D(qSlicerOpenIGTLinkIFModuleWidget);
  d->setupUi(this);
  this->Superclass::setup();

  // --------------------------------------------------
  // Connectors section
  //  Connector List View
  connect(d->ConnectorListView, SIGNAL(currentNodeChanged(vtkMRMLNode*)),
          d->ConnectorPropertyWidget, SLOT(setMRMLIGTLConnectorNode(vtkMRMLNode*)));
  d->ConnectorPropertyWidget->setMRMLIGTLConnectorNode(static_cast<vtkMRMLNode*>(0));

  //  Add(+) / Remove(-) Connector Buttons
  connect(d->AddConnectorButton, SIGNAL(clicked()), this,
          SLOT(onAddConnectorButtonClicked()));
  connect(d->RemoveConnectorButton, SIGNAL(clicked()), this,
          SLOT(onRemoveConnectorButtonClicked()));

  // --------------------------------------------------
  //  I/O Configuration Section
  connect(this, SIGNAL(mrmlSceneChanged(vtkMRMLScene*)),
          d->IGTIONodeSelectorWidget, SLOT(setMRMLScene(vtkMRMLScene*)));
  connect(d->IOTreeView, SIGNAL(ioTreeViewUpdated(int,vtkMRMLIGTLConnectorNode*,int)),
          d->IGTIONodeSelectorWidget, SLOT(updateEnabledStatus(int,vtkMRMLIGTLConnectorNode*,int)));

  // --------------------------------------------------
  //  Visualization Section
  connect(d->EnableLocatorDriverCheckBox, SIGNAL(toggled(bool)), this,
          SLOT(setLocatorDriverVisible(bool)));
  this->setLocatorDriverVisible(d->EnableLocatorDriverCheckBox->isChecked());

  // TODO We should probably listen for the logic and implement a onLogicModified() slot
  //      Doing so we would be able to update the UI if the locator is externally enabled.

  connect(&d->ImportDataAndEventsTimer, SIGNAL(timeout()),
          this, SLOT(importDataAndEvents()));
  d->ImportDataAndEventsTimer.start(5);

}

//-----------------------------------------------------------------------------
void qSlicerOpenIGTLinkIFModuleWidget::setMRMLScene(vtkMRMLScene* scene)
{
  Q_D(qSlicerOpenIGTLinkIFModuleWidget);

  this->Superclass::setMRMLScene(scene);
  if (scene == NULL)
    {
    return;
    }
  d->ConnectorListView->setMRMLScene(scene);
  d->IOTreeView->setMRMLScene(scene);
}

//-----------------------------------------------------------------------------
void qSlicerOpenIGTLinkIFModuleWidget::onAddConnectorButtonClicked()
{
  qMRMLNodeFactory::createNode(this->mrmlScene(), "vtkMRMLIGTLConnectorNode");
}

//-----------------------------------------------------------------------------
void qSlicerOpenIGTLinkIFModuleWidget::onRemoveConnectorButtonClicked()
{
  Q_D(qSlicerOpenIGTLinkIFModuleWidget);
  vtkMRMLNode * node = d->ConnectorListView->currentNode();
  if (!node)
    {
    return;
    }
  vtkMRMLIGTLConnectorNode * connectorNode = vtkMRMLIGTLConnectorNode::SafeDownCast(node);
  Q_ASSERT(connectorNode);
  connectorNode->Stop();
  this->mrmlScene()->RemoveNode(connectorNode);
}

//-----------------------------------------------------------------------------
void qSlicerOpenIGTLinkIFModuleWidget::setLocatorDriverVisible(bool visible)
{
  Q_D(qSlicerOpenIGTLinkIFModuleWidget);
  d->logic()->EnableLocatorDriver(visible);
}

//-----------------------------------------------------------------------------
void qSlicerOpenIGTLinkIFModuleWidget::importDataAndEvents()
{
  Q_D(qSlicerOpenIGTLinkIFModuleWidget);
  d->logic()->ImportEvents();
  d->logic()->ImportFromCircularBuffers();
}
<|endoftext|>


<commit_before>#include <benchmark/benchmark.h>
#include <cstdlib>
#include <map>
#include <iostream>
#include <random>
#include <set>

#include "database.h"
#include "util.h"

using namespace naivedb;

using namespace std::chrono;

double total = 0;

#define TIMED_TEST_BEGIN \
    do{ steady_clock::time_point t1 = steady_clock::now();

#define TIMED_TEST_END(TEST_NAME) \
    steady_clock::time_point t2 = steady_clock::now(); \
    auto time = duration_cast<duration<double>>(t2 - t1).count(); \
    total+=time; \
    std::cout << TEST_NAME << " finished in " << time << " seconds. " << std::endl; \
} while(0);

void MixedTest(int nrec) {

/*
(1) 向数据库写nrec条记录。
(2) 通过关键字读回nrec条记录。
(3) 执行下面的循环nrec×5次。
(a) 随机读一条记录。
(b) 每循环37次，随机删除一条记录。
(c) 每循环11次，随机添加一条记录并读取这条记录。
(d) 每循环17次，随机替换一条记录为新记录。在连续两次替换中，一次用同样大小的记录替换，一次用比以前更长的记录替换。
(4) 将此进程写的所有记录删除。每删除一条记录，随机地寻找10条记录。
 */

    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    std::default_random_engine generator(seed);

    const int KeySize = 16;
    const int ValueSize = 100;

    DatabaseOption option;
    option.memory_limitation = 1024 * 1024 * 1024;
    Database database(std::tmpnam(nullptr), option);

    std::vector<std::string> keys;
    std::set<std::string> values;

    char *buf = new char[ValueSize * 2];

    int ikey = 0;
    for (; ikey < nrec; ikey++) {
        std::string key = numberToString(ikey, KeySize - 1);
        keys.push_back(key);
    }
    for (int i = 0; i < nrec * 2; i++) { values.emplace(generateRandomString(ValueSize)); }
    auto iter_value = values.begin();

    std::shuffle(keys.begin(), keys.end(), generator);

    // Test 1
    TIMED_TEST_BEGIN
    for (const auto &key:keys) {
        database.set(key, (++iter_value)->c_str(), ValueSize, false);
    }
    TIMED_TEST_END("Test 1")

    std::shuffle(keys.begin(), keys.end(), generator);

    // Test 2
    TIMED_TEST_BEGIN
    for (const auto &key:keys) {
        database.get(key, buf);
    }
    TIMED_TEST_END("Test 2")

    // Test 3
    TIMED_TEST_BEGIN
    for (int i = 0; i < nrec * 5; i++) {
        std::uniform_int_distribution<int> dist(0, keys.size() - 1);
        const std::string key_to_search = keys.at(dist(generator));

        // (a)
        database.get(key_to_search, buf);

        // (b)
        if (i % 37 == 0) {
            std::uniform_int_distribution<int> dist(0, keys.size() - 1);
            int index = dist(generator);
            const std::string key_to_delete = keys[index];
            keys[index] = keys.back();
            keys.pop_back();

            database.remove(key_to_delete);
        }

        // (c)
        if (i % 11 == 0) {
            const std::string key_to_insert = numberToString(ikey++, KeySize - 1);

            keys.push_back(key_to_insert);

            database.set(key_to_insert, (++iter_value)->c_str(), ValueSize, false);
            database.get(key_to_insert, buf);
        }

        // (d)
        if (i % 17 == 0) {
            std::uniform_int_distribution<int> dist(0, keys.size() - 1);
            const std::string key = keys.at(dist(generator));

            int len = ValueSize;
            if (i % 34 == 0)len *= 2;

            const std::string value = generateRandomString(len);

            database.set(key, value.c_str(), len, true);
        }

    }
    TIMED_TEST_END("Test 3")

    std::shuffle(keys.begin(), keys.end(), generator);

    // Test 4
    TIMED_TEST_BEGIN
    for (int i = 0; i < keys.size(); i++) {
        const std::string &key = keys[i];

        database.remove(key);

        if (i == keys.size() - 1)break; // no more keys for query
        for (int j = 0; j < 10; j++) {
            std::uniform_int_distribution<int> dist(i + 1, keys.size() - 1);
            const std::string key_to_search = keys.at(dist(generator));

            database.get(key_to_search, buf);
        }
    }
    TIMED_TEST_END("Test 4")

    delete[] buf;
}

int main() {
    int nrec = 2;
    int max_nrec = 1 << 21;
    while(nrec < max_nrec) {
        total = 0;
        int iteration = 1000;
        for(int i = 0; i < iteration; i++) {
            MixedTest(nrec);
        }
        double mean_time = total / iteration;
        std::cout << "nrec = " << nrec << "    time = " << mean_time;
        nrec <<= 1;
    }
    return  0;
}<commit_msg>Benchmark format<commit_after>#include <benchmark/benchmark.h>
#include <cstdlib>
#include <map>
#include <iostream>
#include <random>
#include <set>

#include "database.h"
#include "util.h"

using namespace naivedb;

using namespace std::chrono;

double total = 0;

#define TIMED_TEST_BEGIN \
    do{ steady_clock::time_point t1 = steady_clock::now();

#define TIMED_TEST_END(TEST_NAME) \
    steady_clock::time_point t2 = steady_clock::now(); \
    auto time = duration_cast<duration<double>>(t2 - t1).count(); \
    total+=time; \
    std::cout << TEST_NAME << " finished in " << time << " seconds. " << std::endl; \
} while(0);

void MixedTest(int nrec) {

/*
(1) 向数据库写nrec条记录。
(2) 通过关键字读回nrec条记录。
(3) 执行下面的循环nrec×5次。
(a) 随机读一条记录。
(b) 每循环37次，随机删除一条记录。
(c) 每循环11次，随机添加一条记录并读取这条记录。
(d) 每循环17次，随机替换一条记录为新记录。在连续两次替换中，一次用同样大小的记录替换，一次用比以前更长的记录替换。
(4) 将此进程写的所有记录删除。每删除一条记录，随机地寻找10条记录。
 */

    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    std::default_random_engine generator(seed);

    const int KeySize = 16;
    const int ValueSize = 100;

    DatabaseOption option;
    option.memory_limitation = 1024 * 1024 * 1024;
    Database database(std::tmpnam(nullptr), option);

    std::vector<std::string> keys;
    std::set<std::string> values;

    char *buf = new char[ValueSize * 2];

    int ikey = 0;
    for (; ikey < nrec; ikey++) {
        std::string key = numberToString(ikey, KeySize - 1);
        keys.push_back(key);
    }
    for (int i = 0; i < nrec * 2; i++) { values.emplace(generateRandomString(ValueSize)); }
    auto iter_value = values.begin();

    std::shuffle(keys.begin(), keys.end(), generator);

    // Test 1
    TIMED_TEST_BEGIN
    for (const auto &key:keys) {
        database.set(key, (++iter_value)->c_str(), ValueSize, false);
    }
    TIMED_TEST_END("Test 1")

    std::shuffle(keys.begin(), keys.end(), generator);

    // Test 2
    TIMED_TEST_BEGIN
    for (const auto &key:keys) {
        database.get(key, buf);
    }
    TIMED_TEST_END("Test 2")

    // Test 3
    TIMED_TEST_BEGIN
    for (int i = 0; i < nrec * 5; i++) {
        std::uniform_int_distribution<int> dist(0, keys.size() - 1);
        const std::string key_to_search = keys.at(dist(generator));

        // (a)
        database.get(key_to_search, buf);

        // (b)
        if (i % 37 == 0) {
            std::uniform_int_distribution<int> dist(0, keys.size() - 1);
            int index = dist(generator);
            const std::string key_to_delete = keys[index];
            keys[index] = keys.back();
            keys.pop_back();

            database.remove(key_to_delete);
        }

        // (c)
        if (i % 11 == 0) {
            const std::string key_to_insert = numberToString(ikey++, KeySize - 1);

            keys.push_back(key_to_insert);

            database.set(key_to_insert, (++iter_value)->c_str(), ValueSize, false);
            database.get(key_to_insert, buf);
        }

        // (d)
        if (i % 17 == 0) {
            std::uniform_int_distribution<int> dist(0, keys.size() - 1);
            const std::string key = keys.at(dist(generator));

            int len = ValueSize;
            if (i % 34 == 0)len *= 2;

            const std::string value = generateRandomString(len);

            database.set(key, value.c_str(), len, true);
        }

    }
    TIMED_TEST_END("Test 3")

    std::shuffle(keys.begin(), keys.end(), generator);

    // Test 4
    TIMED_TEST_BEGIN
    for (int i = 0; i < keys.size(); i++) {
        const std::string &key = keys[i];

        database.remove(key);

        if (i == keys.size() - 1)break; // no more keys for query
        for (int j = 0; j < 10; j++) {
            std::uniform_int_distribution<int> dist(i + 1, keys.size() - 1);
            const std::string key_to_search = keys.at(dist(generator));

            database.get(key_to_search, buf);
        }
    }
    TIMED_TEST_END("Test 4")

    delete[] buf;
}

int main() {
    int nrec = 2;
    int max_nrec = 1 << 21;
    while(nrec < max_nrec) {
        total = 0;
        int iteration = 1000;
        for(int i = 0; i < iteration; i++) {
            MixedTest(nrec);
        }
        double mean_time = total / iteration;
        std::cout << "nrec = " << nrec << "    time = " << mean_time << std::endl;
        nrec <<= 1;
    }
    return  0;
}<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QByteArray>
#include <tascoreutils.h>
#include <testabilityutils.h>
#include <testabilitysettings.h>
#include <taslogger.h>
#include <QTcpSocket>
#include <QDomElement>
#include <QDomDocument>
#include <QFile>

#include "servermonitor.h"

#ifdef Q_OS_SYMBIAN
#include <e32base.h>
_LIT( KQTasServerName, "qttasserver" );
#endif

const static QString SERVER_PATH = "qttasserver";

const static QString CLOSE_APP = "<TasCommands service=\"closeApplication\" name=\"\" id=\"\">"
    "<Target TasId=\"Application\"><Command name=\"Close\" uid=\"0\"/></Target></TasCommands>";

const static QString SERVER_PING = "<TasCommands service=\"listApps\">"
    "<Target TasId=\"Application\"><Command name=\"listApps\"/></Target></TasCommands>";

const static QString NOT_CONNECTED = "Down";

const static QString CONNECTED = "Connected";

const static QString NOT_RESPONDING = "Not responding";

const static QString RUNNING = "Running";

#ifdef Q_OS_SYMBIAN
const static QString SERVERINI =  "c:\\system\\data\\qttasserver.ini";
#endif

ServerMonitor::ServerMonitor(QObject* parent)
    :QObject(parent)
{
    mClient = new TasClient();
    connect(mClient, SIGNAL(error(const QString&)), this, SLOT(error(const QString&)));
    connect(mClient, SIGNAL(info(const QString&)), this, SLOT(info(const QString&)));
    connect(mClient, SIGNAL(serverResponse(const QString&)), this, SLOT(serverResponse(const QString&)));

    QString appName = TestabilityUtils::getApplicationName();
    TasLogger::logger()->setLogFile(appName+".log");
    TasLogger::logger()->setLevel(DEBUG);
    TasLogger::logger()->clearLogFile();

}

ServerMonitor::~ServerMonitor()
{
    delete mClient;
}

void ServerMonitor::serverState()
{
    mState = STATUS;
    emit serverDebug("Get server status..");
    mClient->sendMessage(SERVER_PING);
}

void ServerMonitor::restartServer()
{
    emit beginMonitor();
    mState = RESTART;
    emit serverDebug("Restarting server...");
    emit serverDebug("Stopping server...");
    mClient->sendMessage(CLOSE_APP);
}

void ServerMonitor::startServer()
{
    emit beginMonitor();
    mState = START;
    emit serverDebug("Starting server....");
    QProcess::startDetached(SERVER_PATH);
    emit serverDebug("Process started wait a bit...");
    QTimer::singleShot(3000, this, SLOT(serverState()));
}

void ServerMonitor::stopServer()
{
    emit beginMonitor();
    mState = STOP;
    emit serverDebug("Stopping server...");
    mClient->sendMessage(CLOSE_APP);
    TasLogger::logger()->debug("ServerMonitor::stopServer");
}

void ServerMonitor::info(const QString& message)
{
    emit serverDebug(message);
}

void ServerMonitor::error(const QString& message)
{
    TasLogger::logger()->debug("ServerMonitor::error " + message);
    emit serverDebug(message);
    emit serverState(NOT_CONNECTED);
    if(mState != RESTART){
        emit stopMonitor();
    }
    if(mState == STOP || mState == RESTART){
        emit serverDebug("Connection was closed. Server appears to have stopped.");
        killServer();
        if(mState == RESTART){
            TasCoreUtils::wait(1000);
            startServer();
        }
    }
}

void ServerMonitor::serverResponse(const QString& message)
{
    TasLogger::logger()->debug("ServerMonitor::serverResponse " + message);
    if(mState == STOP || mState == RESTART){
        emit serverDebug("Close command ok server stopping.");
    }
    else{
        QDomDocument doc("TasMessage");
        if(mState == STATUS && doc.setContent(message)){
            emit serverDebug("Currently registered applications:");
            QDomNodeList targets = doc.elementsByTagName (QString("object"));
            int count = targets.count();
            for (int i = 0; i < count; i++){
                QDomElement target = targets.item(i).toElement();
                if(target.attribute("type") == "application"){
                    emit serverDebug(target.attribute("name"));
                }
            }
        }
        else{
            emit serverDebug(message);
        }
        emit serverState(RUNNING);
        emit stopMonitor();
    }
}

void ServerMonitor::killServer()
{
    TasLogger::logger()->debug("ServerMonitor::killServer");
#ifdef Q_OS_SYMBIAN
    TFindProcess findProcess;
    TFullName processName;
    while ( findProcess.Next( processName ) == KErrNone )
        {
        if ( ( processName.Find( KQTasServerName ) != KErrNotFound ) )
            {
            RProcess process;
            TInt err = process.Open( findProcess );
            if( err == KErrNone)
                {
                if( process.ExitType() != EExitPending )
                    {
                    process.Close();
                    }
                else
                    {
                    process.Kill(0);
                    process.Close();
                    break;
                    }
                }
            }
        }
#else
    //make sure connections are re opened
    delete mClient;
    mClient = new TasClient();
    connect(mClient, SIGNAL(error(const QString&)), this, SLOT(error(const QString&)));
    connect(mClient, SIGNAL(info(const QString&)), this, SLOT(info(const QString&)));
    connect(mClient, SIGNAL(serverResponse(const QString&)), this, SLOT(serverResponse(const QString&)));
#endif
}

#ifdef Q_OS_SYMBIAN
void ServerMonitor::enablePluginLoad()
{
    emit serverDebug("Attempting to enable plugin loading...");
    QProcess process;
    process.start("TasHookActivator");
    if(process.waitForStarted()){
        emit serverDebug("Plugin enabler started successfully.");
        if(process.waitForFinished()){
            emit serverDebug("Plugin enabler executed successfully.");
            emit serverDebug("Applications should now load the plugin.");
        }
        else{
            emit serverDebug("Plugin enabler did not finish properly.");
        }
    }
    else{
        emit serverDebug("Could not start enabler. " + process.errorString());
    }
}

void ServerMonitor::setAutoStart(bool autostart)
{
    if(autostart){
        emit serverDebug("Setting autostart value on");
        if(TestabilitySettings::settings()->setValue(AUTO_START, "on")){
            emit serverDebug("Setting autostart value on succeeded.");
        }
        else{
            emit serverDebug("Setting autostart value on failed.");
        }
    }
    else{
        emit serverDebug("Setting autostart value off");
        if(TestabilitySettings::settings()->setValue(AUTO_START, "off")){
            emit serverDebug("Setting autostart value off succeeded.");
        }
        else{
            emit serverDebug("Setting autostart value off failed.");
        }
    }
}

bool ServerMonitor::autostartState()
{
    return TestabilityUtils::autostart();
}

#endif

TasClient::TasClient()
{
    TasLogger::logger()->debug("TasClient::TasClient");
    mTimer.setSingleShot(true);
    mConnected = false;
    TasLogger::logger()->debug("TasClient::TasClient make socket");
    mSocket = new TasClientSocket(mServerConnection);
	connect(mSocket, SIGNAL(socketClosed()), this, SLOT(connectionClosed()));
    TasLogger::logger()->debug("TasClient::TasClient set responsehandler");
    mSocket->setResponseHandler(this);
    //connectToServer();
    connect(&mTimer, SIGNAL(timeout()), this, SLOT(connectionTimeout()));
    mSending = false;
    TasLogger::logger()->debug("TasClient::TasClient done");
}

TasClient::~TasClient()
{
    delete mSocket;
}

void TasClient::connectionClosed()
{
    TasLogger::logger()->debug("TasClient::connectionClosed");
    if(mConnected){
        mConnected = false;
        emit error("Connection was closed by server.");
    }
}

bool TasClient::connectToServer()
{
#if defined(TAS_NOLOCALSOCKET)
    mServerConnection.connectToHost(QT_SERVER_NAME, QT_SERVER_PORT);
#else
    mServerConnection.connectToServer(LOCAL_SERVER_NAME);
#endif
    mConnected = mServerConnection.waitForConnected(3000);
    return mConnected;
}

void TasClient::sendMessage(const QString& message)
{
    if(mTimer.isActive()){
        emit error("Processing earlier message.");
    }
    else{
        if(!mConnected){
            emit info("Not connected to server. Connecting...");
            connectToServer();
        }
        if(mConnected){
            emit info("Connection succesfull, sending message...");
            sendData(message);
        }
        else{
            emit error("Could not connect to server (maybe not running).");
        }
    }
}

void TasClient::sendData(const QString& message)
{
    TasLogger::logger()->debug("TasClient::sendData");
    mTimer.start(10000);
    mMessageId = qrand();
    if(!mSocket->sendRequest(mMessageId, message)){
        mTimer.stop();
        mConnected = false;
        mServerConnection.close();
        emit error("Socket not writable!");
    }
    TasLogger::logger()->debug("TasClient::sendData done");
}

void TasClient::serviceResponse(TasMessage& response)
{
    TasLogger::logger()->debug("TasClient::serviceResponse");
    if(response.messageId() == mMessageId){
        mTimer.stop();
        emit serverResponse(response.dataAsString());
    }
    else{
        emit error("Server responded with an invalid message.");
    }
}

void TasClient::connectionTimeout()
{
    mServerConnection.close();
    mConnected = false;
    emit error("Server did not respond in time.");
}

<commit_msg>Win7 ui crash fix<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QByteArray>
#include <tascoreutils.h>
#include <testabilityutils.h>
#include <testabilitysettings.h>
#include <taslogger.h>
#include <QTcpSocket>
#include <QDomElement>
#include <QDomDocument>
#include <QFile>

#include "servermonitor.h"

#ifdef Q_OS_SYMBIAN
#include <e32base.h>
_LIT( KQTasServerName, "qttasserver" );
#endif

const static QString SERVER_PATH = "qttasserver";

const static QString CLOSE_APP = "<TasCommands service=\"closeApplication\" name=\"\" id=\"\">"
    "<Target TasId=\"Application\"><Command name=\"Close\" uid=\"0\"/></Target></TasCommands>";

const static QString SERVER_PING = "<TasCommands service=\"listApps\">"
    "<Target TasId=\"Application\"><Command name=\"listApps\"/></Target></TasCommands>";

const static QString NOT_CONNECTED = "Down";

const static QString CONNECTED = "Connected";

const static QString NOT_RESPONDING = "Not responding";

const static QString RUNNING = "Running";

#ifdef Q_OS_SYMBIAN
const static QString SERVERINI =  "c:\\system\\data\\qttasserver.ini";
#endif

ServerMonitor::ServerMonitor(QObject* parent)
    :QObject(parent)
{
    mClient = new TasClient();
    connect(mClient, SIGNAL(error(const QString&)), this, SLOT(error(const QString&)));
    connect(mClient, SIGNAL(info(const QString&)), this, SLOT(info(const QString&)));
    connect(mClient, SIGNAL(serverResponse(const QString&)), this, SLOT(serverResponse(const QString&)));

    QString appName = TestabilityUtils::getApplicationName();
    TasLogger::logger()->setLogFile(appName+".log");
    TasLogger::logger()->setLevel(DEBUG);
    TasLogger::logger()->clearLogFile();

}

ServerMonitor::~ServerMonitor()
{
    delete mClient;
}

void ServerMonitor::serverState()
{
    mState = STATUS;
    emit serverDebug("Get server status..");
    mClient->sendMessage(SERVER_PING);
}

void ServerMonitor::restartServer()
{
    emit beginMonitor();
    mState = RESTART;
    emit serverDebug("Restarting server...");
    emit serverDebug("Stopping server...");
    mClient->sendMessage(CLOSE_APP);
}

void ServerMonitor::startServer()
{
    emit beginMonitor();
    mState = START;
    emit serverDebug("Starting server....");
    QProcess::startDetached(SERVER_PATH);
    emit serverDebug("Process started wait a bit...");
    QTimer::singleShot(3000, this, SLOT(serverState()));
}

void ServerMonitor::stopServer()
{
    emit beginMonitor();
    mState = STOP;
    emit serverDebug("Stopping server...");
    mClient->sendMessage(CLOSE_APP);
    TasLogger::logger()->debug("ServerMonitor::stopServer");
}

void ServerMonitor::info(const QString& message)
{
    emit serverDebug(message);
}

void ServerMonitor::error(const QString& message)
{
    TasLogger::logger()->debug("ServerMonitor::error " + message);
    emit serverDebug(message);
    emit serverState(NOT_CONNECTED);
    if(mState != RESTART){
        emit stopMonitor();
    }
    if(mState == STOP || mState == RESTART){
        emit serverDebug("Connection was closed. Server appears to have stopped.");
        killServer();
        if(mState == RESTART){
            TasCoreUtils::wait(1000);
            startServer();
        }
    }
}

void ServerMonitor::serverResponse(const QString& message)
{
    TasLogger::logger()->debug("ServerMonitor::serverResponse " + message);
    if(mState == STOP || mState == RESTART){
        emit serverDebug("Close command ok server stopping.");
    }
    else{
        QDomDocument doc("TasMessage");
        if(mState == STATUS && doc.setContent(message)){
            emit serverDebug("Currently registered applications:");
            QDomNodeList targets = doc.elementsByTagName (QString("object"));
            int count = targets.count();
            for (int i = 0; i < count; i++){
                QDomElement target = targets.item(i).toElement();
                if(target.attribute("type") == "application"){
                    emit serverDebug(target.attribute("name"));
                }
            }
        }
        else{
            emit serverDebug(message);
        }
        emit serverState(RUNNING);
        emit stopMonitor();
    }
}

void ServerMonitor::killServer()
{
    TasLogger::logger()->debug("ServerMonitor::killServer");
#ifdef Q_OS_SYMBIAN
    TFindProcess findProcess;
    TFullName processName;
    while ( findProcess.Next( processName ) == KErrNone )
        {
        if ( ( processName.Find( KQTasServerName ) != KErrNotFound ) )
            {
            RProcess process;
            TInt err = process.Open( findProcess );
            if( err == KErrNone)
                {
                if( process.ExitType() != EExitPending )
                    {
                    process.Close();
                    }
                else
                    {
                    process.Kill(0);
                    process.Close();
                    break;
                    }
                }
            }
        }
#else
    //make sure connections are re opened
    mClient->deleteLater();
    mClient = new TasClient();
    connect(mClient, SIGNAL(error(const QString&)), this, SLOT(error(const QString&)));
    connect(mClient, SIGNAL(info(const QString&)), this, SLOT(info(const QString&)));
    connect(mClient, SIGNAL(serverResponse(const QString&)), this, SLOT(serverResponse(const QString&)));
#endif
}

#ifdef Q_OS_SYMBIAN
void ServerMonitor::enablePluginLoad()
{
    emit serverDebug("Attempting to enable plugin loading...");
    QProcess process;
    process.start("TasHookActivator");
    if(process.waitForStarted()){
        emit serverDebug("Plugin enabler started successfully.");
        if(process.waitForFinished()){
            emit serverDebug("Plugin enabler executed successfully.");
            emit serverDebug("Applications should now load the plugin.");
        }
        else{
            emit serverDebug("Plugin enabler did not finish properly.");
        }
    }
    else{
        emit serverDebug("Could not start enabler. " + process.errorString());
    }
}

void ServerMonitor::setAutoStart(bool autostart)
{
    if(autostart){
        emit serverDebug("Setting autostart value on");
        if(TestabilitySettings::settings()->setValue(AUTO_START, "on")){
            emit serverDebug("Setting autostart value on succeeded.");
        }
        else{
            emit serverDebug("Setting autostart value on failed.");
        }
    }
    else{
        emit serverDebug("Setting autostart value off");
        if(TestabilitySettings::settings()->setValue(AUTO_START, "off")){
            emit serverDebug("Setting autostart value off succeeded.");
        }
        else{
            emit serverDebug("Setting autostart value off failed.");
        }
    }
}

bool ServerMonitor::autostartState()
{
    return TestabilityUtils::autostart();
}

#endif

TasClient::TasClient()
{
    TasLogger::logger()->debug("TasClient::TasClient");
    mTimer.setSingleShot(true);
    mConnected = false;
    TasLogger::logger()->debug("TasClient::TasClient make socket");
    mSocket = new TasClientSocket(mServerConnection);
	connect(mSocket, SIGNAL(socketClosed()), this, SLOT(connectionClosed()));
    TasLogger::logger()->debug("TasClient::TasClient set responsehandler");
    mSocket->setResponseHandler(this);
    //connectToServer();
    connect(&mTimer, SIGNAL(timeout()), this, SLOT(connectionTimeout()));
    mSending = false;
    TasLogger::logger()->debug("TasClient::TasClient done");
}

TasClient::~TasClient()
{
    delete mSocket;
}

void TasClient::connectionClosed()
{
    TasLogger::logger()->debug("TasClient::connectionClosed");
    if(mConnected){
        mConnected = false;
        emit error("Connection was closed by server.");
    }
}

bool TasClient::connectToServer()
{
#if defined(TAS_NOLOCALSOCKET)
    mServerConnection.connectToHost(QT_SERVER_NAME, QT_SERVER_PORT);
#else
    mServerConnection.connectToServer(LOCAL_SERVER_NAME);
#endif
    mConnected = mServerConnection.waitForConnected(3000);
    return mConnected;
}

void TasClient::sendMessage(const QString& message)
{
    if(mTimer.isActive()){
        emit error("Processing earlier message.");
    }
    else{
        if(!mConnected){
            emit info("Not connected to server. Connecting...");
            connectToServer();
        }
        if(mConnected){
            emit info("Connection succesfull, sending message...");
            sendData(message);
        }
        else{
            emit error("Could not connect to server (maybe not running).");
        }
    }
}

void TasClient::sendData(const QString& message)
{
    TasLogger::logger()->debug("TasClient::sendData");
    mTimer.start(10000);
    mMessageId = qrand();
    if(!mSocket->sendRequest(mMessageId, message)){
        mTimer.stop();
        mConnected = false;
        mServerConnection.close();
        emit error("Socket not writable!");
    }
    TasLogger::logger()->debug("TasClient::sendData done");
}

void TasClient::serviceResponse(TasMessage& response)
{
    TasLogger::logger()->debug("TasClient::serviceResponse");
    if(response.messageId() == mMessageId){
        mTimer.stop();
        emit serverResponse(response.dataAsString());
    }
    else{
        emit error("Server responded with an invalid message.");
    }
}

void TasClient::connectionTimeout()
{
    mServerConnection.close();
    mConnected = false;
    emit error("Server did not respond in time.");
}

<|endoftext|>


<commit_before>#include "../common/init.h"
#include "../common/timer.h"

#include "util/font.h"
#include "util/pointer.h"
#include "util/stretch-bitmap.h"
#include "util/input/input.h"
#include "util/input/input-manager.h"

#include "util/gui/animation.h"
#include "util/gui/box.h"
#include "util/gui/container.h"
#include "util/gui/context-box.h"
#include "util/gui/coordinate.h"
#include "util/gui/cutscene.h"
#include "util/gui/fadetool.h"
#include "util/gui/keys.h"
#include "util/gui/keyinput.h"
#include "util/gui/keyinput_manager.h"
#include "util/gui/lineedit.h"
#include "util/gui/rectarea.h"
#include "util/gui/popup-box.h"
#include "util/gui/scroll-list.h"
#include "util/gui/select-list.h"
#include "util/gui/tabbed-box.h"
#include "util/gui/timer.h"
#include "util/gui/widget.h"

#include <string>
#include <vector>

using namespace std;
using namespace Gui;

enum Keys{
    Up=0,
    Down,
    Left,
    Right,
    Esc,
    Enter,
};

/*! Gui Component */
class GuiComponent : public ScrollItem{
public:
    GuiComponent(const std::string & name):
    name(name),
    active(false){
    }
    virtual ~GuiComponent(){
    }
    // pure virtual funcs
    virtual void up() = 0;
    virtual void down() = 0;
    virtual void right() = 0;
    virtual void left() = 0;
    virtual void actComponent() = 0;
    virtual void drawComponent(const Graphics::Bitmap & where, const Font & font) = 0;

    void draw(int x, int y, const Graphics::Bitmap & where, const Font & font, int distance) const{
        if (active){
            font.printf(x, y, Graphics::makeColor(255, 0, 255), where, name, 0);
        } else {
            font.printf(x, y, Graphics::makeColor(255, 255, 255), where, name, 0);
        }
    }
    int size(const Font & font) const{
        return font.textLength(name.c_str());
    }
    void toggle(){
        active = !active;
    }
protected:
    std::string name;
    bool active;
};

/*! Box Gui Component */
class TestBox : public GuiComponent {
public:
    TestBox():
    GuiComponent("Gui::Box"),
    size(Gui::RelativePoint(-.5, -.5), Gui::RelativePoint(.5, .5)){
        box.colors.body = Graphics::makeColor(255, 255, 255);
        box.colors.border = Graphics::makeColor(0, 0, 255);
    }
    void up(){
        size.growVertical(.01);
    }
    void down(){
        size.growVertical(-.01);
    }
    void right(){
        size.growHorizontal(.01);
    }
    void left(){
        size.growHorizontal(-.01);
    }
    void actComponent(){
        box.location.growTo(size);
    }
    void drawComponent(const Graphics::Bitmap & where, const Font & font){
        box.render(where);
        font.printf(320 - font.textLength(name.c_str())/2, 15, Graphics::makeColor(255, 255, 255), where, "%s", 0, name.c_str());
    }
protected:
    Gui::Box box;
    Gui::Coordinate size;
};

/*! Gui Handler */
class GuiHandler {
public:
    GuiHandler():
    selected(false){
        // Initialize components and store
        components.push_back(new TestBox());

        // Set first as active
        components[0].convert<GuiComponent>()->toggle();

        // Finally add component list to scroll list
        list.addItems(components);
    }
    ~GuiHandler(){
    }

    void up(){
        if (!selected){
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
            list.previous();
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
        } else {
            components[list.getCurrentIndex()].convert<GuiComponent>()->up();
        }
    }
    void down(){
        if (!selected){
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
            list.next();
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
        } else {
            components[list.getCurrentIndex()].convert<GuiComponent>()->down();
        }
    }
    void left(){
        if (!selected){
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
            list.previous();
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
        } else {
            components[list.getCurrentIndex()].convert<GuiComponent>()->left();
        }
    }
    void right(){
        if (!selected){
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
            list.next();
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
        } else {
            components[list.getCurrentIndex()].convert<GuiComponent>()->right();
        }
    }

    void act(){
        if (!selected){
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
            list.act();
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
        } else {
            components[list.getCurrentIndex()].convert<GuiComponent>()->actComponent();
        }
    }
    void draw(const Graphics::Bitmap & work, const Font & font){
        if (!selected){
            list.render(work, font);
        } else {
            components[list.getCurrentIndex()].convert<GuiComponent>()->drawComponent(work, font);
        }
    }

    void enter(){
        if (!selected) {
            selected = true;
        }
    }
    void esc(){
        if (selected){
            selected = false;
        }
    }

    bool inComponent(){
        return selected;
    }

protected:
    bool selected;
    std::vector<Util::ReferenceCount<Gui::ScrollItem> > components;
    Gui::NormalList list;
};

class Logic: public Util::Logic {
public:
    Logic(InputMap<Keys> & input, GuiHandler & handler):
    is_done(false),
    input(input),
    handler(handler){
    }

    bool is_done;
    InputMap<Keys> & input;
    GuiHandler & handler;

    bool done(){
        return is_done;
    }

    void run(){
        vector<InputMap<Keys>::InputEvent> out = InputManager::getEvents(input, InputSource());
        for (vector<InputMap<Keys>::InputEvent>::iterator it = out.begin(); it != out.end(); it++){
            const InputMap<Keys>::InputEvent & event = *it;
            if (event.enabled){
                if (event.out == Esc){
                    if (!handler.inComponent()){
                        is_done = true;
                    } else {
                        handler.esc();
                    }
                }
                if (event.out == Up){
                    handler.up();
                }
                if (event.out == Down){
                    handler.down();
                }
                if (event.out == Left){
                    handler.left();
                }
                if (event.out == Right){
                    handler.right();
                }
                if (event.out == Enter){
                    handler.enter();
                }
            }
        }

        handler.act();

    }

    double ticks(double system){
        return system;
    }
};

class Draw: public Util::Draw {
public:
    Draw(GuiHandler & handler):
    handler(handler),
    controls("Controls: Up, Down, Left, Right, Enter, Esc"){
    }

    GuiHandler & handler;
    std::string controls;

    void draw(const Graphics::Bitmap & buffer){
        //buffer.putPixel(rand() % 640, rand() % 480, Graphics::makeColor(rand() % 255, rand() % 255, rand() % 255));
        buffer.clear();
        handler.draw(buffer, Font::getDefaultFont());
        Font::getDefaultFont().printf(320 - Font::getDefaultFont().textLength(controls.c_str())/2, 460, Graphics::makeColor(255, 255, 255), buffer, "%s", 0, controls.c_str());
        buffer.BlitToScreen();
    }
};

int main(int argc, char ** argv){
    Screen::realInit();
    Common::startTimers();

    InputManager manager;
    Graphics::Bitmap screen(Graphics::getScreenBuffer());
    Util::Parameter<Graphics::Bitmap*> use(Graphics::screenParameter, &screen);

    InputMap<Keys> input;
    input.set(Keyboard::Key_ESC, 0, true, Esc);
    input.set(Keyboard::Key_ENTER, 0, true, Enter);
    input.set(Keyboard::Key_UP, 0, true, Up);
    input.set(Keyboard::Key_DOWN, 0, true, Down);
    input.set(Keyboard::Key_LEFT, 0, true, Left);
    input.set(Keyboard::Key_RIGHT, 0, true, Right);

    GuiHandler handler;

    Logic logic(input, handler);
    Draw draw(handler);

    Util::standardLoop(logic, draw);

    Screen::realFinish();
    return 0;
}
#ifdef USE_ALLEGRO
END_OF_MAIN()
#endif
<commit_msg>Added some fillers and implemented FadeTool.<commit_after>#include "../common/init.h"
#include "../common/timer.h"

#include "util/font.h"
#include "util/pointer.h"
#include "util/stretch-bitmap.h"
#include "util/input/input.h"
#include "util/input/input-manager.h"

#include "util/gui/animation.h"
#include "util/gui/box.h"
#include "util/gui/container.h"
#include "util/gui/context-box.h"
#include "util/gui/coordinate.h"
#include "util/gui/cutscene.h"
#include "util/gui/fadetool.h"
#include "util/gui/keys.h"
#include "util/gui/keyinput.h"
#include "util/gui/keyinput_manager.h"
#include "util/gui/lineedit.h"
#include "util/gui/rectarea.h"
#include "util/gui/popup-box.h"
#include "util/gui/scroll-list.h"
#include "util/gui/select-list.h"
#include "util/gui/tabbed-box.h"
#include "util/gui/timer.h"
#include "util/gui/widget.h"

#include <string>
#include <vector>

using namespace std;
using namespace Gui;

enum Keys{
    Up=0,
    Down,
    Left,
    Right,
    Esc,
    Enter,
};

/*! Gui Component */
class GuiComponent : public ScrollItem{
public:
    GuiComponent(const std::string & name):
    name(name),
    active(false){
    }
    virtual ~GuiComponent(){
    }
    // pure virtual funcs
    virtual void up() = 0;
    virtual void down() = 0;
    virtual void right() = 0;
    virtual void left() = 0;
    virtual void actComponent() = 0;
    virtual void drawComponent(const Graphics::Bitmap & where, const Font & font) = 0;

    void draw(int x, int y, const Graphics::Bitmap & where, const Font & font, int distance) const{
        if (active){
            font.printf(x, y, Graphics::makeColor(255, 0, 255), where, name, 0);
        } else {
            font.printf(x, y, Graphics::makeColor(255, 255, 255), where, name, 0);
        }
    }
    int size(const Font & font) const{
        return font.textLength(name.c_str());
    }
    void toggle(){
        active = !active;
    }
protected:
    std::string name;
    bool active;
};

/*! TODO Animation Gui Component */
class TestAnimation : public GuiComponent {
public:
    TestAnimation():
    GuiComponent("Gui::Animation"){
    }
    void up(){
    }
    void down(){
    }
    void right(){
    }
    void left(){
    }
    void actComponent(){
    }
    void drawComponent(const Graphics::Bitmap & where, const Font & font){
        font.printf(320 - font.textLength(name.c_str())/2, 15, Graphics::makeColor(255, 255, 255), where, "%s", 0, name.c_str());
        const std::string info = "TODO - Not Implemented yet";
        font.printf(320 - font.textLength(info.c_str())/2, 240, Graphics::makeColor(255, 255, 255), where, "%s", 0, info.c_str());
    }
protected:
};

/*! Box Gui Component */
class TestBox : public GuiComponent {
public:
    TestBox():
    GuiComponent("Gui::Box"),
    size(Gui::RelativePoint(-.5, -.5), Gui::RelativePoint(.5, .5)){
        box.colors.body = Graphics::makeColor(255, 255, 255);
        box.colors.border = Graphics::makeColor(0, 0, 255);
    }
    void up(){
        size.growVertical(.01);
    }
    void down(){
        size.growVertical(-.01);
    }
    void right(){
        size.growHorizontal(.01);
    }
    void left(){
        size.growHorizontal(-.01);
    }
    void actComponent(){
        box.location.growTo(size);
    }
    void drawComponent(const Graphics::Bitmap & where, const Font & font){
        box.render(where);
        font.printf(320 - font.textLength(name.c_str())/2, 15, Graphics::makeColor(255, 255, 255), where, "%s", 0, name.c_str());
    }
protected:
    Gui::Box box;
    Gui::Coordinate size;
};

/*! TODO ContextBox Gui Component */
class TestContextBox : public GuiComponent {
public:
    TestContextBox():
    GuiComponent("Gui::ContextBox"){
    }
    void up(){
    }
    void down(){
    }
    void right(){
    }
    void left(){
    }
    void actComponent(){
    }
    void drawComponent(const Graphics::Bitmap & where, const Font & font){
        font.printf(320 - font.textLength(name.c_str())/2, 15, Graphics::makeColor(255, 255, 255), where, "%s", 0, name.c_str());
        const std::string info = "TODO - Not Implemented yet";
        font.printf(320 - font.textLength(info.c_str())/2, 240, Graphics::makeColor(255, 255, 255), where, "%s", 0, info.c_str());
    }
protected:
};

/*! TODO Cutscene Gui Component */
class TestCutScene : public GuiComponent {
public:
    TestCutScene():
    GuiComponent("Gui::CutScene"){
    }
    void up(){
    }
    void down(){
    }
    void right(){
    }
    void left(){
    }
    void actComponent(){
    }
    void drawComponent(const Graphics::Bitmap & where, const Font & font){
        font.printf(320 - font.textLength(name.c_str())/2, 15, Graphics::makeColor(255, 255, 255), where, "%s", 0, name.c_str());
        const std::string info = "TODO - Not Implemented yet";
        font.printf(320 - font.textLength(info.c_str())/2, 240, Graphics::makeColor(255, 255, 255), where, "%s", 0, info.c_str());
    }
protected:
};

/*! TODO FadeTool Gui Component */
class TestFadeTool : public GuiComponent {
public:
    TestFadeTool():
    GuiComponent("Gui::FadeTool"),
    time(50),
    bitmap(640, 480){
        bitmap.clear();
        fader.setState(FadeTool::FadeIn);
        fader.setFadeInTime(time);
        fader.setFadeOutTime(time);
    }
    void up(){
        time+=5;
        fader.setFadeInTime(time);
        fader.setFadeOutTime(time);
    }
    void down(){
        time-=5;
        fader.setFadeInTime(time);
        fader.setFadeOutTime(time);
    }
    void right(){
        time+=5;
        fader.setFadeInTime(time);
        fader.setFadeOutTime(time);
    }
    void left(){
        time-=5;
        fader.setFadeInTime(time);
        fader.setFadeOutTime(time);
    }
    void actComponent(){
        fader.act();
        if (fader.getState() == FadeTool::NoFade){
            fader.setState(FadeTool::FadeOut);
        } else if (fader.getState() == FadeTool::EndFade){
            fader.setState(FadeTool::FadeIn);
        }
    }
    void drawComponent(const Graphics::Bitmap & where, const Font & font){
        bitmap.putPixel(rand() % 640, rand() % 480, Graphics::makeColor(rand() % 255, rand() % 255, rand() % 255));
        bitmap.Blit(where);
        font.printf(270, 215, Graphics::makeColor(255, 255, 255), where, "Fade Time: %d", 0, time);
        font.printf(320 - font.textLength(name.c_str())/2, 240, Graphics::makeColor(255, 255, 255), where, "%s", 0, name.c_str());
        fader.draw(where);
    }
protected:
    int time;
    Graphics::Bitmap bitmap;
    Gui::FadeTool fader;
};

/*! Gui Handler */
class GuiHandler {
public:
    GuiHandler():
    selected(false){
        // Initialize components and store
        components.push_back(new TestAnimation());
        components.push_back(new TestBox());
        components.push_back(new TestContextBox());
        components.push_back(new TestCutScene());
        components.push_back(new TestFadeTool());

        // Set first as active
        components[0].convert<GuiComponent>()->toggle();

        // Finally add component list to scroll list
        list.addItems(components);
    }
    ~GuiHandler(){
    }

    void up(){
        if (!selected){
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
            list.previous();
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
        } else {
            components[list.getCurrentIndex()].convert<GuiComponent>()->up();
        }
    }
    void down(){
        if (!selected){
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
            list.next();
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
        } else {
            components[list.getCurrentIndex()].convert<GuiComponent>()->down();
        }
    }
    void left(){
        if (!selected){
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
            list.previous();
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
        } else {
            components[list.getCurrentIndex()].convert<GuiComponent>()->left();
        }
    }
    void right(){
        if (!selected){
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
            list.next();
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
        } else {
            components[list.getCurrentIndex()].convert<GuiComponent>()->right();
        }
    }

    void act(){
        if (!selected){
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
            list.act();
            components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
        } else {
            components[list.getCurrentIndex()].convert<GuiComponent>()->actComponent();
        }
    }
    void draw(const Graphics::Bitmap & work, const Font & font){
        if (!selected){
            list.render(work, font);
        } else {
            components[list.getCurrentIndex()].convert<GuiComponent>()->drawComponent(work, font);
        }
    }

    void enter(){
        if (!selected) {
            selected = true;
        }
    }
    void esc(){
        if (selected){
            selected = false;
        }
    }

    bool inComponent(){
        return selected;
    }

protected:
    bool selected;
    std::vector<Util::ReferenceCount<Gui::ScrollItem> > components;
    Gui::NormalList list;
};

class Logic: public Util::Logic {
public:
    Logic(InputMap<Keys> & input, GuiHandler & handler):
    is_done(false),
    input(input),
    handler(handler){
    }

    bool is_done;
    InputMap<Keys> & input;
    GuiHandler & handler;

    bool done(){
        return is_done;
    }

    void run(){
        vector<InputMap<Keys>::InputEvent> out = InputManager::getEvents(input, InputSource());
        for (vector<InputMap<Keys>::InputEvent>::iterator it = out.begin(); it != out.end(); it++){
            const InputMap<Keys>::InputEvent & event = *it;
            if (event.enabled){
                if (event.out == Esc){
                    if (!handler.inComponent()){
                        is_done = true;
                    } else {
                        handler.esc();
                    }
                }
                if (event.out == Up){
                    handler.up();
                }
                if (event.out == Down){
                    handler.down();
                }
                if (event.out == Left){
                    handler.left();
                }
                if (event.out == Right){
                    handler.right();
                }
                if (event.out == Enter){
                    handler.enter();
                }
            }
        }

        handler.act();

    }

    double ticks(double system){
        return system;
    }
};

class Draw: public Util::Draw {
public:
    Draw(GuiHandler & handler):
    handler(handler),
    controls("Controls: Up, Down, Left, Right, Enter, Esc"){
    }

    GuiHandler & handler;
    std::string controls;

    void draw(const Graphics::Bitmap & buffer){
        //buffer.putPixel(rand() % 640, rand() % 480, Graphics::makeColor(rand() % 255, rand() % 255, rand() % 255));
        buffer.clear();
        handler.draw(buffer, Font::getDefaultFont());
        Font::getDefaultFont().printf(320 - Font::getDefaultFont().textLength(controls.c_str())/2, 460, Graphics::makeColor(255, 255, 255), buffer, "%s", 0, controls.c_str());
        buffer.BlitToScreen();
    }
};

int main(int argc, char ** argv){
    Screen::realInit();
    Common::startTimers();

    InputManager manager;
    Graphics::Bitmap screen(Graphics::getScreenBuffer());
    Util::Parameter<Graphics::Bitmap*> use(Graphics::screenParameter, &screen);

    InputMap<Keys> input;
    input.set(Keyboard::Key_ESC, 0, true, Esc);
    input.set(Keyboard::Key_ENTER, 0, true, Enter);
    input.set(Keyboard::Key_UP, 0, true, Up);
    input.set(Keyboard::Key_DOWN, 0, true, Down);
    input.set(Keyboard::Key_LEFT, 0, true, Left);
    input.set(Keyboard::Key_RIGHT, 0, true, Right);

    GuiHandler handler;

    Logic logic(input, handler);
    Draw draw(handler);

    Util::standardLoop(logic, draw);

    Screen::realFinish();
    return 0;
}
#ifdef USE_ALLEGRO
END_OF_MAIN()
#endif
<|endoftext|>