<commit_before>/* gobby - A GTKmm driven libobby client
 * Copyright (C) 2005 0x539 dev group
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "document.hpp"

Gobby::Document::Document(obby::document& doc)
 : Gtk::ScrolledWindow(), m_doc(doc), m_editing(true)
{
#ifdef WITH_GTKSOURCEVIEW
	m_view.set_show_line_numbers(true);
#endif

	Glib::RefPtr<Gtk::TextBuffer> buf = m_view.get_buffer();

	// Textbuffer signal handlers
	buf->signal_insert().connect(
		sigc::mem_fun(*this, &Document::on_insert), false);
	buf->signal_erase().connect(
		sigc::mem_fun(*this, &Document::on_erase), false);

	// Obby signal handlers
	doc.insert_event().connect(
		sigc::mem_fun(*this, &Document::on_obby_insert) );
	doc.delete_event().connect(
		sigc::mem_fun(*this, &Document::on_obby_delete) );

	// Set initial text
	buf->set_text(doc.get_whole_buffer() );
	m_editing = false;

	set_shadow_type(Gtk::SHADOW_IN);
	set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
	add(m_view);
}

Gobby::Document::~Document()
{
}

const obby::document& Gobby::Document::get_document() const
{
	return m_doc;
}

obby::document& Gobby::Document::get_document()
{
	return m_doc;
}

void Gobby::Document::on_insert(const Gtk::TextBuffer::iterator& begin,
                                const Glib::ustring& text,
                                int foo)
{
	if(m_editing) return;
	m_doc.insert(begin.get_offset(), text);
}

void Gobby::Document::on_erase(const Gtk::TextBuffer::iterator& begin,
                               const Gtk::TextBuffer::iterator& end)
{
	if(m_editing) return;
	m_doc.erase(begin.get_offset(), end.get_offset() );
}

void Gobby::Document::on_obby_insert(const obby::insert_record& record)
{
	m_editing = true;
	Glib::RefPtr<Gtk::TextBuffer> buffer = m_view.get_buffer();
	buffer->insert(buffer->get_iter_at_offset(record.get_position()),
	               record.get_text() );
	m_editing = false;
}

void Gobby::Document::on_obby_delete(const obby::delete_record& record)
{
	m_editing = true;
	Glib::RefPtr<Gtk::TextBuffer> buffer = m_view.get_buffer();
	buffer->erase(buffer->get_iter_at_offset(record.get_begin()),
	              buffer->get_iter_at_offset(record.get_end()) );
	m_editing = false;
}

<commit_msg>[project @ Use a monospaced font for the TextView]<commit_after>/* gobby - A GTKmm driven libobby client
 * Copyright (C) 2005 0x539 dev group
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "document.hpp"

Gobby::Document::Document(obby::document& doc)
 : Gtk::ScrolledWindow(), m_doc(doc), m_editing(true)
{
#ifdef WITH_GTKSOURCEVIEW
	m_view.set_show_line_numbers(true);
#endif
	Glib::RefPtr<Gtk::TextBuffer> buf = m_view.get_buffer();

	Pango::FontDescription desc;
	desc.set_family("monospace");
	m_view.modify_font(desc);

	// Textbuffer signal handlers
	buf->signal_insert().connect(
		sigc::mem_fun(*this, &Document::on_insert), false);
	buf->signal_erase().connect(
		sigc::mem_fun(*this, &Document::on_erase), false);

	// Obby signal handlers
	doc.insert_event().connect(
		sigc::mem_fun(*this, &Document::on_obby_insert) );
	doc.delete_event().connect(
		sigc::mem_fun(*this, &Document::on_obby_delete) );

	// Set initial text
	buf->set_text(doc.get_whole_buffer() );
	m_editing = false;

	set_shadow_type(Gtk::SHADOW_IN);
	set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
	add(m_view);
}

Gobby::Document::~Document()
{
}

const obby::document& Gobby::Document::get_document() const
{
	return m_doc;
}

obby::document& Gobby::Document::get_document()
{
	return m_doc;
}

void Gobby::Document::on_insert(const Gtk::TextBuffer::iterator& begin,
                                const Glib::ustring& text,
                                int foo)
{
	if(m_editing) return;
	m_doc.insert(begin.get_offset(), text);
}

void Gobby::Document::on_erase(const Gtk::TextBuffer::iterator& begin,
                               const Gtk::TextBuffer::iterator& end)
{
	if(m_editing) return;
	m_doc.erase(begin.get_offset(), end.get_offset() );
}

void Gobby::Document::on_obby_insert(const obby::insert_record& record)
{
	m_editing = true;
	Glib::RefPtr<Gtk::TextBuffer> buffer = m_view.get_buffer();
	buffer->insert(buffer->get_iter_at_offset(record.get_position()),
	               record.get_text() );
	m_editing = false;
}

void Gobby::Document::on_obby_delete(const obby::delete_record& record)
{
	m_editing = true;
	Glib::RefPtr<Gtk::TextBuffer> buffer = m_view.get_buffer();
	buffer->erase(buffer->get_iter_at_offset(record.get_begin()),
	              buffer->get_iter_at_offset(record.get_end()) );
	m_editing = false;
}

<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/audio_device/android/low_latency_event.h"

#include <assert.h>

#define HANDLE_EINTR(x) ({                \
      typeof(x) eintr_wrapper_result;     \
      do {                                                        \
        eintr_wrapper_result = (x);                               \
      } while (eintr_wrapper_result == -1 && errno == EINTR);     \
      eintr_wrapper_result;                                       \
    })

namespace webrtc {

const LowLatencyEvent::Handle LowLatencyEvent::kInvalidHandle = -1;
const int LowLatencyEvent::kReadHandle = 0;
const int LowLatencyEvent::kWriteHandle = 1;

LowLatencyEvent::LowLatencyEvent() {
  handles_[kReadHandle] = kInvalidHandle;
  handles_[kWriteHandle] = kInvalidHandle;
}

LowLatencyEvent::~LowLatencyEvent() {
  Stop();
}

bool LowLatencyEvent::Start() {
  assert(handles_[kReadHandle] == kInvalidHandle);
  assert(handles_[kWriteHandle] == kInvalidHandle);

  return socketpair(AF_UNIX, SOCK_STREAM, 0, handles_) == 0;
}

bool LowLatencyEvent::Stop() {
  bool ret = Close(&handles_[kReadHandle]) && Close(&handles_[kWriteHandle]);
  handles_[kReadHandle] = kInvalidHandle;
  handles_[kWriteHandle] = kInvalidHandle;
  return ret;
}

void LowLatencyEvent::SignalEvent(int event_id, int event_msg) {
  WriteFd(event_id, event_msg);
}

void LowLatencyEvent::WaitOnEvent(int* event_id, int* event_msg) {
  ReadFd(event_id, event_msg);
}

bool LowLatencyEvent::Close(Handle* handle) {
  if (*handle == kInvalidHandle) {
    return false;
  }
  int retval = HANDLE_EINTR(close(*handle));
  *handle = kInvalidHandle;
  return retval == 0;
}

void LowLatencyEvent::WriteFd(int message_id, int message) {
  char buffer[sizeof(message_id) + sizeof(message)];
  size_t bytes = sizeof(buffer);
  memcpy(buffer, &message_id, sizeof(message_id));
  memcpy(&buffer[sizeof(message_id)], &message, sizeof(message));
  ssize_t bytes_written = HANDLE_EINTR(write(handles_[kWriteHandle], buffer,
                                             bytes));
  if (bytes_written != static_cast<ssize_t>(bytes)) {
    assert(false);
  }
}

void LowLatencyEvent::ReadFd(int* message_id, int* message) {
  char buffer[sizeof(message_id) + sizeof(message)];
  size_t bytes = sizeof(buffer);
  ssize_t bytes_read = HANDLE_EINTR(read(handles_[kReadHandle], buffer, bytes));
  if (bytes_read == 0) {
    *message_id = 0;
    *message = 0;
    return;
  } else if (bytes_read == static_cast<ssize_t>(bytes)) {
    memcpy(message_id, buffer, sizeof(*message_id));
    memcpy(message, &buffer[sizeof(*message_id)], sizeof(*message));
  } else {
    assert(false);
  }
}

}  // namespace webrtc
<commit_msg>Don't HANDLE_EINTR(close). Use IGNORE_EINTR(close).<commit_after>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/audio_device/android/low_latency_event.h"

#include <assert.h>

#define HANDLE_EINTR(x) ({                \
      typeof(x) eintr_wrapper_result;     \
      do {                                                        \
        eintr_wrapper_result = (x);                               \
      } while (eintr_wrapper_result == -1 && errno == EINTR);     \
      eintr_wrapper_result;                                       \
    })

#define IGNORE_EINTR(x) ({                \
      typeof(x) eintr_wrapper_result;     \
      do {                                                        \
        eintr_wrapper_result = (x);                               \
        if (eintr_wrapper_result == -1 && errno == EINTR) {       \
          eintr_wrapper_result = 0;                               \
        }                                                         \
      } while (0);                                                \
      eintr_wrapper_result;                                       \
    })

namespace webrtc {

const LowLatencyEvent::Handle LowLatencyEvent::kInvalidHandle = -1;
const int LowLatencyEvent::kReadHandle = 0;
const int LowLatencyEvent::kWriteHandle = 1;

LowLatencyEvent::LowLatencyEvent() {
  handles_[kReadHandle] = kInvalidHandle;
  handles_[kWriteHandle] = kInvalidHandle;
}

LowLatencyEvent::~LowLatencyEvent() {
  Stop();
}

bool LowLatencyEvent::Start() {
  assert(handles_[kReadHandle] == kInvalidHandle);
  assert(handles_[kWriteHandle] == kInvalidHandle);

  return socketpair(AF_UNIX, SOCK_STREAM, 0, handles_) == 0;
}

bool LowLatencyEvent::Stop() {
  bool ret = Close(&handles_[kReadHandle]) && Close(&handles_[kWriteHandle]);
  handles_[kReadHandle] = kInvalidHandle;
  handles_[kWriteHandle] = kInvalidHandle;
  return ret;
}

void LowLatencyEvent::SignalEvent(int event_id, int event_msg) {
  WriteFd(event_id, event_msg);
}

void LowLatencyEvent::WaitOnEvent(int* event_id, int* event_msg) {
  ReadFd(event_id, event_msg);
}

bool LowLatencyEvent::Close(Handle* handle) {
  if (*handle == kInvalidHandle) {
    return false;
  }
  int retval = IGNORE_EINTR(close(*handle));
  *handle = kInvalidHandle;
  return retval == 0;
}

void LowLatencyEvent::WriteFd(int message_id, int message) {
  char buffer[sizeof(message_id) + sizeof(message)];
  size_t bytes = sizeof(buffer);
  memcpy(buffer, &message_id, sizeof(message_id));
  memcpy(&buffer[sizeof(message_id)], &message, sizeof(message));
  ssize_t bytes_written = HANDLE_EINTR(write(handles_[kWriteHandle], buffer,
                                             bytes));
  if (bytes_written != static_cast<ssize_t>(bytes)) {
    assert(false);
  }
}

void LowLatencyEvent::ReadFd(int* message_id, int* message) {
  char buffer[sizeof(message_id) + sizeof(message)];
  size_t bytes = sizeof(buffer);
  ssize_t bytes_read = HANDLE_EINTR(read(handles_[kReadHandle], buffer, bytes));
  if (bytes_read == 0) {
    *message_id = 0;
    *message = 0;
    return;
  } else if (bytes_read == static_cast<ssize_t>(bytes)) {
    memcpy(message_id, buffer, sizeof(*message_id));
    memcpy(message, &buffer[sizeof(*message_id)], sizeof(*message));
  } else {
    assert(false);
  }
}

}  // namespace webrtc
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/audio_device/dummy/file_audio_device_factory.h"

#include <cstring>

#include "webrtc/modules/audio_device/dummy/file_audio_device.h"

namespace webrtc {

char FileAudioDeviceFactory::_inputAudioFilename[MAX_FILENAME_LEN] = "";
char FileAudioDeviceFactory::_outputAudioFilename[MAX_FILENAME_LEN] = "";

FileAudioDevice* FileAudioDeviceFactory::CreateFileAudioDevice(
    const int32_t id) {
  // Bail out here if the files aren't set.
  if (strlen(_inputAudioFilename) == 0 || strlen(_outputAudioFilename) == 0) {
    printf("Was compiled with WEBRTC_DUMMY_AUDIO_PLAY_STATIC_FILE "
           "but did not set input/output files to use. Bailing out.\n");
    exit(1);
  }
  return new FileAudioDevice(id, _inputAudioFilename, _outputAudioFilename);
}

void FileAudioDeviceFactory::SetFilenamesToUse(
    const char* inputAudioFilename, const char* outputAudioFilename) {
#ifndef WEBRTC_DUMMY_FILE_DEVICES
  // Sanity: must be compiled with the right define to run this.
  printf("Trying to use dummy file devices, but is not compiled "
         "with WEBRTC_DUMMY_FILE_DEVICES. Bailing out.\n");
  exit(1);
#endif
  assert(strlen(inputAudioFilename) < MAX_FILENAME_LEN &&
         strlen(outputAudioFilename) < MAX_FILENAME_LEN);

  // Copy the strings since we don't know the lifetime of the input pointers.
  strncpy(_inputAudioFilename, inputAudioFilename, MAX_FILENAME_LEN);
  strncpy(_outputAudioFilename, outputAudioFilename, MAX_FILENAME_LEN);
}

}  // namespace webrtc
<commit_msg>Fixing compile error.<commit_after>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/audio_device/dummy/file_audio_device_factory.h"

#include <cstring>

#include "webrtc/modules/audio_device/dummy/file_audio_device.h"

namespace webrtc {

char FileAudioDeviceFactory::_inputAudioFilename[MAX_FILENAME_LEN] = "";
char FileAudioDeviceFactory::_outputAudioFilename[MAX_FILENAME_LEN] = "";

FileAudioDevice* FileAudioDeviceFactory::CreateFileAudioDevice(
    const int32_t id) {
  // Bail out here if the files aren't set.
  if (strlen(_inputAudioFilename) == 0 || strlen(_outputAudioFilename) == 0) {
    printf("Was compiled with WEBRTC_DUMMY_AUDIO_PLAY_STATIC_FILE "
           "but did not set input/output files to use. Bailing out.\n");
    exit(1);
  }
  return new FileAudioDevice(id, _inputAudioFilename, _outputAudioFilename);
}

void FileAudioDeviceFactory::SetFilenamesToUse(
    const char* inputAudioFilename, const char* outputAudioFilename) {
#ifdef WEBRTC_DUMMY_FILE_DEVICES
  assert(strlen(inputAudioFilename) < MAX_FILENAME_LEN &&
         strlen(outputAudioFilename) < MAX_FILENAME_LEN);

  // Copy the strings since we don't know the lifetime of the input pointers.
  strncpy(_inputAudioFilename, inputAudioFilename, MAX_FILENAME_LEN);
  strncpy(_outputAudioFilename, outputAudioFilename, MAX_FILENAME_LEN);
#else
  // Sanity: must be compiled with the right define to run this.
  printf("Trying to use dummy file devices, but is not compiled "
         "with WEBRTC_DUMMY_FILE_DEVICES. Bailing out.\n");
  exit(1);
#endif
}

}  // namespace webrtc
<|endoftext|>


<commit_before>/*
 * QMicroMapTest.cpp
 *
 *  Created on: May 3, 2011
 *      Author: martinc
 */
#include "QMicroMapTest.h"
#include <iostream>
#include "QStationModelGraphicsItem.h"

/////////////////////////////////////////////////////////////////////////////////////////////////
QMicroMapTest::QMicroMapTest(SpatiaLiteDB& db,
		double xmin,
		double ymin,
		double xmax,
		double ymax,
		std::string backgroundColor,
		QWidget* parent):
QDialog(parent),
_xmin(xmin),
_ymin(ymin),
_xmax(xmax),
_ymax(ymax),
_zoomInc(0.1)
{
	// setting up the Qt form
	setupUi(this);

	// we need a layout manager
	QVBoxLayout* vb = new QVBoxLayout(frame);

	// create the micromap and add to the layout
	_mm = new QMicroMap(db, _xmin, _ymin, _xmax, _ymax, backgroundColor);
	vb->addWidget(_mm);

	// collect a list of stations, which will e added to an item group
	QList<QGraphicsItem*> stationList;

	// create one leg of station models
	double wspd = 45;
	double wdir = 15;
	double lon = -86;
	double tdry = 23.0;
	double RH = 75.0;
	double presOrHeight = 1013;
	bool isPres = true;
	int hh = 17;
	int mm = 01;

	for (double lat = 24.0; lat < 29.0; lat += 0.8) {
		QStationModelGraphicsItem* sm
			= new QStationModelGraphicsItem(lon, lat, wspd, wdir, tdry, RH, presOrHeight, isPres, hh, mm, 60);
		wspd += 12;
		wdir += 13;
		lon -= 0.9;
		RH -= 4;
		mm += 3;
		tdry -= 1.3;
		presOrHeight -= 3;
		stationList.append(sm);
	}

	// create a seond leg of station models
	wspd = 55;
	wdir = 15;
	lon = -85;
	hh  -= 2;
	for (double lat = 27.0; lat >= 24.0; lat -= 0.51) {
		QStationModelGraphicsItem* sm
			= new QStationModelGraphicsItem(lon, lat, wspd, wdir, tdry, RH, presOrHeight, isPres, hh, mm, 60);
		wspd += 9;
		wdir += 13;
		lon -= 1.8;
		RH -= 4;
		mm -= 3;
		tdry += .8;
		presOrHeight -= 3;
		stationList.append(sm);
	}

	// create the item group of stations
	_stationGroup = _mm->scene()->createItemGroup(stationList);
	// Allow events to be propagated to the children. Note that the Qt documentation
	// for this is wrong; it states that the default is false, which is not true for
	// a QGraphicsItemGroup.
	_stationGroup->setHandlesChildEvents(false);

	// connect signals
	connect(labels,    SIGNAL(stateChanged(int)),                _mm,  SLOT(labels(int)));
	connect(grid,      SIGNAL(stateChanged(int)),                _mm,  SLOT(grid(int)));
	connect(obs,       SIGNAL(stateChanged(int)),                this, SLOT(obsSlot(int)));
	connect(mousePan,  SIGNAL(toggled(bool)),                    this, SLOT(mouseSlot(bool)));
	connect(mouseZoom, SIGNAL(toggled(bool)),                    this, SLOT(mouseSlot(bool)));
	connect(reset,     SIGNAL(released()),                       _mm,  SLOT(reset()));
	connect(_mm,       SIGNAL(mouseMode(QMicroMap::MOUSE_MODE)), this, SLOT(mouseModeSlot(QMicroMap::MOUSE_MODE)));

}

/////////////////////////////////////////////////////////////////////////////////////////////////
QMicroMapTest::~QMicroMapTest() {

}

/////////////////////////////////////////////////////////////////////////////////////////////////
void QMicroMapTest::mouseSlot(bool b) {

	if (mousePan->isChecked()) {
		_mm->setMouseMode(QMicroMap::MOUSE_PAN);
	} else {
		if (mouseZoom->isChecked()) {
			_mm->setMouseMode(QMicroMap::MOUSE_ZOOM);
		} else {
			if (mouseSelect->isChecked()) {
				_mm->setMouseMode(QMicroMap::MOUSE_SELECT);
			}
		}
	}

}

/////////////////////////////////////////////////////////////////////////////////////////////////
void QMicroMapTest::mouseModeSlot(QMicroMap::MOUSE_MODE mode) {

	switch (mode) {
	case QMicroMap::MOUSE_PAN:
		mousePan->setChecked(true);
		mouseZoom->setChecked(false);
		mouseSelect->setChecked(false);
		break;
	case QMicroMap::MOUSE_ZOOM:
		mousePan->setChecked(false);
		mouseZoom->setChecked(true);
		mouseSelect->setChecked(false);
		break;
	case QMicroMap::MOUSE_SELECT:
		mousePan->setChecked(false);
		mouseZoom->setChecked(false);
		mouseSelect->setChecked(true);
		break;
	}

}

/////////////////////////////////////////////////////////////////////////////////////////////////
void QMicroMapTest::obsSlot(int on) {
	_stationGroup->setVisible(on);
}
<commit_msg>Rearrange a bit of the code.<commit_after>/*
 * QMicroMapTest.cpp
 *
 *  Created on: May 3, 2011
 *      Author: martinc
 */
#include "QMicroMapTest.h"
#include "QStationModelGraphicsItem.h"

/////////////////////////////////////////////////////////////////////////////////////////////////
QMicroMapTest::QMicroMapTest(SpatiaLiteDB& db,
		double xmin,
		double ymin,
		double xmax,
		double ymax,
		std::string backgroundColor,
		QWidget* parent):
QDialog(parent),
_xmin(xmin),
_ymin(ymin),
_xmax(xmax),
_ymax(ymax),
_zoomInc(0.1)
{
	// setting up the Qt form
	setupUi(this);

	// we need a layout manager
	QVBoxLayout* vb = new QVBoxLayout(frame);

	// create the micromap and add to the layout
	_mm = new QMicroMap(db, _xmin, _ymin, _xmax, _ymax, backgroundColor);
	vb->addWidget(_mm);

	// collect a list of stations, which will e added to an item group
	QList<QGraphicsItem*> stationList;

	// create one leg of station models
	double wspd = 45;
	double wdir = 15;
	double lon = -86;
	double tdry = 23.0;
	double RH = 75.0;
	double presOrHeight = 1013;
	bool isPres = true;
	int hh = 17;
	int mm = 01;

	for (double lat = 24.0; lat < 29.0; lat += 0.8) {
		QStationModelGraphicsItem* sm
			= new QStationModelGraphicsItem(lon, lat, wspd, wdir, tdry, RH, presOrHeight, isPres, hh, mm, 60);
		wspd += 12;
		wdir += 13;
		lon -= 0.9;
		RH -= 4;
		mm += 3;
		tdry -= 1.3;
		presOrHeight -= 3;
		stationList.append(sm);
	}

	// create a seond leg of station models
	wspd = 55;
	wdir = 15;
	lon = -85;
	hh  -= 2;
	for (double lat = 27.0; lat >= 24.0; lat -= 0.51) {
		QStationModelGraphicsItem* sm
			= new QStationModelGraphicsItem(lon, lat, wspd, wdir, tdry, RH, presOrHeight, isPres, hh, mm, 60);
		wspd += 9;
		wdir += 13;
		lon -= 1.8;
		RH -= 4;
		mm -= 3;
		tdry += .8;
		presOrHeight -= 3;
		stationList.append(sm);
	}

	// create the item group of stations
	_stationGroup = _mm->scene()->createItemGroup(stationList);
	// Allow events to be propagated to the children. Note that the Qt documentation
	// for this is wrong; it states that the default is false, which is not true for
	// a QGraphicsItemGroup.
	_stationGroup->setHandlesChildEvents(false);

	// connect signals
	connect(labels,      SIGNAL(stateChanged(int)),                _mm,  SLOT(labels(int)));
	connect(grid,        SIGNAL(stateChanged(int)),                _mm,  SLOT(grid(int)));
	connect(reset,       SIGNAL(released()),                       _mm,  SLOT(reset()));

	connect(obs,         SIGNAL(stateChanged(int)),                this, SLOT(obsSlot(int)));
	connect(mousePan,    SIGNAL(toggled(bool)),                    this, SLOT(mouseSlot(bool)));
	connect(mouseZoom,   SIGNAL(toggled(bool)),                    this, SLOT(mouseSlot(bool)));
	connect(mouseSelect, SIGNAL(toggled(bool)),                    this, SLOT(mouseSlot(bool)));
	connect(_mm,         SIGNAL(mouseMode(QMicroMap::MOUSE_MODE)), this, SLOT(mouseModeSlot(QMicroMap::MOUSE_MODE)));

}

/////////////////////////////////////////////////////////////////////////////////////////////////
QMicroMapTest::~QMicroMapTest() {

}

/////////////////////////////////////////////////////////////////////////////////////////////////
void QMicroMapTest::mouseSlot(bool b) {

	if (mousePan->isChecked()) {
		_mm->setMouseMode(QMicroMap::MOUSE_PAN);
	} else {
		if (mouseZoom->isChecked()) {
			_mm->setMouseMode(QMicroMap::MOUSE_ZOOM);
		} else {
			if (mouseSelect->isChecked()) {
				_mm->setMouseMode(QMicroMap::MOUSE_SELECT);
			}
		}
	}

}

/////////////////////////////////////////////////////////////////////////////////////////////////
void QMicroMapTest::mouseModeSlot(QMicroMap::MOUSE_MODE mode) {

	switch (mode) {
	case QMicroMap::MOUSE_PAN:
		mousePan->setChecked(true);
		mouseZoom->setChecked(false);
		mouseSelect->setChecked(false);
		break;
	case QMicroMap::MOUSE_ZOOM:
		mousePan->setChecked(false);
		mouseZoom->setChecked(true);
		mouseSelect->setChecked(false);
		break;
	case QMicroMap::MOUSE_SELECT:
		mousePan->setChecked(false);
		mouseZoom->setChecked(false);
		mouseSelect->setChecked(true);
		break;
	}

}

/////////////////////////////////////////////////////////////////////////////////////////////////
void QMicroMapTest::obsSlot(int on) {
	_stationGroup->setVisible(on);
}
<|endoftext|>


<commit_before>#include <GG/EveLayout.h>

#include <GG/EveGlue.h>
#include <GG/EveParser.h>
#include <GG/GUI.h>
#include <GG/Timer.h>
#include <GG/Wnd.h>
#include <GG/SDL/SDLGUI.h>
#include <GG/adobe/adam.hpp>

#include <boost/filesystem.hpp>

#include <fstream>

#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>

#include "TestingUtils.h"

struct Action
{
    Action()
        {}
    Action(const GG::Pt& pt_1, const GG::Pt& pt_2, bool drag) :
        m_pt_1(pt_1),
        m_pt_2(pt_2),
        m_drag(drag)
        {}
    GG::Pt m_pt_1;
    GG::Pt m_pt_2;
    bool m_drag;
};

const char* g_eve_file = 0;
const char* g_adam_file = 0;
const char* g_output_dir = 0;
std::vector<Action> g_click_locations;
bool g_generate_variants = false;
bool g_dont_exit = false;
bool g_test_signals = false;

struct GenerateEvents
{
    GenerateEvents(GG::Timer& timer, GG::Wnd* dialog, const std::string& input_stem) :
        m_iteration(0),
        m_dialog(dialog),
        m_input_stem(input_stem)
        {}
    void operator()(unsigned int, GG::Timer* timer)
        {
            if (m_iteration <= g_click_locations.size()) {
                GG::GUI::GetGUI()->SaveWndAsPNG(m_dialog, OutputFilename());
                if (m_iteration) {
                    const Action& action = g_click_locations[m_iteration - 1];
                    if (action.m_drag) {
                        GG::GUI::GetGUI()->HandleGGEvent(GG::GUI::LPRESS, GG::Key(), boost::uint32_t(), GG::Flags<GG::ModKey>(), action.m_pt_1, GG::Pt());
                        GG::GUI::GetGUI()->HandleGGEvent(GG::GUI::MOUSEMOVE, GG::Key(), boost::uint32_t(), GG::Flags<GG::ModKey>(), action.m_pt_2, GG::Pt());
                        GG::GUI::GetGUI()->HandleGGEvent(GG::GUI::LRELEASE, GG::Key(), boost::uint32_t(), GG::Flags<GG::ModKey>(), action.m_pt_2, GG::Pt());
                    } else {
                        if (action.m_pt_1 != action.m_pt_2) {
                            GG::GUI::GetGUI()->QueueGGEvent(GG::GUI::LPRESS, GG::Key(), boost::uint32_t(), GG::Flags<GG::ModKey>(), action.m_pt_2, GG::Pt());
                            GG::GUI::GetGUI()->QueueGGEvent(GG::GUI::LRELEASE, GG::Key(), boost::uint32_t(), GG::Flags<GG::ModKey>(), action.m_pt_2, GG::Pt());
                        }
                        GG::GUI::GetGUI()->HandleGGEvent(GG::GUI::LPRESS, GG::Key(), boost::uint32_t(), GG::Flags<GG::ModKey>(), action.m_pt_1, GG::Pt());
                        GG::GUI::GetGUI()->HandleGGEvent(GG::GUI::LRELEASE, GG::Key(), boost::uint32_t(), GG::Flags<GG::ModKey>(), action.m_pt_1, GG::Pt());
                    }
                }
                timer->Reset();
            } else {
                m_dialog->EndRun();
            }
            ++m_iteration;
        }
    std::string OutputFilename()
        {
            boost::filesystem::path out(g_output_dir);
            std::string filename = m_input_stem;
            if (g_generate_variants) {
                filename += '_';
                filename += static_cast<char>('a' + m_iteration);
            }
            filename += ".png";
            out /= filename;
            return out.string();
        }
    std::size_t m_iteration;
    GG::Wnd* m_dialog;
    std::string m_input_stem;
};

class MinimalGGApp : public GG::SDLGUI
{
public:
    MinimalGGApp();

    virtual void Enter2DMode();
    virtual void Exit2DMode();

private:
    virtual void GLInit();
    virtual void Initialize();
    virtual void FinalCleanup();
};

MinimalGGApp::MinimalGGApp() :
    SDLGUI(1024, 768, false, "Minimal GG App")
{}

void MinimalGGApp::Enter2DMode()
{
    glPushAttrib(GL_ENABLE_BIT | GL_PIXEL_MODE_BIT | GL_TEXTURE_BIT);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_LIGHTING);
    glDisable(GL_CULL_FACE);
    glEnable(GL_TEXTURE_2D);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glViewport(0, 0, Value(AppWidth()), Value(AppHeight()));

    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();

    glOrtho(0.0, Value(AppWidth()), Value(AppHeight()), 0.0, 0.0, Value(AppWidth()));

    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();
}

void MinimalGGApp::Exit2DMode()
{
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glPopAttrib();
}

void MinimalGGApp::GLInit()
{
    double ratio = Value(AppWidth() * 1.0) / Value(AppHeight());

    glEnable(GL_BLEND);
    glEnable(GL_CULL_FACE);
    glEnable(GL_DEPTH_TEST);
    glClearColor(0, 0, 0, 0);
    glViewport(0, 0, Value(AppWidth()), Value(AppHeight()));
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(50.0, ratio, 1.0, 10.0);
    gluLookAt(0.0, 0.0, 5.0,
              0.0, 0.0, 0.0,
              0.0, 1.0, 0.0);
    glMatrixMode(GL_MODELVIEW);
}

bool ButtonHandler(adobe::name_t name, const adobe::any_regular_t&)
{ return name == adobe::static_name_t("ok") || name == adobe::static_name_t("cancel"); }

void SignalTester(adobe::name_t widget_type, adobe::name_t signal, adobe::name_t widget_id, const adobe::any_regular_t& value)
{
    if (widget_type == adobe::static_name_t("button")) {
        BOOST_CHECK(signal == adobe::static_name_t("clicked"));
        BOOST_CHECK(!widget_id || widget_id == adobe::static_name_t("test_id"));
        if (!widget_id)
            BOOST_CHECK(value == adobe::any_regular_t(std::string("button value 1")));
        else
            BOOST_CHECK(value == adobe::any_regular_t(std::string("button value 2")));
    } else if (widget_type == adobe::static_name_t("checkbox")) {
        BOOST_CHECK(signal == adobe::static_name_t("checked"));
        BOOST_CHECK(!widget_id || widget_id == adobe::static_name_t("test_id"));
        if (!widget_id)
            BOOST_CHECK(value == adobe::any_regular_t(std::string("checkbox value 1")));
        else
            BOOST_CHECK(value == adobe::any_regular_t(std::string("checkbox value 2")));
    } else if (widget_type == adobe::static_name_t("radio_button")) {
        BOOST_CHECK(signal == adobe::static_name_t("checked"));
        BOOST_CHECK(!widget_id || widget_id == adobe::static_name_t("test_id"));
        if (!widget_id)
            BOOST_CHECK(value == adobe::any_regular_t(std::string("radio button value 1")));
        else
            BOOST_CHECK(value == adobe::any_regular_t(std::string("radio button value 2")));
    } else if (widget_type == adobe::static_name_t("slider")) {
        BOOST_CHECK(signal == adobe::static_name_t("slid") ||
                    signal == adobe::static_name_t("slid_and_stopped"));
        BOOST_CHECK(!widget_id || widget_id == adobe::static_name_t("test_id"));
        if (!widget_id)
            BOOST_CHECK(value == adobe::any_regular_t(25));
        else
            BOOST_CHECK(value == adobe::any_regular_t(75));
    }
}

void MinimalGGApp::Initialize()
{
    boost::filesystem::path eve(g_eve_file);
    boost::filesystem::path adam(g_adam_file);
    std::auto_ptr<GG::EveDialog> eve_dialog(
        g_test_signals ?
        GG::MakeEveDialog(eve, adam, &ButtonHandler, &SignalTester) :
        GG::MakeEveDialog(eve, adam, &ButtonHandler)
    );

    boost::filesystem::path input(g_eve_file);
    std::string input_stem =
#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 3
        input.stem().native()
#else
        input.stem()
#endif
        ;
    GG::Timer timer(100);
    if (!g_dont_exit)
        GG::Connect(timer.FiredSignal, GenerateEvents(timer, eve_dialog.get(), input_stem));
    eve_dialog->Run();

    std::cout << "Terminating action: " << eve_dialog->TerminatingAction() << "\n"
              << "Result:";

    if (eve_dialog->Result().empty())
        std::cout << " <no result set>\n";
    else
        std::cout << "\n" << eve_dialog->Result();
    std::cout << std::endl;

    Exit(0);
}

void MinimalGGApp::FinalCleanup()
{}

BOOST_AUTO_TEST_CASE( eve_layout )
{
    MinimalGGApp app;
    app();
}

// Most of this is boilerplate cut-and-pasted from Boost.Test.  We need to
// select which test(s) to do, so we can't use it here unmodified.

#ifdef BOOST_TEST_ALTERNATIVE_INIT_API
bool init_unit_test()                   {
#else
::boost::unit_test::test_suite*
init_unit_test_suite( int, char* [] )   {
#endif

#ifdef BOOST_TEST_MODULE
    using namespace ::boost::unit_test;
    assign_op( framework::master_test_suite().p_name.value, BOOST_TEST_STRINGIZE( BOOST_TEST_MODULE ).trim( "\"" ), 0 );

#endif

#ifdef BOOST_TEST_ALTERNATIVE_INIT_API
    return true;
}
#else
    return 0;
}
#endif

int BOOST_TEST_CALL_DECL
main( int argc, char* argv[] )
{
    g_eve_file = argv[1];
    g_adam_file = argv[2];
    g_output_dir = argv[3];
    int i = 4;
    std::string token;
    std::size_t comma_1;
    while (i < argc && (token = argv[i], comma_1 = token.find(',')) != std::string::npos) {
        g_generate_variants = true;
        std::size_t comma_2 = token.find(',', comma_1 + 1);
        GG::Pt point_1(GG::X(boost::lexical_cast<int>(token.substr(0, comma_1))),
                       GG::Y(boost::lexical_cast<int>(token.substr(comma_1 + 1, comma_2 - comma_1 - 1))));
        GG::Pt point_2 = point_1;
        bool drag = false;
        if (comma_2 != std::string::npos) {
            std::size_t comma_3 = token.find(',', comma_2 + 1);
            std::size_t end = token.find('d', comma_3 + 1);
            drag = end != std::string::npos;
            point_2 = GG::Pt(GG::X(boost::lexical_cast<int>(token.substr(comma_2 + 1, comma_3 - comma_2 - 1))),
                             GG::Y(boost::lexical_cast<int>(token.substr(comma_3 + 1, end - comma_3 - 1))));
        }
        g_click_locations.push_back(Action(point_1, point_2, drag));
        ++i;
    }
    if (i < argc && (token = argv[i], token == "test_signals")) {
        g_test_signals = true;
        ++i;
    }
    if (i < argc)
        g_dont_exit = true;
    return ::boost::unit_test::unit_test_main( &init_unit_test, argc, argv );
}
<commit_msg>Added some instrumentation to TestEveLayout.cpp.<commit_after>#include <GG/EveLayout.h>

#include <GG/EveGlue.h>
#include <GG/EveParser.h>
#include <GG/GUI.h>
#include <GG/Timer.h>
#include <GG/Wnd.h>
#include <GG/SDL/SDLGUI.h>
#include <GG/adobe/adam.hpp>

#include <boost/filesystem.hpp>

#include <fstream>

#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>

#include "TestingUtils.h"

struct Action
{
    Action()
        {}
    Action(const GG::Pt& pt_1, const GG::Pt& pt_2, bool drag) :
        m_pt_1(pt_1),
        m_pt_2(pt_2),
        m_drag(drag)
        {}
    GG::Pt m_pt_1;
    GG::Pt m_pt_2;
    bool m_drag;
};

const char* g_eve_file = 0;
const char* g_adam_file = 0;
const char* g_output_dir = 0;
std::vector<Action> g_click_locations;
bool g_generate_variants = false;
bool g_dont_exit = false;
bool g_test_signals = false;

struct GenerateEvents
{
    GenerateEvents(GG::Timer& timer, GG::Wnd* dialog, const std::string& input_stem) :
        m_iteration(0),
        m_dialog(dialog),
        m_input_stem(input_stem)
        {}
    void operator()(unsigned int, GG::Timer* timer)
        {
            if (m_iteration <= g_click_locations.size()) {
                GG::GUI::GetGUI()->SaveWndAsPNG(m_dialog, OutputFilename());
                if (m_iteration) {
                    const Action& action = g_click_locations[m_iteration - 1];
                    if (action.m_drag) {
                        GG::GUI::GetGUI()->HandleGGEvent(GG::GUI::LPRESS, GG::Key(), boost::uint32_t(), GG::Flags<GG::ModKey>(), action.m_pt_1, GG::Pt());
                        GG::GUI::GetGUI()->HandleGGEvent(GG::GUI::MOUSEMOVE, GG::Key(), boost::uint32_t(), GG::Flags<GG::ModKey>(), action.m_pt_2, GG::Pt());
                        GG::GUI::GetGUI()->HandleGGEvent(GG::GUI::LRELEASE, GG::Key(), boost::uint32_t(), GG::Flags<GG::ModKey>(), action.m_pt_2, GG::Pt());
                    } else {
                        if (action.m_pt_1 != action.m_pt_2) {
                            GG::GUI::GetGUI()->QueueGGEvent(GG::GUI::LPRESS, GG::Key(), boost::uint32_t(), GG::Flags<GG::ModKey>(), action.m_pt_2, GG::Pt());
                            GG::GUI::GetGUI()->QueueGGEvent(GG::GUI::LRELEASE, GG::Key(), boost::uint32_t(), GG::Flags<GG::ModKey>(), action.m_pt_2, GG::Pt());
                        }
                        GG::GUI::GetGUI()->HandleGGEvent(GG::GUI::LPRESS, GG::Key(), boost::uint32_t(), GG::Flags<GG::ModKey>(), action.m_pt_1, GG::Pt());
                        GG::GUI::GetGUI()->HandleGGEvent(GG::GUI::LRELEASE, GG::Key(), boost::uint32_t(), GG::Flags<GG::ModKey>(), action.m_pt_1, GG::Pt());
                    }
                }
                timer->Reset();
            } else {
                m_dialog->EndRun();
            }
            ++m_iteration;
        }
    std::string OutputFilename()
        {
            boost::filesystem::path out(g_output_dir);
            std::string filename = m_input_stem;
            if (g_generate_variants) {
                filename += '_';
                filename += static_cast<char>('a' + m_iteration);
            }
            filename += ".png";
            out /= filename;
            return out.string();
        }
    std::size_t m_iteration;
    GG::Wnd* m_dialog;
    std::string m_input_stem;
};

class MinimalGGApp : public GG::SDLGUI
{
public:
    MinimalGGApp();

    virtual void Enter2DMode();
    virtual void Exit2DMode();

private:
    virtual void GLInit();
    virtual void Initialize();
    virtual void FinalCleanup();
};

MinimalGGApp::MinimalGGApp() :
    SDLGUI(1024, 768, false, "Minimal GG App")
{}

void MinimalGGApp::Enter2DMode()
{
    glPushAttrib(GL_ENABLE_BIT | GL_PIXEL_MODE_BIT | GL_TEXTURE_BIT);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_LIGHTING);
    glDisable(GL_CULL_FACE);
    glEnable(GL_TEXTURE_2D);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glViewport(0, 0, Value(AppWidth()), Value(AppHeight()));

    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();

    glOrtho(0.0, Value(AppWidth()), Value(AppHeight()), 0.0, 0.0, Value(AppWidth()));

    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();
}

void MinimalGGApp::Exit2DMode()
{
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glPopAttrib();
}

void MinimalGGApp::GLInit()
{
    double ratio = Value(AppWidth() * 1.0) / Value(AppHeight());

    glEnable(GL_BLEND);
    glEnable(GL_CULL_FACE);
    glEnable(GL_DEPTH_TEST);
    glClearColor(0, 0, 0, 0);
    glViewport(0, 0, Value(AppWidth()), Value(AppHeight()));
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(50.0, ratio, 1.0, 10.0);
    gluLookAt(0.0, 0.0, 5.0,
              0.0, 0.0, 0.0,
              0.0, 1.0, 0.0);
    glMatrixMode(GL_MODELVIEW);
}

bool ButtonHandler(adobe::name_t name, const adobe::any_regular_t&)
{ return name == adobe::static_name_t("ok") || name == adobe::static_name_t("cancel"); }

void SignalTester(adobe::name_t widget_type, adobe::name_t signal, adobe::name_t widget_id, const adobe::any_regular_t& value)
{
#define INSTRUMENT 0
#if INSTRUMENT
    std::cerr << "Testing unbound signals ...\n";
#endif
    if (widget_type == adobe::static_name_t("button")) {
#if INSTRUMENT
        std::cerr << "Testing unbound button signals ...\n";
#endif
        BOOST_CHECK(signal == adobe::static_name_t("clicked"));
        BOOST_CHECK(!widget_id || widget_id == adobe::static_name_t("test_id"));
        if (!widget_id)
            BOOST_CHECK(value == adobe::any_regular_t(std::string("button value 1")));
        else
            BOOST_CHECK(value == adobe::any_regular_t(std::string("button value 2")));
    } else if (widget_type == adobe::static_name_t("checkbox")) {
#if INSTRUMENT
        std::cerr << "Testing unbound checkbox signals ...\n";
#endif
        BOOST_CHECK(signal == adobe::static_name_t("checked"));
        BOOST_CHECK(!widget_id || widget_id == adobe::static_name_t("test_id"));
        if (!widget_id)
            BOOST_CHECK(value == adobe::any_regular_t(std::string("checkbox value 1")));
        else
            BOOST_CHECK(value == adobe::any_regular_t(std::string("checkbox value 2")));
    } else if (widget_type == adobe::static_name_t("radio_button")) {
#if INSTRUMENT
        std::cerr << "Testing unbound radio_button signals ...\n";
#endif
        BOOST_CHECK(signal == adobe::static_name_t("checked"));
        BOOST_CHECK(!widget_id || widget_id == adobe::static_name_t("test_id"));
        if (!widget_id)
            BOOST_CHECK(value == adobe::any_regular_t(std::string("radio button value 1")));
        else
            BOOST_CHECK(value == adobe::any_regular_t(std::string("radio button value 2")));
    } else if (widget_type == adobe::static_name_t("slider")) {
#if INSTRUMENT
        std::cerr << "Testing unbound slider signals ...\n";
#endif
        BOOST_CHECK(signal == adobe::static_name_t("slid") ||
                    signal == adobe::static_name_t("slid_and_stopped"));
        BOOST_CHECK(!widget_id || widget_id == adobe::static_name_t("test_id"));
        if (!widget_id)
            BOOST_CHECK(value == adobe::any_regular_t(25));
        else
            BOOST_CHECK(value == adobe::any_regular_t(75));
    } else if (widget_type == adobe::static_name_t("edit_text")) {
#if INSTRUMENT
        std::cerr << "Testing unbound edit_text signals ...\n";
#endif
        BOOST_CHECK(signal == adobe::static_name_t("edited") ||
                    signal == adobe::static_name_t("focus_update"));
        BOOST_CHECK(!widget_id || widget_id == adobe::static_name_t("test_id"));
        if (!widget_id)
            BOOST_CHECK(value == adobe::any_regular_t(std::string("edited value")));
        else
            BOOST_CHECK(value == adobe::any_regular_t(std::string("focus_update value")));
    }
#undef INSTRUMENT
}

void MinimalGGApp::Initialize()
{
    boost::filesystem::path eve(g_eve_file);
    boost::filesystem::path adam(g_adam_file);
    std::auto_ptr<GG::EveDialog> eve_dialog(
        g_test_signals ?
        GG::MakeEveDialog(eve, adam, &ButtonHandler, &SignalTester) :
        GG::MakeEveDialog(eve, adam, &ButtonHandler)
    );

    boost::filesystem::path input(g_eve_file);
    std::string input_stem =
#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 3
        input.stem().native()
#else
        input.stem()
#endif
        ;
    GG::Timer timer(100);
    if (!g_dont_exit)
        GG::Connect(timer.FiredSignal, GenerateEvents(timer, eve_dialog.get(), input_stem));
    eve_dialog->Run();

    std::cout << "Terminating action: " << eve_dialog->TerminatingAction() << "\n"
              << "Result:";

    if (eve_dialog->Result().empty())
        std::cout << " <no result set>\n";
    else
        std::cout << "\n" << eve_dialog->Result();
    std::cout << std::endl;

    Exit(0);
}

void MinimalGGApp::FinalCleanup()
{}

BOOST_AUTO_TEST_CASE( eve_layout )
{
    MinimalGGApp app;
    app();
}

// Most of this is boilerplate cut-and-pasted from Boost.Test.  We need to
// select which test(s) to do, so we can't use it here unmodified.

#ifdef BOOST_TEST_ALTERNATIVE_INIT_API
bool init_unit_test()                   {
#else
::boost::unit_test::test_suite*
init_unit_test_suite( int, char* [] )   {
#endif

#ifdef BOOST_TEST_MODULE
    using namespace ::boost::unit_test;
    assign_op( framework::master_test_suite().p_name.value, BOOST_TEST_STRINGIZE( BOOST_TEST_MODULE ).trim( "\"" ), 0 );

#endif

#ifdef BOOST_TEST_ALTERNATIVE_INIT_API
    return true;
}
#else
    return 0;
}
#endif

int BOOST_TEST_CALL_DECL
main( int argc, char* argv[] )
{
    g_eve_file = argv[1];
    g_adam_file = argv[2];
    g_output_dir = argv[3];
    int i = 4;
    std::string token;
    std::size_t comma_1;
    while (i < argc && (token = argv[i], comma_1 = token.find(',')) != std::string::npos) {
        g_generate_variants = true;
        std::size_t comma_2 = token.find(',', comma_1 + 1);
        GG::Pt point_1(GG::X(boost::lexical_cast<int>(token.substr(0, comma_1))),
                       GG::Y(boost::lexical_cast<int>(token.substr(comma_1 + 1, comma_2 - comma_1 - 1))));
        GG::Pt point_2 = point_1;
        bool drag = false;
        if (comma_2 != std::string::npos) {
            std::size_t comma_3 = token.find(',', comma_2 + 1);
            std::size_t end = token.find('d', comma_3 + 1);
            drag = end != std::string::npos;
            point_2 = GG::Pt(GG::X(boost::lexical_cast<int>(token.substr(comma_2 + 1, comma_3 - comma_2 - 1))),
                             GG::Y(boost::lexical_cast<int>(token.substr(comma_3 + 1, end - comma_3 - 1))));
        }
        g_click_locations.push_back(Action(point_1, point_2, drag));
        ++i;
    }
    if (i < argc && (token = argv[i], token == "test_signals")) {
        g_test_signals = true;
        ++i;
    }
    if (i < argc)
        g_dont_exit = true;
    return ::boost::unit_test::unit_test_main( &init_unit_test, argc, argv );
}
<|endoftext|>


<commit_before>// RUN: cat %s | %cling -Xclang -verify -I%p | FileCheck %s

// The test verifies the expected behavior in cling::utils::Transform class,
// which is supposed to provide different transformation of AST nodes and types.

#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/LookupHelper.h"
#include "cling/Utils/AST.h"
#include "clang/AST/Type.h"
#include "llvm/ADT/SmallSet.h"
#include "clang/Sema/Sema.h"

.rawInput 1

typedef double Double32_t;
typedef int Int_t;
typedef long Long_t;
typedef Int_t* IntPtr_t;

template <typename T> class A {};
template <typename T, typename U> class B {};
template <typename T, typename U> class C {};
typedef C<A<B<Double32_t, Int_t> >, Double32_t > CTD;
typedef C<A<B<const Double32_t, const Int_t> >, Double32_t > CTDConst;

#include <string>

namespace Details {
   class Impl {};
}

namespace NS {
   template <typename T, int size = 0> class ArrayType {};
   template <typename T> class Array {};

   template <typename T> class Container {
   public:
      class Content {};
      typedef T Value_t;
      typedef Content Content_t;
      typedef ::Details::Impl Impl_t;
   };

   template <typename T> class TDataPoint {};
   typedef TDataPoint<float> TDataPointF;
   typedef TDataPoint<Double32_t> TDataPointD32;
}

.rawInput 0

const cling::LookupHelper& lookup = gCling->getLookupHelper();

const clang::ASTContext& Ctx = gCling->getSema().getASTContext();
llvm::SmallSet<const clang::Type*, 4> skip;
skip.insert(lookup.findType("Double32_t").getTypePtr());
const clang::Type* t = 0;
clang::QualType QT;
using namespace cling::utils;

// Test desugaring pointers types:
QT = lookup.findType("Int_t*");
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK:(const char * const) "int *"

QT = lookup.findType("const IntPtr_t*");
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK:(const char * const) "int *const *"

// Test desugaring reference (both r- or l- value) types:
QT = lookup.findType("const IntPtr_t&");
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK:(const char * const) "int *const &"

//TODO: QT = lookup.findType("IntPtr_t[32]");

//Desugar template parameters:
lookup.findScope("A<B<Double32_t, Int_t*> >", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK:(const char * const) "A<B<Double32_t, int *> >"

lookup.findScope("CTD", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "C<A<B<Double32_t, int> >, Double32_t>"

lookup.findScope("CTDConst", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "C<A<B<const Double32_t, const int> >, Double32_t>"

lookup.findScope("std::pair<const std::string,int>", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "std::pair<const std::string, int>"

lookup.findScope("NS::Array<NS::ArrayType<double> >", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "NS::Array<NS::ArrayType<double> >"

lookup.findScope("NS::Array<NS::ArrayType<Double32_t> >", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "NS::Array<NS::ArrayType<Double32_t> >"

lookup.findScope("NS::Container<Long_t>::Content", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "NS::Container<long>::Content"

QT = lookup.findType("NS::Container<Long_t>::Value_t");
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "long"

lookup.findScope("NS::Container<Long_t>::Content_t", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "NS::Container<long>::Content"

lookup.findScope("NS::Container<Long_t>::Impl_t", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "::Details::Impl"
// Note it should probably return "Details::Impl"

lookup.findScope("NS::Container<Double32_t>::Content", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "NS::Container<Double32_t>::Content"

QT = lookup.findType("NS::Container<Double32_t>::Value_t");
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "double"
// Really we would want it to say Double32_t but oh well.

lookup.findScope("NS::Container<Double32_t>::Content_t", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "NS::Container<Double32_t>::Content"

lookup.findScope("NS::Container<Double32_t>::Impl_t", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "::Details::Impl"
// Note it should probably return "Details::Impl"

lookup.findScope("NS::TDataPointF", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "NS::TDataPoint<float>"

lookup.findScope("NS::TDataPointD32", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "NS::TDataPoint<Double32_t>"
<commit_msg>No need of -verify and -I for that test.<commit_after>// RUN: cat %s | %cling -I%p | FileCheck %s

// The test verifies the expected behavior in cling::utils::Transform class,
// which is supposed to provide different transformation of AST nodes and types.

#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/LookupHelper.h"
#include "cling/Utils/AST.h"
#include "clang/AST/Type.h"
#include "llvm/ADT/SmallSet.h"
#include "clang/Sema/Sema.h"

.rawInput 1

typedef double Double32_t;
typedef int Int_t;
typedef long Long_t;
typedef Int_t* IntPtr_t;

template <typename T> class A {};
template <typename T, typename U> class B {};
template <typename T, typename U> class C {};
typedef C<A<B<Double32_t, Int_t> >, Double32_t > CTD;
typedef C<A<B<const Double32_t, const Int_t> >, Double32_t > CTDConst;

#include <string>

namespace Details {
   class Impl {};
}

namespace NS {
   template <typename T, int size = 0> class ArrayType {};
   template <typename T> class Array {};

   template <typename T> class Container {
   public:
      class Content {};
      typedef T Value_t;
      typedef Content Content_t;
      typedef ::Details::Impl Impl_t;
   };

   template <typename T> class TDataPoint {};
   typedef TDataPoint<float> TDataPointF;
   typedef TDataPoint<Double32_t> TDataPointD32;
}

.rawInput 0

const cling::LookupHelper& lookup = gCling->getLookupHelper();

const clang::ASTContext& Ctx = gCling->getSema().getASTContext();
llvm::SmallSet<const clang::Type*, 4> skip;
skip.insert(lookup.findType("Double32_t").getTypePtr());
const clang::Type* t = 0;
clang::QualType QT;
using namespace cling::utils;

// Test desugaring pointers types:
QT = lookup.findType("Int_t*");
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK:(const char * const) "int *"

QT = lookup.findType("const IntPtr_t*");
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK:(const char * const) "int *const *"

// Test desugaring reference (both r- or l- value) types:
QT = lookup.findType("const IntPtr_t&");
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK:(const char * const) "int *const &"

//TODO: QT = lookup.findType("IntPtr_t[32]");

//Desugar template parameters:
lookup.findScope("A<B<Double32_t, Int_t*> >", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK:(const char * const) "A<B<Double32_t, int *> >"

lookup.findScope("CTD", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "C<A<B<Double32_t, int> >, Double32_t>"

lookup.findScope("CTDConst", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "C<A<B<const Double32_t, const int> >, Double32_t>"

lookup.findScope("std::pair<const std::string,int>", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "std::pair<const std::string, int>"

lookup.findScope("NS::Array<NS::ArrayType<double> >", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "NS::Array<NS::ArrayType<double> >"

lookup.findScope("NS::Array<NS::ArrayType<Double32_t> >", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "NS::Array<NS::ArrayType<Double32_t> >"

lookup.findScope("NS::Container<Long_t>::Content", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "NS::Container<long>::Content"

QT = lookup.findType("NS::Container<Long_t>::Value_t");
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "long"

lookup.findScope("NS::Container<Long_t>::Content_t", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "NS::Container<long>::Content"

lookup.findScope("NS::Container<Long_t>::Impl_t", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "::Details::Impl"
// Note it should probably return "Details::Impl"

lookup.findScope("NS::Container<Double32_t>::Content", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "NS::Container<Double32_t>::Content"

QT = lookup.findType("NS::Container<Double32_t>::Value_t");
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "double"
// Really we would want it to say Double32_t but oh well.

lookup.findScope("NS::Container<Double32_t>::Content_t", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "NS::Container<Double32_t>::Content"

lookup.findScope("NS::Container<Double32_t>::Impl_t", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "::Details::Impl"
// Note it should probably return "Details::Impl"

lookup.findScope("NS::TDataPointF", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "NS::TDataPoint<float>"

lookup.findScope("NS::TDataPointD32", &t);
QT = clang::QualType(t, 0);
Transform::GetPartiallyDesugaredType(Ctx, QT, skip).getAsString().c_str()
// CHECK: (const char * const) "NS::TDataPoint<Double32_t>"
<|endoftext|>


<commit_before>/* Copyright (c) 2018 PaddlePaddle Authors. 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 "paddle/fluid/operators/fused/fusion_seqpool_concat_op.h"
#include <string>
#include <vector>
#include "paddle/fluid/operators/jit/kernels.h"

namespace paddle {
namespace operators {

void FusionSeqPoolConcatOp::InferShape(
    framework::InferShapeContext* ctx) const {
  PADDLE_ENFORCE_GE(ctx->Inputs("X").size(), 1UL,
                    "Inputs(X) of FusionSeqPoolConcatOp should not be empty.");
  PADDLE_ENFORCE(ctx->HasOutput("Out"),
                 "Output(Out) of FusionSeqPoolConcatOp should not be null.");
  int axis = ctx->Attrs().Get<int>("axis");
  PADDLE_ENFORCE_EQ(axis, 1,
                    "FusionSeqPoolConcatOp only supports concat axis=1 yet.");

  auto ins_dims = ctx->GetInputsDim("X");
  const size_t n = ins_dims.size();
  PADDLE_ENFORCE_GT(n, 0UL, "Input tensors count should > 0.");
  if (n == 1) {
    LOG(WARNING) << "Only have one input, may waste memory";
  }

  // The output height should be confirmed in Compute,
  // since input lod is not accessible here.
  PADDLE_ENFORCE_EQ(ins_dims[0].size(), 2,
                    "The dims size of first input should be 2.");
  ctx->SetOutputDim("Out", {-1, ins_dims[0][axis] * static_cast<int>(n)});

  if (!ctx->IsRuntime()) {
    // when compiling, the LodLevel of Out is set to be 1, which is consistent
    // with that in running time.
    ctx->SetLoDLevel("Out", 1);
  }
}

framework::OpKernelType FusionSeqPoolConcatOp::GetExpectedKernelType(
    const framework::ExecutionContext& ctx) const {
  return framework::OpKernelType(
      OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace());
}

void FusionSeqPoolConcatOpMaker::Make() {
  AddInput("X", "(LoDTensor) Input tensors of this operator.").AsDuplicable();
  AddOutput("Out", "(LoDTensor) Output tensor of concat operator.");
  AddAttr<std::string>("pooltype",
                       "(string, default 'SUM') some of the pooling "
                       "pooltype of SequencePoolOp.")
      .SetDefault("SUM")
      .InEnum({"AVERAGE", "SUM", "SQRT"});
  AddAttr<int>("axis",
               "The axis along which the input tensors will be concatenated. "
               "Only supports concat axis=1 yet.")
      .SetDefault(1);
  AddComment(R"DOC(
Fusion Sequence Pool of pooltype(sum, average and sqrt) and Concat Operator.
)DOC");
}

template <typename T>
class FusionSeqPoolConcatKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto ins = ctx.MultiInput<LoDTensor>("X");
    auto* out = ctx.Output<LoDTensor>("Out");
    std::string pooltype = ctx.Attr<std::string>("pooltype");
    auto x0_lod = ins[0]->lod();
    auto x0_dims = ins[0]->dims();
    auto y_dims = out->dims();
    size_t bs = x0_lod[0].size() - 1;
    out->Resize({static_cast<int64_t>(bs), y_dims[1]});
    framework::LoD y_lod(1);
    y_lod[0].resize(bs + 1);
    for (size_t i = 0; i <= bs; ++i) {
      y_lod[0][i] = i;
    }
    out->set_lod(y_lod);
    auto place = ctx.GetPlace();
    T* y_data = out->mutable_data<T>(place);

    int w = ins[0]->numel() / x0_dims[0];
    PADDLE_ENFORCE_EQ(y_dims[1] % w, 0,
                      "The output of dims[1] should be dividable of w");
    jit::seq_pool_attr_t attr(w, jit::SeqPoolType::kSum);
    if (pooltype == "AVERAGE") {
      attr.type = jit::SeqPoolType::kAvg;
    } else if (pooltype == "SQRT") {
      attr.type = jit::SeqPoolType::kSqrt;
    }
    auto seqpool =
        jit::KernelFuncs<jit::SeqPoolTuple<T>, platform::CPUPlace>::Cache().At(
            attr);
    size_t n = ins.size();
    size_t dst_step_size = n * w;
    for (size_t i = 0; i < n; ++i) {
      auto x_dims = ins[i]->dims();
      auto x_lod = ins[i]->lod()[0];
      const T* src = ins[i]->data<T>();
      T* dst = y_data + i * w;
      PADDLE_ENFORCE_EQ(static_cast<int>(ins[i]->numel() / x_dims[0]), w,
                        "Width of all inputs should be equal.");
      PADDLE_ENFORCE_EQ(x_lod.size(), bs + 1,
                        "Batchsize of all inputs should be equal.");
      for (size_t j = 0; j < bs; ++j) {
        attr.h = static_cast<int>(x_lod[j + 1] - x_lod[j]);
        seqpool(src, dst, &attr);
        dst += dst_step_size;
        src += attr.h * attr.w;
      }
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(fusion_seqpool_concat, ops::FusionSeqPoolConcatOp,
                  ops::FusionSeqPoolConcatOpMaker);

REGISTER_OP_CPU_KERNEL(fusion_seqpool_concat,
                       ops::FusionSeqPoolConcatKernel<float>,
                       ops::FusionSeqPoolConcatKernel<double>);
<commit_msg>error message enhancement for fusion_seqpool_concat_op. test=develop (#23563)<commit_after>/* Copyright (c) 2018 PaddlePaddle Authors. 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 "paddle/fluid/operators/fused/fusion_seqpool_concat_op.h"
#include <string>
#include <vector>
#include "paddle/fluid/operators/jit/kernels.h"

namespace paddle {
namespace operators {

void FusionSeqPoolConcatOp::InferShape(
    framework::InferShapeContext* ctx) const {
  PADDLE_ENFORCE_GE(ctx->Inputs("X").size(), 1UL,
                    platform::errors::InvalidArgument(
                        "Inputs(X) of FusionSeqPoolConcatOp should be greated "
                        "than 1, but received value is %d.",
                        ctx->Inputs("X").size()));
  OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "FusionSeqPoolConcat");
  int axis = ctx->Attrs().Get<int>("axis");
  PADDLE_ENFORCE_EQ(axis, 1, platform::errors::InvalidArgument(
                                 "FusionSeqPoolConcatOp only supports concat "
                                 "axis=1 yet, but received axis value is %d",
                                 axis));

  auto ins_dims = ctx->GetInputsDim("X");
  const size_t n = ins_dims.size();
  PADDLE_ENFORCE_GT(n, 0UL, platform::errors::InvalidArgument(
                                "Input tensors count should be greater than 0, "
                                "but received value is %d.",
                                n));
  if (n == 1) {
    LOG(WARNING) << "Only have one input, may waste memory";
  }

  // The output height should be confirmed in Compute,
  // since input lod is not accessible here.
  PADDLE_ENFORCE_EQ(ins_dims[0].size(), 2,
                    platform::errors::InvalidArgument(
                        "The dims size of first input should be equal to 2, "
                        "but received value is %d.",
                        ins_dims[0].size()));
  ctx->SetOutputDim("Out", {-1, ins_dims[0][axis] * static_cast<int>(n)});

  if (!ctx->IsRuntime()) {
    // when compiling, the LodLevel of Out is set to be 1, which is consistent
    // with that in running time.
    ctx->SetLoDLevel("Out", 1);
  }
}

framework::OpKernelType FusionSeqPoolConcatOp::GetExpectedKernelType(
    const framework::ExecutionContext& ctx) const {
  return framework::OpKernelType(
      OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace());
}

void FusionSeqPoolConcatOpMaker::Make() {
  AddInput("X", "(LoDTensor) Input tensors of this operator.").AsDuplicable();
  AddOutput("Out", "(LoDTensor) Output tensor of concat operator.");
  AddAttr<std::string>("pooltype",
                       "(string, default 'SUM') some of the pooling "
                       "pooltype of SequencePoolOp.")
      .SetDefault("SUM")
      .InEnum({"AVERAGE", "SUM", "SQRT"});
  AddAttr<int>("axis",
               "The axis along which the input tensors will be concatenated. "
               "Only supports concat axis=1 yet.")
      .SetDefault(1);
  AddComment(R"DOC(
Fusion Sequence Pool of pooltype(sum, average and sqrt) and Concat Operator.
)DOC");
}

template <typename T>
class FusionSeqPoolConcatKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto ins = ctx.MultiInput<LoDTensor>("X");
    auto* out = ctx.Output<LoDTensor>("Out");
    std::string pooltype = ctx.Attr<std::string>("pooltype");
    auto x0_lod = ins[0]->lod();
    auto x0_dims = ins[0]->dims();
    auto y_dims = out->dims();
    size_t bs = x0_lod[0].size() - 1;
    out->Resize({static_cast<int64_t>(bs), y_dims[1]});
    framework::LoD y_lod(1);
    y_lod[0].resize(bs + 1);
    for (size_t i = 0; i <= bs; ++i) {
      y_lod[0][i] = i;
    }
    out->set_lod(y_lod);
    auto place = ctx.GetPlace();
    T* y_data = out->mutable_data<T>(place);

    int w = ins[0]->numel() / x0_dims[0];
    PADDLE_ENFORCE_EQ(y_dims[1] % w, 0,
                      platform::errors::InvalidArgument(
                          "The output of dims[1] should be dividable of w, but "
                          "dims[1] is %d, w is %d.",
                          y_dims[1], w));
    jit::seq_pool_attr_t attr(w, jit::SeqPoolType::kSum);
    if (pooltype == "AVERAGE") {
      attr.type = jit::SeqPoolType::kAvg;
    } else if (pooltype == "SQRT") {
      attr.type = jit::SeqPoolType::kSqrt;
    }
    auto seqpool =
        jit::KernelFuncs<jit::SeqPoolTuple<T>, platform::CPUPlace>::Cache().At(
            attr);
    size_t n = ins.size();
    size_t dst_step_size = n * w;
    for (size_t i = 0; i < n; ++i) {
      auto x_dims = ins[i]->dims();
      auto x_lod = ins[i]->lod()[0];
      const T* src = ins[i]->data<T>();
      T* dst = y_data + i * w;
      PADDLE_ENFORCE_EQ(
          static_cast<int>(ins[i]->numel() / x_dims[0]), w,
          platform::errors::InvalidArgument(
              "Width of all inputs should be equal, but the width of the %d-th "
              "input %d is not equal to the previous %d",
              i, static_cast<int>(ins[i]->numel() / x_dims[0]), w));
      PADDLE_ENFORCE_EQ(
          x_lod.size(), bs + 1,
          platform::errors::InvalidArgument(
              "Batchsize of all inputs should be equal, but the value of the "
              "%d-th %d is not equal to the previous %d.",
              i, x_lod.size(), bs + 1));
      for (size_t j = 0; j < bs; ++j) {
        attr.h = static_cast<int>(x_lod[j + 1] - x_lod[j]);
        seqpool(src, dst, &attr);
        dst += dst_step_size;
        src += attr.h * attr.w;
      }
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(fusion_seqpool_concat, ops::FusionSeqPoolConcatOp,
                  ops::FusionSeqPoolConcatOpMaker);

REGISTER_OP_CPU_KERNEL(fusion_seqpool_concat,
                       ops::FusionSeqPoolConcatKernel<float>,
                       ops::FusionSeqPoolConcatKernel<double>);
<|endoftext|>


<commit_before>//Copyright (c) 2011 Krishna Rajendran <krishna@emptybox.org>.
//Licensed under an MIT/X11 license. See LICENSE file for details.

extern "C" {
#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
}

#include "eldb.hpp"
#include "eldb_gtk_globalkeybind.hpp"

namespace elgtk {

struct KeyList;
struct ValueList;

struct Window {
  eldb::Eldb eldb;

  GtkWidget *window;
  GtkWidget *searchEntry;
  KeyList   *keyList;
  ValueList *valueList;

  Window();

  static void destroy();
  static void searchEntryChanged( GtkWidget *widget, Window *window );
  static int keySnooper( GtkWidget *widget, GdkEventKey *event, gpointer data );
  void layout();
};

struct KeyList {
  GtkWidget         *treeView;
  GtkListStore      *listStore;
  GtkTreeViewColumn *column;
  GtkCellRenderer   *nameRenderer;
  GtkTreeSelection  *select;

  enum Columns {
    KEY_COLUMN = 0,
    VALUE_COLUMN
  };

  KeyList( ValueList *valueList );
  static void changed( GtkTreeSelection *widget, ValueList *valueList );
};

struct ValueList {
  GtkWidget* vBox;
  ValueList();
};

Window::Window() {

  if ( !eldb.init( "" ) ) {
    exit(1);
  }

  window      = gtk_window_new( GTK_WINDOW_TOPLEVEL );
  searchEntry = gtk_entry_new();
  valueList   = new ValueList();
  keyList     = new KeyList( valueList );
  layout();

  GError *error;
  if ( ! gtk_window_set_icon_from_file( GTK_WINDOW( window ), "exolobe_tray.png", &error ) ) {
    fprintf( stderr, "%s\n", error->message );
    g_error_free( error );
  }

  g_signal_connect( searchEntry, "changed", G_CALLBACK( searchEntryChanged ), this );

  g_signal_connect( window, "destroy", G_CALLBACK( destroy ), NULL );
  gtk_window_set_title( GTK_WINDOW( window ), "The Exo Lobe" );
  gtk_window_set_default_size( GTK_WINDOW( window ), 800, 300 );

  gtk_widget_show_all( window );
  gtk_window_stick( GTK_WINDOW( window ) );
  gtk_window_set_keep_above( GTK_WINDOW( window ), 1 );

  searchEntryChanged( searchEntry, this );

  gtk_key_snooper_install( keySnooper, window );
  gtk_window_set_focus( GTK_WINDOW( window ), 0 );

  globalBinding( GTK_WINDOW( window ) );
}

KeyList::KeyList( ValueList *valueList ) {
  listStore    = gtk_list_store_new( 2, G_TYPE_STRING, G_TYPE_STRING );
  treeView     = gtk_tree_view_new_with_model( GTK_TREE_MODEL( listStore ) );
  nameRenderer = gtk_cell_renderer_text_new();

  column       = gtk_tree_view_column_new_with_attributes( "Keys", nameRenderer, "text", KEY_COLUMN,  (void *)NULL );
  gtk_tree_view_append_column( GTK_TREE_VIEW( treeView ), column );

  g_object_unref( G_OBJECT( listStore ) );

  select = gtk_tree_view_get_selection( GTK_TREE_VIEW ( treeView ) );
  gtk_tree_selection_set_mode( select, GTK_SELECTION_SINGLE );

  g_signal_connect( select, "changed", G_CALLBACK( KeyList::changed ), valueList );
}

void KeyList::changed( GtkTreeSelection *selection, ValueList *valueList ) {
  GtkTreeIter iter;
  GtkTreeModel *model;
  //const char *key;

  if ( gtk_tree_selection_get_selected( selection, &model, &iter ) ) {
/*    gtk_tree_model_get( model, &iter, VALUE_COLUMN, &key, -1 );
    GtkTextBuffer *buffer = gtk_text_view_get_buffer( textView );
    gtk_text_buffer_set_text( buffer, key, -1 );*/
  }
}

ValueList::ValueList() {
  vBox = gtk_vbox_new( FALSE, 3 );
  //TODO gtk_text_view_set_wrap_mode( GTK_TEXT_VIEW( textView ), GTK_WRAP_WORD_CHAR );
}

void Window::destroy( ) {
  gtk_main_quit ();
}

void Window::searchEntryChanged( GtkWidget *widget, Window *window ) {
  const char *text;
  GtkTreeIter iter;
  GtkListStore *keyStore =  window->keyList->listStore;

  gtk_list_store_clear( keyStore );
  text = gtk_entry_get_text( GTK_ENTRY( widget ) );

  auto result = window->eldb.find( text );

  if ( result->count ) {
    for ( auto key: result->keys ) {
      fprintf( stdout, "%s :\n", key->key.c_str() );

      for ( auto value: key->values ) {
        fprintf( stdout, "\t%s\n", value->value.c_str() );

        gtk_list_store_append( keyStore, &iter );
        gtk_list_store_set( keyStore, &iter,
          KeyList::KEY_COLUMN  , key->key.c_str(),
          KeyList::VALUE_COLUMN, value->value.c_str(),
          -1 );
      }
    }
  } else {
    fprintf( stderr, "No Results\n" );
  }
}

void Window::layout() {
  GtkWidget *table            = gtk_table_new( 3, 3, FALSE );
  GtkWidget *textViewScroller = gtk_scrolled_window_new( NULL, NULL );
  GtkWidget *keyListScroller  = gtk_scrolled_window_new( NULL, NULL );

  gtk_container_set_border_width( GTK_CONTAINER( window ), 5 );

  gtk_table_attach( GTK_TABLE( table ), searchEntry, 0, 3, 0, 1, GtkAttachOptions( GTK_EXPAND | GTK_FILL ), GTK_SHRINK, 0, 0 );
  gtk_table_attach_defaults( GTK_TABLE( table ), keyListScroller, 0, 1, 1, 3 );
  gtk_table_attach_defaults( GTK_TABLE( table ), textViewScroller, 1, 3, 1, 3 );

  gtk_container_add( GTK_CONTAINER( keyListScroller ), keyList->treeView );
  gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( textViewScroller ), valueList->vBox );

  gtk_table_set_row_spacings( GTK_TABLE( table ), 2 );
  gtk_table_set_col_spacings( GTK_TABLE( table ), 2 );

  gtk_container_add( GTK_CONTAINER( window ), table );
}

int Window::keySnooper( GtkWidget *widget, GdkEventKey *event, gpointer data ) {
  if ( event->keyval == GDK_KEY_q && event->state & GDK_CONTROL_MASK ) {
    destroy( );
  }

  if ( event->keyval == GDK_KEY_Escape ) {
    gtk_window_set_focus( GTK_WINDOW( data ), 0 );
  }

  return 0;
}

} //namespace elgtk

int main( int argc, char **argv ) {

  gtk_init( &argc, &argv );

  elgtk::Window window;

  gtk_main();

  return 0;
}

<commit_msg>Stop printing search results to stdout in gtk app<commit_after>//Copyright (c) 2011 Krishna Rajendran <krishna@emptybox.org>.
//Licensed under an MIT/X11 license. See LICENSE file for details.

extern "C" {
#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
}

#include "eldb.hpp"
#include "eldb_gtk_globalkeybind.hpp"

namespace elgtk {

struct KeyList;
struct ValueList;

struct Window {
  eldb::Eldb eldb;

  GtkWidget *window;
  GtkWidget *searchEntry;
  KeyList   *keyList;
  ValueList *valueList;

  Window();

  static void destroy();
  static void searchEntryChanged( GtkWidget *widget, Window *window );
  static int keySnooper( GtkWidget *widget, GdkEventKey *event, gpointer data );
  void layout();
};

struct KeyList {
  GtkWidget         *treeView;
  GtkListStore      *listStore;
  GtkTreeViewColumn *column;
  GtkCellRenderer   *nameRenderer;
  GtkTreeSelection  *select;

  enum Columns {
    KEY_COLUMN = 0,
    VALUE_COLUMN
  };

  KeyList( ValueList *valueList );
  static void changed( GtkTreeSelection *widget, ValueList *valueList );
};

struct ValueList {
  GtkWidget* vBox;
  ValueList();
};

Window::Window() {

  if ( !eldb.init( "" ) ) {
    exit(1);
  }

  window      = gtk_window_new( GTK_WINDOW_TOPLEVEL );
  searchEntry = gtk_entry_new();
  valueList   = new ValueList();
  keyList     = new KeyList( valueList );
  layout();

  GError *error;
  if ( ! gtk_window_set_icon_from_file( GTK_WINDOW( window ), "exolobe_tray.png", &error ) ) {
    fprintf( stderr, "%s\n", error->message );
    g_error_free( error );
  }

  g_signal_connect( searchEntry, "changed", G_CALLBACK( searchEntryChanged ), this );

  g_signal_connect( window, "destroy", G_CALLBACK( destroy ), NULL );
  gtk_window_set_title( GTK_WINDOW( window ), "The Exo Lobe" );
  gtk_window_set_default_size( GTK_WINDOW( window ), 800, 300 );

  gtk_widget_show_all( window );
  gtk_window_stick( GTK_WINDOW( window ) );
  gtk_window_set_keep_above( GTK_WINDOW( window ), 1 );

  searchEntryChanged( searchEntry, this );

  gtk_key_snooper_install( keySnooper, window );
  gtk_window_set_focus( GTK_WINDOW( window ), 0 );

  globalBinding( GTK_WINDOW( window ) );
}

KeyList::KeyList( ValueList *valueList ) {
  listStore    = gtk_list_store_new( 2, G_TYPE_STRING, G_TYPE_STRING );
  treeView     = gtk_tree_view_new_with_model( GTK_TREE_MODEL( listStore ) );
  nameRenderer = gtk_cell_renderer_text_new();

  column       = gtk_tree_view_column_new_with_attributes( "Keys", nameRenderer, "text", KEY_COLUMN,  (void *)NULL );
  gtk_tree_view_append_column( GTK_TREE_VIEW( treeView ), column );

  g_object_unref( G_OBJECT( listStore ) );

  select = gtk_tree_view_get_selection( GTK_TREE_VIEW ( treeView ) );
  gtk_tree_selection_set_mode( select, GTK_SELECTION_SINGLE );

  g_signal_connect( select, "changed", G_CALLBACK( KeyList::changed ), valueList );
}

void KeyList::changed( GtkTreeSelection *selection, ValueList *valueList ) {
  GtkTreeIter iter;
  GtkTreeModel *model;
  //const char *key;

  if ( gtk_tree_selection_get_selected( selection, &model, &iter ) ) {
/*    gtk_tree_model_get( model, &iter, VALUE_COLUMN, &key, -1 );
    GtkTextBuffer *buffer = gtk_text_view_get_buffer( textView );
    gtk_text_buffer_set_text( buffer, key, -1 );*/
  }
}

ValueList::ValueList() {
  vBox = gtk_vbox_new( FALSE, 3 );
  //TODO gtk_text_view_set_wrap_mode( GTK_TEXT_VIEW( textView ), GTK_WRAP_WORD_CHAR );
}

void Window::destroy( ) {
  gtk_main_quit ();
}

void Window::searchEntryChanged( GtkWidget *widget, Window *window ) {
  const char *text;
  GtkTreeIter iter;
  GtkListStore *keyStore =  window->keyList->listStore;

  gtk_list_store_clear( keyStore );
  text = gtk_entry_get_text( GTK_ENTRY( widget ) );

  auto result = window->eldb.find( text );

  if ( result->count ) {
    for ( auto key: result->keys ) {

      for ( auto value: key->values ) {

        gtk_list_store_append( keyStore, &iter );
        gtk_list_store_set( keyStore, &iter,
          KeyList::KEY_COLUMN  , key->key.c_str(),
          KeyList::VALUE_COLUMN, value->value.c_str(),
          -1 );
      }
    }
  } else {
    fprintf( stderr, "No Results\n" );
  }
}

void Window::layout() {
  GtkWidget *table            = gtk_table_new( 3, 3, FALSE );
  GtkWidget *textViewScroller = gtk_scrolled_window_new( NULL, NULL );
  GtkWidget *keyListScroller  = gtk_scrolled_window_new( NULL, NULL );

  gtk_container_set_border_width( GTK_CONTAINER( window ), 5 );

  gtk_table_attach( GTK_TABLE( table ), searchEntry, 0, 3, 0, 1, GtkAttachOptions( GTK_EXPAND | GTK_FILL ), GTK_SHRINK, 0, 0 );
  gtk_table_attach_defaults( GTK_TABLE( table ), keyListScroller, 0, 1, 1, 3 );
  gtk_table_attach_defaults( GTK_TABLE( table ), textViewScroller, 1, 3, 1, 3 );

  gtk_container_add( GTK_CONTAINER( keyListScroller ), keyList->treeView );
  gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( textViewScroller ), valueList->vBox );

  gtk_table_set_row_spacings( GTK_TABLE( table ), 2 );
  gtk_table_set_col_spacings( GTK_TABLE( table ), 2 );

  gtk_container_add( GTK_CONTAINER( window ), table );
}

int Window::keySnooper( GtkWidget *widget, GdkEventKey *event, gpointer data ) {
  if ( event->keyval == GDK_KEY_q && event->state & GDK_CONTROL_MASK ) {
    destroy( );
  }

  if ( event->keyval == GDK_KEY_Escape ) {
    gtk_window_set_focus( GTK_WINDOW( data ), 0 );
  }

  return 0;
}

} //namespace elgtk

int main( int argc, char **argv ) {

  gtk_init( &argc, &argv );

  elgtk::Window window;

  gtk_main();

  return 0;
}

<|endoftext|>