<commit_before>// LICENSE/*{{{*/
/*
  sxc - Simple Xmpp Client
  Copyright (C) 2008 Dennis Felsing, Andreas Waidler

  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 3 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, see <http://www.gnu.org/licenses/>.
 */
/*}}}*/

/* $Id$ */

// INCLUDES/*{{{*/

#include <string>
#include <fstream>
#include <pthread.h>

#include <errno.h>
#include <sstream>
#include <sys/stat.h>
#include "InputBase.h"
#include "../Exception/FileInputException.h"
#include "../Exception/Errno.h"
#include "../Exception/Type.h"

/*}}}*/

File::InputBase::InputBase()/*{{{*/
: _isFifoValid(false),
  _isLocked(false),
  _isThreadRunning(false)
{
}

/*}}}*/
File::InputBase::~InputBase()/*{{{*/
{
    _close();
}

/*}}}*/
void File::InputBase::initialize()/*{{{*/
{
    // Generate the path string.
    _path = _createPath();

    // Check the FIFO. Normally, the FIFO should exist with
    // the right permissions, except sxc has not been run before (in this
    // directory) or someone tampered with the directory structure.
    try {
        _validateFile();
    } catch (Exception::FileInputException e) {
        // If the FIFO is simply missing, try to create it. In any other case
        // we have encountered an unexpected error and let it bubble up.
        if (Exception::FileMissing != e.getType())
            throw e;
        _create();
    }

    // Everything went fine; path is okay. Open FIFO.
    _fifo.open(_path.c_str());
}

/*}}}*/
void File::InputBase::listen(bool blocking)/*{{{*/
{
    // Do not start to listen if the FIFO is currently locked. Otherwise we
    // could end up handling the input twice.
    if (_isLocked)
        // FIXME
        return;

    _isLocked = true;
    // Start the thread in the background.
    pthread_create(&_thread, NULL, _listen, this);
    // Join the thread when this functions should read in a blocking way.
    if (true == blocking)
        pthread_join(_thread, NULL);
}

/*}}}*/
void File::InputBase::_read()/*{{{*/
{
    // Refuse to read from an invalid FIFO.
    if (!_isFifoValid) {
        throw Exception::FileInputException(Exception::BadFile, "Refusing to read.");
    }

    // Gets filled with everything that is written until the other end closes
    // the pipe.
    std::string input;
    // Input is read line by line and put in buffer.
    std::string buffer;
    while (getline(_fifo, buffer)) {
        input += buffer;
    }
    _handleInput(input);
}

/*}}}*/
void File::InputBase::_close()/*{{{*/
{
    if (_isThreadRunning) {
        pthread_cancel(_thread);
        _isThreadRunning = false;
    }
    if (_isLocked) {
        _fifo.close();
        _isLocked = false;
    }
}

/*}}}*/
void File::InputBase::_create()/*{{{*/
{
    // Try to create FIFO with chmod 600.
    if (0 == mkfifo(_path.c_str(), S_IRUSR | S_IWUSR))
        return;

    // Creation of FIFO failed.
    Exception::Type type = Exception::errnoToType(errno);
    std::string message  = "Could not create FIFO " + _path;
    throw Exception::FileInputException(type, message);
}

/*}}}*/
void File::InputBase::_validateFile()/*{{{*/
{
    // Try to get file stats, needed for analyzing the chmod of the file.
    struct stat fstat;
    if (0 != stat(_path.c_str(), &fstat)) {
        Exception::Type type = Exception::errnoToType(errno);
        std::string message  = "Could not get FIFO fstat: " + _path;
        throw Exception::FileInputException(type, message);
    }

    // Is this really a FIFO?
    if (!S_ISFIFO(fstat.st_mode)) {
        std::string message  = "Not a FIFO: " + _path;
        throw Exception::FileInputException(Exception::BadFile, message);
    }

    // Check for chmod 600:
    if (0 == fstat.st_mode & S_IRUSR
    || 0 == fstat.st_mode & S_IWUSR
    || 0 != fstat.st_mode & S_IRGRP
    || 0 != fstat.st_mode & S_IWGRP
    || 0 != fstat.st_mode & S_IROTH
    || 0 != fstat.st_mode & S_IWOTH) {
        // Converts __mode_t st_mode to human-readable string (octal notation):
        std::stringstream mode;
        mode << std::oct << fstat.st_mode;
        // Extract only necessary part (user, group, other) from file mode:
        std::string message = _path + ": Chmod should be 600, found "
                            + mode.str().substr(2);
        throw Exception::FileInputException(Exception::BadFile, message);
    }

    _isFifoValid = true;
}

/*}}}*/
void *File::InputBase::_listen(void *fifo)/*{{{*/
{
    InputBase *that = (InputBase *) fifo;
    that->_isThreadRunning = true;
    do {
        // _read() reads blocking until the other end closes the pipe. This
        // loop will always restart _read() after it handled some input and
        // returned.
        that->_read();
    } while (true);

    return NULL;
}

/*}}}*/

// Use no tabs at all; four spaces indentation; max. eighty chars per line.
// vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker

<commit_msg>Fix InputBase::listen() throws FileInputException when FIFO is locked.<commit_after>// LICENSE/*{{{*/
/*
  sxc - Simple Xmpp Client
  Copyright (C) 2008 Dennis Felsing, Andreas Waidler

  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 3 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, see <http://www.gnu.org/licenses/>.
 */
/*}}}*/

/* $Id$ */

// INCLUDES/*{{{*/

#include <string>
#include <fstream>
#include <pthread.h>

#include <errno.h>
#include <sstream>
#include <sys/stat.h>
#include "InputBase.h"
#include "../Exception/FileInputException.h"
#include "../Exception/Errno.h"
#include "../Exception/Type.h"

/*}}}*/

File::InputBase::InputBase()/*{{{*/
: _isFifoValid(false),
  _isLocked(false),
  _isThreadRunning(false)
{
}

/*}}}*/
File::InputBase::~InputBase()/*{{{*/
{
    _close();
}

/*}}}*/
void File::InputBase::initialize()/*{{{*/
{
    // Generate the path string.
    _path = _createPath();

    // Check the FIFO. Normally, the FIFO should exist with
    // the right permissions, except sxc has not been run before (in this
    // directory) or someone tampered with the directory structure.
    try {
        _validateFile();
    } catch (Exception::FileInputException e) {
        // If the FIFO is simply missing, try to create it. In any other case
        // we have encountered an unexpected error and let it bubble up.
        if (Exception::FileMissing != e.getType())
            throw e;
        _create();
    }

    // Everything went fine; path is okay. Open FIFO.
    _fifo.open(_path.c_str());
}

/*}}}*/
void File::InputBase::listen(bool blocking)/*{{{*/
{
    // Do not start to listen if the FIFO is currently locked. Otherwise we
    // could end up handling the input twice.
    if (_isLocked) {
        std::string message = _path + " already locked.";
        throw Exception::FileInputException(Exception::FileLocked, message);
        return;
    }

    _isLocked = true;
    // Start the thread in the background.
    pthread_create(&_thread, NULL, _listen, this);
    // Join the thread when this functions should read in a blocking way.
    if (true == blocking)
        pthread_join(_thread, NULL);
}

/*}}}*/
void File::InputBase::_read()/*{{{*/
{
    // Refuse to read from an invalid FIFO.
    if (!_isFifoValid) {
        throw Exception::FileInputException(Exception::BadFile, "Refusing to read.");
    }

    // Gets filled with everything that is written until the other end closes
    // the pipe.
    std::string input;
    // Input is read line by line and put in buffer.
    std::string buffer;
    while (getline(_fifo, buffer)) {
        input += buffer;
    }
    _handleInput(input);
}

/*}}}*/
void File::InputBase::_close()/*{{{*/
{
    if (_isThreadRunning) {
        pthread_cancel(_thread);
        _isThreadRunning = false;
    }
    if (_isLocked) {
        _fifo.close();
        _isLocked = false;
    }
}

/*}}}*/
void File::InputBase::_create()/*{{{*/
{
    // Try to create FIFO with chmod 600.
    if (0 == mkfifo(_path.c_str(), S_IRUSR | S_IWUSR))
        return;

    // Creation of FIFO failed.
    Exception::Type type = Exception::errnoToType(errno);
    std::string message  = "Could not create FIFO " + _path;
    throw Exception::FileInputException(type, message);
}

/*}}}*/
void File::InputBase::_validateFile()/*{{{*/
{
    // Try to get file stats, needed for analyzing the chmod of the file.
    struct stat fstat;
    if (0 != stat(_path.c_str(), &fstat)) {
        Exception::Type type = Exception::errnoToType(errno);
        std::string message  = "Could not get FIFO fstat: " + _path;
        throw Exception::FileInputException(type, message);
    }

    // Is this really a FIFO?
    if (!S_ISFIFO(fstat.st_mode)) {
        std::string message  = "Not a FIFO: " + _path;
        throw Exception::FileInputException(Exception::BadFile, message);
    }

    // Check for chmod 600:
    if (0 == fstat.st_mode & S_IRUSR
    || 0 == fstat.st_mode & S_IWUSR
    || 0 != fstat.st_mode & S_IRGRP
    || 0 != fstat.st_mode & S_IWGRP
    || 0 != fstat.st_mode & S_IROTH
    || 0 != fstat.st_mode & S_IWOTH) {
        // Converts __mode_t st_mode to human-readable string (octal notation):
        std::stringstream mode;
        mode << std::oct << fstat.st_mode;
        // Extract only necessary part (user, group, other) from file mode:
        std::string message = _path + ": Chmod should be 600, found "
                            + mode.str().substr(2);
        throw Exception::FileInputException(Exception::BadFile, message);
    }

    _isFifoValid = true;
}

/*}}}*/
void *File::InputBase::_listen(void *fifo)/*{{{*/
{
    InputBase *that = (InputBase *) fifo;
    that->_isThreadRunning = true;
    do {
        // _read() reads blocking until the other end closes the pipe. This
        // loop will always restart _read() after it handled some input and
        // returned.
        that->_read();
    } while (true);

    return NULL;
}

/*}}}*/

// Use no tabs at all; four spaces indentation; max. eighty chars per line.
// vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker

<|endoftext|>


<commit_before>#pragma once
#include "Game.h"
#include <SDL2/SDL_mixer.h>
#include "SDLDeletersFunctor.h"

namespace REKFramework
{
	Game::Game()
	{
		//The window we'll be rendering to
		window = nullptr;

		// Engine renderer
		renderer = nullptr;

		// The class who manage all input
		inputMngr = nullptr;

		// Handle the game behavior according to the context (In-game, Pause, Menu etc...)
		gameContextMngr = nullptr;

		// Manage all sounds
		soundMngr = nullptr;

		gameMenu = nullptr;
		boardGame = nullptr;
	}

	Game::~Game()
	{

	}

	void Game::Loop(SDL_Event& e)
	{
		bool quitGame = false;

		while (!quitGame)
		{
			SDL_RenderClear(renderer.get());

			if (inputMngr != nullptr)
				inputMngr->CheckInput(e, quitGame);

			if (boardGame != nullptr)
			{
				if (!boardGame->IsGameOver())
				{
					boardGame->Update();
				}

				boardGame->Draw();
			}

			HandleGameMenu();

			if (boardGame != nullptr)
			{
				if (boardGame->IsGameOver() && GameContextManager::CurrentGameContext == GameContextEnum::INGAME)
				{
					gameContextMngr->ExecuteStartButtonAction();
				}
			}

			//Update the surface
			//SDL_UpdateWindowSurface(window); // software rendering : Not good
			SDL_RenderPresent(renderer.get()); // GPU rendering : Good !

		}
	}

	// Return true if no error
	bool Game::Init()
	{
		bool isInitOk = true;

		//Initialize SDL
		if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER) < 0)
		{
			ErrorMessageManager::WriteErrorMessageToConsole("SDL could not initialize! SDL_Error : ");
			isInitOk = false;
		}
		else
		{
			window = std::shared_ptr<SDL_Window>(
				SDL_CreateWindow("The best game ever !", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN)
				, SdlDeleter()
				);

			if (window == nullptr)
			{
				ErrorMessageManager::WriteErrorMessageToConsole("Window could not be created! SDL_Error : ");
				isInitOk = false;
			}
			else
			{
				renderer = std::shared_ptr<SDL_Renderer>(
					SDL_CreateRenderer(window.get(), -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)
					, SdlDeleter()
					);

				if (renderer == nullptr)
				{
					ErrorMessageManager::WriteErrorMessageToConsole("Renderer could not be created! SDL_Error : ");
					isInitOk = false;
				}
				else
				{
					// Init screen with light grey all over the surface
					SDL_SetRenderDrawColor(renderer.get(), 0xCC, 0xCC, 0xCC, SDL_ALPHA_OPAQUE);

					gameContextMngr = std::make_shared<GameContextManager>();

					inputMngr = std::make_unique<InputManager>(gameContextMngr);

					// SDL_ttf
					if (TTF_Init() != 0)
					{
						ErrorMessageManager::WriteErrorMessageToConsole("Could not load SDL_ttf, SDL_Error : ");
						isInitOk = false;
					}
					else
					{
						soundMngr = std::make_shared<SoundManager>();
						if (soundMngr->Init() < 0)
						{
							ErrorMessageManager::WriteErrorMessageToConsole("Could not Init SDL2_Mixer with OGG format, SDL_Error : ");
							isInitOk = false;
						}

						soundMngr->PlayMusic("resources/songs/MUS_N_CD_1.ogg", 2000);

						SetSDLMainObjectsToProvider();
					}
				}
			}
		}

		return isInitOk;
	}

	void Game::Execute()
	{
		if (Init())
		{
			SDL_Event e;
			Loop(e);
		}
	}

	void Game::SetSDLMainObjectsToProvider() const
	{
		SDLMainObjectsProvider::renderer = renderer;
		SDLMainObjectsProvider::window = window;
	}

	void Game::HandleGameMenu()
	{

		if (gameContextMngr != nullptr && GameContextManager::CurrentGameContext == GameContextEnum::MENU)
		{
			if (gameMenu == nullptr)
			{
				gameMenu = std::make_shared<GameMenu>(soundMngr);
				gameContextMngr->SetGameMenu(gameMenu);
				soundMngr->PlaySound("resources/sounds/MenuClick.wav", 1);
			}
			gameMenu->Draw();
		}

		if (GameContextManager::CurrentGameContext == GameContextEnum::INGAME && gameMenu != nullptr)
		{

			gameMenu.reset();
			soundMngr->PlaySound("resources/sounds/MenuOver.wav", 1);

			if (boardGame != nullptr && boardGame->IsGameOver())
			{
				// We leave menu after game over and restart a new game
				if (GameContextManager::CurrentGameContext == GameContextEnum::INGAME)
				{
					boardGame.reset();
					boardGame = nullptr;
					boardGame = std::make_shared<Board>();
					gameContextMngr->SetBoardGame(boardGame);
				}
			}
			else if (boardGame == nullptr)
			{
				boardGame = std::make_shared<Board>();
				gameContextMngr->SetBoardGame(boardGame);
			}
		}
	}

}
<commit_msg>Commentary<commit_after>#pragma once
#include "Game.h"
#include <SDL2/SDL_mixer.h>
#include "SDLDeletersFunctor.h"

namespace REKFramework
{
	Game::Game()
	{
		//The window we'll be rendering to
		window = nullptr;

		// Engine renderer
		renderer = nullptr;

		// The class who manage all input
		inputMngr = nullptr;

		// Handle the game behavior according to the context (In-game, Pause, Menu etc...)
		gameContextMngr = nullptr;

		// Manage all sounds
		soundMngr = nullptr;

		gameMenu = nullptr;
		boardGame = nullptr;
	}

	Game::~Game()
	{

	}

	void Game::Loop(SDL_Event& e)
	{
		bool quitGame = false;

		while (!quitGame)
		{
			SDL_RenderClear(renderer.get());

			if (inputMngr != nullptr)
				inputMngr->CheckInput(e, quitGame);

			if (boardGame != nullptr)
			{
				if (!boardGame->IsGameOver())
				{
					boardGame->Update();
				}

				boardGame->Draw();
			}

			HandleGameMenu();

			// Handle Game Over
			if (boardGame != nullptr)
			{
				if (boardGame->IsGameOver() && GameContextManager::CurrentGameContext == GameContextEnum::INGAME)
				{
					gameContextMngr->ExecuteStartButtonAction();
				}
			}

			//Update the surface
			//SDL_UpdateWindowSurface(window); // software rendering : Not good
			SDL_RenderPresent(renderer.get()); // GPU rendering : Good !

		}
	}

	// Return true if no error
	bool Game::Init()
	{
		bool isInitOk = true;

		//Initialize SDL
		if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER) < 0)
		{
			ErrorMessageManager::WriteErrorMessageToConsole("SDL could not initialize! SDL_Error : ");
			isInitOk = false;
		}
		else
		{
			window = std::shared_ptr<SDL_Window>(
				SDL_CreateWindow("The best game ever !", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN)
				, SdlDeleter()
				);

			if (window == nullptr)
			{
				ErrorMessageManager::WriteErrorMessageToConsole("Window could not be created! SDL_Error : ");
				isInitOk = false;
			}
			else
			{
				renderer = std::shared_ptr<SDL_Renderer>(
					SDL_CreateRenderer(window.get(), -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)
					, SdlDeleter()
					);

				if (renderer == nullptr)
				{
					ErrorMessageManager::WriteErrorMessageToConsole("Renderer could not be created! SDL_Error : ");
					isInitOk = false;
				}
				else
				{
					// Init screen with light grey all over the surface
					SDL_SetRenderDrawColor(renderer.get(), 0xCC, 0xCC, 0xCC, SDL_ALPHA_OPAQUE);

					gameContextMngr = std::make_shared<GameContextManager>();

					inputMngr = std::make_unique<InputManager>(gameContextMngr);

					// SDL_ttf
					if (TTF_Init() != 0)
					{
						ErrorMessageManager::WriteErrorMessageToConsole("Could not load SDL_ttf, SDL_Error : ");
						isInitOk = false;
					}
					else
					{
						soundMngr = std::make_shared<SoundManager>();
						if (soundMngr->Init() < 0)
						{
							ErrorMessageManager::WriteErrorMessageToConsole("Could not Init SDL2_Mixer with OGG format, SDL_Error : ");
							isInitOk = false;
						}

						soundMngr->PlayMusic("resources/songs/MUS_N_CD_1.ogg", 2000);

						SetSDLMainObjectsToProvider();
					}
				}
			}
		}

		return isInitOk;
	}

	void Game::Execute()
	{
		if (Init())
		{
			SDL_Event e;
			Loop(e);
		}
	}

	void Game::SetSDLMainObjectsToProvider() const
	{
		SDLMainObjectsProvider::renderer = renderer;
		SDLMainObjectsProvider::window = window;
	}

	void Game::HandleGameMenu()
	{

		if (gameContextMngr != nullptr && GameContextManager::CurrentGameContext == GameContextEnum::MENU)
		{
			if (gameMenu == nullptr)
			{
				gameMenu = std::make_shared<GameMenu>(soundMngr);
				gameContextMngr->SetGameMenu(gameMenu);
				soundMngr->PlaySound("resources/sounds/MenuClick.wav", 1);
			}
			gameMenu->Draw();
		}

		if (GameContextManager::CurrentGameContext == GameContextEnum::INGAME && gameMenu != nullptr)
		{

			gameMenu.reset();
			soundMngr->PlaySound("resources/sounds/MenuOver.wav", 1);

			if (boardGame != nullptr && boardGame->IsGameOver())
			{
				// We leave menu after game over and restart a new game
				if (GameContextManager::CurrentGameContext == GameContextEnum::INGAME)
				{
					boardGame.reset();
					boardGame = nullptr;
					boardGame = std::make_shared<Board>();
					gameContextMngr->SetBoardGame(boardGame);
				}
			}
			else if (boardGame == nullptr)
			{
				boardGame = std::make_shared<Board>();
				gameContextMngr->SetBoardGame(boardGame);
			}
		}
	}

}
<|endoftext|>


<commit_before>// @(#)root/gpad:$Name$:$Id$
// Author: Nenad Buncic   20/02/96

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

/////////////////////////////////////////////////////////////////////////
//                                                                     //
//   ControlBar is fully user configurable tool which provides fast    //
// access to frequently used operations. User can choose between       //
// buttons and drawnbuttons (let's say icons) and assign to them his   //
// own actions (let's say ROOT or C++ commands).                       //
//
// The macro belows shows an example of controlbar.
// To execute an item, click with the left mouse button.
// To see the HELP of a button, click on the right mouse button.
//
//{
//   gROOT.Reset("a");
//   TControlBar bar("vertical");
//   bar.AddButton("Help to run demos",".x demoshelp.C",
//                 "Explains how to run the demos");
//   bar.AddButton("framework",        ".x framework.C",
//                 "An Example of Object Oriented User Interface");
//   bar.AddButton("hsimple",          ".x hsimple.C",
//                 "An Example Creating Histograms/Ntuples on File");
//   bar.AddButton("hsum",             ".x hsum.C",
//                 "Filling histograms and some graphics options");
//   bar.AddButton("canvas",           ".x canvas.C",
//                 "Canvas and Pad Management");
//   bar.AddButton("formula1",         ".x formula1.C",
//                 "Simple Formula and Functions");
//   bar.AddButton("fillrandom",       ".x fillrandom.C",
//                 "Histograms with Random Numbers from a Function");
//   bar.AddButton("fit1",             ".x fit1.C",
//                 "A Simple Fitting Example");
//   bar.AddButton("h1draw",           ".x h1draw.C",
//                 "Drawing Options for 1D Histograms");
//   bar.AddButton("graph",            ".x graph.C",
//                 "Examples of a simple graph");
//   bar.AddButton("tornado",          ".x tornado.C",
//                 "Examples of 3-D PolyMarkers");
//   bar.AddButton("shapes",           ".x shapes.C",
//                 "The Geometry Shapes");
//   bar.AddButton("atlasna49",        ".x atlasna49.C",
//                 "Creating and Viewing Geometries");
//   bar.AddButton("file_layout",      ".x file.C",
//                 "The ROOT file format");
//   bar.AddButton("tree_layout",      ".x tree.C",
//                 "The Tree Data Structure");
//   bar.AddButton("ntuple1",          ".x ntuple1.C",
//                 "Ntuples and Selections");
//   bar.AddButton("run benchmarks",   ".x benchmarks.C",
//                 "Runs all the ROOT benchmarks");
//   bar.AddButton("rootmarks",        ".x rootmarks.C",
//                 "Prints an estimated ROOTMARKS for your machine");
//   bar.AddButton("edit_hsimple",     ".!ved hsimple.C &",
//                 "Invokes the text editor on file hsimple.C");
//   bar.AddButton("Close Bar",        "gROOT.Reset("a")",
//                 "Close ControlBar");
//   bar.Show();
//   gROOT.SaveContext();
//}
//
//Begin_Html
/*

*/
//End_Html
//
//                                                                     //
/////////////////////////////////////////////////////////////////////////

#include "TControlBar.h"
#include "TGuiFactory.h"
#include "TList.h"

ClassImp(TControlBar)

//_______________________________________________________________________
TControlBar::TControlBar() : TControlBarButton()
{
    fControlBarImp = 0;
    fOrientation   = 0;
    fButtons       = 0;
    fNoroc         = 1;
}

//_______________________________________________________________________
TControlBar::TControlBar(const char *orientation, const char *title)
            : TControlBarButton(title, "", "", "button")

{
    Initialize(-999, -999);
    SetOrientation( orientation );
}

//_______________________________________________________________________
TControlBar::TControlBar(const char *orientation, const char *title, Int_t x, Int_t y)
            : TControlBarButton(title, "", "", "button")

{
    Initialize(x, y);
    SetOrientation( orientation );
}

//_______________________________________________________________________
TControlBar::~TControlBar()
{
    delete fControlBarImp;

    if( fButtons )
        fButtons->Delete();

    fButtons       = 0;
    fControlBarImp = 0;
}

//_______________________________________________________________________
void TControlBar::AddButton(TControlBarButton &button)
{
    AddButton( &button );
}

//_______________________________________________________________________
void TControlBar::AddButton(TControlBarButton *button)
{
    if( fButtons && button )
        fButtons->Add( button );
}

//_______________________________________________________________________
void TControlBar::AddButton(const char *label, const char *action, const char *hint, const char *type)
{
    TControlBarButton *button = new TControlBarButton( label, action, hint, type );
    AddButton( button );
}

//_______________________________________________________________________
void TControlBar::AddControlBar(TControlBar &controlBar)
{
    AddControlBar( &controlBar );
}

//_______________________________________________________________________
void TControlBar::AddControlBar(TControlBar *controlBar)
{
    if( fButtons && controlBar )
        fButtons->Add( controlBar );
}

//_______________________________________________________________________
void TControlBar::AddSeparator()
{

}

//_______________________________________________________________________
void TControlBar::Create()
{
    if( fControlBarImp )
        fControlBarImp->Create();
}

//_______________________________________________________________________
void TControlBar::Hide()
{
    if( fControlBarImp )
        fControlBarImp->Hide();
}

//_______________________________________________________________________
void TControlBar::Initialize(Int_t x, Int_t y)
{
   if (x == -999)
      fControlBarImp = gGuiFactory->CreateControlBarImp( this, GetName() );
   else
      fControlBarImp = gGuiFactory->CreateControlBarImp( this, GetName(), x, y );

    fButtons       = new TList();
    fNoroc         = 1;
}

//_______________________________________________________________________
void TControlBar::SetOrientation(const char *o)
{
    fOrientation = kVertical;

    if( *o ) {
        if( !strcasecmp( o, "vertical" ) )
            fOrientation = kVertical;
        else if( !strcasecmp( o, "horizontal" ) )
            fOrientation = kHorizontal;
        else
            Error( "SetOrientation", "Unknown orientation: '%s' !\n\t\t(choice of: %s, %s)",
                    o, "vertical", "horizontal" );
    }
}

//_______________________________________________________________________
void TControlBar::SetOrientation(Int_t o)
{
    fOrientation = kVertical;

    if( ( o == kVertical ) || ( o == kHorizontal ) )
        fOrientation = o;
    else
        Error( "SetOrientation", "Unknown orientation: %d !\n\t\t(choice of: %d, %d)",
                o, kVertical, kHorizontal );
}

//_______________________________________________________________________
void TControlBar::Show()
{
    if( fControlBarImp )
        fControlBarImp->Show();
}
<commit_msg>Take into account TStyle::SetScreenFactor in the constructor. This allows to position the controlbar at a fix position independently of the screen size.<commit_after>// @(#)root/gpad:$Name:  $:$Id: TControlBar.cxx,v 1.1.1.1 2000/05/16 17:00:41 rdm Exp $
// Author: Nenad Buncic   20/02/96

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

/////////////////////////////////////////////////////////////////////////
//                                                                     //
//   ControlBar is fully user configurable tool which provides fast    //
// access to frequently used operations. User can choose between       //
// buttons and drawnbuttons (let's say icons) and assign to them his   //
// own actions (let's say ROOT or C++ commands).                       //
//
// The macro belows shows an example of controlbar.
// To execute an item, click with the left mouse button.
// To see the HELP of a button, click on the right mouse button.
//
//{
//   gROOT.Reset("a");
//   TControlBar bar("vertical");
//   bar.AddButton("Help to run demos",".x demoshelp.C",
//                 "Explains how to run the demos");
//   bar.AddButton("framework",        ".x framework.C",
//                 "An Example of Object Oriented User Interface");
//   bar.AddButton("hsimple",          ".x hsimple.C",
//                 "An Example Creating Histograms/Ntuples on File");
//   bar.AddButton("hsum",             ".x hsum.C",
//                 "Filling histograms and some graphics options");
//   bar.AddButton("canvas",           ".x canvas.C",
//                 "Canvas and Pad Management");
//   bar.AddButton("formula1",         ".x formula1.C",
//                 "Simple Formula and Functions");
//   bar.AddButton("fillrandom",       ".x fillrandom.C",
//                 "Histograms with Random Numbers from a Function");
//   bar.AddButton("fit1",             ".x fit1.C",
//                 "A Simple Fitting Example");
//   bar.AddButton("h1draw",           ".x h1draw.C",
//                 "Drawing Options for 1D Histograms");
//   bar.AddButton("graph",            ".x graph.C",
//                 "Examples of a simple graph");
//   bar.AddButton("tornado",          ".x tornado.C",
//                 "Examples of 3-D PolyMarkers");
//   bar.AddButton("shapes",           ".x shapes.C",
//                 "The Geometry Shapes");
//   bar.AddButton("atlasna49",        ".x atlasna49.C",
//                 "Creating and Viewing Geometries");
//   bar.AddButton("file_layout",      ".x file.C",
//                 "The ROOT file format");
//   bar.AddButton("tree_layout",      ".x tree.C",
//                 "The Tree Data Structure");
//   bar.AddButton("ntuple1",          ".x ntuple1.C",
//                 "Ntuples and Selections");
//   bar.AddButton("run benchmarks",   ".x benchmarks.C",
//                 "Runs all the ROOT benchmarks");
//   bar.AddButton("rootmarks",        ".x rootmarks.C",
//                 "Prints an estimated ROOTMARKS for your machine");
//   bar.AddButton("edit_hsimple",     ".!ved hsimple.C &",
//                 "Invokes the text editor on file hsimple.C");
//   bar.AddButton("Close Bar",        "gROOT.Reset("a")",
//                 "Close ControlBar");
//   bar.Show();
//   gROOT.SaveContext();
//}
//
//Begin_Html
/*

*/
//End_Html
//
//                                                                     //
/////////////////////////////////////////////////////////////////////////

#include "TControlBar.h"
#include "TGuiFactory.h"
#include "TList.h"
#include "TStyle.h"

ClassImp(TControlBar)

//_______________________________________________________________________
TControlBar::TControlBar() : TControlBarButton()
{
    fControlBarImp = 0;
    fOrientation   = 0;
    fButtons       = 0;
    fNoroc         = 1;
}

//_______________________________________________________________________
TControlBar::TControlBar(const char *orientation, const char *title)
            : TControlBarButton(title, "", "", "button")

{
    Initialize(-999, -999);
    SetOrientation( orientation );
}

//_______________________________________________________________________
TControlBar::TControlBar(const char *orientation, const char *title, Int_t x, Int_t y)
            : TControlBarButton(title, "", "", "button")

{
    Int_t xs = (Int_t)(x*gStyle->GetScreenFactor());
    Int_t ys = (Int_t)(y*gStyle->GetScreenFactor());
    Initialize(xs, ys);
    SetOrientation( orientation );
}

//_______________________________________________________________________
TControlBar::~TControlBar()
{
    delete fControlBarImp;

    if( fButtons )
        fButtons->Delete();

    fButtons       = 0;
    fControlBarImp = 0;
}

//_______________________________________________________________________
void TControlBar::AddButton(TControlBarButton &button)
{
    AddButton( &button );
}

//_______________________________________________________________________
void TControlBar::AddButton(TControlBarButton *button)
{
    if( fButtons && button )
        fButtons->Add( button );
}

//_______________________________________________________________________
void TControlBar::AddButton(const char *label, const char *action, const char *hint, const char *type)
{
    TControlBarButton *button = new TControlBarButton( label, action, hint, type );
    AddButton( button );
}

//_______________________________________________________________________
void TControlBar::AddControlBar(TControlBar &controlBar)
{
    AddControlBar( &controlBar );
}

//_______________________________________________________________________
void TControlBar::AddControlBar(TControlBar *controlBar)
{
    if( fButtons && controlBar )
        fButtons->Add( controlBar );
}

//_______________________________________________________________________
void TControlBar::AddSeparator()
{

}

//_______________________________________________________________________
void TControlBar::Create()
{
    if( fControlBarImp )
        fControlBarImp->Create();
}

//_______________________________________________________________________
void TControlBar::Hide()
{
    if( fControlBarImp )
        fControlBarImp->Hide();
}

//_______________________________________________________________________
void TControlBar::Initialize(Int_t x, Int_t y)
{
   if (x == -999)
      fControlBarImp = gGuiFactory->CreateControlBarImp( this, GetName() );
   else
      fControlBarImp = gGuiFactory->CreateControlBarImp( this, GetName(), x, y );

    fButtons       = new TList();
    fNoroc         = 1;
}

//_______________________________________________________________________
void TControlBar::SetOrientation(const char *o)
{
    fOrientation = kVertical;

    if( *o ) {
        if( !strcasecmp( o, "vertical" ) )
            fOrientation = kVertical;
        else if( !strcasecmp( o, "horizontal" ) )
            fOrientation = kHorizontal;
        else
            Error( "SetOrientation", "Unknown orientation: '%s' !\n\t\t(choice of: %s, %s)",
                    o, "vertical", "horizontal" );
    }
}

//_______________________________________________________________________
void TControlBar::SetOrientation(Int_t o)
{
    fOrientation = kVertical;

    if( ( o == kVertical ) || ( o == kHorizontal ) )
        fOrientation = o;
    else
        Error( "SetOrientation", "Unknown orientation: %d !\n\t\t(choice of: %d, %d)",
                o, kVertical, kHorizontal );
}

//_______________________________________________________________________
void TControlBar::Show()
{
    if( fControlBarImp )
        fControlBarImp->Show();
}
<|endoftext|>


<commit_before>#include "bulkDataNTDDSSubscriber.h"
#include <iostream>

using namespace AcsBulkdata;
using namespace std;
using namespace ACSErrTypeCommon;
using namespace ACS_DDS_Errors;

BulkDataNTDDSSubscriber::BulkDataNTDDSSubscriber(DDS::DomainParticipant *p, const DDSConfiguration &ddsCfg) :
		BulkDataNTDDS(p, ddsCfg)
{
	subscriber_m = createDDSSubscriber();
}

BulkDataNTDDSSubscriber::~BulkDataNTDDSSubscriber()
{
	try
	{
		destroyDDSSubscriber();
	}
	catch(ACSErr::ACSbaseExImpl &ex)
	{
		ex.log();
	}
}//~BulkDataNTDDSSubscriber

DDS::Subscriber* BulkDataNTDDSSubscriber::createDDSSubscriber()
{
	AUTO_TRACE(__PRETTY_FUNCTION__);

	if (participant_m==NULL)
	{
		printf("BulkDataNTDDSSubscriber::BulkDataNTDDSSubscriber participant NULL\n");
		return NULL;
	}

	DDS::Subscriber *sub = participant_m->create_subscriber_with_profile(
			ddsCfg_m.libraryQos.c_str(), ddsCfg_m.profileQos.c_str(),
			0, DDS::STATUS_MASK_NONE);
	if(sub==NULL)
	{
		DDSSubscriberCreateProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		throw ex;
	}
	return sub;
}//createDDSSubscriber

void BulkDataNTDDSSubscriber::destroyDDSSubscriber()
{
	AUTO_TRACE(__PRETTY_FUNCTION__);
	DDS::ReturnCode_t ret;
	ret = participant_m->delete_subscriber(subscriber_m);
	subscriber_m = 0;
	if (ret!=DDS::RETCODE_OK)
	{
		DDSSubscriberDestroyProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDDSTypeCode(ret);
		throw ex;
	}//if
}//destroyDDSSubscriber

ACSBulkData::BulkDataNTFrameDataReader* BulkDataNTDDSSubscriber::createDDSReader(DDS::Topic *topic, DDS::DataReaderListener *listener)
{
	AUTO_TRACE(__PRETTY_FUNCTION__);

	if (subscriber_m==NULL || topic==NULL || listener==NULL)
	{
		NullPointerExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setVariable("publisher_m, topic or listener");
		throw ex;
	}

	DDS::DataReader *dr = subscriber_m->create_datareader_with_profile(topic,
			ddsCfg_m.libraryQos.c_str(), ddsCfg_m.profileQos.c_str(),
			listener,
			DDS::STATUS_MASK_ALL/*ALL_STATUS*/);
	if(dr==NULL)
	{
		DDSDRCreateProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		throw ex;
	}//if

	return dr;
}

void BulkDataNTDDSSubscriber::destroyDDSReader(ACSBulkData::BulkDataNTFrameDataReader *dr)
{
	AUTO_TRACE(__PRETTY_FUNCTION__);
	DDS::ReturnCode_t ret;

	ret = subscriber_m->delete_datareader(dr);
	if (ret!=DDS::RETCODE_OK)
	{
		ACS_SHORT_LOG((LM_ERROR, "Problem deleting data reader (%d)", ret));
	}
}
<commit_msg>narrow data reader to BulkDataNTFrameDataReader in createDDSReader<commit_after>#include "bulkDataNTDDSSubscriber.h"
#include <iostream>

using namespace AcsBulkdata;
using namespace std;
using namespace ACSErrTypeCommon;
using namespace ACS_DDS_Errors;

BulkDataNTDDSSubscriber::BulkDataNTDDSSubscriber(DDS::DomainParticipant *p, const DDSConfiguration &ddsCfg) :
		BulkDataNTDDS(p, ddsCfg)
{
	subscriber_m = createDDSSubscriber();
}

BulkDataNTDDSSubscriber::~BulkDataNTDDSSubscriber()
{
	try
	{
		destroyDDSSubscriber();
	}
	catch(ACSErr::ACSbaseExImpl &ex)
	{
		ex.log();
	}
}//~BulkDataNTDDSSubscriber

DDS::Subscriber* BulkDataNTDDSSubscriber::createDDSSubscriber()
{
	AUTO_TRACE(__PRETTY_FUNCTION__);

	if (participant_m==NULL)
	{
		printf("BulkDataNTDDSSubscriber::BulkDataNTDDSSubscriber participant NULL\n");
		return NULL;
	}

	DDS::Subscriber *sub = participant_m->create_subscriber_with_profile(
			ddsCfg_m.libraryQos.c_str(), ddsCfg_m.profileQos.c_str(),
			0, DDS::STATUS_MASK_NONE);
	if(sub==NULL)
	{
		DDSSubscriberCreateProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		throw ex;
	}
	return sub;
}//createDDSSubscriber

void BulkDataNTDDSSubscriber::destroyDDSSubscriber()
{
	AUTO_TRACE(__PRETTY_FUNCTION__);
	DDS::ReturnCode_t ret;
	ret = participant_m->delete_subscriber(subscriber_m);
	subscriber_m = 0;
	if (ret!=DDS::RETCODE_OK)
	{
		DDSSubscriberDestroyProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDDSTypeCode(ret);
		throw ex;
	}//if
}//destroyDDSSubscriber

ACSBulkData::BulkDataNTFrameDataReader* BulkDataNTDDSSubscriber::createDDSReader(DDS::Topic *topic, DDS::DataReaderListener *listener)
{
	AUTO_TRACE(__PRETTY_FUNCTION__);

	if (subscriber_m==NULL || topic==NULL || listener==NULL)
	{
		NullPointerExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setVariable("publisher_m, topic or listener");
		throw ex;
	}

	DDS::DataReader *dr = subscriber_m->create_datareader_with_profile(topic,
			ddsCfg_m.libraryQos.c_str(), ddsCfg_m.profileQos.c_str(),
			listener,
			DDS::STATUS_MASK_ALL);
	if(dr==NULL)
	{
		DDSDRCreateProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		throw ex;
	}//if

	return ACSBulkData::BulkDataNTFrameDataReader::narrow(dr);
}

void BulkDataNTDDSSubscriber::destroyDDSReader(ACSBulkData::BulkDataNTFrameDataReader *dr)
{
	AUTO_TRACE(__PRETTY_FUNCTION__);
	DDS::ReturnCode_t ret;

	ret = subscriber_m->delete_datareader(dr);
	if (ret!=DDS::RETCODE_OK)
	{
		ACS_SHORT_LOG((LM_ERROR, "Problem deleting data reader (%d)", ret));
	}
}
<|endoftext|>


<commit_before>#ifndef AIKIDO_PATH_PIECEWISELINEAR_TRAJECTORY_HPP_
#define AIKIDO_PATH_PIECEWISELINEAR_TRAJECTORY_HPP_

#include "Trajectory.hpp"
#include "../statespace/GeodesicInterpolator.hpp"

namespace aikido {
namespace path {

/// Implements a piecewise linear trajectory
class PiecewiseLinearTrajectory : public Trajectory
{
public:
  /// Constructs an empty trajectory.
  ///
  /// \param _stateSpace state space this trajectory is defined in
  /// \param _interpolator interpolator used to interpolate between waypoints
  PiecewiseLinearTrajectory(
    aikido::statespace::StateSpacePtr _sspace,
    aikido::statespace::InterpolatorPtr _interpolator);

  /// Add a waypoint to the trajectory at the given time.
  ///
  /// \param _t time of the waypoint
  /// \param _state state at the waypoint
  void addWaypoint(double _t,
                   const aikido::statespace::StateSpace::State *_state);

  /// Gets a waypoint.
  ///
  /// \param _index waypoint index
  /// \return state of the waypoint at index \c _index
  const statespace::StateSpace::State* getWaypoint(size_t _index) const;

  /// Gets the number of waypoints.
  size_t getNumWaypoints() const;

  // Documentation inherited
  aikido::statespace::StateSpacePtr getStateSpace() const override;

  /// Gets the interpolator used to interpolate between waypoints.
  aikido::statespace::InterpolatorPtr getInterpolator() const;

  // Documentation inherited
  size_t getNumDerivatives() const override;

  // Documentation inherited
  double getStartTime() const override;

  // Documentation inherited
  double getEndTime() const override;

  // Documentation inherited
  double getDuration() const override;

  // Documentation inherited
  void evaluate(double _t,
                aikido::statespace::StateSpace::State *_state) const override;

  // Documentation inherited
  Eigen::VectorXd evaluate(double _t, int _derivative) const override;

private:
  /// Waypint in the trajectory.
  struct Waypoint
  {
    Waypoint(double _t, aikido::statespace::StateSpace::State *_state);

    /// Comparator to allow sorting waypoints based on time
    bool operator<(const Waypoint &rhs) const;

    /// Comparator to allow sorting waypoints based on time
    bool operator<(const double &rhs) const;

    double t;
    aikido::statespace::StateSpace::State *state;
  };

  /// Get the index of the first waypoint whose time value is larger than _t.
  /// Throws std::domain_error if _t is larger than last waypoint in the
  /// trajectory.
  int getWaypointIndexAfterTime(double _t) const;

  aikido::statespace::StateSpacePtr mStateSpace;
  aikido::statespace::InterpolatorPtr mInterpolator;
  std::vector<Waypoint> mWaypoints;
};

using PiecewiseLinearTrajectoryPtr = std::shared_ptr<PiecewiseLinearTrajectory>;

} // namespace path
} // namespace aikido

#endif // ifndef AIKIDO_PATH_PIECEWISELINEAR_TRAJECTORY_HPP_
<commit_msg>Fixed docstring.<commit_after>#ifndef AIKIDO_PATH_PIECEWISELINEAR_TRAJECTORY_HPP_
#define AIKIDO_PATH_PIECEWISELINEAR_TRAJECTORY_HPP_

#include "Trajectory.hpp"
#include "../statespace/GeodesicInterpolator.hpp"

namespace aikido {
namespace path {

/// Trajectory that uses an \c Interpolator to interpolate between waypoints.
class PiecewiseLinearTrajectory : public Trajectory
{
public:
  /// Constructs an empty trajectory.
  ///
  /// \param _stateSpace state space this trajectory is defined in
  /// \param _interpolator interpolator used to interpolate between waypoints
  PiecewiseLinearTrajectory(
    aikido::statespace::StateSpacePtr _sspace,
    aikido::statespace::InterpolatorPtr _interpolator);

  /// Add a waypoint to the trajectory at the given time.
  ///
  /// \param _t time of the waypoint
  /// \param _state state at the waypoint
  void addWaypoint(double _t,
                   const aikido::statespace::StateSpace::State *_state);

  /// Gets a waypoint.
  ///
  /// \param _index waypoint index
  /// \return state of the waypoint at index \c _index
  const statespace::StateSpace::State* getWaypoint(size_t _index) const;

  /// Gets the number of waypoints.
  size_t getNumWaypoints() const;

  // Documentation inherited
  aikido::statespace::StateSpacePtr getStateSpace() const override;

  /// Gets the interpolator used to interpolate between waypoints.
  aikido::statespace::InterpolatorPtr getInterpolator() const;

  // Documentation inherited
  size_t getNumDerivatives() const override;

  // Documentation inherited
  double getStartTime() const override;

  // Documentation inherited
  double getEndTime() const override;

  // Documentation inherited
  double getDuration() const override;

  // Documentation inherited
  void evaluate(double _t,
                aikido::statespace::StateSpace::State *_state) const override;

  // Documentation inherited
  Eigen::VectorXd evaluate(double _t, int _derivative) const override;

private:
  /// Waypint in the trajectory.
  struct Waypoint
  {
    Waypoint(double _t, aikido::statespace::StateSpace::State *_state);

    /// Comparator to allow sorting waypoints based on time
    bool operator<(const Waypoint &rhs) const;

    /// Comparator to allow sorting waypoints based on time
    bool operator<(const double &rhs) const;

    double t;
    aikido::statespace::StateSpace::State *state;
  };

  /// Get the index of the first waypoint whose time value is larger than _t.
  /// Throws std::domain_error if _t is larger than last waypoint in the
  /// trajectory.
  int getWaypointIndexAfterTime(double _t) const;

  aikido::statespace::StateSpacePtr mStateSpace;
  aikido::statespace::InterpolatorPtr mInterpolator;
  std::vector<Waypoint> mWaypoints;
};

using PiecewiseLinearTrajectoryPtr = std::shared_ptr<PiecewiseLinearTrajectory>;

} // namespace path
} // namespace aikido

#endif // ifndef AIKIDO_PATH_PIECEWISELINEAR_TRAJECTORY_HPP_
<|endoftext|>


<commit_before>//
// examples/offset_cxx03.cpp
// -------------------------
//
// Copyright (c) 2015 Daniel Joos
//
// Distributed under MIT license. (See file LICENSE)
//
// ----------------------------------
//
// This example shows how to create a 'OffsetRequest' to get the information
// about the latest offset of a specific topic-partition
// On success, this example prints the retrieved offset to stdout. Errors will
// be printed to stderr.
//

#include <iostream>
#include <boost/asio.hpp>
#include <libkafka_asio/libkafka_asio.h>

using libkafka_asio::Client;
using libkafka_asio::OffsetRequest;
using libkafka_asio::OffsetResponse;

void HandleRequest(const Client::ErrorCodeType& err,
                   const OffsetResponse::OptionalType& response)
{
  if (err || !response)
  {
    std::cerr
      << "Error: " << boost::system::system_error(err).what()
      << std::endl;
    return;
  }
  OffsetResponse::PartitionOffset::OptionalType offset =
    response->TopicPartitionOffset("mytopic", 1);
  if (!offset || offset->offsets.empty())
  {
    std::cerr << "Failed to fetch offset!" << std::endl;
    return;
  }
  std::cout
    << "Received latest offset: " << offset->offsets[0]
    << std::endl;
}

int main(int argc, char** argv)
{
  Client::Configuration configuration;
  configuration.auto_connect = true;
  configuration.client_id = "libkafka_asio_example";
  configuration.socket_timeout = 2000;
  configuration.AddBrokerFromString("192.168.59.104:49156");

  boost::asio::io_service ios;
  Client client(ios, configuration);

  // Request the latest offset for partition 1 of topic 'mytopic' on the
  // configured broker.
  using libkafka_asio::constants::kOffsetTimeLatest;
  OffsetRequest request;
  request.FetchTopicOffset("mytopic", 1, kOffsetTimeLatest);

  client.AsyncRequest(request, &HandleRequest);

  ios.run();
  return 0;
}<commit_msg>Adapted example to changes<commit_after>//
// examples/offset_cxx03.cpp
// -------------------------
//
// Copyright (c) 2015 Daniel Joos
//
// Distributed under MIT license. (See file LICENSE)
//
// ----------------------------------
//
// This example shows how to create a 'OffsetRequest' to get the information
// about the latest offset of a specific topic-partition
// On success, this example prints the retrieved offset to stdout. Errors will
// be printed to stderr.
//

#include <iostream>
#include <boost/asio.hpp>
#include <libkafka_asio/libkafka_asio.h>

using libkafka_asio::Client;
using libkafka_asio::OffsetRequest;
using libkafka_asio::OffsetResponse;

void HandleRequest(const Client::ErrorCodeType& err,
                   const OffsetResponse::OptionalType& response)
{
  if (err || !response)
  {
    std::cerr
      << "Error: " << boost::system::system_error(err).what()
      << std::endl;
    return;
  }
  OffsetResponse::Topic::Partition::OptionalType offset =
    response->TopicPartitionOffset("mytopic", 1);
  if (!offset || offset->offsets.empty())
  {
    std::cerr << "Failed to fetch offset!" << std::endl;
    return;
  }
  std::cout
    << "Received latest offset: " << offset->offsets[0]
    << std::endl;
}

int main(int argc, char** argv)
{
  Client::Configuration configuration;
  configuration.auto_connect = true;
  configuration.client_id = "libkafka_asio_example";
  configuration.socket_timeout = 2000;
  configuration.AddBrokerFromString("192.168.59.104:49156");

  boost::asio::io_service ios;
  Client client(ios, configuration);

  // Request the latest offset for partition 1 of topic 'mytopic' on the
  // configured broker.
  using libkafka_asio::constants::kOffsetTimeLatest;
  OffsetRequest request;
  request.FetchTopicOffset("mytopic", 1, kOffsetTimeLatest);

  client.AsyncRequest(request, &HandleRequest);

  ios.run();
  return 0;
}<|endoftext|>


<commit_before><commit_msg>[skip-ci] improve TPad::Print doc (#9181)<commit_after><|endoftext|>


<commit_before>#include "StdAfx.h"
#include "UIGifAnim.h"

///////////////////////////////////////////////////////////////////////////////////////
DECLARE_HANDLE(HZIP);	// An HZIP identifies a zip file that has been opened
typedef DWORD ZRESULT;
typedef struct
{
	int index;                 // index of this file within the zip
	char name[MAX_PATH];       // filename within the zip
	DWORD attr;                // attributes, as in GetFileAttributes.
	FILETIME atime,ctime,mtime;// access, create, modify filetimes
	long comp_size;            // sizes of item, compressed and uncompressed. These
	long unc_size;             // may be -1 if not yet known (e.g. being streamed in)
} ZIPENTRY;
typedef struct
{
	int index;                 // index of this file within the zip
	TCHAR name[MAX_PATH];      // filename within the zip
	DWORD attr;                // attributes, as in GetFileAttributes.
	FILETIME atime,ctime,mtime;// access, create, modify filetimes
	long comp_size;            // sizes of item, compressed and uncompressed. These
	long unc_size;             // may be -1 if not yet known (e.g. being streamed in)
} ZIPENTRYW;
#define OpenZip OpenZipU
#define CloseZip(hz) CloseZipU(hz)
extern HZIP OpenZipU(void *z,unsigned int len,DWORD flags);
extern ZRESULT CloseZipU(HZIP hz);
#ifdef _UNICODE
#define ZIPENTRY ZIPENTRYW
#define GetZipItem GetZipItemW
#define FindZipItem FindZipItemW
#else
#define GetZipItem GetZipItemA
#define FindZipItem FindZipItemA
#endif
extern ZRESULT GetZipItemA(HZIP hz, int index, ZIPENTRY *ze);
extern ZRESULT GetZipItemW(HZIP hz, int index, ZIPENTRYW *ze);
extern ZRESULT FindZipItemA(HZIP hz, const TCHAR *name, bool ic, int *index, ZIPENTRY *ze);
extern ZRESULT FindZipItemW(HZIP hz, const TCHAR *name, bool ic, int *index, ZIPENTRYW *ze);
extern ZRESULT UnzipItem(HZIP hz, int index, void *dst, unsigned int len, DWORD flags);
///////////////////////////////////////////////////////////////////////////////////////

namespace DuiLib
{

	CGifAnimUI::CGifAnimUI(void)
	{
		m_pGifImage			=	NULL;
		m_pPropertyItem		=	NULL;
		m_nFrameCount		=	0;
		m_nFramePosition	=	0;
		m_bIsAutoPlay		=	true;
		m_bIsAutoSize		=	false;
		m_bIsPlaying		=	false;

	}

	CGifAnimUI::~CGifAnimUI(void)
	{
		DeleteGif();
		m_pManager->KillTimer( this, EVENT_TIEM_ID );

	}

	LPCTSTR CGifAnimUI::GetClass() const
	{
		return _T("GifAnimUI");
	}

	LPVOID CGifAnimUI::GetInterface( LPCTSTR pstrName )
	{
		if( _tcscmp(pstrName, DUI_CTR_GIFANIM) == 0 ) return static_cast<CGifAnimUI*>(this);
		return CControlUI::GetInterface(pstrName);
	}

	void CGifAnimUI::DoInit()
	{
		InitGifImage();
	}

	void CGifAnimUI::DoPaint(HDC hDC, const RECT& rcPaint, CControlUI* pStopControl)
	{
		if ( NULL == m_pGifImage )
		{
			InitGifImage();
		}
		DrawFrame( hDC );
	}

	void CGifAnimUI::DoEvent( TEventUI& event )
	{
		if( event.Type == UIEVENT_TIMER )
			OnTimer( (UINT_PTR)event.wParam );
	}

	void CGifAnimUI::SetVisible(bool bVisible /* = true */)
	{
		CControlUI::SetVisible(bVisible);
		if (bVisible)
			PlayGif();
		else
			StopGif();
	}

	void CGifAnimUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue)
	{
		if( _tcscmp(pstrName, _T("bkimage")) == 0 ) SetBkImage(pstrValue);
		else if( _tcscmp(pstrName, _T("autoplay")) == 0 ) {
			SetAutoPlay(_tcscmp(pstrValue, _T("true")) == 0);
		}
		else if( _tcscmp(pstrName, _T("autosize")) == 0 ) {
			SetAutoSize(_tcscmp(pstrValue, _T("true")) == 0);
		}
		else
			CControlUI::SetAttribute(pstrName, pstrValue);
	}

	void CGifAnimUI::SetBkImage(LPCTSTR pStrImage)
	{
		if( m_sBkImage == pStrImage || NULL == pStrImage) return;

		m_sBkImage = pStrImage;

		StopGif();
		DeleteGif();

		Invalidate();

	}

	LPCTSTR CGifAnimUI::GetBkImage()
	{
		return m_sBkImage.GetData();
	}

	void CGifAnimUI::SetAutoPlay(bool bIsAuto)
	{
		m_bIsAutoPlay = bIsAuto;
	}

	bool CGifAnimUI::IsAutoPlay() const
	{
		return m_bIsAutoPlay;
	}

	void CGifAnimUI::SetAutoSize(bool bIsAuto)
	{
		m_bIsAutoSize = bIsAuto;
	}

	bool CGifAnimUI::IsAutoSize() const
	{
		return m_bIsAutoSize;
	}

	void CGifAnimUI::PlayGif()
	{
		if (m_bIsPlaying || m_pGifImage == NULL)
		{
			return;
		}

		long lPause = ((long*) m_pPropertyItem->value)[m_nFramePosition] * 10;
		if ( lPause == 0 ) lPause = 100;
		m_pManager->SetTimer( this, EVENT_TIEM_ID, lPause );

		m_bIsPlaying = true;
	}

	void CGifAnimUI::PauseGif()
	{
		if (!m_bIsPlaying || m_pGifImage == NULL)
		{
			return;
		}

		m_pManager->KillTimer(this, EVENT_TIEM_ID);
		this->Invalidate();
		m_bIsPlaying = false;
	}

	void CGifAnimUI::StopGif()
	{
		if (!m_bIsPlaying)
		{
			return;
		}

		m_pManager->KillTimer(this, EVENT_TIEM_ID);
		m_nFramePosition = 0;
		this->Invalidate();
		m_bIsPlaying = false;
	}

	void CGifAnimUI::InitGifImage()
	{
		m_pGifImage = LoadGifFromFile(GetBkImage());
		if ( NULL == m_pGifImage ) return;
		UINT nCount	= 0;
		nCount	=	m_pGifImage->GetFrameDimensionsCount();
		GUID* pDimensionIDs	=	new GUID[ nCount ];
		m_pGifImage->GetFrameDimensionsList( pDimensionIDs, nCount );
		m_nFrameCount	=	m_pGifImage->GetFrameCount( &pDimensionIDs[0] );
		int nSize		=	m_pGifImage->GetPropertyItemSize( PropertyTagFrameDelay );
		m_pPropertyItem	=	(Gdiplus::PropertyItem*) malloc( nSize );
		m_pGifImage->GetPropertyItem( PropertyTagFrameDelay, nSize, m_pPropertyItem );
		delete  pDimensionIDs;
		pDimensionIDs = NULL;

		if (m_bIsAutoSize)
		{
			SetFixedWidth(m_pGifImage->GetWidth());
			SetFixedHeight(m_pGifImage->GetHeight());
		}
		if (m_bIsAutoPlay)
		{
			PlayGif();
		}
	}

	void CGifAnimUI::DeleteGif()
	{
		if ( m_pGifImage != NULL )
		{
			delete m_pGifImage;
			m_pGifImage = NULL;
		}

		if ( m_pPropertyItem != NULL )
		{
			free( m_pPropertyItem );
			m_pPropertyItem = NULL;
		}
		m_nFrameCount		=	0;
		m_nFramePosition	=	0;
	}

	void CGifAnimUI::OnTimer( UINT_PTR idEvent )
	{
		if ( idEvent != EVENT_TIEM_ID )
			return;
		m_pManager->KillTimer( this, EVENT_TIEM_ID );
		this->Invalidate();

		m_nFramePosition = (++m_nFramePosition) % m_nFrameCount;

		long lPause = ((long*) m_pPropertyItem->value)[m_nFramePosition] * 10;
		if ( lPause == 0 ) lPause = 100;
		m_pManager->SetTimer( this, EVENT_TIEM_ID, lPause );
	}

	void CGifAnimUI::DrawFrame( HDC hDC )
	{
		if ( NULL == hDC || NULL == m_pGifImage ) return;
		GUID pageGuid = Gdiplus::FrameDimensionTime;
		Gdiplus::Graphics graphics( hDC );
		graphics.DrawImage( m_pGifImage, m_rcItem.left, m_rcItem.top, m_rcItem.right-m_rcItem.left, m_rcItem.bottom-m_rcItem.top );
		m_pGifImage->SelectActiveFrame( &pageGuid, m_nFramePosition );
	}

	Gdiplus::Image* CGifAnimUI::LoadGifFromFile(LPCTSTR pstrGifPath)
	{
		LPBYTE pData = NULL;
		DWORD dwSize = 0;

		do
		{
			CDuiString sFile = CPaintManagerUI::GetResourcePath();
			if( CPaintManagerUI::GetResourceZip().IsEmpty() ) {
				sFile += pstrGifPath;
				HANDLE hFile = ::CreateFile(sFile.GetData(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, \
					FILE_ATTRIBUTE_NORMAL, NULL);
				if( hFile == INVALID_HANDLE_VALUE ) break;
				dwSize = ::GetFileSize(hFile, NULL);
				if( dwSize == 0 ) break;

				DWORD dwRead = 0;
				pData = new BYTE[ dwSize ];
				::ReadFile( hFile, pData, dwSize, &dwRead, NULL );
				::CloseHandle( hFile );

				if( dwRead != dwSize ) {
					delete[] pData;
					pData = NULL;
					break;
				}
			}
			else {
				sFile += CPaintManagerUI::GetResourceZip();
				HZIP hz = NULL;
				if( CPaintManagerUI::IsCachedResourceZip() ) hz = (HZIP)CPaintManagerUI::GetResourceZipHandle();
				else hz = OpenZip((void*)sFile.GetData(), 0, 2);
				if( hz == NULL ) break;
				ZIPENTRY ze;
				int i;
				if( FindZipItem(hz, pstrGifPath, true, &i, &ze) != 0 ) break;
				dwSize = ze.unc_size;
				if( dwSize == 0 ) break;
				pData = new BYTE[ dwSize ];
				int res = UnzipItem(hz, i, pData, dwSize, 3);
				if( res != 0x00000000 && res != 0x00000600) {
					delete[] pData;
					pData = NULL;
					if( !CPaintManagerUI::IsCachedResourceZip() ) CloseZip(hz);
					break;
				}
				if( !CPaintManagerUI::IsCachedResourceZip() ) CloseZip(hz);
			}

		} while (0);

		while (!pData)
		{
			//ͼƬ, ֱȥȡbitmap.m_lpstrָ·
			HANDLE hFile = ::CreateFile(pstrGifPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, \
				FILE_ATTRIBUTE_NORMAL, NULL);
			if( hFile == INVALID_HANDLE_VALUE ) break;
			dwSize = ::GetFileSize(hFile, NULL);
			if( dwSize == 0 ) break;

			DWORD dwRead = 0;
			pData = new BYTE[ dwSize ];
			::ReadFile( hFile, pData, dwSize, &dwRead, NULL );
			::CloseHandle( hFile );

			if( dwRead != dwSize ) {
				delete[] pData;
				pData = NULL;
			}
			break;
		}
		if (!pData)
		{
			return NULL;
		}

		Gdiplus::Image* pImage = LoadGifFromMemory(pData, dwSize);
		delete pData;
		return pImage;
	}

	Gdiplus::Image* CGifAnimUI::LoadGifFromMemory( LPVOID pBuf,size_t dwSize )
	{
		HGLOBAL hMem = ::GlobalAlloc(GMEM_FIXED, dwSize);
		BYTE* pMem = (BYTE*)::GlobalLock(hMem);

		memcpy(pMem, pBuf, dwSize);

		IStream* pStm = NULL;
		::CreateStreamOnHGlobal(hMem, TRUE, &pStm);
		Gdiplus::Image *pImg = Gdiplus::Image::FromStream(pStm);
		if(!pImg || pImg->GetLastStatus() != Gdiplus::Ok)
		{
			pStm->Release();
			::GlobalUnlock(hMem);
			return 0;
		}
		return pImg;
	}

}<commit_msg>Update UIGifAnim.cpp<commit_after>#include "StdAfx.h"
#include "UIGifAnim.h"

///////////////////////////////////////////////////////////////////////////////////////
DECLARE_HANDLE(HZIP);	// An HZIP identifies a zip file that has been opened
typedef DWORD ZRESULT;
typedef struct
{
	int index;                 // index of this file within the zip
	char name[MAX_PATH];       // filename within the zip
	DWORD attr;                // attributes, as in GetFileAttributes.
	FILETIME atime,ctime,mtime;// access, create, modify filetimes
	long comp_size;            // sizes of item, compressed and uncompressed. These
	long unc_size;             // may be -1 if not yet known (e.g. being streamed in)
} ZIPENTRY;
typedef struct
{
	int index;                 // index of this file within the zip
	TCHAR name[MAX_PATH];      // filename within the zip
	DWORD attr;                // attributes, as in GetFileAttributes.
	FILETIME atime,ctime,mtime;// access, create, modify filetimes
	long comp_size;            // sizes of item, compressed and uncompressed. These
	long unc_size;             // may be -1 if not yet known (e.g. being streamed in)
} ZIPENTRYW;
#define OpenZip OpenZipU
#define CloseZip(hz) CloseZipU(hz)
extern HZIP OpenZipU(void *z,unsigned int len,DWORD flags);
extern ZRESULT CloseZipU(HZIP hz);
#ifdef _UNICODE
#define ZIPENTRY ZIPENTRYW
#define GetZipItem GetZipItemW
#define FindZipItem FindZipItemW
#else
#define GetZipItem GetZipItemA
#define FindZipItem FindZipItemA
#endif
extern ZRESULT GetZipItemA(HZIP hz, int index, ZIPENTRY *ze);
extern ZRESULT GetZipItemW(HZIP hz, int index, ZIPENTRYW *ze);
extern ZRESULT FindZipItemA(HZIP hz, const TCHAR *name, bool ic, int *index, ZIPENTRY *ze);
extern ZRESULT FindZipItemW(HZIP hz, const TCHAR *name, bool ic, int *index, ZIPENTRYW *ze);
extern ZRESULT UnzipItem(HZIP hz, int index, void *dst, unsigned int len, DWORD flags);
///////////////////////////////////////////////////////////////////////////////////////

namespace DuiLib
{

	CGifAnimUI::CGifAnimUI(void)
	{
		m_pGifImage			=	NULL;
		m_pPropertyItem		=	NULL;
		m_nFrameCount		=	0;
		m_nFramePosition	=	0;
		m_bIsAutoPlay		=	true;
		m_bIsAutoSize		=	false;
		m_bIsPlaying		=	false;

	}

	CGifAnimUI::~CGifAnimUI(void)
	{
		DeleteGif();
		m_pManager->KillTimer( this, EVENT_TIEM_ID );

	}

	LPCTSTR CGifAnimUI::GetClass() const
	{
		return _T("GifAnimUI");
	}

	LPVOID CGifAnimUI::GetInterface( LPCTSTR pstrName )
	{
		if( _tcscmp(pstrName, DUI_CTR_GIFANIM) == 0 ) return static_cast<CGifAnimUI*>(this);
		return CControlUI::GetInterface(pstrName);
	}

	void CGifAnimUI::DoInit()
	{
		InitGifImage();
	}

	void CGifAnimUI::DoPaint(HDC hDC, const RECT& rcPaint, CControlUI* pStopControl)
	{
		if ( NULL == m_pGifImage )
		{
			InitGifImage();
		}
		DrawFrame( hDC );
	}

	void CGifAnimUI::DoEvent( TEventUI& event )
	{
		if( event.Type == UIEVENT_TIMER )
			OnTimer( (UINT_PTR)event.wParam );
	}

	void CGifAnimUI::SetVisible(bool bVisible /* = true */)
	{
		CControlUI::SetVisible(bVisible);
		if (bVisible)
			PlayGif();
		else
			StopGif();
	}

	void CGifAnimUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue)
	{
		if( _tcscmp(pstrName, _T("bkimage")) == 0 ) SetBkImage(pstrValue);
		else if( _tcscmp(pstrName, _T("autoplay")) == 0 ) {
			SetAutoPlay(_tcscmp(pstrValue, _T("true")) == 0);
		}
		else if( _tcscmp(pstrName, _T("autosize")) == 0 ) {
			SetAutoSize(_tcscmp(pstrValue, _T("true")) == 0);
		}
		else
			CControlUI::SetAttribute(pstrName, pstrValue);
	}

	void CGifAnimUI::SetBkImage(LPCTSTR pStrImage)
	{
		if( m_sBkImage == pStrImage || NULL == pStrImage) return;

		m_sBkImage = pStrImage;

		StopGif();
		DeleteGif();

		Invalidate();

	}

	LPCTSTR CGifAnimUI::GetBkImage()
	{
		return m_sBkImage.GetData();
	}

	void CGifAnimUI::SetAutoPlay(bool bIsAuto)
	{
		m_bIsAutoPlay = bIsAuto;
	}

	bool CGifAnimUI::IsAutoPlay() const
	{
		return m_bIsAutoPlay;
	}

	void CGifAnimUI::SetAutoSize(bool bIsAuto)
	{
		m_bIsAutoSize = bIsAuto;
	}

	bool CGifAnimUI::IsAutoSize() const
	{
		return m_bIsAutoSize;
	}

	void CGifAnimUI::PlayGif()
	{
		if (m_bIsPlaying || m_pGifImage == NULL)
		{
			return;
		}

		long lPause = ((long*) m_pPropertyItem->value)[m_nFramePosition] * 10;
		if ( lPause == 0 ) lPause = 100;
		m_pManager->SetTimer( this, EVENT_TIEM_ID, lPause );

		m_bIsPlaying = true;
	}

	void CGifAnimUI::PauseGif()
	{
		if (!m_bIsPlaying || m_pGifImage == NULL)
		{
			return;
		}

		m_pManager->KillTimer(this, EVENT_TIEM_ID);
		this->Invalidate();
		m_bIsPlaying = false;
	}

	void CGifAnimUI::StopGif()
	{
		if (!m_bIsPlaying)
		{
			return;
		}

		m_pManager->KillTimer(this, EVENT_TIEM_ID);
		m_nFramePosition = 0;
		this->Invalidate();
		m_bIsPlaying = false;
	}

	void CGifAnimUI::InitGifImage()
	{
		m_pGifImage = LoadGifFromFile(GetBkImage());
		if ( NULL == m_pGifImage ) return;
		UINT nCount	= 0;
		nCount	=	m_pGifImage->GetFrameDimensionsCount();
		GUID* pDimensionIDs	=	new GUID[ nCount ];
		m_pGifImage->GetFrameDimensionsList( pDimensionIDs, nCount );
		m_nFrameCount	=	m_pGifImage->GetFrameCount( &pDimensionIDs[0] );
		int nSize		=	m_pGifImage->GetPropertyItemSize( PropertyTagFrameDelay );
		m_pPropertyItem	=	(Gdiplus::PropertyItem*) malloc( nSize );
		m_pGifImage->GetPropertyItem( PropertyTagFrameDelay, nSize, m_pPropertyItem );
		delete  pDimensionIDs;
		pDimensionIDs = NULL;

		if (m_bIsAutoSize)
		{
			SetFixedWidth(m_pGifImage->GetWidth());
			SetFixedHeight(m_pGifImage->GetHeight());
		}
		if (m_bIsAutoPlay && nSize > 0)
		{
			PlayGif();
		}
	}

	void CGifAnimUI::DeleteGif()
	{
		if ( m_pGifImage != NULL )
		{
			delete m_pGifImage;
			m_pGifImage = NULL;
		}

		if ( m_pPropertyItem != NULL )
		{
			free( m_pPropertyItem );
			m_pPropertyItem = NULL;
		}
		m_nFrameCount		=	0;
		m_nFramePosition	=	0;
	}

	void CGifAnimUI::OnTimer( UINT_PTR idEvent )
	{
		if ( idEvent != EVENT_TIEM_ID )
			return;
		m_pManager->KillTimer( this, EVENT_TIEM_ID );
		this->Invalidate();

		m_nFramePosition = (++m_nFramePosition) % m_nFrameCount;

		long lPause = ((long*) m_pPropertyItem->value)[m_nFramePosition] * 10;
		if ( lPause == 0 ) lPause = 100;
		m_pManager->SetTimer( this, EVENT_TIEM_ID, lPause );
	}

	void CGifAnimUI::DrawFrame( HDC hDC )
	{
		if ( NULL == hDC || NULL == m_pGifImage ) return;
		GUID pageGuid = Gdiplus::FrameDimensionTime;
		Gdiplus::Graphics graphics( hDC );
		graphics.DrawImage( m_pGifImage, m_rcItem.left, m_rcItem.top, m_rcItem.right-m_rcItem.left, m_rcItem.bottom-m_rcItem.top );
		m_pGifImage->SelectActiveFrame( &pageGuid, m_nFramePosition );
	}

	Gdiplus::Image* CGifAnimUI::LoadGifFromFile(LPCTSTR pstrGifPath)
	{
		LPBYTE pData = NULL;
		DWORD dwSize = 0;

		do
		{
			CDuiString sFile = CPaintManagerUI::GetResourcePath();
			if( CPaintManagerUI::GetResourceZip().IsEmpty() ) {
				sFile += pstrGifPath;
				HANDLE hFile = ::CreateFile(sFile.GetData(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, \
					FILE_ATTRIBUTE_NORMAL, NULL);
				if( hFile == INVALID_HANDLE_VALUE ) break;
				dwSize = ::GetFileSize(hFile, NULL);
				if( dwSize == 0 ) break;

				DWORD dwRead = 0;
				pData = new BYTE[ dwSize ];
				::ReadFile( hFile, pData, dwSize, &dwRead, NULL );
				::CloseHandle( hFile );

				if( dwRead != dwSize ) {
					delete[] pData;
					pData = NULL;
					break;
				}
			}
			else {
				sFile += CPaintManagerUI::GetResourceZip();
				HZIP hz = NULL;
				if( CPaintManagerUI::IsCachedResourceZip() ) hz = (HZIP)CPaintManagerUI::GetResourceZipHandle();
				else hz = OpenZip((void*)sFile.GetData(), 0, 2);
				if( hz == NULL ) break;
				ZIPENTRY ze;
				int i;
				if( FindZipItem(hz, pstrGifPath, true, &i, &ze) != 0 ) break;
				dwSize = ze.unc_size;
				if( dwSize == 0 ) break;
				pData = new BYTE[ dwSize ];
				int res = UnzipItem(hz, i, pData, dwSize, 3);
				if( res != 0x00000000 && res != 0x00000600) {
					delete[] pData;
					pData = NULL;
					if( !CPaintManagerUI::IsCachedResourceZip() ) CloseZip(hz);
					break;
				}
				if( !CPaintManagerUI::IsCachedResourceZip() ) CloseZip(hz);
			}

		} while (0);

		while (!pData)
		{
			//读不到图片, 则直接去读取bitmap.m_lpstr指向的路径
			HANDLE hFile = ::CreateFile(pstrGifPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, \
				FILE_ATTRIBUTE_NORMAL, NULL);
			if( hFile == INVALID_HANDLE_VALUE ) break;
			dwSize = ::GetFileSize(hFile, NULL);
			if( dwSize == 0 ) break;

			DWORD dwRead = 0;
			pData = new BYTE[ dwSize ];
			::ReadFile( hFile, pData, dwSize, &dwRead, NULL );
			::CloseHandle( hFile );

			if( dwRead != dwSize ) {
				delete[] pData;
				pData = NULL;
			}
			break;
		}
		if (!pData)
		{
			return NULL;
		}

		Gdiplus::Image* pImage = LoadGifFromMemory(pData, dwSize);
		delete pData;
		return pImage;
	}

	Gdiplus::Image* CGifAnimUI::LoadGifFromMemory( LPVOID pBuf,size_t dwSize )
	{
		HGLOBAL hMem = ::GlobalAlloc(GMEM_FIXED, dwSize);
		BYTE* pMem = (BYTE*)::GlobalLock(hMem);

		memcpy(pMem, pBuf, dwSize);

		IStream* pStm = NULL;
		::CreateStreamOnHGlobal(hMem, TRUE, &pStm);
		Gdiplus::Image *pImg = Gdiplus::Image::FromStream(pStm);
		if(!pImg || pImg->GetLastStatus() != Gdiplus::Ok)
		{
			pStm->Release();
			::GlobalUnlock(hMem);
			return 0;
		}
		return pImg;
	}

}
<|endoftext|>


<commit_before>/*
 *  Software License Agreement (BSD License)
 *
 *  Copyright (c) 2016-2020, Natalnet Laboratory for Perceptual Robotics
 *  All rights reserved.
 *  Redistribution and use in source and binary forms, with or without modification, are permitted provided
 *  that the following conditions are met:
 *
 *  1. Redistributions of source code must retain the above copyright notice, this list of conditions and
 *     the following disclaimer.
 *
 *  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
 *     the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 *  3. Neither the name of the copyright holder 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 HOLDER 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.
 *
 *  Authors:
 *
 *  Bruno Silva
 *  Rodrigo Xavier
 */

#include <cstdio>
#include <pcl/common/io.h>
#include <pcl/common/transforms.h>
#include <pcl/filters/filter.h>
#include <pcl/filters/uniform_sampling.h>
#include <pcl/point_cloud.h>
#include <sstream>

#include <geometry.h>
#include <reconstruction_visualizer.h>

using namespace std;

ReconstructionVisualizer::ReconstructionVisualizer()
{
    // Initialize attributs
    num_clouds_ = 0, num_lines_ = 0, num_ref_frames_ = 0, num_edges_ = 0;
    prev_pos_ = pcl::PointXYZ();
    curr_pos_ = pcl::PointXYZ();

    // Setup PCL visualizer
    viewer_ = PCLVisualizerPtr(new pcl::visualization::PCLVisualizer("3D Reconstruction"));
    viewer_->setBackgroundColor(0.6, 0.6, 0.6);
    viewer_->initCameraParameters();
    viewer_->setSize(640, 480);
    viewer_->setCameraPosition(
        0.5,
        0.5,
        -1.5, // pos
        0.5,
        0.5,
        0.0, // view
        0.0,
        -1.0,
        0.0); // up;
}

ReconstructionVisualizer::ReconstructionVisualizer(const std::string& title)
{
    // Initialize attributs
    num_clouds_ = 0, num_lines_ = 0, num_ref_frames_ = 0, num_edges_ = 0;

    // Setup PCL visualizer
    viewer_ = PCLVisualizerPtr(new pcl::visualization::PCLVisualizer(title));
    viewer_->setBackgroundColor(0.6, 0.6, 0.6);
    viewer_->initCameraParameters();
    viewer_->setSize(640, 480);
    viewer_->setCameraPosition(
        0.5,
        0.5,
        -1.5, // pos
        0.5,
        0.5,
        0.0, // view
        0.0,
        -1.0,
        0.0); // up;
}

void ReconstructionVisualizer::addCameraPath(const Eigen::Affine3f& pose)
{
    // Set camera pose
    curr_pos_.x = pose(0, 3);
    curr_pos_.y = pose(1, 3);
    curr_pos_.z = pose(2, 3);

    stringstream line_name;
    line_name << "line" << num_lines_++;
    viewer_->addLine(prev_pos_, curr_pos_, 1.0, 0.0, 0.0, line_name.str());
    viewer_->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, 5, line_name.str());

    prev_pos_ = curr_pos_;
}

void ReconstructionVisualizer::addReferenceFrame(const Eigen::Affine3f& pose, const std::string& text)
{
    // Add frame
    stringstream frame_name;
    frame_name << "ref" << num_ref_frames_;
    viewer_->addCoordinateSystem(0.2, pose, frame_name.str());
    num_ref_frames_++;
    // Add text
    PointT text_pos;
    text_pos.x = pose(0, 3) + 0.02;
    text_pos.y = pose(1, 3) + 0.05;
    text_pos.z = pose(2, 3);
    frame_name << "_text";
    viewer_->addText3D(text, text_pos, 0.025, 1, 1, 1, frame_name.str());
}

void ReconstructionVisualizer::addKeyFrame(const Keyframe& kf)
{
    stringstream frame_name;
    frame_name << "kf" << kf.idx_;
    viewer_->addCoordinateSystem(0.2, kf.pose_, frame_name.str());
    addQuantizedPointCloud(kf.local_cloud_, 0.01, kf.pose_, frame_name.str() + "_cloud");
    // Add text
    PointT text_pos;
    text_pos.x = kf.pose_(0, 3) + 0.02;
    text_pos.y = kf.pose_(1, 3) + 0.05;
    text_pos.z = kf.pose_(2, 3);
    viewer_->addText3D(frame_name.str(), text_pos, 0.015, 1, 0, 0, frame_name.str() + "_text");
}

void ReconstructionVisualizer::addPointCloud(const pcl::PointCloud<PointT>::Ptr& cloud, const Eigen::Affine3f& pose,
                                             const std::string& cloud_name)
{
    // Create a new point cloud
    pcl::PointCloud<PointT>::Ptr transf_cloud(new pcl::PointCloud<PointT>);

    // Transform point cloud
    pcl::transformPointCloud(*cloud, *transf_cloud, pose);

    string name;
    stringstream cloud_name_ss;
    cloud_name_ss << "cloud" << num_clouds_++;
    if(cloud_name == "")
        name = cloud_name_ss.str();
    else
        name = cloud_name;

    pcl::visualization::PointCloudColorHandlerRGBField<PointT> rgb(transf_cloud);
    if (!viewer_->updatePointCloud<PointT>(transf_cloud, rgb, name))
        viewer_->addPointCloud<PointT>(transf_cloud, rgb, name);

    // pcl::visualization::PointCloudColorHandlerCustom<PointT> blue(curr_cloud, 0, 0, 255);
}

void ReconstructionVisualizer::addQuantizedPointCloud(const pcl::PointCloud<PointT>::Ptr& cloud, const float& radius,
                                                      const Eigen::Affine3f& pose, const std::string& cloud_name)
{
    // Create a new point cloud
    pcl::PointCloud<PointT>::Ptr quant_cloud(new pcl::PointCloud<PointT>);

    // Quantize the point cloud
    pcl::UniformSampling<PointT> uniform_sampling;
    uniform_sampling.setInputCloud(cloud);
    uniform_sampling.setRadiusSearch(radius);
    uniform_sampling.filter(*quant_cloud);
    addPointCloud(quant_cloud, pose, cloud_name);
}

void ReconstructionVisualizer::addEdge(
    const Eigen::Vector3d& vertix_from,
    const Eigen::Vector3d& vertix_to,
    const string& name,
    const Eigen::Vector3f& color)
{
    // Create the "from" and "to" pcl points
    pcl::PointXYZ from_pt(vertix_from(0), vertix_from(1), vertix_from(2));
    pcl::PointXYZ to_pt(vertix_to(0), vertix_to(1), vertix_to(2));

    // Add an arrow that connects from_pt -> to_pt
    viewer_->addArrow(to_pt, from_pt, color(0, 0), color(1, 0), color(2, 0), false, name);

    // Updating the number of edges
    num_edges_++;
}

void ReconstructionVisualizer::viewReferenceFrame(const Eigen::Affine3f& pose, const std::string& text)
{
    viewer_->removeCoordinateSystem(text);
    viewer_->addCoordinateSystem(0.3, pose, text);
    PointT pose_txt;
    pose_txt.x = pose(0, 3) + 0.02;
    pose_txt.y = pose(1, 3) + 0.05;
    pose_txt.z = pose(2, 3);
    stringstream ss;
    ss << text << "_text";
    viewer_->removeText3D(ss.str());
    viewer_->addText3D(text, pose_txt, 0.025, 1, 1, 1, ss.str());
}

void ReconstructionVisualizer::viewPointCloud(const pcl::PointCloud<PointT>::Ptr& cloud, const Eigen::Affine3f& pose)
{
    // Create a new point cloud
    pcl::PointCloud<PointT>::Ptr transf_cloud(new pcl::PointCloud<PointT>);

    // Transform point cloud
    pcl::transformPointCloud(*cloud, *transf_cloud, pose);

    pcl::visualization::PointCloudColorHandlerRGBField<PointT> rgb(transf_cloud);
    // this line triggers a runtime error due to undefined behavior on PCL code
    if (!viewer_->updatePointCloud<PointT>(transf_cloud, rgb, "cloud"))
        viewer_->addPointCloud<PointT>(transf_cloud, rgb, "cloud");
}

void ReconstructionVisualizer::viewQuantizedPointCloud(
    const pcl::PointCloud<PointT>::Ptr& cloud,
    const float& radius,
    const Eigen::Affine3f& pose)
{
    // Create a new point cloud
    pcl::PointCloud<PointT>::Ptr quant_cloud(new pcl::PointCloud<PointT>);

    // Quantize the point cloud
    pcl::UniformSampling<PointT> uniform_sampling;
    uniform_sampling.setInputCloud(cloud);
    uniform_sampling.setRadiusSearch(radius);
    uniform_sampling.filter(*quant_cloud);
    viewPointCloud(quant_cloud, pose);
}

void ReconstructionVisualizer::updateKeyFrame(const Keyframe& kf)
{
    // Grab names of coord. system and point cloud
    stringstream frame_name;
    frame_name << "kf" << kf.idx_;

    MLOG_DEBUG(EventLogger::M_VISUALIZATION, "@ReconstructionVisualizer::updateKeyframe: "
                                             "Updating keyframe %lu\n", kf.idx_);

    // Grab transformation from the original kf pose to its optimized kf pose
    Eigen::Affine3f rel_transf = relativeTransform(kf.pose_, kf.opt_pose_);

    // Update coord. system
    viewer_->updateCoordinateSystemPose(frame_name.str(), rel_transf);

    // Update point cloud
    viewer_->updatePointCloudPose(frame_name.str() + "_cloud", rel_transf);

    // Update text
    PointT text_pos;
    text_pos.x = kf.opt_pose_(0, 3) + 0.02;
    text_pos.y = kf.opt_pose_(1, 3) + 0.05;
    text_pos.z = kf.opt_pose_(2, 3);
    viewer_->removeText3D(frame_name.str() + "_text");
    viewer_->addText3D(frame_name.str(), text_pos, 0.015, 1, 0, 0, frame_name.str() + "_text");
}

void ReconstructionVisualizer::removeEdge(const string& name) { viewer_->removeShape(name); }

void ReconstructionVisualizer::setCameraPosition(const float& pos_x, const float& pos_y, const float& pos_z)
{
    // Given the x y and z, set the camera position
    viewer_->setCameraPosition(
        pos_x,
        pos_y,
        pos_z, // eye
        0.0,
        0.0,
        50.0, // center
        0.0,
        -1.0,
        0.0); // up
}

void ReconstructionVisualizer::spin() { viewer_->spin(); }

void ReconstructionVisualizer::spinOnce() { viewer_->spinOnce(); }

void ReconstructionVisualizer::close() { viewer_->close(); }

void ReconstructionVisualizer::resetVisualizer()
{
    viewer_->removeAllShapes();
    viewer_->removeAllCoordinateSystems();
    viewer_->removeAllPointClouds();
}

void ReconstructionVisualizer::removeAllVertexesAndEdges() { viewer_->removeAllShapes(); }
<commit_msg>Corrected rel. transformation to be applied in the keyframe point cloud.<commit_after>/*
 *  Software License Agreement (BSD License)
 *
 *  Copyright (c) 2016-2020, Natalnet Laboratory for Perceptual Robotics
 *  All rights reserved.
 *  Redistribution and use in source and binary forms, with or without modification, are permitted provided
 *  that the following conditions are met:
 *
 *  1. Redistributions of source code must retain the above copyright notice, this list of conditions and
 *     the following disclaimer.
 *
 *  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
 *     the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 *  3. Neither the name of the copyright holder 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 HOLDER 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.
 *
 *  Authors:
 *
 *  Bruno Silva
 *  Rodrigo Xavier
 */

#include <cstdio>
#include <pcl/common/io.h>
#include <pcl/common/transforms.h>
#include <pcl/filters/filter.h>
#include <pcl/filters/uniform_sampling.h>
#include <pcl/point_cloud.h>
#include <sstream>

#include <geometry.h>
#include <reconstruction_visualizer.h>

using namespace std;

ReconstructionVisualizer::ReconstructionVisualizer()
{
    // Initialize attributs
    num_clouds_ = 0, num_lines_ = 0, num_ref_frames_ = 0, num_edges_ = 0;
    prev_pos_ = pcl::PointXYZ();
    curr_pos_ = pcl::PointXYZ();

    // Setup PCL visualizer
    viewer_ = PCLVisualizerPtr(new pcl::visualization::PCLVisualizer("3D Reconstruction"));
    viewer_->setBackgroundColor(0.6, 0.6, 0.6);
    viewer_->initCameraParameters();
    viewer_->setSize(640, 480);
    viewer_->setCameraPosition(
        0.5,
        0.5,
        -1.5, // pos
        0.5,
        0.5,
        0.0, // view
        0.0,
        -1.0,
        0.0); // up;
}

ReconstructionVisualizer::ReconstructionVisualizer(const std::string& title)
{
    // Initialize attributs
    num_clouds_ = 0, num_lines_ = 0, num_ref_frames_ = 0, num_edges_ = 0;

    // Setup PCL visualizer
    viewer_ = PCLVisualizerPtr(new pcl::visualization::PCLVisualizer(title));
    viewer_->setBackgroundColor(0.6, 0.6, 0.6);
    viewer_->initCameraParameters();
    viewer_->setSize(640, 480);
    viewer_->setCameraPosition(
        0.5,
        0.5,
        -1.5, // pos
        0.5,
        0.5,
        0.0, // view
        0.0,
        -1.0,
        0.0); // up;
}

void ReconstructionVisualizer::addCameraPath(const Eigen::Affine3f& pose)
{
    // Set camera pose
    curr_pos_.x = pose(0, 3);
    curr_pos_.y = pose(1, 3);
    curr_pos_.z = pose(2, 3);

    stringstream line_name;
    line_name << "line" << num_lines_++;
    viewer_->addLine(prev_pos_, curr_pos_, 1.0, 0.0, 0.0, line_name.str());
    viewer_->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, 5, line_name.str());

    prev_pos_ = curr_pos_;
}

void ReconstructionVisualizer::addReferenceFrame(const Eigen::Affine3f& pose, const std::string& text)
{
    // Add frame
    stringstream frame_name;
    frame_name << "ref" << num_ref_frames_;
    viewer_->addCoordinateSystem(0.2, pose, frame_name.str());
    num_ref_frames_++;
    // Add text
    PointT text_pos;
    text_pos.x = pose(0, 3) + 0.02;
    text_pos.y = pose(1, 3) + 0.05;
    text_pos.z = pose(2, 3);
    frame_name << "_text";
    viewer_->addText3D(text, text_pos, 0.025, 1, 1, 1, frame_name.str());
}

void ReconstructionVisualizer::addKeyFrame(const Keyframe& kf)
{
    stringstream frame_name;
    frame_name << "kf" << kf.idx_;
    viewer_->addCoordinateSystem(0.2, kf.pose_, frame_name.str());
    addQuantizedPointCloud(kf.local_cloud_, 0.01, kf.pose_, frame_name.str() + "_cloud");
    // Add text
    PointT text_pos;
    text_pos.x = kf.pose_(0, 3) + 0.02;
    text_pos.y = kf.pose_(1, 3) + 0.05;
    text_pos.z = kf.pose_(2, 3);
    viewer_->addText3D(frame_name.str(), text_pos, 0.015, 1, 0, 0, frame_name.str() + "_text");
}

void ReconstructionVisualizer::addPointCloud(const pcl::PointCloud<PointT>::Ptr& cloud, const Eigen::Affine3f& pose,
                                             const std::string& cloud_name)
{
    // Create a new point cloud
    pcl::PointCloud<PointT>::Ptr transf_cloud(new pcl::PointCloud<PointT>);

    // Transform point cloud
    pcl::transformPointCloud(*cloud, *transf_cloud, pose);

    string name;
    stringstream cloud_name_ss;
    cloud_name_ss << "cloud" << num_clouds_++;
    if(cloud_name == "")
        name = cloud_name_ss.str();
    else
        name = cloud_name;

    pcl::visualization::PointCloudColorHandlerRGBField<PointT> rgb(transf_cloud);
    if (!viewer_->updatePointCloud<PointT>(transf_cloud, rgb, name))
        viewer_->addPointCloud<PointT>(transf_cloud, rgb, name);

    // pcl::visualization::PointCloudColorHandlerCustom<PointT> blue(curr_cloud, 0, 0, 255);
}

void ReconstructionVisualizer::addQuantizedPointCloud(const pcl::PointCloud<PointT>::Ptr& cloud, const float& radius,
                                                      const Eigen::Affine3f& pose, const std::string& cloud_name)
{
    // Create a new point cloud
    pcl::PointCloud<PointT>::Ptr quant_cloud(new pcl::PointCloud<PointT>);

    // Quantize the point cloud
    pcl::UniformSampling<PointT> uniform_sampling;
    uniform_sampling.setInputCloud(cloud);
    uniform_sampling.setRadiusSearch(radius);
    uniform_sampling.filter(*quant_cloud);
    addPointCloud(quant_cloud, pose, cloud_name);
}

void ReconstructionVisualizer::addEdge(
    const Eigen::Vector3d& vertix_from,
    const Eigen::Vector3d& vertix_to,
    const string& name,
    const Eigen::Vector3f& color)
{
    // Create the "from" and "to" pcl points
    pcl::PointXYZ from_pt(vertix_from(0), vertix_from(1), vertix_from(2));
    pcl::PointXYZ to_pt(vertix_to(0), vertix_to(1), vertix_to(2));

    // Add an arrow that connects from_pt -> to_pt
    viewer_->addArrow(to_pt, from_pt, color(0, 0), color(1, 0), color(2, 0), false, name);

    // Updating the number of edges
    num_edges_++;
}

void ReconstructionVisualizer::viewReferenceFrame(const Eigen::Affine3f& pose, const std::string& text)
{
    viewer_->removeCoordinateSystem(text);
    viewer_->addCoordinateSystem(0.3, pose, text);
    PointT pose_txt;
    pose_txt.x = pose(0, 3) + 0.02;
    pose_txt.y = pose(1, 3) + 0.05;
    pose_txt.z = pose(2, 3);
    stringstream ss;
    ss << text << "_text";
    viewer_->removeText3D(ss.str());
    viewer_->addText3D(text, pose_txt, 0.025, 1, 1, 1, ss.str());
}

void ReconstructionVisualizer::viewPointCloud(const pcl::PointCloud<PointT>::Ptr& cloud, const Eigen::Affine3f& pose)
{
    // Create a new point cloud
    pcl::PointCloud<PointT>::Ptr transf_cloud(new pcl::PointCloud<PointT>);

    // Transform point cloud
    pcl::transformPointCloud(*cloud, *transf_cloud, pose);

    pcl::visualization::PointCloudColorHandlerRGBField<PointT> rgb(transf_cloud);
    // this line triggers a runtime error due to undefined behavior on PCL code
    if (!viewer_->updatePointCloud<PointT>(transf_cloud, rgb, "cloud"))
        viewer_->addPointCloud<PointT>(transf_cloud, rgb, "cloud");
}

void ReconstructionVisualizer::viewQuantizedPointCloud(
    const pcl::PointCloud<PointT>::Ptr& cloud,
    const float& radius,
    const Eigen::Affine3f& pose)
{
    // Create a new point cloud
    pcl::PointCloud<PointT>::Ptr quant_cloud(new pcl::PointCloud<PointT>);

    // Quantize the point cloud
    pcl::UniformSampling<PointT> uniform_sampling;
    uniform_sampling.setInputCloud(cloud);
    uniform_sampling.setRadiusSearch(radius);
    uniform_sampling.filter(*quant_cloud);
    viewPointCloud(quant_cloud, pose);
}

void ReconstructionVisualizer::updateKeyFrame(const Keyframe& kf)
{
    // Grab names of coord. system and point cloud
    stringstream frame_name;
    frame_name << "kf" << kf.idx_;

    MLOG_DEBUG(EventLogger::M_VISUALIZATION, "@ReconstructionVisualizer::updateKeyframe: "
                                             "Updating keyframe %lu\n", kf.idx_);

    // Grab transformation from the original kf pose to its optimized kf pose
    // (point transformation and not pose transformation)
    Eigen::Affine3f rel_transf = kf.opt_pose_ * kf.pose_.inverse();

    // Update coord. system
    viewer_->updateCoordinateSystemPose(frame_name.str(), rel_transf);

    // Update point cloud
    viewer_->updatePointCloudPose(frame_name.str() + "_cloud", rel_transf);

    // Update text
    PointT text_pos;
    text_pos.x = kf.opt_pose_(0, 3) + 0.02;
    text_pos.y = kf.opt_pose_(1, 3) + 0.05;
    text_pos.z = kf.opt_pose_(2, 3);
    viewer_->removeText3D(frame_name.str() + "_text");
    viewer_->addText3D(frame_name.str(), text_pos, 0.015, 1, 0, 0, frame_name.str() + "_text");
}

void ReconstructionVisualizer::removeEdge(const string& name) { viewer_->removeShape(name); }

void ReconstructionVisualizer::setCameraPosition(const float& pos_x, const float& pos_y, const float& pos_z)
{
    // Given the x y and z, set the camera position
    viewer_->setCameraPosition(
        pos_x,
        pos_y,
        pos_z, // eye
        0.0,
        0.0,
        50.0, // center
        0.0,
        -1.0,
        0.0); // up
}

void ReconstructionVisualizer::spin() { viewer_->spin(); }

void ReconstructionVisualizer::spinOnce() { viewer_->spinOnce(); }

void ReconstructionVisualizer::close() { viewer_->close(); }

void ReconstructionVisualizer::resetVisualizer()
{
    viewer_->removeAllShapes();
    viewer_->removeAllCoordinateSystems();
    viewer_->removeAllPointClouds();
}

void ReconstructionVisualizer::removeAllVertexesAndEdges() { viewer_->removeAllShapes(); }
<|endoftext|>