<commit_before>/**
 * \file
 * \brief StaticRawFifoQueue class header
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-01-09
 */

#ifndef INCLUDE_DISTORTOS_STATICRAWFIFOQUEUE_HPP_
#define INCLUDE_DISTORTOS_STATICRAWFIFOQUEUE_HPP_

#include "RawFifoQueue.hpp"

namespace distortos
{

/**
 * \brief StaticRawFifoQueue class is a variant of RawFifoQueue that has automatic storage for queue's contents.
 *
 * \param T is the type of data in queue
 * \param QueueSize is the maximum number of elements in queue
 */

template<typename T, size_t QueueSize>
class StaticRawFifoQueue : public RawFifoQueue
{
public:

	/**
	 * \brief StaticRawFifoQueue's constructor
	 */

	explicit StaticRawFifoQueue() :
			RawFifoQueue{storage_}
	{

	}

private:

	/// storage for queue's contents
	std::array<typename std::aligned_storage<sizeof(T), alignof(T)>::type, QueueSize> storage_;
};

/**
 * \brief StaticRawFifoQueueFromSize type alias is a variant of StaticRawFifoQueue which uses size of element (instead
 * of type) as template argument.
 *
 * \param ElementSize is the size of single queue element, bytes
 * \param QueueSize is the maximum number of elements in queue
 */

template<size_t ElementSize, size_t QueueSize>
using StaticRawFifoQueueFromSize =
		StaticRawFifoQueue<typename std::aligned_storage<ElementSize, ElementSize>::type, QueueSize>;

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_STATICRAWFIFOQUEUE_HPP_
<commit_msg>StaticRawFifoQueue: use composition instead of inheritance<commit_after>/**
 * \file
 * \brief StaticRawFifoQueue class header
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-10-15
 */

#ifndef INCLUDE_DISTORTOS_STATICRAWFIFOQUEUE_HPP_
#define INCLUDE_DISTORTOS_STATICRAWFIFOQUEUE_HPP_

#include "RawFifoQueue.hpp"

namespace distortos
{

/**
 * \brief StaticRawFifoQueue class is a wrapper for RawFifoQueue that also provides automatic storage for queue's
 * contents.
 *
 * \note Objects of this class can be safely casted to (const) reference to RawFifoQueue.
 *
 * \param T is the type of data in queue
 * \param QueueSize is the maximum number of elements in queue
 */

template<typename T, size_t QueueSize>
class StaticRawFifoQueue
{
public:

	/**
	 * \brief StaticRawFifoQueue's constructor
	 */

	explicit StaticRawFifoQueue() :
			rawFifoQueue_{storage_}
	{

	}

	/**
	 * \brief conversion to RawFifoQueue&
	 *
	 * \return reference to internal RawFifoQueue object
	 */

	operator RawFifoQueue&()
	{
		return rawFifoQueue_;
	}

	/**
	 * \brief conversion to const RawFifoQueue&
	 *
	 * \return const reference to internal RawFifoQueue object
	 */

	operator const RawFifoQueue&() const
	{
		return rawFifoQueue_;
	}

	/**
	 * \brief Wrapper for RawFifoQueue::pop(void*, size_t)
	 */

	int pop(void* const buffer, const size_t size)
	{
		return rawFifoQueue_.pop(buffer, size);
	}

	/**
	 * \brief Wrapper for RawFifoQueue::pop(T&)
	 */

	template<typename U>
	int pop(U& buffer)
	{
		return rawFifoQueue_.pop(buffer);
	}

	/**
	 * \brief Wrapper for RawFifoQueue::push(const void*, size_t)
	 */

	int push(const void* const data, const size_t size)
	{
		return rawFifoQueue_.push(data, size);
	}

	/**
	 * \brief Wrapper for RawFifoQueue::push(const T&)
	 */

	template<typename U>
	int push(const U& data)
	{
		return rawFifoQueue_.push(data);
	}

	/**
	 * \brief Wrapper for RawFifoQueue::tryPop(void*, size_t)
	 */

	int tryPop(void* const buffer, const size_t size)
	{
		return rawFifoQueue_.tryPop(buffer, size);
	}

	/**
	 * \brief Wrapper for RawFifoQueue::tryPop(T&)
	 */

	template<typename U>
	int tryPop(U& buffer)
	{
		return rawFifoQueue_.tryPop(buffer);
	}

	/**
	 * \brief Wrapper for RawFifoQueue::tryPopFor(std::chrono::duration<Rep, Period>, void*, size_t)
	 */

	template<typename Rep, typename Period>
	int tryPopFor(const std::chrono::duration<Rep, Period> duration, void* const buffer, const size_t size)
	{
		return rawFifoQueue_.tryPopFor(duration, buffer, size);
	}

	/**
	 * \brief Wrapper for RawFifoQueue::tryPopFor(std::chrono::duration<Rep, Period>, T&)
	 */

	template<typename Rep, typename Period, typename U>
	int tryPopFor(const std::chrono::duration<Rep, Period> duration, U& buffer)
	{
		return rawFifoQueue_.tryPopFor(duration, buffer);
	}

	/**
	 * \brief Wrapper for RawFifoQueue::tryPopUntil(std::chrono::time_point<TickClock, Duration>, void*, size_t)
	 */

	template<typename Duration>
	int tryPopUntil(const std::chrono::time_point<TickClock, Duration> timePoint, void* const buffer, const size_t size)
	{
		return rawFifoQueue_.tryPopUntil(timePoint, buffer, size);
	}

	/**
	 * \brief Wrapper for RawFifoQueue::tryPopUntil(std::chrono::time_point<TickClock, Duration>, T&)
	 */

	template<typename Duration, typename U>
	int tryPopUntil(const std::chrono::time_point<TickClock, Duration> timePoint, U& buffer)
	{
		return rawFifoQueue_.tryPopUntil(timePoint, buffer);
	}

	/**
	 * \brief Wrapper for RawFifoQueue::tryPush(const void*, size_t)
	 */

	int tryPush(const void* const data, const size_t size)
	{
		return rawFifoQueue_.tryPush(data, size);
	}

	/**
	 * \brief Wrapper for RawFifoQueue::tryPush(const T&)
	 */

	template<typename U>
	int tryPush(const U& data)
	{
		return rawFifoQueue_.tryPush(data);
	}

	/**
	 * \brief Wrapper for RawFifoQueue::tryPushFor(std::chrono::duration<Rep, Period>, const void*, size_t)
	 */

	template<typename Rep, typename Period>
	int tryPushFor(const std::chrono::duration<Rep, Period> duration, const void* const data, const size_t size)
	{
		return rawFifoQueue_.tryPushFor(duration, data, size);
	}

	/**
	 * \brief Wrapper for RawFifoQueue::tryPushFor(std::chrono::duration<Rep, Period>, const T&)
	 */

	template<typename Rep, typename Period, typename U>
	int tryPushFor(const std::chrono::duration<Rep, Period> duration, const U& data)
	{
		return rawFifoQueue_.tryPushFor(duration, data);
	}

	/**
	 * \brief Wrapper for RawFifoQueue::tryPushUntil(std::chrono::time_point<TickClock, Duration>, const void*, size_t)
	 */

	template<typename Duration>
	int tryPushUntil(const std::chrono::time_point<TickClock, Duration> timePoint, const void* const data,
			const size_t size)
	{
		return rawFifoQueue_.tryPushUntil(timePoint, data, size);
	}

	/**
	 * \brief Wrapper for RawFifoQueue::tryPushUntil(std::chrono::time_point<TickClock, Duration>, const T&)
	 */

	template<typename Duration, typename U>
	int tryPushUntil(const std::chrono::time_point<TickClock, Duration> timePoint, const U& data)
	{
		return rawFifoQueue_.tryPushUntil(timePoint, data);
	}

private:

	/// storage for queue's contents
	std::array<typename std::aligned_storage<sizeof(T), alignof(T)>::type, QueueSize> storage_;

	/// internal RawFifoQueue object
	RawFifoQueue rawFifoQueue_;
};

/**
 * \brief StaticRawFifoQueueFromSize type alias is a variant of StaticRawFifoQueue which uses size of element (instead
 * of type) as template argument.
 *
 * \param ElementSize is the size of single queue element, bytes
 * \param QueueSize is the maximum number of elements in queue
 */

template<size_t ElementSize, size_t QueueSize>
using StaticRawFifoQueueFromSize =
		StaticRawFifoQueue<typename std::aligned_storage<ElementSize, ElementSize>::type, QueueSize>;

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_STATICRAWFIFOQUEUE_HPP_
<|endoftext|>


<commit_before>#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int menu();

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

	if (menu() == 1){
		cout << "prueba1";
	}else if (menu() == 2){
		cout << "prueba2";
	}else if (menu() == 3){
		cout << "prueba3";
	}

	return 0;
}

int menu(){
	int opcion;

	cout << "Programa #1 (16)" << endl
		<< "Porgrama #2 (21)" << endl
		<< "Programa #3(357)" << endl
		<< "Ingrese una opcion: ";
	cin >> opcion;

	return opcion;
}

<commit_msg>haciendo ejercicio numero 16<commit_after>#include <iostream>
#include <cmath>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int menu();
double PowerDigitSum(double, double);

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

	if (menu() == 1){
		double base, expo;
		cout << endl;

		cout << "Ingrese una base: ";
		cin >> base;

		cout << "Ingrese una potencia: ";
		cin >> expo;
		cout << endl;

		PowerDigitSum(base, expo);

	}else if (menu() == 2){
		cout << "prueba2";
	}else if (menu() == 3){
		cout << "prueba3";
	}

	return 0;
}

int menu(){
	int opcion;

	cout << "Programa #1 (16)" << endl
		<< "Porgrama #2 (21)" << endl
		<< "Programa #3(357)" << endl
		<< "Ingrese una opcion: ";
	cin >> opcion;

	return opcion;
}

double PowerDigitSum(double base, double expo){//no esta terminado
	double exponencial = pow(base, expo);

	cout << resultado;

	return resultado;
}

<|endoftext|>


<commit_before><commit_msg>#103861#; use also for the onscreen position the parent position<commit_after><|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS changefileheader (1.2.234); FILE MERGED 2008/04/01 12:38:47 thb 1.2.234.2: #i85898# Stripping all external header guards 2008/03/31 13:58:01 rt 1.2.234.1: #i87441# Change license header to LPGL v3.<commit_after><|endoftext|>


<commit_before><commit_msg>renaissance1: #i107215# Fixed 64bit compilation problem.<commit_after><|endoftext|>


<commit_before>#pragma once
#include "mtao/geometry/prune_vertices.hpp"
#include <map>

namespace mtao { namespace geometry {
    //expects a mtao::vector<mtao::Vector<T,D>>
    template <typename Container
        , typename Vec = typename Container::value_type
        , typename T = typename Vec::Scalar
        , int D = Vec::RowsAtCompileTime
        >
        std::tuple<Container,std::map<size_t,size_t>> prune(const Container& V, T eps = T(1e-8)) {
            Container ret_vec;
            KDTree<T,D> tree;
            std::map<size_t,size_t> remap;
            for(size_t i=0; i<V.size(); ++i) {
                remap[i] = tree.pruning_insertion(V[i],eps);
            }
            return {tree.points(),remap};
        }

}}
<commit_msg>updating for pruning functionality<commit_after>#pragma once
#include "mtao/geometry/prune_vertices.hpp"
#include <map>

namespace mtao { namespace geometry {
    //expects a mtao::vector<mtao::Vector<T,D>>
    template <typename Container
        , typename Vec = typename Container::value_type
        , typename T = typename Vec::Scalar
        , int D = Vec::RowsAtCompileTime
        >
        std::tuple<Container,std::map<size_t,size_t>> prune(const Container& V, T eps = T(1e-8)) {
            using mtao::geometry;
            Container ret_vec;
            KDTree<T,D> tree;
            std::map<size_t,size_t> remap;
            for(size_t i=0; i<V.size(); ++i) {
                remap[i] = tree.pruning_insertion(V[i],eps);
            }
            return {tree.points(),remap};
        }

}}
<|endoftext|>


<commit_before><commit_msg>Add to response md5_content<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2019 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#ifndef TAO_PEGTL_CONTRIB_REP_STRING_HPP
#define TAO_PEGTL_CONTRIB_REP_STRING_HPP

#include <cstddef>

#include "../config.hpp"
#include "../internal/string.hpp"

namespace tao
{
   namespace TAO_PEGTL_NAMESPACE
   {
      namespace internal
      {
         template< std::size_t, typename, char... >
         struct make_rep_string;

         template< char... Ss, char... Cs >
         struct make_rep_string< 0, string< Ss... >, Cs... >
         {
            using type = string< Ss... >;
         };

         template< std::size_t N, char... Ss, char... Cs >
         struct make_rep_string< N, string< Ss... >, Cs... >
            : make_rep_string< N - 1, string< Ss..., Cs... >, Cs... >
         {
         };

      }  // namespace internal

      inline namespace ascii
      {
         template< std::size_t N, char... Cs >
         struct rep_string
            : internal::make_rep_string< N, string<>, Cs... >::type
         {};

      }  // namespace ascii

   }  // namespace TAO_PEGTL_NAMESPACE

}  // namespace tao

#endif
<commit_msg>Add missing qualification<commit_after>// Copyright (c) 2019 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#ifndef TAO_PEGTL_CONTRIB_REP_STRING_HPP
#define TAO_PEGTL_CONTRIB_REP_STRING_HPP

#include <cstddef>

#include "../config.hpp"
#include "../internal/string.hpp"

namespace tao
{
   namespace TAO_PEGTL_NAMESPACE
   {
      namespace internal
      {
         template< std::size_t, typename, char... >
         struct make_rep_string;

         template< char... Ss, char... Cs >
         struct make_rep_string< 0, string< Ss... >, Cs... >
         {
            using type = string< Ss... >;
         };

         template< std::size_t N, char... Ss, char... Cs >
         struct make_rep_string< N, string< Ss... >, Cs... >
            : make_rep_string< N - 1, string< Ss..., Cs... >, Cs... >
         {
         };

      }  // namespace internal

      inline namespace ascii
      {
         template< std::size_t N, char... Cs >
         struct rep_string
            : internal::make_rep_string< N, internal::string<>, Cs... >::type
         {};

      }  // namespace ascii

   }  // namespace TAO_PEGTL_NAMESPACE

}  // namespace tao

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2011-2013 Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#define _GNU_SOURCE

#include <cassert>
#include <cstring>
#include <vector>

#include <dlfcn.h>
#include <signal.h>

#include "os.h"

std::string os::GetModulePathFromAddr(void *address, std::size_t max_length) {
  std::vector<char> name(max_length + 1);
  if (address != 0) {
    Dl_info info;
    dladdr(address, &info);
    strncpy(&name[0], info.dli_fname, max_length);
  }
  return std::string(&name[0]);
}

static os::ExceptionHandler except_handler = 0;
static struct sigaction prev_sigsegv_action;
static __thread bool this_thread_handles_sigsegv;

static void HandleSIGSEGV(int sig, siginfo_t *info, void *context)
{
  if (!::this_thread_handles_sigsegv) {
    return;
  }

  if (::except_handler != 0) {
    ::except_handler(context);
  }

  sigaction(sig, &::prev_sigsegv_action, 0);
  raise(sig);
}

void os::SetExceptionHandler(ExceptionHandler handler) {
  assert(::except_handler == 0 && "Only one thread may set exception handler");

  ::this_thread_handles_sigsegv = true;
  ::except_handler = handler;

  struct sigaction action = {0};
  sigemptyset(&action.sa_mask);
  action.sa_sigaction = HandleSIGSEGV;
  action.sa_flags = SA_SIGINFO;

  sigaction(SIGSEGV, &action, &::prev_sigsegv_action);
}

static os::InterruptHandler interrupt_handler;
static struct sigaction prev_sigint_action;
static __thread bool this_thread_handles_sigint;

static void HandleSIGINT(int sig, siginfo_t *info, void *context) {
  if (!::this_thread_handles_sigint) {
    return;
  }

  if (::interrupt_handler != 0) {
    ::interrupt_handler(context);
  }

  sigaction(sig, &::prev_sigint_action, 0);
  raise(sig);
}

void os::SetInterruptHandler(InterruptHandler handler) {
  assert(::except_handler == 0 && "Only one thread may set interrupt handler");

  ::this_thread_handles_sigint = true;
  ::interrupt_handler = handler;

  struct sigaction action = {0};
  sigemptyset(&action.sa_mask);
  action.sa_sigaction = HandleSIGINT;
  action.sa_flags = SA_SIGINFO;

  sigaction(SIGINT, &action, &::prev_sigint_action);
}
<commit_msg>Fix assert() condition<commit_after>// Copyright (c) 2011-2013 Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#define _GNU_SOURCE

#include <cassert>
#include <cstring>
#include <vector>

#include <dlfcn.h>
#include <signal.h>

#include "os.h"

std::string os::GetModulePathFromAddr(void *address, std::size_t max_length) {
  std::vector<char> name(max_length + 1);
  if (address != 0) {
    Dl_info info;
    dladdr(address, &info);
    strncpy(&name[0], info.dli_fname, max_length);
  }
  return std::string(&name[0]);
}

static os::ExceptionHandler except_handler = 0;
static struct sigaction prev_sigsegv_action;
static __thread bool this_thread_handles_sigsegv;

static void HandleSIGSEGV(int sig, siginfo_t *info, void *context)
{
  if (!::this_thread_handles_sigsegv) {
    return;
  }

  if (::except_handler != 0) {
    ::except_handler(context);
  }

  sigaction(sig, &::prev_sigsegv_action, 0);
  raise(sig);
}

void os::SetExceptionHandler(ExceptionHandler handler) {
  assert(::except_handler == 0 && "Only one thread may set exception handler");

  ::this_thread_handles_sigsegv = true;
  ::except_handler = handler;

  struct sigaction action = {0};
  sigemptyset(&action.sa_mask);
  action.sa_sigaction = HandleSIGSEGV;
  action.sa_flags = SA_SIGINFO;

  sigaction(SIGSEGV, &action, &::prev_sigsegv_action);
}

static os::InterruptHandler interrupt_handler;
static struct sigaction prev_sigint_action;
static __thread bool this_thread_handles_sigint;

static void HandleSIGINT(int sig, siginfo_t *info, void *context) {
  if (!::this_thread_handles_sigint) {
    return;
  }

  if (::interrupt_handler != 0) {
    ::interrupt_handler(context);
  }

  sigaction(sig, &::prev_sigint_action, 0);
  raise(sig);
}

void os::SetInterruptHandler(InterruptHandler handler) {
  assert(::interrupt_handler == 0 && "Only one thread may set interrupt handler");

  ::this_thread_handles_sigint = true;
  ::interrupt_handler = handler;

  struct sigaction action = {0};
  sigemptyset(&action.sa_mask);
  action.sa_sigaction = HandleSIGINT;
  action.sa_flags = SA_SIGINFO;

  sigaction(SIGINT, &action, &::prev_sigint_action);
}
<|endoftext|>


<commit_before><commit_msg>Fix fapi2::current_err bug in checker.H<commit_after><|endoftext|>


<commit_before>#include <windows.h>
#include <screen_capturer.h>
#include <tchar.h>
#include <psapi.h>
#include <iostream>
#include <ostream>
#include <stdio.h>
#include <boost/thread/mutex.hpp>
#include <winuser.h>
#include <wingdi.h>
#include <img_processing.h>
#include <ancillary_functions.h>
#include <gdiplus.h>

struct result_data Screen_Capturer::takeSnapshot(std::string p_name, struct result_data (*foo)(void*, void*), void* arg){
	HWND main_window = retrieveHWND(p_name);
	struct result_data rdt;
	rdt.difference = NULL;
	rdt.threshold = NULL;
	std::cout << "Handle in screen capturer " << main_window << "\n";
	if(main_window == 0){
		std::cout << "Main Window still not found\n";
		return rdt;
	}
	RECT dimensions;
	GetWindowRect(main_window, &dimensions);
	//***********************************************************************************************************************
	//http://stackoverflow.com/questions/7292757/how-to-get-screenshot-of-a-window-as-bitmap-object-in-c : Davide Piras******
	//***********************************************************************************************************************
    HDC hdcScreen = GetDC(NULL);
    //Sets image size
    HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen, dimensions.right - dimensions.left, dimensions.bottom - dimensions.top);
   	HDC pic = CreateCompatibleDC(hdcScreen);
    SelectObject(pic, hbmp);
	if(!PrintWindow(main_window, pic, PW_CLIENTONLY)){
		std::cerr << "\nCouldn't Find Process\n";
		main_window = 0; //if this fails, the process must be closed
		DeleteDC(pic);
		DeleteDC(hdcScreen);
		DeleteObject(hbmp);
		CloseHandle(main_window);
		return rdt;
	}
	rdt = (*foo)(hbmp, arg);
	//***********************************************************************************************************************
	//http://stackoverflow.com/questions/7292757/how-to-get-screenshot-of-a-window-as-bitmap-object-in-c : Davide Piras******
	//***********************************************************************************************************************
    DeleteDC(pic);
    DeleteDC(hdcScreen);
    DeleteObject(hbmp);
	CloseHandle(main_window);
	return rdt;
}

float Screen_Capturer::saveHBITMAP_SC(void* bmp, void* name){
	HBITMAP hbmp = (HBITMAP) bmp;
	const char* rname = (char*) name;
	return saveHBITMAP(hbmp, rname);
}

float Screen_Capturer::compHBITMAP_WSC(void* sc_bmp, void* o_bmp){
	HBITMAP sc_bmp_hb = (HBITMAP) sc_bmp;
	HBITMAP o_bmp_hb = (HBITMAP) o_bmp;
	float result = Img_Processing::compareMemoryImg(sc_bmp_hb, o_bmp_hb);
	return result;
}

struct result_data Screen_Capturer::compHBITMAP_SEL(void* sc_bmp, void* data){
	HBITMAP sc_bmp_hb = (HBITMAP) sc_bmp;
	struct Scaling_Info* scaling = (struct Scaling_Info*) data;
	Gdiplus::Bitmap img1(scaling->pic_data_array->bmp, NULL);
	//std::cout << "Dimensions precrop: " << img1.GetWidth() << "  " << img1.GetHeight() << std::endl;
	return Img_Processing::compareMemoryImgSel(sc_bmp_hb, scaling->pic_data_array->bmp, scaling->pic_data_array->x, scaling->pic_data_array->y, scaling);
}<commit_msg>changed for namespace added methods, fixed memory leaks<commit_after>#include <windows.h>
#include <screen_capturer.h>
#include <tchar.h>
#include <psapi.h>
#include <iostream>
#include <ostream>
#include <stdio.h>
#include <winuser.h>
#include <wingdi.h>
#include <img_processing.h>
//#include <ancillary_functions.h>

using namespace Ancillary_Function;

namespace Screen_Capturer{

	int takeSnapshot(Gdiplus::Bitmap** m, std::string p_name){
		HWND main_window = retrieveHWND(p_name);
		RECT dimensions;
		delete *m; // clear old image

		GetWindowRect(main_window, &dimensions);
		//***********************************************************************************************************************
		//http://stackoverflow.com/questions/7292757/how-to-get-screenshot-of-a-window-as-bitmap-object-in-c : Davide Piras******
		//***********************************************************************************************************************
	    HDC hdcScreen = GetDC(NULL);
	    //Sets image size
	    HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen, dimensions.right - dimensions.left, dimensions.bottom - dimensions.top);
	   	HDC pic = CreateCompatibleDC(hdcScreen);
	    SelectObject(pic, hbmp);
		if(!PrintWindow(main_window, pic, PW_CLIENTONLY)){
			*m = NULL;
			//main_window = 0; //if this fails, the process must be closed
			DeleteDC(pic);
			DeleteDC(hdcScreen);
			DeleteObject(hbmp);
			CloseHandle(main_window);
			return -1;
		}
		//***********************************************************************************************************************
		//http://stackoverflow.com/questions/7292757/how-to-get-screenshot-of-a-window-as-bitmap-object-in-c : Davide Piras******
		//***********************************************************************************************************************
	    *m = Gdiplus::Bitmap::FromHBITMAP(hbmp, NULL);
	    DeleteDC(pic);
	    DeleteDC(hdcScreen);
	    DeleteObject(hbmp);
		if(GetHandleInformation(main_window, NULL)) CloseHandle(main_window);
		return 0;
	}

	result_data takeSnapshot(std::string p_name, struct result_data (*foo)(void*, void*), void* arg){
		HWND main_window = retrieveHWND(p_name);
		struct result_data rdt;
		rdt.difference = NULL;
		rdt.threshold = NULL;
		std::cout << "Handle in screen capturer " << main_window << "\n";
		if(main_window == 0){
			std::cout << "Main Window still not found\n";
			return rdt;
		}
		RECT dimensions;
		GetWindowRect(main_window, &dimensions);
		//***********************************************************************************************************************
		//http://stackoverflow.com/questions/7292757/how-to-get-screenshot-of-a-window-as-bitmap-object-in-c : Davide Piras******
		//***********************************************************************************************************************
	    HDC hdcScreen = GetDC(NULL);
	    //Sets image size
	    HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen, dimensions.right - dimensions.left, dimensions.bottom - dimensions.top);
	   	HDC pic = CreateCompatibleDC(hdcScreen);
	    SelectObject(pic, hbmp);
		if(!PrintWindow(main_window, pic, PW_CLIENTONLY)){
			std::cerr << "\nCouldn't Find Process\n";
			main_window = 0; //if this fails, the process must be closed
			DeleteDC(pic);
			DeleteDC(hdcScreen);
			DeleteObject(hbmp);
			CloseHandle(main_window);
			return rdt;
		}
		rdt = (*foo)(hbmp, arg);
		//***********************************************************************************************************************
		//http://stackoverflow.com/questions/7292757/how-to-get-screenshot-of-a-window-as-bitmap-object-in-c : Davide Piras******
		//***********************************************************************************************************************
	    DeleteDC(pic);
	    DeleteDC(hdcScreen);
	    DeleteObject(hbmp);
		CloseHandle(main_window);
		return rdt;
	}

	float saveHBITMAP_SC(void* bmp, void* name){
		HBITMAP hbmp = (HBITMAP) bmp;
		const char* rname = (char*) name;
		return saveHBITMAP(hbmp, rname);
	}

	float compHBITMAP_WSC(void* sc_bmp, void* o_bmp){
		HBITMAP sc_bmp_hb = (HBITMAP) sc_bmp;
		HBITMAP o_bmp_hb = (HBITMAP) o_bmp;
		float result = Img_Processing::compareMemoryImg(sc_bmp_hb, o_bmp_hb);
		return result;
	}

	result_data compHBITMAP_SEL(void* sc_bmp, void* data){
		HBITMAP sc_bmp_hb = (HBITMAP) sc_bmp;
		struct Scaling_Info* scaling = (struct Scaling_Info*) data;
		Gdiplus::Bitmap img1(scaling->pic_data_array->bmp, NULL);
		//std::cout << "Dimensions precrop: " << img1.GetWidth() << "  " << img1.GetHeight() << std::endl;
		return Img_Processing::compareMemoryImgSel(sc_bmp_hb, scaling->pic_data_array->bmp, scaling->pic_data_array->x, scaling->pic_data_array->y, scaling);
	}
}<|endoftext|>


<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/browser/xwalk_browser_main_parts_android.h"

#include "base/android/path_utils.h"
#include "base/base_paths_android.h"
#include "base/files/file_path.h"
#include "base/file_util.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/sys_info.h"
#include "base/threading/sequenced_worker_pool.h"
#include "cc/base/switches.h"
#include "content/public/browser/android/compositor.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_store_factory.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/result_codes.h"
#include "grit/net_resources.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/network_change_notifier.h"
#include "net/base/net_module.h"
#include "net/base/net_util.h"
#include "ui/base/layout.h"
#include "ui/base/l10n/l10n_util_android.h"
#include "ui/base/resource/resource_bundle.h"
#include "xwalk/extensions/browser/xwalk_extension_service.h"
#include "xwalk/extensions/common/xwalk_extension.h"
#include "xwalk/extensions/common/xwalk_extension_switches.h"
#include "xwalk/runtime/browser/android/cookie_manager.h"
#include "xwalk/runtime/browser/runtime_context.h"
#include "xwalk/runtime/browser/xwalk_runner.h"
#include "xwalk/runtime/common/xwalk_runtime_features.h"

namespace {

base::StringPiece PlatformResourceProvider(int key) {
  if (key == IDR_DIR_HEADER_HTML) {
    base::StringPiece html_data =
        ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
            IDR_DIR_HEADER_HTML);
    return html_data;
  }
  return base::StringPiece();
}

}  // namespace

namespace xwalk {

using content::BrowserThread;
using extensions::XWalkExtension;

XWalkBrowserMainPartsAndroid::XWalkBrowserMainPartsAndroid(
    const content::MainFunctionParams& parameters)
    : XWalkBrowserMainParts(parameters) {
}

XWalkBrowserMainPartsAndroid::~XWalkBrowserMainPartsAndroid() {
}

void XWalkBrowserMainPartsAndroid::PreEarlyInitialization() {
  net::NetworkChangeNotifier::SetFactory(
      new net::NetworkChangeNotifierFactoryAndroid());

  CommandLine::ForCurrentProcess()->AppendSwitch(
      cc::switches::kCompositeToMailbox);

  // Initialize the Compositor.
  content::Compositor::Initialize();

  XWalkBrowserMainParts::PreEarlyInitialization();
}

void XWalkBrowserMainPartsAndroid::PreMainMessageLoopStart() {
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  // Disable ExtensionProcess for Android.
  // External extensions will run in the BrowserProcess (in process mode).
  command_line->AppendSwitch(switches::kXWalkDisableExtensionProcess);

  // Enable WebGL for Android.
  command_line->AppendSwitch(switches::kIgnoreGpuBlacklist);

  // Disable HW encoding/decoding acceleration for WebRTC on Android.
  // FIXME: Remove these switches for Android when Android OS is removed from
  // GPU accelerated_video_decode blacklist or we stop ignoring the GPU
  // blacklist.
  command_line->AppendSwitch(switches::kDisableWebRtcHWDecoding);
  command_line->AppendSwitch(switches::kDisableWebRtcHWEncoding);

  if (!command_line->HasSwitch(cc::switches::kNumRasterThreads)) {
    // Enable multiple threads for rasterization to take advantage of multi CPU
    // cores. Only valid when ImplSidePainting is enabled.
    const int num_of_cpu_cores = base::SysInfo::NumberOfProcessors();
    command_line->AppendSwitchASCII(cc::switches::kNumRasterThreads,
                                    base::IntToString(num_of_cpu_cores));
  }

  XWalkBrowserMainParts::PreMainMessageLoopStart();

  startup_url_ = GURL();
}

void XWalkBrowserMainPartsAndroid::PostMainMessageLoopStart() {
  base::MessageLoopForUI::current()->Start();
}

void XWalkBrowserMainPartsAndroid::PreMainMessageLoopRun() {
  net::NetModule::SetResourceProvider(PlatformResourceProvider);
  if (parameters_.ui_task) {
    parameters_.ui_task->Run();
    delete parameters_.ui_task;
    run_default_message_loop_ = false;
  }

  xwalk_runner_->PreMainMessageLoopRun();

  runtime_context_ = xwalk_runner_->runtime_context();
  extension_service_ = xwalk_runner_->extension_service();

  // Prepare the cookie store.
  base::FilePath user_data_dir;
  if (!PathService::Get(base::DIR_ANDROID_APP_DATA, &user_data_dir)) {
    NOTREACHED() << "Failed to get app data directory for Crosswalk";
  }

  base::FilePath cookie_store_path = user_data_dir.Append(
      FILE_PATH_LITERAL("Cookies"));
  scoped_refptr<base::SequencedTaskRunner> background_task_runner =
      BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
          BrowserThread::GetBlockingPool()->GetSequenceToken());

  cookie_store_ = content::CreatePersistentCookieStore(
      cookie_store_path,
      true,
      NULL,
      NULL,
      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO),
      background_task_runner);

  cookie_store_->GetCookieMonster()->SetPersistSessionCookies(true);
  SetCookieMonsterOnNetworkStackInit(cookie_store_->GetCookieMonster());
}

void XWalkBrowserMainPartsAndroid::PostMainMessageLoopRun() {
  XWalkBrowserMainParts::PostMainMessageLoopRun();

  base::MessageLoopForUI::current()->Start();
}

void XWalkBrowserMainPartsAndroid::CreateInternalExtensionsForExtensionThread(
    content::RenderProcessHost* host,
    extensions::XWalkExtensionVector* extensions) {
  // On Android part, the ownership of each extension object will be transferred
  // to XWalkExtensionServer after this method is called. It is a rule enforced
  // by extension system that XWalkExtensionServer must own the extension
  // objects and extension instances.
  extensions::XWalkExtensionVector::const_iterator it = extensions_.begin();
  for (; it != extensions_.end(); ++it)
    extensions->push_back(*it);
}

void XWalkBrowserMainPartsAndroid::RegisterExtension(
    scoped_ptr<XWalkExtension> extension) {
  // Since the creation of extension object is driven by Java side, and each
  // Java extension is backed by a native extension object. However, the Java
  // object may be destroyed by Android lifecycle management without destroying
  // the native side object. We keep the reference to native extension object
  // to make sure we can reuse the native object if Java extension is re-created
  // on resuming.
  extensions_.push_back(extension.release());
}

XWalkExtension* XWalkBrowserMainPartsAndroid::LookupExtension(
    const std::string& name) {
  extensions::XWalkExtensionVector::const_iterator it = extensions_.begin();
  for (; it != extensions_.end(); ++it) {
    XWalkExtension* extension = *it;
    if (name == extension->name()) return extension;
  }

  return NULL;
}

}  // namespace xwalk
<commit_msg>[Android] Only force enabling WebGL for Android on IA.<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/browser/xwalk_browser_main_parts_android.h"

#include "base/android/path_utils.h"
#include "base/base_paths_android.h"
#include "base/files/file_path.h"
#include "base/file_util.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/sys_info.h"
#include "base/threading/sequenced_worker_pool.h"
#include "cc/base/switches.h"
#include "content/public/browser/android/compositor.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_store_factory.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/result_codes.h"
#include "grit/net_resources.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/network_change_notifier.h"
#include "net/base/net_module.h"
#include "net/base/net_util.h"
#include "ui/base/layout.h"
#include "ui/base/l10n/l10n_util_android.h"
#include "ui/base/resource/resource_bundle.h"
#include "xwalk/extensions/browser/xwalk_extension_service.h"
#include "xwalk/extensions/common/xwalk_extension.h"
#include "xwalk/extensions/common/xwalk_extension_switches.h"
#include "xwalk/runtime/browser/android/cookie_manager.h"
#include "xwalk/runtime/browser/runtime_context.h"
#include "xwalk/runtime/browser/xwalk_runner.h"
#include "xwalk/runtime/common/xwalk_runtime_features.h"

namespace {

base::StringPiece PlatformResourceProvider(int key) {
  if (key == IDR_DIR_HEADER_HTML) {
    base::StringPiece html_data =
        ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
            IDR_DIR_HEADER_HTML);
    return html_data;
  }
  return base::StringPiece();
}

}  // namespace

namespace xwalk {

using content::BrowserThread;
using extensions::XWalkExtension;

XWalkBrowserMainPartsAndroid::XWalkBrowserMainPartsAndroid(
    const content::MainFunctionParams& parameters)
    : XWalkBrowserMainParts(parameters) {
}

XWalkBrowserMainPartsAndroid::~XWalkBrowserMainPartsAndroid() {
}

void XWalkBrowserMainPartsAndroid::PreEarlyInitialization() {
  net::NetworkChangeNotifier::SetFactory(
      new net::NetworkChangeNotifierFactoryAndroid());

  CommandLine::ForCurrentProcess()->AppendSwitch(
      cc::switches::kCompositeToMailbox);

  // Initialize the Compositor.
  content::Compositor::Initialize();

  XWalkBrowserMainParts::PreEarlyInitialization();
}

void XWalkBrowserMainPartsAndroid::PreMainMessageLoopStart() {
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  // Disable ExtensionProcess for Android.
  // External extensions will run in the BrowserProcess (in process mode).
  command_line->AppendSwitch(switches::kXWalkDisableExtensionProcess);

  // Only force to enable WebGL for Android for IA platforms because
  // we've tested the WebGL conformance test. For other platforms, just
  // follow up the behavior defined by Chromium upstream.
#if defined(ARCH_CPU_X86)
  command_line->AppendSwitch(switches::kIgnoreGpuBlacklist);
#endif

  // Disable HW encoding/decoding acceleration for WebRTC on Android.
  // FIXME: Remove these switches for Android when Android OS is removed from
  // GPU accelerated_video_decode blacklist or we stop ignoring the GPU
  // blacklist.
  command_line->AppendSwitch(switches::kDisableWebRtcHWDecoding);
  command_line->AppendSwitch(switches::kDisableWebRtcHWEncoding);

  if (!command_line->HasSwitch(cc::switches::kNumRasterThreads)) {
    // Enable multiple threads for rasterization to take advantage of multi CPU
    // cores. Only valid when ImplSidePainting is enabled.
    const int num_of_cpu_cores = base::SysInfo::NumberOfProcessors();
    command_line->AppendSwitchASCII(cc::switches::kNumRasterThreads,
                                    base::IntToString(num_of_cpu_cores));
  }

  XWalkBrowserMainParts::PreMainMessageLoopStart();

  startup_url_ = GURL();
}

void XWalkBrowserMainPartsAndroid::PostMainMessageLoopStart() {
  base::MessageLoopForUI::current()->Start();
}

void XWalkBrowserMainPartsAndroid::PreMainMessageLoopRun() {
  net::NetModule::SetResourceProvider(PlatformResourceProvider);
  if (parameters_.ui_task) {
    parameters_.ui_task->Run();
    delete parameters_.ui_task;
    run_default_message_loop_ = false;
  }

  xwalk_runner_->PreMainMessageLoopRun();

  runtime_context_ = xwalk_runner_->runtime_context();
  extension_service_ = xwalk_runner_->extension_service();

  // Prepare the cookie store.
  base::FilePath user_data_dir;
  if (!PathService::Get(base::DIR_ANDROID_APP_DATA, &user_data_dir)) {
    NOTREACHED() << "Failed to get app data directory for Crosswalk";
  }

  base::FilePath cookie_store_path = user_data_dir.Append(
      FILE_PATH_LITERAL("Cookies"));
  scoped_refptr<base::SequencedTaskRunner> background_task_runner =
      BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
          BrowserThread::GetBlockingPool()->GetSequenceToken());

  cookie_store_ = content::CreatePersistentCookieStore(
      cookie_store_path,
      true,
      NULL,
      NULL,
      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO),
      background_task_runner);

  cookie_store_->GetCookieMonster()->SetPersistSessionCookies(true);
  SetCookieMonsterOnNetworkStackInit(cookie_store_->GetCookieMonster());
}

void XWalkBrowserMainPartsAndroid::PostMainMessageLoopRun() {
  XWalkBrowserMainParts::PostMainMessageLoopRun();

  base::MessageLoopForUI::current()->Start();
}

void XWalkBrowserMainPartsAndroid::CreateInternalExtensionsForExtensionThread(
    content::RenderProcessHost* host,
    extensions::XWalkExtensionVector* extensions) {
  // On Android part, the ownership of each extension object will be transferred
  // to XWalkExtensionServer after this method is called. It is a rule enforced
  // by extension system that XWalkExtensionServer must own the extension
  // objects and extension instances.
  extensions::XWalkExtensionVector::const_iterator it = extensions_.begin();
  for (; it != extensions_.end(); ++it)
    extensions->push_back(*it);
}

void XWalkBrowserMainPartsAndroid::RegisterExtension(
    scoped_ptr<XWalkExtension> extension) {
  // Since the creation of extension object is driven by Java side, and each
  // Java extension is backed by a native extension object. However, the Java
  // object may be destroyed by Android lifecycle management without destroying
  // the native side object. We keep the reference to native extension object
  // to make sure we can reuse the native object if Java extension is re-created
  // on resuming.
  extensions_.push_back(extension.release());
}

XWalkExtension* XWalkBrowserMainPartsAndroid::LookupExtension(
    const std::string& name) {
  extensions::XWalkExtensionVector::const_iterator it = extensions_.begin();
  for (; it != extensions_.end(); ++it) {
    XWalkExtension* extension = *it;
    if (name == extension->name()) return extension;
  }

  return NULL;
}

}  // namespace xwalk
<|endoftext|>


<commit_before>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string>
#include <cctype>

#include "list.hxx"
#include "../interp.hxx"
#include "../command.hxx"
#include "../argument.hxx"
#include "../function.hxx"
#include "../common.hxx"
#include "default_tokeniser.hxx"

using namespace std;

namespace tglng {
  bool list::escape(wstring* out, const wstring* in,
                    Interpreter& interp, unsigned) {
    wstring str(in[0]);

    //See what characters of concern are present
    bool
      hasSpace = false,
      hasParen = false,
      hasBrack = false,
      hasBrace = false,
      hasSlash = false;
    for (unsigned i = 0; i < str.size(); ++i) {
      hasSpace |= iswspace(str[i]);
      hasParen |= str[i] == L'(' || str[i] == L')';
      hasBrack |= str[i] == L'[' || str[i] == L']';
      hasBrace |= str[i] == L'{' || str[i] == L'}';
      hasSlash |= str[i] == L'\\';
    }

    /* The string must be enclosed in a parenthesis-like pair only if it
     * contains spaces or any other parentheses.
     * Try to use a paren which is not present in the string. If all types are
     * used, use braces and escape the others.
     */
    bool escapeBraces = hasParen && hasBrack && hasBrace;

    //Escape backslashes, and braces if needed
    if (hasSlash || escapeBraces) {
      for (unsigned i = 0; i < str.size(); ++i) {
        if (str[i] == L'\\')
          str.insert(i++, 1, L'\\');
        else if ((str[i] == L'{' || str[i] == L'}') &&
                 escapeBraces)
          str.insert(i++, 1, L'\\');
      }
    }

    if (hasSpace || hasParen || hasBrack || hasBrace) {
      if (!hasParen)
        str = L'(' + str + L')';
      else if (!hasBrack)
        str = L'[' + str + L']';
      else
        str = L'{' + str + L'}';
    }

    out[0] = str;
    return true;
  }

  bool list::append(wstring* out, const wstring* in,
                    Interpreter& interp, unsigned) {
    if (!escape(out, in+1, interp, 0)) return false;
    if (!in[0].empty())
      out[0] = in[0] + L' ' + out[0];
    return true;
  }

  bool list::car(wstring* out, const wstring* in,
                 Interpreter& interp, unsigned silent) {
    wstring preout[2], prein[2];
    prein[0] = in[0];
    prein[1] = L"e";
    if (!defaultTokeniserPreprocessor(preout, prein,
                                      interp, 0))
      return false;

    if (preout[0].empty()) {
      if (!silent)
        wcerr << L"tglng: error: list-car: empty list" << endl;
      return false;
    }

    prein[0] = preout[0];
    return defaultTokeniser(out, prein, interp, 0);
  }

  bool list::map(wstring* out, const wstring* in,
                 Interpreter& interp, unsigned) {
    Function fun;
    if (!Function::get(fun, interp,
                       in[0], 1, 1))
      return false;

    out[0].clear();

    wstring carout[2];
    wstring remainder(in[1]);
    while (car(carout, &remainder, interp, 1)) {
      wstring appin[2];
      if (!fun.exec(appin+1, carout, interp, fun.parm))
        return false;

      appin[0] = out[0];
      remainder = carout[1];
      if (!append(out, appin, interp, 0))
        return false;
    }

    return true;
  }

  bool list::fold(wstring* out, const wstring* in,
                  Interpreter& interp, unsigned) {
    Function fun;
    if (!Function::get(fun, interp,
                       in[0], 1, 2))
      return false;

    out[0] = in[2];

    wstring carout[2];
    wstring remainder(in[1]);
    while (car(carout, &remainder, interp, 1)) {
      wstring funin[2];
      funin[0] = carout[0];
      funin[1] = out[0];
      if (!fun.exec(out, funin, interp, fun.parm))
        return false;

      remainder = carout[1];
    }

    return true;
  }

  bool list::filter(wstring* out, const wstring* in,
                    Interpreter& interp, unsigned) {
    Function fun;
    if (!Function::get(fun, interp,
                       in[0], 1, 1))
      return false;

    out[0].clear();
    wstring carout[2];
    wstring remainder(in[1]);
    while (car(carout, &remainder, interp, 1)) {
      wstring appin[2];
      if (!fun.exec(appin+1, carout, interp, fun.parm))
        return false;

      if (parseBool(appin[1])) {
        appin[1] = carout[0];
        appin[0] = out[0];
        if (!append(out, appin, interp, 0))
          return false;
      }

      remainder = carout[1];
    }

    return true;
  }

  static GlobalBinding<TFunctionParser<1,1,list::escape> >
  _listEscape(L"list-escape");
  static GlobalBinding<TFunctionParser<1,2,list::append> >
  _listAppend(L"list-append");
  static GlobalBinding<TFunctionParser<1,2,list::map> >
  _listMap(L"list-map");
  static GlobalBinding<TFunctionParser<1,3,list::fold> >
  _listFold(L"list-fold");
  static GlobalBinding<TFunctionParser<1,2,list::filter> >
  _listFilter(L"list-filter");
}
<commit_msg>Add missing binding to list-car.<commit_after>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string>
#include <cctype>

#include "list.hxx"
#include "../interp.hxx"
#include "../command.hxx"
#include "../argument.hxx"
#include "../function.hxx"
#include "../common.hxx"
#include "default_tokeniser.hxx"

using namespace std;

namespace tglng {
  bool list::escape(wstring* out, const wstring* in,
                    Interpreter& interp, unsigned) {
    wstring str(in[0]);

    //See what characters of concern are present
    bool
      hasSpace = false,
      hasParen = false,
      hasBrack = false,
      hasBrace = false,
      hasSlash = false;
    for (unsigned i = 0; i < str.size(); ++i) {
      hasSpace |= iswspace(str[i]);
      hasParen |= str[i] == L'(' || str[i] == L')';
      hasBrack |= str[i] == L'[' || str[i] == L']';
      hasBrace |= str[i] == L'{' || str[i] == L'}';
      hasSlash |= str[i] == L'\\';
    }

    /* The string must be enclosed in a parenthesis-like pair only if it
     * contains spaces or any other parentheses.
     * Try to use a paren which is not present in the string. If all types are
     * used, use braces and escape the others.
     */
    bool escapeBraces = hasParen && hasBrack && hasBrace;

    //Escape backslashes, and braces if needed
    if (hasSlash || escapeBraces) {
      for (unsigned i = 0; i < str.size(); ++i) {
        if (str[i] == L'\\')
          str.insert(i++, 1, L'\\');
        else if ((str[i] == L'{' || str[i] == L'}') &&
                 escapeBraces)
          str.insert(i++, 1, L'\\');
      }
    }

    if (hasSpace || hasParen || hasBrack || hasBrace) {
      if (!hasParen)
        str = L'(' + str + L')';
      else if (!hasBrack)
        str = L'[' + str + L']';
      else
        str = L'{' + str + L'}';
    }

    out[0] = str;
    return true;
  }

  bool list::append(wstring* out, const wstring* in,
                    Interpreter& interp, unsigned) {
    if (!escape(out, in+1, interp, 0)) return false;
    if (!in[0].empty())
      out[0] = in[0] + L' ' + out[0];
    return true;
  }

  bool list::car(wstring* out, const wstring* in,
                 Interpreter& interp, unsigned silent) {
    wstring preout[2], prein[2];
    prein[0] = in[0];
    prein[1] = L"e";
    if (!defaultTokeniserPreprocessor(preout, prein,
                                      interp, 0))
      return false;

    if (preout[0].empty()) {
      if (!silent)
        wcerr << L"tglng: error: list-car: empty list" << endl;
      return false;
    }

    prein[0] = preout[0];
    return defaultTokeniser(out, prein, interp, 0);
  }

  bool list::map(wstring* out, const wstring* in,
                 Interpreter& interp, unsigned) {
    Function fun;
    if (!Function::get(fun, interp,
                       in[0], 1, 1))
      return false;

    out[0].clear();

    wstring carout[2];
    wstring remainder(in[1]);
    while (car(carout, &remainder, interp, 1)) {
      wstring appin[2];
      if (!fun.exec(appin+1, carout, interp, fun.parm))
        return false;

      appin[0] = out[0];
      remainder = carout[1];
      if (!append(out, appin, interp, 0))
        return false;
    }

    return true;
  }

  bool list::fold(wstring* out, const wstring* in,
                  Interpreter& interp, unsigned) {
    Function fun;
    if (!Function::get(fun, interp,
                       in[0], 1, 2))
      return false;

    out[0] = in[2];

    wstring carout[2];
    wstring remainder(in[1]);
    while (car(carout, &remainder, interp, 1)) {
      wstring funin[2];
      funin[0] = carout[0];
      funin[1] = out[0];
      if (!fun.exec(out, funin, interp, fun.parm))
        return false;

      remainder = carout[1];
    }

    return true;
  }

  bool list::filter(wstring* out, const wstring* in,
                    Interpreter& interp, unsigned) {
    Function fun;
    if (!Function::get(fun, interp,
                       in[0], 1, 1))
      return false;

    out[0].clear();
    wstring carout[2];
    wstring remainder(in[1]);
    while (car(carout, &remainder, interp, 1)) {
      wstring appin[2];
      if (!fun.exec(appin+1, carout, interp, fun.parm))
        return false;

      if (parseBool(appin[1])) {
        appin[1] = carout[0];
        appin[0] = out[0];
        if (!append(out, appin, interp, 0))
          return false;
      }

      remainder = carout[1];
    }

    return true;
  }

  static GlobalBinding<TFunctionParser<2,1,list::car> >
  _listCar(L"list-car");
  static GlobalBinding<TFunctionParser<1,1,list::escape> >
  _listEscape(L"list-escape");
  static GlobalBinding<TFunctionParser<1,2,list::append> >
  _listAppend(L"list-append");
  static GlobalBinding<TFunctionParser<1,2,list::map> >
  _listMap(L"list-map");
  static GlobalBinding<TFunctionParser<1,3,list::fold> >
  _listFold(L"list-fold");
  static GlobalBinding<TFunctionParser<1,2,list::filter> >
  _listFilter(L"list-filter");
}
<|endoftext|>


<commit_before>/*
   Copyright (c) 2010, The Mineserver Project
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
 * Neither the name of the The Mineserver Project 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 BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <deque>
#include <fstream>
#include <vector>
#include <ctime>
#include <math.h>
#ifdef WIN32
  #include <winsock2.h>
#else
  #include <netinet/in.h>
  #include <string.h>
#endif

#include "logger.h"
#include "constants.h"

#include "tools.h"
#include "map.h"
#include "user.h"
#include "chat.h"
#include "config.h"
#include "physics.h"

namespace
{

void reportError(User *user, std::string message)
{
  Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "Error! " + COLOR_RED + message, Chat::USER);
}

void playerList(User *user, std::string command, std::deque<std::string> args)
{
  Chat::get().sendUserlist(user);
}

void about(User *user, std::string command, std::deque<std::string> args)
{
  Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + Conf::get().sValue("servername")+
                      "Running Mineserver v." + VERSION, Chat::USER);
}

// TODO: Check if rulesfile exists
void rules(User *user, std::string command, std::deque<std::string> args)
{
  User *tUser = user;
  if(!args.empty() && user->admin)
    tUser = getUserByNick(args[0]);
  if(tUser != NULL)
  {
    // Send rules
    std::ifstream ifs( RULESFILE.c_str());
    std::string temp;

    if(ifs.fail())
    {
      std::cout << "> Warning: " << RULESFILE << " not found." << std::endl;
      return;
    }
    else
    {
      while(getline(ifs, temp))
      {
        // If not a comment
        if(temp.empty() || temp[0] == COMMENTPREFIX)
          Chat::get().sendMsg(tUser, temp, Chat::USER);
      }
      ifs.close();
    }
  }
  else
    reportError(user, "User " + args[0] + " not found (see /players)");
}

void home(User *user, std::string command, std::deque<std::string> args)
{
  Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "Teleported you home!", Chat::USER);
  user->teleport(Map::get().spawnPos.x(), Map::get().spawnPos.y() + 2, Map::get().spawnPos.z());
}

void kit(User *user, std::string command, std::deque<std::string> args)
{
  if(!args.empty())
  {
    std::vector<int> kitItems = Conf::get().vValue("kit_" + args[0]);
    // If kit is found
    if(!kitItems.empty())
    {
      for(std::vector<int>::iterator iter = kitItems.begin(), end = kitItems.end();
          iter != end;
          ++iter)
      {
        spawnedItem item;
        item.EID     = generateEID();
        item.item    = *iter;
        item.count   = 1;
        item.health=0;
        item.pos.x() = static_cast<int>(user->pos.x*32 + (rand() % 30));
        item.pos.y() = static_cast<int>(user->pos.y*32);
        item.pos.z() = static_cast<int>(user->pos.z*32 + (rand() % 30));
        Map::get().sendPickupSpawn(item);
        kitItems.pop_back();
      }
    }
    else
      reportError(user, "Kit " + args[0] + " not found");
  }
}

void saveMap(User *user, std::string command, std::deque<std::string> args)
{
  Map::get().saveWholeMap();
  Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "SERVER:" + COLOR_RED + " Saved map to disc",
                      Chat::USER);
}

void kick(User *user, std::string command, std::deque<std::string> args)
{
  if(!args.empty())
  {
    std::string victim = args[0];

    User *tUser        = getUserByNick(victim);

    if(tUser != NULL)
    {
      args.pop_front();
      std::string kickMsg;
      if(args.empty())
        kickMsg = Conf::get().sValue("default_kick_message");
      else
      {
        while(!args.empty())
        {
          kickMsg += args[0] + " ";
          args.pop_front();
        }
      }

      tUser->kick(kickMsg);
    }
    else
      reportError(user, "User " + victim + " not found (see /players)");
  }
  else
    reportError(user, "Usage: /kick user [reason]");
}

void coordinateTeleport(User *user, std::string command, std::deque<std::string> args)
{
  if(args.size() > 2)
  {
    LOG(user->nick + " teleport to: " + args[0] + " " + args[1] + " " + args[2]);
    double x = atof(args[0].c_str());
    double y = atof(args[1].c_str());
    double z = atof(args[2].c_str());
    user->teleport(x, y, z);
  }
}

void userTeleport(User *user, std::string command, std::deque<std::string> args)
{
  if(args.size() == 1)
  {
    LOG(user->nick + " teleport to: " + args[0]);
    User *tUser = getUserByNick(args[0]);
    if(tUser != NULL)
      user->teleport(tUser->pos.x, tUser->pos.y + 2, tUser->pos.z);
    else
      reportError(user, "User " + args[0] + " not found (see /players)");
  }
  else if(args.size() == 2)
  {
    LOG(user->nick + ": teleport " + args[0] + " to " + args[1]);

    User *whoUser = getUserByNick(args[0]);
    User *toUser   = getUserByNick(args[1]);

    if(whoUser != NULL && toUser != NULL)
    {
      whoUser->teleport(toUser->pos.x, toUser->pos.y + 2, toUser->pos.z);
      Chat::get().sendMsg(user, COLOR_MAGENTA + "Teleported!", Chat::USER);
    }
    else
    {
      reportError(user, "User " + (whoUser == NULL ? args[0] : args[1])+
                  " not found (see /players");
    }
  }
}

void reloadConfiguration(User *user, std::string command, std::deque<std::string> args)
{
  Chat::get().loadAdmins(ADMINFILE);
  Conf::get().load(CONFIGFILE);

  // Set physics enable state based on config
  Physics::get().enabled = ((Conf::get().iValue("liquid_physics") == 0) ? false : true);

  Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "SERVER:" + COLOR_RED+
                      " Reloaded admins and config", Chat::USER);

  // Note that the MOTD is loaded on-demand each time it is requested
}

bool isValidItem(int id)
{
  if(id < 1)  // zero or negative items are all invalid
    return false;

  if(id > 91 && id < 256)  // these are undefined blocks and items
    return false;

  if(id == 2256 || id == 2257)  // records are special cased
    return true;

  if(id > 350)  // high items are invalid
    return false;

  if(id >= BLOCK_RED_CLOTH && id <= BLOCK_GRAY_CLOTH)  // coloured cloth causes client crashes
    return false;

  return true;
}

int roundUpTo(int x, int nearest)
{
  x += (nearest - 1);
  x /= nearest;
  x *= nearest;
  return x;
}

void giveItems(User *user, std::string command, std::deque<std::string> args)
{
  User *tUser = NULL;
  int itemId = 0, itemCount = 1, itemStacks = 1;

  if(args.size() > 1)
  {
    tUser = getUserByNick(args[0]);

    //First check if item is a number
    itemId = atoi(args[1].c_str());

    //If item was not a number, search the name from config
    if(itemId == 0)
      itemId = Conf::get().iValue(args[1]);

    // Check item validity
    if(!isValidItem(itemId))
    {
      reportError(user, "Item " + args[1] + " not found.");
      return;
    }

    if(args.size() > 2)
    {
      itemCount = atoi(args[2].c_str());
      // If multiple stacks
      itemStacks = roundUpTo(itemCount, 64) / 64;
      itemCount  -= (itemStacks-1) * 64;
    }
  }
  else
    reportError(user, "Too few parameters.");

  if(tUser)
  {
    int amount = 64;
    for(int i = 0; i < itemStacks; i++)
    {
      // if last stack
      if(i == itemStacks - 1)
        amount = itemCount;

      spawnedItem item;
      item.EID     = generateEID();
      item.item    = itemId;
      item.health  = 0;
      item.count   = amount;
      item.pos.x() = static_cast<int>(tUser->pos.x * 32);
      item.pos.y() = static_cast<int>(tUser->pos.y * 32);
      item.pos.z() = static_cast<int>(tUser->pos.z * 32);

      Map::get().sendPickupSpawn(item);
    }

    Chat::get().sendMsg(user, COLOR_RED + user->nick + " spawned " + args[1], Chat::ADMINS);
  }
  else
    reportError(user, "User " + args[0] + " not found (see /players)");
}

}

void Chat::registerStandardCommands()
{
  registerCommand("players", playerList, false);
  registerCommand("about", about, false);
  registerCommand("rules", rules, false);
  registerCommand("home", home, false);
  registerCommand("kit", kit, false);
  registerCommand("save", saveMap, true);
  registerCommand("kick", kick, true);
  registerCommand("ctp", coordinateTeleport, true);
  registerCommand("tp", userTeleport, true);
  registerCommand("reload", reloadConfiguration, true);
  registerCommand("give", giveItems, true);
}
<commit_msg>Fixed rules and give<commit_after>/*
   Copyright (c) 2010, The Mineserver Project
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
 * Neither the name of the The Mineserver Project 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 BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <deque>
#include <fstream>
#include <vector>
#include <ctime>
#include <math.h>
#ifdef WIN32
  #include <winsock2.h>
#else
  #include <netinet/in.h>
  #include <string.h>
#endif

#include "logger.h"
#include "constants.h"

#include "tools.h"
#include "map.h"
#include "user.h"
#include "chat.h"
#include "config.h"
#include "physics.h"

namespace
{

void reportError(User *user, std::string message)
{
  Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "Error! " + COLOR_RED + message, Chat::USER);
}

void playerList(User *user, std::string command, std::deque<std::string> args)
{
  Chat::get().sendUserlist(user);
}

void about(User *user, std::string command, std::deque<std::string> args)
{
  Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + Conf::get().sValue("servername")+
                      "Running Mineserver v." + VERSION, Chat::USER);
}

// TODO: Check if rulesfile exists
void rules(User *user, std::string command, std::deque<std::string> args)
{
  User *tUser = user;
  if(!args.empty() && user->admin)
    tUser = getUserByNick(args[0]);
  if(tUser != NULL)
  {
    // Send rules
    std::ifstream ifs( RULESFILE.c_str());
    std::string temp;

    if(ifs.fail())
    {
      std::cout << "> Warning: " << RULESFILE << " not found." << std::endl;
      return;
    }
    else
    {
      while(getline(ifs, temp))
      {
        // If not a comment
        if(temp.empty() || temp[0] != COMMENTPREFIX)
          Chat::get().sendMsg(tUser, temp, Chat::USER);
      }
      ifs.close();
    }
  }
  else
    reportError(user, "User " + args[0] + " not found (see /players)");
}

void home(User *user, std::string command, std::deque<std::string> args)
{
  Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "Teleported you home!", Chat::USER);
  user->teleport(Map::get().spawnPos.x(), Map::get().spawnPos.y() + 2, Map::get().spawnPos.z());
}

void kit(User *user, std::string command, std::deque<std::string> args)
{
  if(!args.empty())
  {
    std::vector<int> kitItems = Conf::get().vValue("kit_" + args[0]);
    // If kit is found
    if(!kitItems.empty())
    {
      for(std::vector<int>::iterator iter = kitItems.begin(), end = kitItems.end();
          iter != end;
          ++iter)
      {
        spawnedItem item;
        item.EID     = generateEID();
        item.item    = *iter;
        item.count   = 1;
        item.health=0;
        item.pos.x() = static_cast<int>(user->pos.x*32 + (rand() % 30));
        item.pos.y() = static_cast<int>(user->pos.y*32);
        item.pos.z() = static_cast<int>(user->pos.z*32 + (rand() % 30));
        Map::get().sendPickupSpawn(item);
        kitItems.pop_back();
      }
    }
    else
      reportError(user, "Kit " + args[0] + " not found");
  }
}

void saveMap(User *user, std::string command, std::deque<std::string> args)
{
  Map::get().saveWholeMap();
  Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "SERVER:" + COLOR_RED + " Saved map to disc",
                      Chat::USER);
}

void kick(User *user, std::string command, std::deque<std::string> args)
{
  if(!args.empty())
  {
    std::string victim = args[0];

    User *tUser        = getUserByNick(victim);

    if(tUser != NULL)
    {
      args.pop_front();
      std::string kickMsg;
      if(args.empty())
        kickMsg = Conf::get().sValue("default_kick_message");
      else
      {
        while(!args.empty())
        {
          kickMsg += args[0] + " ";
          args.pop_front();
        }
      }

      tUser->kick(kickMsg);
    }
    else
      reportError(user, "User " + victim + " not found (see /players)");
  }
  else
    reportError(user, "Usage: /kick user [reason]");
}

void coordinateTeleport(User *user, std::string command, std::deque<std::string> args)
{
  if(args.size() > 2)
  {
    LOG(user->nick + " teleport to: " + args[0] + " " + args[1] + " " + args[2]);
    double x = atof(args[0].c_str());
    double y = atof(args[1].c_str());
    double z = atof(args[2].c_str());
    user->teleport(x, y, z);
  }
}

void userTeleport(User *user, std::string command, std::deque<std::string> args)
{
  if(args.size() == 1)
  {
    LOG(user->nick + " teleport to: " + args[0]);
    User *tUser = getUserByNick(args[0]);
    if(tUser != NULL)
      user->teleport(tUser->pos.x, tUser->pos.y + 2, tUser->pos.z);
    else
      reportError(user, "User " + args[0] + " not found (see /players)");
  }
  else if(args.size() == 2)
  {
    LOG(user->nick + ": teleport " + args[0] + " to " + args[1]);

    User *whoUser = getUserByNick(args[0]);
    User *toUser   = getUserByNick(args[1]);

    if(whoUser != NULL && toUser != NULL)
    {
      whoUser->teleport(toUser->pos.x, toUser->pos.y + 2, toUser->pos.z);
      Chat::get().sendMsg(user, COLOR_MAGENTA + "Teleported!", Chat::USER);
    }
    else
    {
      reportError(user, "User " + (whoUser == NULL ? args[0] : args[1])+
                  " not found (see /players");
    }
  }
}

void reloadConfiguration(User *user, std::string command, std::deque<std::string> args)
{
  Chat::get().loadAdmins(ADMINFILE);
  Conf::get().load(CONFIGFILE);

  // Set physics enable state based on config
  Physics::get().enabled = ((Conf::get().iValue("liquid_physics") == 0) ? false : true);

  Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "SERVER:" + COLOR_RED+
                      " Reloaded admins and config", Chat::USER);

  // Note that the MOTD is loaded on-demand each time it is requested
}

bool isValidItem(int id)
{
  if(id < 1)  // zero or negative items are all invalid
    return false;

  if(id > 91 && id < 256)  // these are undefined blocks and items
    return false;

  if(id == 2256 || id == 2257)  // records are special cased
    return true;

  if(id > 350)  // high items are invalid
    return false;

  if(id >= BLOCK_RED_CLOTH && id <= BLOCK_GRAY_CLOTH)  // coloured cloth causes client crashes
    return false;

  return true;
}

int roundUpTo(int x, int nearest)
{
  x += (nearest - 1);
  x /= nearest;
  x *= nearest;
  return x;
}

void giveItems(User *user, std::string command, std::deque<std::string> args)
{
  User *tUser = NULL;
  int itemId = 0, itemCount = 1, itemStacks = 1;

  if(args.size() > 1)
  {
    tUser = getUserByNick(args[0]);

    //First check if item is a number
    itemId = atoi(args[1].c_str());

    //If item was not a number, search the name from config
    if(itemId == 0)
      itemId = Conf::get().iValue(args[1]);

    // Check item validity
    if(!isValidItem(itemId))
    {
      reportError(user, "Item " + args[1] + " not found.");
      return;
    }

    if(args.size() > 2)
    {
      itemCount = atoi(args[2].c_str());
      // If multiple stacks
      itemStacks = roundUpTo(itemCount, 64) / 64;
      itemCount  -= (itemStacks-1) * 64;
    }
  }
  else
  {
    reportError(user, "Too few parameters.");
	  return;
  }

  if(tUser)
  {
    int amount = 64;
    for(int i = 0; i < itemStacks; i++)
    {
      // if last stack
      if(i == itemStacks - 1)
        amount = itemCount;

      spawnedItem item;
      item.EID     = generateEID();
      item.item    = itemId;
      item.health  = 0;
      item.count   = amount;
      item.pos.x() = static_cast<int>(tUser->pos.x * 32);
      item.pos.y() = static_cast<int>(tUser->pos.y * 32);
      item.pos.z() = static_cast<int>(tUser->pos.z * 32);

      Map::get().sendPickupSpawn(item);
    }

    Chat::get().sendMsg(user, COLOR_RED + user->nick + " spawned " + args[1], Chat::ADMINS);
  }
  else
    reportError(user, "User " + args[0] + " not found (see /players)");
}

void Chat::registerStandardCommands()
{
  registerCommand("players", playerList, false);
  registerCommand("about", about, false);
  registerCommand("rules", rules, false);
  registerCommand("home", home, false);
  registerCommand("kit", kit, false);
  registerCommand("save", saveMap, true);
  registerCommand("kick", kick, true);
  registerCommand("ctp", coordinateTeleport, true);
  registerCommand("tp", userTeleport, true);
  registerCommand("reload", reloadConfiguration, true);
  registerCommand("give", giveItems, true);
}
<|endoftext|>


<commit_before>/**
 *
 * Copyright (c) 2011-2012, Kitty Barnett
 *
 * The source code in this file is provided to you under the terms of the
 * GNU Lesser General Public License, version 2.1, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. Terms of the LGPL can be found in doc/LGPL-licence.txt
 * in this distribution, or online at http://www.gnu.org/licenses/lgpl-2.1.txt
 *
 * By copying, modifying or distributing this software, you acknowledge that
 * you have read and understood your obligations described above, and agree to
 * abide by those obligations.
 *
 */

#include "llviewerprecompiledheaders.h"

#include "llagent.h"
#include "llassetuploadresponders.h"
#include "llcheckboxctrl.h"
#include "lldiriterator.h"
#include "llfloaterreg.h"
#include "llfolderview.h"
#include "llinventoryfunctions.h"
#include "llinventorymodel.h"
#include "llinventorypanel.h"
#include "llscrolllistctrl.h"
#include "llviewerassettype.h"
#include "llviewerinventory.h"
#include "llviewerregion.h"

#include "llfloaterscriptrecover.h"

const std::string NEW_LSL_NAME = "New Script";

std::string fixNewScriptDefaultName(const std::string& scriptName)
{
	std::string fixedScriptName = scriptName;
	if (scriptName == NEW_LSL_NAME)
	{
		LLStringUtil::replaceChar(fixedScriptName, ' ', '_');
	}
	return fixedScriptName;
}

// ============================================================================
// LLFloaterScriptRecover
//

LLFloaterScriptRecover::LLFloaterScriptRecover(const LLSD& sdKey)
	: LLFloater(sdKey)
{
}

void LLFloaterScriptRecover::onOpen(const LLSD& sdKey)
{
	LLScrollListCtrl* pListCtrl = findChild<LLScrollListCtrl>("script_list");

	LLSD sdBhvrRow; LLSD& sdBhvrColumns = sdBhvrRow["columns"];
	sdBhvrColumns[0] = LLSD().with("column", "script_check").with("type", "checkbox");
	sdBhvrColumns[1] = LLSD().with("column", "script_name").with("type", "text");

	pListCtrl->clearRows();
	for (LLSD::array_const_iterator itFile = sdKey["files"].beginArray(), endFile = sdKey["files"].endArray();
			itFile != endFile;  ++itFile)
	{
		const LLSD& sdFile = *itFile;

		sdBhvrRow["value"] = sdFile;
		sdBhvrColumns[0]["value"] = true;
		sdBhvrColumns[1]["value"] = sdFile["name"];

		pListCtrl->addElement(sdBhvrRow, ADD_BOTTOM);
	}
}

BOOL LLFloaterScriptRecover::postBuild()
{
	findChild<LLUICtrl>("recover_btn")->setCommitCallback(boost::bind(&LLFloaterScriptRecover::onBtnRecover, this));
	findChild<LLUICtrl>("cancel_btn")->setCommitCallback(boost::bind(&LLFloaterScriptRecover::onBtnCancel, this));

	return TRUE;
}

void LLFloaterScriptRecover::onBtnCancel()
{
	LLScrollListCtrl* pListCtrl = findChild<LLScrollListCtrl>("script_list");

	// Delete all listed files
	std::vector<LLScrollListItem*> items = pListCtrl->getAllData();
	for (std::vector<LLScrollListItem*>::const_iterator itItem = items.begin(); itItem != items.end(); ++itItem)
	{
		LLFile::remove((*itItem)->getValue().asString());
	}

	closeFloater();
}

void LLFloaterScriptRecover::onBtnRecover()
{
	LLScrollListCtrl* pListCtrl = findChild<LLScrollListCtrl>("script_list");

	// Recover all selected, delete any unselected
	std::vector<LLScrollListItem*> items = pListCtrl->getAllData(); LLSD sdFiles;
	for (std::vector<LLScrollListItem*>::const_iterator itItem = items.begin(); itItem != items.end(); ++itItem)
	{
		LLScrollListCheck* pCheckColumn = dynamic_cast<LLScrollListCheck*>((*itItem)->getColumn(0));
		if (!pCheckColumn)
			continue;

		const LLSD sdFile = (*itItem)->getValue();
		if (pCheckColumn->getCheckBox()->getValue().asBoolean())
			sdFiles.append(sdFile);
		else
			LLFile::remove(sdFile["path"]);
	}

	if (!sdFiles.emptyArray())
		new LLScriptRecoverQueue(sdFiles);

	closeFloater();
}

// ============================================================================
// LLCreateRecoverScriptCallback
//

class LLCreateRecoverScriptCallback : public LLInventoryCallback
{
public:
	LLCreateRecoverScriptCallback(LLScriptRecoverQueue* pRecoverQueue)
		: LLInventoryCallback(), mRecoverQueue(pRecoverQueue)
	{
	}

	void fire(const LLUUID& idItem)
	{
		mRecoverQueue->onCreateScript(idItem);
	}

protected:
	LLScriptRecoverQueue* mRecoverQueue;
};

// ============================================================================
// LLScriptRecoverQueue
//

// static
void LLScriptRecoverQueue::recoverIfNeeded()
{
	const std::string strTempPath = LLFile::tmpdir();
	LLSD sdData, &sdFiles = sdData["files"];

	LLDirIterator itFiles(strTempPath, "*.lslbackup"); std::string strFilename;
	while (itFiles.next(strFilename))
	{
		// Build a friendly name for the file
		std::string strName = gDirUtilp->getBaseFileName(strFilename, true);
		std::string::size_type offset = strName.find_last_of("-");
		if ( (std::string::npos != offset) && (offset != 0) && (offset == strName.length() - 9))
			strName.erase(strName.length() - 9);

		LLStringUtil::trim(strName);
		if (0 == strName.length())
			strName = "(Unknown script)";

		sdFiles.append(LLSD().with("path", strTempPath + strFilename).with("name", strName));
	}

	if (sdFiles.size())
		LLFloaterReg::showInstance("script_recover", sdData);
}

LLScriptRecoverQueue::LLScriptRecoverQueue(const LLSD& sdFiles)
{
	for (LLSD::array_const_iterator itFile = sdFiles.beginArray(), endFile = sdFiles.endArray(); itFile != endFile;  ++itFile)
	{
		const LLSD& sdFile = *itFile;
		if (LLFile::isfile(sdFile["path"]))
			m_FileQueue.insert(std::pair<std::string, LLSD>(sdFile["path"], sdFile));
	}
	recoverNext();
}

bool LLScriptRecoverQueue::recoverNext()
{
	/**
	 * Steps:
	 *  (1) create a script inventory item under Lost and Found
	 *  (2) once we have the item's UUID we can upload the script
	 *  (3) once the script is uploaded we move on to the next item
	 */
	const LLUUID idFNF = gInventory.findCategoryUUIDForType(LLFolderType::FT_LOST_AND_FOUND);

	// Sanity check - if the associated UUID is non-null then this file is already being processed
	filename_queue_t::const_iterator itFile = m_FileQueue.begin();
	while ( (itFile != m_FileQueue.end()) && (itFile->second.has("item")) && (itFile->second["item"].asUUID().notNull()) )
		++itFile;

	if (m_FileQueue.end() == itFile)
	{
		LLInventoryPanel* pInvPanel = LLInventoryPanel::getActiveInventoryPanel(TRUE);
		if (pInvPanel)
		{
			LLFolderViewFolder* pFVF = dynamic_cast<LLFolderViewFolder*>(pInvPanel->getRootFolder()->getItemByID(idFNF));
			if (pFVF)
			{
				pFVF->setOpenArrangeRecursively(TRUE, LLFolderViewFolder::RECURSE_UP);
				pInvPanel->setSelection(idFNF, TRUE);
			}
		}

		delete this;
		return false;
	}

	std::string strItemDescr;
	LLViewerAssetType::generateDescriptionFor(LLAssetType::AT_LSL_TEXT, strItemDescr);

	// Ansariel: Need to work around a bug preventing us from creating a
	//           script with the default name for new scripts
	std::string strScriptName = fixNewScriptDefaultName(itFile->second["name"].asString());

	create_inventory_item(gAgent.getID(), gAgent.getSessionID(), idFNF, LLTransactionID::tnull,
	                      strScriptName, strItemDescr, LLAssetType::AT_LSL_TEXT, LLInventoryType::IT_LSL,
	                      NOT_WEARABLE, PERM_MOVE | PERM_TRANSFER, new LLCreateRecoverScriptCallback(this));
	return true;
}

void LLScriptRecoverQueue::onCreateScript(const LLUUID& idItem)
{
	const LLViewerInventoryItem* pItem = gInventory.getItem(idItem);
	if (!pItem)
	{
		// TODO: error handling
		return;
	}

	std::string strFileName;
	for (filename_queue_t::iterator itFile = m_FileQueue.begin(); itFile != m_FileQueue.end(); ++itFile)
	{
		if (fixNewScriptDefaultName(itFile->second["name"].asString()) != pItem->getName())
			continue;
		strFileName = itFile->second["path"].asString();
		itFile->second["item"] = idItem;
		break;
	}

	LLSD sdBody;
	sdBody["item_id"] = idItem;
	sdBody["target"] = "lsl2";

	std::string strCapsUrl = gAgent.getRegion()->getCapability("UpdateScriptAgent");
	LLHTTPClient::post(strCapsUrl, sdBody,
	                   new LLUpdateAgentInventoryResponder(sdBody, strFileName, LLAssetType::AT_LSL_TEXT,
	                                                       boost::bind(&LLScriptRecoverQueue::onSavedScript, this, _1, _2, _3),
	                                                       boost::bind(&LLScriptRecoverQueue::onUploadError, this, _1)));
}

void LLScriptRecoverQueue::onSavedScript(const LLUUID& idItem, const LLSD&, bool fSuccess)
{
	LLPointer<LLViewerInventoryItem> pItem = gInventory.getItem(idItem);
	if (pItem.notNull())
	{
		filename_queue_t::iterator itFile = m_FileQueue.begin();
		while ( (itFile != m_FileQueue.end()) && ((!itFile->second.has("item")) || (itFile->second["item"].asUUID() != idItem)) )
			++itFile;
		if (itFile != m_FileQueue.end())
		{
			// Ansariel: Rename back scripts with default name
			std::string strScriptName = itFile->second["name"].asString();
			if (strScriptName == NEW_LSL_NAME)
			{
				LLPointer<LLViewerInventoryItem> pNewItem = new LLViewerInventoryItem(pItem);
				pNewItem->rename(strScriptName);
				pNewItem->updateServer(FALSE);
				gInventory.updateItem(pNewItem);
				gInventory.notifyObservers();
			}

			LLFile::remove(itFile->first);
			m_FileQueue.erase(itFile);
		}
	}
	recoverNext();
}

bool LLScriptRecoverQueue::onUploadError(const std::string& strFilename)
{
	// Skip over the file when there's an error, we can try again on the next relog
	filename_queue_t::iterator itFile = m_FileQueue.find(strFilename);
	if (itFile != m_FileQueue.end())
	{
		LLViewerInventoryItem* pItem = gInventory.getItem(itFile->second["item"]);
		if (pItem)
			gInventory.changeItemParent(pItem, gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH), FALSE);
		m_FileQueue.erase(itFile);
	}
	recoverNext();
	return false;
}

// ============================================================================
<commit_msg>Build fix in llfloaterscriptrecover.cpp<commit_after>/**
 *
 * Copyright (c) 2011-2012, Kitty Barnett
 *
 * The source code in this file is provided to you under the terms of the
 * GNU Lesser General Public License, version 2.1, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. Terms of the LGPL can be found in doc/LGPL-licence.txt
 * in this distribution, or online at http://www.gnu.org/licenses/lgpl-2.1.txt
 *
 * By copying, modifying or distributing this software, you acknowledge that
 * you have read and understood your obligations described above, and agree to
 * abide by those obligations.
 *
 */

#include "llviewerprecompiledheaders.h"

#include "llagent.h"
#include "llassetuploadresponders.h"
#include "llcheckboxctrl.h"
#include "lldiriterator.h"
#include "llfloaterreg.h"
#include "llfolderview.h"
#include "llinventoryfunctions.h"
#include "llinventorymodel.h"
#include "llinventorypanel.h"
#include "llscrolllistctrl.h"
#include "llviewerassettype.h"
#include "llviewerinventory.h"
#include "llviewerregion.h"

#include "llfloaterscriptrecover.h"

const std::string NEW_LSL_NAME = "New Script";

std::string fixNewScriptDefaultName(const std::string& scriptName)
{
	std::string fixedScriptName = scriptName;
	if (scriptName == NEW_LSL_NAME)
	{
		LLStringUtil::replaceChar(fixedScriptName, ' ', '_');
	}
	return fixedScriptName;
}

// ============================================================================
// LLFloaterScriptRecover
//

LLFloaterScriptRecover::LLFloaterScriptRecover(const LLSD& sdKey)
	: LLFloater(sdKey)
{
}

void LLFloaterScriptRecover::onOpen(const LLSD& sdKey)
{
	LLScrollListCtrl* pListCtrl = findChild<LLScrollListCtrl>("script_list");

	LLSD sdBhvrRow; LLSD& sdBhvrColumns = sdBhvrRow["columns"];
	sdBhvrColumns[0] = LLSD().with("column", "script_check").with("type", "checkbox");
	sdBhvrColumns[1] = LLSD().with("column", "script_name").with("type", "text");

	pListCtrl->clearRows();
	for (LLSD::array_const_iterator itFile = sdKey["files"].beginArray(), endFile = sdKey["files"].endArray();
			itFile != endFile;  ++itFile)
	{
		const LLSD& sdFile = *itFile;

		sdBhvrRow["value"] = sdFile;
		sdBhvrColumns[0]["value"] = true;
		sdBhvrColumns[1]["value"] = sdFile["name"];

		pListCtrl->addElement(sdBhvrRow, ADD_BOTTOM);
	}
}

BOOL LLFloaterScriptRecover::postBuild()
{
	findChild<LLUICtrl>("recover_btn")->setCommitCallback(boost::bind(&LLFloaterScriptRecover::onBtnRecover, this));
	findChild<LLUICtrl>("cancel_btn")->setCommitCallback(boost::bind(&LLFloaterScriptRecover::onBtnCancel, this));

	return TRUE;
}

void LLFloaterScriptRecover::onBtnCancel()
{
	LLScrollListCtrl* pListCtrl = findChild<LLScrollListCtrl>("script_list");

	// Delete all listed files
	std::vector<LLScrollListItem*> items = pListCtrl->getAllData();
	for (std::vector<LLScrollListItem*>::const_iterator itItem = items.begin(); itItem != items.end(); ++itItem)
	{
		LLFile::remove((*itItem)->getValue().asString());
	}

	closeFloater();
}

void LLFloaterScriptRecover::onBtnRecover()
{
	LLScrollListCtrl* pListCtrl = findChild<LLScrollListCtrl>("script_list");

	// Recover all selected, delete any unselected
	std::vector<LLScrollListItem*> items = pListCtrl->getAllData(); LLSD sdFiles;
	for (std::vector<LLScrollListItem*>::const_iterator itItem = items.begin(); itItem != items.end(); ++itItem)
	{
		LLScrollListCheck* pCheckColumn = dynamic_cast<LLScrollListCheck*>((*itItem)->getColumn(0));
		if (!pCheckColumn)
			continue;

		const LLSD sdFile = (*itItem)->getValue();
		if (pCheckColumn->getCheckBox()->getValue().asBoolean())
			sdFiles.append(sdFile);
		else
			LLFile::remove(sdFile["path"]);
	}

	if (!sdFiles.emptyArray())
		new LLScriptRecoverQueue(sdFiles);

	closeFloater();
}

// ============================================================================
// LLCreateRecoverScriptCallback
//

class LLCreateRecoverScriptCallback : public LLInventoryCallback
{
public:
	LLCreateRecoverScriptCallback(LLScriptRecoverQueue* pRecoverQueue)
		: LLInventoryCallback(), mRecoverQueue(pRecoverQueue)
	{
	}

	void fire(const LLUUID& idItem)
	{
		mRecoverQueue->onCreateScript(idItem);
	}

protected:
	LLScriptRecoverQueue* mRecoverQueue;
};

// ============================================================================
// LLScriptRecoverQueue
//

// static
void LLScriptRecoverQueue::recoverIfNeeded()
{
	const std::string strTempPath = LLFile::tmpdir();
	LLSD sdData, &sdFiles = sdData["files"];

	LLDirIterator itFiles(strTempPath, "*.lslbackup"); std::string strFilename;
	while (itFiles.next(strFilename))
	{
		// Build a friendly name for the file
		std::string strName = gDirUtilp->getBaseFileName(strFilename, true);
		std::string::size_type offset = strName.find_last_of("-");
		if ( (std::string::npos != offset) && (offset != 0) && (offset == strName.length() - 9))
			strName.erase(strName.length() - 9);

		LLStringUtil::trim(strName);
		if (0 == strName.length())
			strName = "(Unknown script)";

		sdFiles.append(LLSD().with("path", strTempPath + strFilename).with("name", strName));
	}

	if (sdFiles.size())
		LLFloaterReg::showInstance("script_recover", sdData);
}

LLScriptRecoverQueue::LLScriptRecoverQueue(const LLSD& sdFiles)
{
	for (LLSD::array_const_iterator itFile = sdFiles.beginArray(), endFile = sdFiles.endArray(); itFile != endFile;  ++itFile)
	{
		const LLSD& sdFile = *itFile;
		if (LLFile::isfile(sdFile["path"]))
			m_FileQueue.insert(std::pair<std::string, LLSD>(sdFile["path"], sdFile));
	}
	recoverNext();
}

bool LLScriptRecoverQueue::recoverNext()
{
	/**
	 * Steps:
	 *  (1) create a script inventory item under Lost and Found
	 *  (2) once we have the item's UUID we can upload the script
	 *  (3) once the script is uploaded we move on to the next item
	 */
	const LLUUID idFNF = gInventory.findCategoryUUIDForType(LLFolderType::FT_LOST_AND_FOUND);

	// Sanity check - if the associated UUID is non-null then this file is already being processed
	filename_queue_t::const_iterator itFile = m_FileQueue.begin();
	while ( (itFile != m_FileQueue.end()) && (itFile->second.has("item")) && (itFile->second["item"].asUUID().notNull()) )
		++itFile;

	if (m_FileQueue.end() == itFile)
	{
		LLInventoryPanel* pInvPanel = LLInventoryPanel::getActiveInventoryPanel(TRUE);
		LLFolderViewFolder* pFVF = dynamic_cast<LLFolderViewFolder*>(pInvPanel ? pInvPanel->getItemByID(idFNF) : NULL);
		if (pFVF)
		{
			pFVF->setOpenArrangeRecursively(TRUE, LLFolderViewFolder::RECURSE_UP);
			pInvPanel->setSelection(idFNF, TRUE);
		}

		delete this;
		return false;
	}

	std::string strItemDescr;
	LLViewerAssetType::generateDescriptionFor(LLAssetType::AT_LSL_TEXT, strItemDescr);

	// Ansariel: Need to work around a bug preventing us from creating a
	//           script with the default name for new scripts
	std::string strScriptName = fixNewScriptDefaultName(itFile->second["name"].asString());

	create_inventory_item(gAgent.getID(), gAgent.getSessionID(), idFNF, LLTransactionID::tnull,
	                      strScriptName, strItemDescr, LLAssetType::AT_LSL_TEXT, LLInventoryType::IT_LSL,
	                      NOT_WEARABLE, PERM_MOVE | PERM_TRANSFER, new LLCreateRecoverScriptCallback(this));
	return true;
}

void LLScriptRecoverQueue::onCreateScript(const LLUUID& idItem)
{
	const LLViewerInventoryItem* pItem = gInventory.getItem(idItem);
	if (!pItem)
	{
		// TODO: error handling
		return;
	}

	std::string strFileName;
	for (filename_queue_t::iterator itFile = m_FileQueue.begin(); itFile != m_FileQueue.end(); ++itFile)
	{
		if (fixNewScriptDefaultName(itFile->second["name"].asString()) != pItem->getName())
			continue;
		strFileName = itFile->second["path"].asString();
		itFile->second["item"] = idItem;
		break;
	}

	LLSD sdBody;
	sdBody["item_id"] = idItem;
	sdBody["target"] = "lsl2";

	std::string strCapsUrl = gAgent.getRegion()->getCapability("UpdateScriptAgent");
	LLHTTPClient::post(strCapsUrl, sdBody,
	                   new LLUpdateAgentInventoryResponder(sdBody, strFileName, LLAssetType::AT_LSL_TEXT,
	                                                       boost::bind(&LLScriptRecoverQueue::onSavedScript, this, _1, _2, _3),
	                                                       boost::bind(&LLScriptRecoverQueue::onUploadError, this, _1)));
}

void LLScriptRecoverQueue::onSavedScript(const LLUUID& idItem, const LLSD&, bool fSuccess)
{
	LLPointer<LLViewerInventoryItem> pItem = gInventory.getItem(idItem);
	if (pItem.notNull())
	{
		filename_queue_t::iterator itFile = m_FileQueue.begin();
		while ( (itFile != m_FileQueue.end()) && ((!itFile->second.has("item")) || (itFile->second["item"].asUUID() != idItem)) )
			++itFile;
		if (itFile != m_FileQueue.end())
		{
			// Ansariel: Rename back scripts with default name
			std::string strScriptName = itFile->second["name"].asString();
			if (strScriptName == NEW_LSL_NAME)
			{
				LLPointer<LLViewerInventoryItem> pNewItem = new LLViewerInventoryItem(pItem);
				pNewItem->rename(strScriptName);
				pNewItem->updateServer(FALSE);
				gInventory.updateItem(pNewItem);
				gInventory.notifyObservers();
			}

			LLFile::remove(itFile->first);
			m_FileQueue.erase(itFile);
		}
	}
	recoverNext();
}

bool LLScriptRecoverQueue::onUploadError(const std::string& strFilename)
{
	// Skip over the file when there's an error, we can try again on the next relog
	filename_queue_t::iterator itFile = m_FileQueue.find(strFilename);
	if (itFile != m_FileQueue.end())
	{
		LLViewerInventoryItem* pItem = gInventory.getItem(itFile->second["item"]);
		if (pItem)
			gInventory.changeItemParent(pItem, gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH), FALSE);
		m_FileQueue.erase(itFile);
	}
	recoverNext();
	return false;
}

// ============================================================================
<|endoftext|>


<commit_before>#pragma once

#include "Quantities.hpp"
#include "NamedQuantities.hpp"
#include "Numbers.hpp"
#include "SI.hpp"

namespace principia {
// This namespace contains the non-SI units associated with the CGS and the CGS-
// Gaussian system of units listed in the BIPM's SI brochure 8, section 4.1,
// table 9, http://www.bipm.org/en/si/si_brochure/chapter4/table9.html.
namespace CGS {
quantities::Length const Centimetre = SI::Centi(SI::Metre);
using SI::Gram;
using SI::Second;

quantities::Energy const Erg  = 1e-7 * SI::Joule;
quantities::Force  const Dyne = 1e-5 * SI::Newton;

quantities::Pressure const Barye = 1 * Dyne / Centimetre.Pow<2>();

quantities::DynamicViscosity const Poise = Barye * Second;
quantities::KinematicViscosity const Stokes = Centimetre.Pow<2>() / Second;

quantities::Luminance   const Stilb = SI::Candela * Centimetre.Pow<-2>();
quantities::Illuminance const Phot  = Stilb * SI::Steradian ;

quantities::Acceleration const Gal = Centimetre / Second.Pow<2>();

quantities::MagneticFluxDensity const Gauss   = 1e-4 * SI::Tesla;
quantities::MagneticFlux        const Maxwell = Gauss * Centimetre.Pow<2>();
quantities::MagneticField       const Œrsted  = 1e3 / (4 * π * SI::Steradian) *
                                                SI::Ampere / SI::Metre;

quantities::SpectroscopicWavenumber const Kayser = SI::Cycle / Centimetre;
}  // namespace CGS
}  // namespace principia
<commit_msg>namespace cgs.<commit_after>#pragma once

#include "Quantities.hpp"
#include "NamedQuantities.hpp"
#include "Numbers.hpp"
#include "SI.hpp"

namespace principia {
// This namespace contains the non-SI units associated with the CGS and the CGS-
// Gaussian system of units listed in the BIPM's SI brochure 8, section 4.1,
// table 9, http://www.bipm.org/en/si/si_brochure/chapter4/table9.html.
namespace cgs {
quantities::Length const Centimetre = SI::Centi(SI::Metre);
using SI::Gram;
using SI::Second;

quantities::Energy const Erg  = 1e-7 * SI::Joule;
quantities::Force  const Dyne = 1e-5 * SI::Newton;

quantities::Pressure const Barye = 1 * Dyne / Centimetre.Pow<2>();

quantities::DynamicViscosity const Poise = Barye * Second;
quantities::KinematicViscosity const Stokes = Centimetre.Pow<2>() / Second;

quantities::Luminance   const Stilb = SI::Candela * Centimetre.Pow<-2>();
quantities::Illuminance const Phot  = Stilb * SI::Steradian ;

quantities::Acceleration const Gal = Centimetre / Second.Pow<2>();

quantities::MagneticFluxDensity const Gauss   = 1e-4 * SI::Tesla;
quantities::MagneticFlux        const Maxwell = Gauss * Centimetre.Pow<2>();
quantities::MagneticField       const Œrsted  = 1e3 / (4 * π * SI::Steradian) *
                                                SI::Ampere / SI::Metre;

quantities::SpectroscopicWavenumber const Kayser = SI::Cycle / Centimetre;
}  // namespace cgs
}  // namespace principia
<|endoftext|>


<commit_before>/*
Copyright 2015 Adam Grandquist

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.
 */
/**
 * @author Adam Grandquist
 * @copyright Apache
 */

#ifndef REQL_CPP_TYPES_HPP_
#define REQL_CPP_TYPES_HPP_

#include <map>
#include <memory>
#include <string>
#include <vector>

namespace ReQL {

namespace _C {

extern "C" {

#include "./ReQL.h"

}

namespace CTypes {

typedef std::unique_ptr<ReQL_Byte[]> string;
typedef std::unique_ptr<ReQL_Obj_t> object;
typedef std::unique_ptr<ReQL_Obj_t*[]> array;
typedef std::unique_ptr<ReQL_Pair_t[]> pairs;
typedef std::unique_ptr<ReQL_Conn_t> connection;
typedef std::unique_ptr<ReQL_Cur_t> cursor;

}  // namespace Types
}  // namespace _C

class Query;

namespace Types {

typedef std::string string;
typedef std::vector<Query> array;
typedef std::map<string, Query> object;

}  // namespace Types
}  // namespace ReQL

#endif  // REQL_CPP_TYPES_HPP_
<commit_msg>Fix comment.<commit_after>/*
Copyright 2015 Adam Grandquist

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.
 */
/**
 * @author Adam Grandquist
 * @copyright Apache
 */

#ifndef REQL_CPP_TYPES_HPP_
#define REQL_CPP_TYPES_HPP_

#include <map>
#include <memory>
#include <string>
#include <vector>

namespace ReQL {

namespace _C {

#include "./ReQL.h"

namespace CTypes {

typedef std::unique_ptr<ReQL_Byte[]> string;
typedef std::unique_ptr<ReQL_Obj_t> object;
typedef std::unique_ptr<ReQL_Obj_t*[]> array;
typedef std::unique_ptr<ReQL_Pair_t[]> pairs;
typedef std::unique_ptr<ReQL_Conn_t> connection;
typedef std::unique_ptr<ReQL_Cur_t> cursor;

}  // namespace CTypes
}  // namespace _C

class Query;

namespace Types {

typedef std::string string;
typedef std::vector<Query> array;
typedef std::map<string, Query> object;

}  // namespace Types
}  // namespace ReQL

#endif  // REQL_CPP_TYPES_HPP_
<|endoftext|>