<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_CORE_GAME_HANDLER_HPP
#define RJ_CORE_GAME_HANDLER_HPP

#include "game.hpp"
#include "game_window.hpp"
#include "render.hpp"
#include <rectojump/game/background/background_manager.hpp>
#include <rectojump/game/editor/editor.hpp>
#include <rectojump/game/main_menu/main_menu.hpp>
#include <rectojump/game/popup_manager.hpp>
#include <rectojump/global/common.hpp>
#include <rectojump/global/config_settings.hpp>
#include <rectojump/shared/data_manager.hpp>
#include <rectojump/shared/level_manager/level_manager.hpp>

#include <mlk/containers/container_utl.h>
#include <mlk/tools/bitset.h>

namespace rj
{
	class game_handler
	{
		game_window& m_game_window;
		data_manager& m_datamgr;
		level_manager& m_lvmgr;

		render<game_handler> m_render;
		background_manager m_backgroundmgr;
		game<game_handler> m_game;
		editor<game_handler, decltype(m_game)> m_editor;
		main_menu<game_handler> m_mainmenu;
		popup_manager<game_handler> m_popupmgr;
		debug_info<game_handler, decltype(m_game)> m_debug_info;

		mlk::ebitset<state, state::num> m_current_states;

	public:
		game_handler(game_window& gw, data_manager& dm, level_manager& lm) :
			m_game_window{gw},
			m_datamgr{dm},
			m_lvmgr{lm},
			m_render{*this},
			m_backgroundmgr{m_render},
			m_game{*this},
			m_editor{*this},
			m_mainmenu{*this},
			m_popupmgr{*this},
			m_debug_info{*this}
		{this->init();}

		void load_level(const level_id& id)
		{
			auto& lv(m_lvmgr.get_level(id));
			if(!lv.is_valid())
			{
				m_popupmgr.create_popup<popup_type::error>("Failed to load level: not a valid level");
				return;
			}

			m_backgroundmgr.clear();

			this->deactivate_state(state::main_menu);
			this->activate_state(state::game);

			m_game.load_level(lv);
		}

		template<typename... Args>
		void render_object(Args&&... args)
		{m_game_window.draw(std::forward<Args>(args)...);}

		template<typename Input_Type, state active_state, typename On_Input, typename... Input_Type_Args>
		void add_input(On_Input&& func, Input_Type_Args&&... keys_btns)
		{
			add_input_helper<(sizeof...(keys_btns) > 1), Input_Type, active_state, On_Input, Input_Type_Args...>
			{*this, std::forward<On_Input>(func), std::forward<Input_Type_Args>(keys_btns)...};
		}

		// getters
		auto get_render() noexcept
		-> decltype(m_render)&
		{return m_render;}

		auto get_gamewindow() noexcept
		-> decltype(m_game_window)&
		{return m_game_window;}

		auto get_game() noexcept
		-> decltype(m_game)&
		{return m_game;}

		auto get_backgroundmgr() noexcept
		-> decltype(m_backgroundmgr)&
		{return m_backgroundmgr;}

		auto get_mainmenu() noexcept
		-> decltype(m_mainmenu)&
		{return m_mainmenu;}

		auto get_datamgr() noexcept
		-> decltype(m_datamgr)&
		{return m_datamgr;}

		auto get_levelmgr() noexcept
		-> decltype(m_lvmgr)&
		{return m_lvmgr;}

		auto get_debuginfo() noexcept
		-> decltype(m_debug_info)&
		{return m_debug_info;}

		auto get_popupmgr() noexcept
		-> decltype(m_popupmgr)&
		{return m_popupmgr;}

	private:
		void init()
		{
			m_current_states |= state::main_menu;

			m_game_window.get_updater().on_update += [this](dur duration){this->update(duration);};
			m_game_window.get_updater().on_render += [this]{this->render();};

			settings::on_changed() +=
			[this]{m_game_window.set_size(settings::get_window_size());};

			m_mainmenu.get_menu_start()->get_items().on_event("editor",
			[this]
			{
				this->deactivate_state(state::main_menu);
				this->activate_state(state::editor);
				m_editor.on_activate();
			});

			this->init_pointers();
			this->init_input();
		}

		void init_pointers() noexcept
		{
			m_game.set_levelmgr(&m_lvmgr);
		}

		void init_input()
		{
			// global input
			on_key_pressed(key::F) +=
			[this]
			{
				m_game_window.toggle_fullscreen();
				rj::settings::set_fullscreen(m_game_window.get_fullscreen());
			};

			on_key_pressed(key::T) +=
			[this]{m_game_window.toggle_titlebar();};

			on_keys_pressed(key::LShift, key::D) +=
			[this]{this->toggle_state(state::debug_info);};

			on_keys_pressed(key::LShift, key::Q) +=
			[this]{m_game_window.stop();};

			// window input
			on_key_pressed(key::Escape) +=
			[this]{if(!this->is_active(state::main_menu)) return; m_game_window.stop();};

			// game input
			on_key_pressed(key::P) +=
			[this]
			{
				if(this->is_active(state::game))
				{
					m_current_states.remove(state::game);
					m_current_states |= state::game_menu;
					return;
				}
				else if(this->is_active(state::game_menu))
				{
					m_current_states.remove(state::game_menu);
					m_current_states |= state::game;
					return;
				}
			};

			on_key_pressed(key::D) +=
			[this]{if(!this->is_active(state::game)) return; m_game.get_world().c_player();};

			on_btn_pressed(btn::Left) +=
			[this](const vec2f& pos)
			{
				if(!this->is_active(state::game))
					return;
				m_game.get_world().c_ent(pos);
			};

			on_btn_pressed(btn::Right) +=
			[this](const vec2f& pos)
			{
				if(!this->is_active(state::game))
					return;
				m_game.get_world().c_ent_death(pos);
			};

			on_key_pressed(key::A) +=
			[this]
			{
				if(!this->is_active(state::game))
					return;
				m_game.get_world().c_world();
			};

			// editor input
			on_btn_pressed(btn::Left) +=
			[this](const vec2f& pos){m_editor.on_mouse_left(pos);};

			on_btn_pressed(btn::Right) +=
			[this](const vec2f& pos){m_editor.on_mouse_right(pos);};
		}

		void activate_state(state s)
		{m_current_states |= s;}

		void deactivate_state(state s)
		{m_current_states.remove(s);}

		void toggle_state(state s)
		{m_current_states.toggle(s);}

		bool is_active(state s) const
		{return m_current_states & s;}

		void set_only_state(state s)
		{
			m_current_states.remove_all();
			m_current_states |= s;
		}

		void update(dur duration)
		{
			m_backgroundmgr.update(duration);

			if(this->is_active(state::game))
				m_game.update(duration);

			else if(this->is_active(state::editor))
			{
				m_editor.update(duration);
				m_game.get_world().get_entityhandler().update(duration);
			}

			else if(this->is_active(state::main_menu))
				m_mainmenu.update(duration);

			if(this->is_active(state::debug_info))
				m_debug_info.update(duration);

			m_popupmgr.update(duration);
		}

		void render()
		{
			m_backgroundmgr.render();

			// render game when in game menu
			if(this->is_active(state::game) || this->is_active(state::game_menu))
				m_game.render();

			else if(this->is_active(state::editor))
			{
				m_editor.render();
				m_game.get_world().get_entityhandler().render();
			}

			else if(this->is_active(state::main_menu))
				m_mainmenu.render();

			if(this->is_active(state::debug_info))
				m_debug_info.render();

			m_popupmgr.render();
		}

		// multi_args: true, Input_Type = key
		template<bool multi_args, typename Input_Type, state s, typename On_Input, typename... Input_Type_Args>
		struct add_input_helper
		{
			add_input_helper(const game_handler& gh, On_Input&& func, Input_Type_Args&&... keys)
			{
				on_keys_pressed(std::forward<Input_Type_Args>(keys)...) +=
				[&gh, func]{if(gh.is_active(s)) func();};
			}
		};

		// multi_args: false, Input_Type = key
		template<typename Input_Type, state s, typename On_Input, typename... Input_Type_Args>
		struct add_input_helper<false, Input_Type, s, On_Input, Input_Type_Args...>
		{
			add_input_helper(const game_handler& gh, On_Input&& func, Input_Type_Args&&... k)
			{
				on_key_pressed(std::forward<Input_Type_Args>(k)...) +=
				[&gh, func]{if(gh.is_active(s)) func();};
			}
		};

		// multi_args: false, Input_Type = btn
		template<state s, typename On_Input, typename... Input_Type_Args>
		struct add_input_helper<false, btn, s, On_Input, Input_Type_Args...>
		{
			add_input_helper(const game_handler& gh, On_Input&& func, Input_Type_Args&&... k)
			{
				on_btn_pressed(std::forward<Input_Type_Args>(k)...) +=
				[&gh, func](const vec2f& pos)
				{if(gh.is_active(s)) func(pos);};
			}
		};
	};
}

#endif // RJ_CORE_GAME_HANDLER_HPP
<commit_msg>game_handler: add_input<T> automatic gets the right type (key/btn)<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_CORE_GAME_HANDLER_HPP
#define RJ_CORE_GAME_HANDLER_HPP

#include "game.hpp"
#include "game_window.hpp"
#include "render.hpp"
#include <rectojump/game/background/background_manager.hpp>
#include <rectojump/game/editor/editor.hpp>
#include <rectojump/game/main_menu/main_menu.hpp>
#include <rectojump/game/popup_manager.hpp>
#include <rectojump/global/common.hpp>
#include <rectojump/global/config_settings.hpp>
#include <rectojump/shared/data_manager.hpp>
#include <rectojump/shared/level_manager/level_manager.hpp>

#include <mlk/containers/container_utl.h>
#include <mlk/tools/bitset.h>

namespace rj
{
	class game_handler
	{
		game_window& m_game_window;
		data_manager& m_datamgr;
		level_manager& m_lvmgr;

		render<game_handler> m_render;
		background_manager m_backgroundmgr;
		game<game_handler> m_game;
		editor<game_handler, decltype(m_game)> m_editor;
		main_menu<game_handler> m_mainmenu;
		popup_manager<game_handler> m_popupmgr;
		debug_info<game_handler, decltype(m_game)> m_debug_info;

		mlk::ebitset<state, state::num> m_current_states;

	public:
		game_handler(game_window& gw, data_manager& dm, level_manager& lm) :
			m_game_window{gw},
			m_datamgr{dm},
			m_lvmgr{lm},
			m_render{*this},
			m_backgroundmgr{m_render},
			m_game{*this},
			m_editor{*this},
			m_mainmenu{*this},
			m_popupmgr{*this},
			m_debug_info{*this}
		{this->init();}

		void load_level(const level_id& id)
		{
			auto& lv(m_lvmgr.get_level(id));
			if(!lv.is_valid())
			{
				m_popupmgr.create_popup<popup_type::error>("Failed to load level: not a valid level");
				return;
			}

			m_backgroundmgr.clear();

			this->deactivate_state(state::main_menu);
			this->activate_state(state::game);

			m_game.load_level(lv);
		}

		template<typename... Args>
		void render_object(Args&&... args)
		{m_game_window.draw(std::forward<Args>(args)...);}

		template<state active_state, typename On_Input, typename... Input_Type_Args>
		void add_input(On_Input&& func, Input_Type_Args&&... keys_btns)
		{
			add_input_helper<(sizeof...(keys_btns) > 1), typename std::tuple_element<0, std::tuple<Input_Type_Args...>>::type, active_state, On_Input, Input_Type_Args...>
			{*this, std::forward<On_Input>(func), std::forward<Input_Type_Args>(keys_btns)...};
		}

		// getters
		auto get_render() noexcept
		-> decltype(m_render)&
		{return m_render;}

		auto get_gamewindow() noexcept
		-> decltype(m_game_window)&
		{return m_game_window;}

		auto get_game() noexcept
		-> decltype(m_game)&
		{return m_game;}

		auto get_backgroundmgr() noexcept
		-> decltype(m_backgroundmgr)&
		{return m_backgroundmgr;}

		auto get_mainmenu() noexcept
		-> decltype(m_mainmenu)&
		{return m_mainmenu;}

		auto get_datamgr() noexcept
		-> decltype(m_datamgr)&
		{return m_datamgr;}

		auto get_levelmgr() noexcept
		-> decltype(m_lvmgr)&
		{return m_lvmgr;}

		auto get_debuginfo() noexcept
		-> decltype(m_debug_info)&
		{return m_debug_info;}

		auto get_popupmgr() noexcept
		-> decltype(m_popupmgr)&
		{return m_popupmgr;}

	private:
		void init()
		{
			m_current_states |= state::main_menu;

			m_game_window.get_updater().on_update += [this](dur duration){this->update(duration);};
			m_game_window.get_updater().on_render += [this]{this->render();};

			settings::on_changed() +=
			[this]{m_game_window.set_size(settings::get_window_size());};

			m_mainmenu.get_menu_start()->get_items().on_event("editor",
			[this]
			{
				this->deactivate_state(state::main_menu);
				this->activate_state(state::editor);
				m_editor.on_activate();
			});

			this->init_pointers();
			this->init_input();
		}

		void init_pointers() noexcept
		{
			m_game.set_levelmgr(&m_lvmgr);
		}

		void init_input()
		{
			// global input
			on_key_pressed(key::F) +=
			[this]
			{
				m_game_window.toggle_fullscreen();
				rj::settings::set_fullscreen(m_game_window.get_fullscreen());
			};

			on_key_pressed(key::T) +=
			[this]{m_game_window.toggle_titlebar();};

			on_keys_pressed(key::LShift, key::D) +=
			[this]{this->toggle_state(state::debug_info);};

			on_keys_pressed(key::LShift, key::Q) +=
			[this]{m_game_window.stop();};

			// window input
			on_key_pressed(key::Escape) +=
			[this]{if(!this->is_active(state::main_menu)) return; m_game_window.stop();};

			// game input
			on_key_pressed(key::P) +=
			[this]
			{
				if(this->is_active(state::game))
				{
					m_current_states.remove(state::game);
					m_current_states |= state::game_menu;
					return;
				}
				else if(this->is_active(state::game_menu))
				{
					m_current_states.remove(state::game_menu);
					m_current_states |= state::game;
					return;
				}
			};

			on_key_pressed(key::D) +=
			[this]{if(!this->is_active(state::game)) return; m_game.get_world().c_player();};

			on_btn_pressed(btn::Left) +=
			[this](const vec2f& pos)
			{
				if(!this->is_active(state::game))
					return;
				m_game.get_world().c_ent(pos);
			};

			on_btn_pressed(btn::Right) +=
			[this](const vec2f& pos)
			{
				if(!this->is_active(state::game))
					return;
				m_game.get_world().c_ent_death(pos);
			};

			on_key_pressed(key::A) +=
			[this]
			{
				if(!this->is_active(state::game))
					return;
				m_game.get_world().c_world();
			};
		}

		void activate_state(state s)
		{m_current_states |= s;}

		void deactivate_state(state s)
		{m_current_states.remove(s);}

		void toggle_state(state s)
		{m_current_states.toggle(s);}

		bool is_active(state s) const
		{return m_current_states & s;}

		void set_only_state(state s)
		{
			m_current_states.remove_all();
			m_current_states |= s;
		}

		void update(dur duration)
		{
			m_backgroundmgr.update(duration);

			if(this->is_active(state::game))
				m_game.update(duration);

			else if(this->is_active(state::editor))
			{
				m_editor.update(duration);
				m_game.get_world().get_entityhandler().update(duration);
			}

			else if(this->is_active(state::main_menu))
				m_mainmenu.update(duration);

			if(this->is_active(state::debug_info))
				m_debug_info.update(duration);

			m_popupmgr.update(duration);
		}

		void render()
		{
			m_backgroundmgr.render();

			// render game when in game menu
			if(this->is_active(state::game) || this->is_active(state::game_menu))
				m_game.render();

			else if(this->is_active(state::editor))
			{
				m_editor.render();
				m_game.get_world().get_entityhandler().render();
			}

			else if(this->is_active(state::main_menu))
				m_mainmenu.render();

			if(this->is_active(state::debug_info))
				m_debug_info.render();

			m_popupmgr.render();
		}

		// multi_args: true, Input_Type = key
		template<bool multi_args, typename Input_Type, state s, typename On_Input, typename... Input_Type_Args>
		struct add_input_helper
		{
			add_input_helper(const game_handler& gh, On_Input&& func, Input_Type_Args&&... keys)
			{
				on_keys_pressed(std::forward<Input_Type_Args>(keys)...) +=
				[&gh, func]{if(gh.is_active(s)) func();};
			}
		};

		// multi_args: false, Input_Type = key
		template<typename Input_Type, state s, typename On_Input, typename... Input_Type_Args>
		struct add_input_helper<false, Input_Type, s, On_Input, Input_Type_Args...>
		{
			add_input_helper(const game_handler& gh, On_Input&& func, Input_Type_Args&&... k)
			{
				on_key_pressed(std::forward<Input_Type_Args>(k)...) +=
				[&gh, func]{if(gh.is_active(s)) func();};
			}
		};

		// multi_args: false, Input_Type = btn
		template<state s, typename On_Input, typename... Input_Type_Args>
		struct add_input_helper<false, btn, s, On_Input, Input_Type_Args...>
		{
			add_input_helper(const game_handler& gh, On_Input&& func, Input_Type_Args&&... k)
			{
				on_btn_pressed(std::forward<Input_Type_Args>(k)...) +=
				[&gh, func](const vec2f& pos)
				{if(gh.is_active(s)) func(pos);};
			}
		};
	};
}

#endif // RJ_CORE_GAME_HANDLER_HPP
<|endoftext|>


<commit_before>#include <node.h>
#include <initializer_list>

#include "Pump.h"
#include "calculator/PumpEfficiency.h"
#include "calculator/OptimalPumpEfficiency.h"
#include "calculator/MotorRatedPower.h"
#include "calculator/OptimalMotorRatedPower.h"
#include "calculator/MotorShaftPower.h"
#include "calculator/OptimalMotorShaftPower.h"
#include "calculator/PumpShaftPower.h"
#include "calculator/OptimalPumpShaftPower.h"
#include "calculator/MotorEfficiency.h"
#include "calculator/OptimalMotorEfficiency.h"
#include "calculator/MotorPowerFactor.h"
#include "calculator/OptimalMotorPowerFactor.h"
#include "calculator/MotorCurrent.h"
#include "calculator/OptimalMotorCurrent.h"
#include "calculator/MotorPower.h"
#include "calculator/OptimalMotorPower.h"
#include "AnnualEnergy.h"
#include "AnnualCost.h"
#include "AnnualSavingsPotential.h"
#include "OptimizationRating.h"

using namespace v8;

Local<Array> r;
Isolate* iso;
Local<Object> inp;

void set(std::initializer_list <double> args) {
  for (auto d : args) {
    r->Set(r->Length(),Number::New(iso,d));
  }
}
double get(const char *nm) {
  return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue();
}
void Results(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  r = Array::New(iso);
  inp = args[0]->ToObject();

  auto drive = static_cast<Pump::Drive>(get("drive"));
  auto effCls = static_cast<Motor::EfficiencyClass>(get("efficiency_class"));

  auto loadMeth = FieldData::LoadEstimationMethod::POWER;
  double mp = get("motor_field_power");
  double mc = get("motor_field_current");
  if (mc>0) {
    loadMeth = FieldData::LoadEstimationMethod::CURRENT;
    mp = (new MotorPower(0,mc,0,get("field_voltage")))->calculate();//motor power (makes no sense, it IS motor power), motor a, motorpf
  } else {
    mc = (new MotorCurrent(get("motor_rated_power"),mp,get("motor_rated_speed"),effCls)/*get("field_voltage")*/)->calculate();//motor a, motor power, recursive arg!!
  }
  set({
    (new PumpEfficiency(get("specific_gravity"),get("flow"),get("head"),0))->calculate(),//pumpShaftPower
    (new OptimalPumpEfficiency(static_cast<Pump::Style>(get("style")),
      get("pump_rated_speed"),get("viscosity"),get("stages"),get("flow"),get("head"),static_cast<Pump::Speed>(!get("speed"))))->calculate(),//
    mp,
    (new OptimalMotorRatedPower(0,get("margin")))->calculate(),//motorshaftpower
    (new MotorShaftPower(0,mp,get("motor_rated_speed"),effCls))->calculate(),//motor eff
    (new OptimalMotorShaftPower(0,drive))->calculate(),//pumpshaftpower
    (new PumpShaftPower(0,drive))->calculate(),//motorshaftpower
    (new OptimalPumpShaftPower(get("flow"),get("head"),get("specific_gravity"),0))->calculate(),//pumpeff
    (new MotorEfficiency(get("line"),get("motor_rated_speed"),effCls,get("motor_rated_power"),
      loadMeth,0,mc,get("field_voltage")))->calculate(),//motorKwh??
    (new OptimalMotorEfficiency(get("motor_rated_power"),0))->calculate(),//motor shaft power
    (new MotorPowerFactor(get("line"),get("rpm"),effCls,get("power_rating"),
      loadMeth,0,mc,get("field_voltage")))->calculate(),//motor kwh
    (new OptimalMotorPowerFactor(get("motor_rated_power"),0))->calculate(),//opt motor power?
    mc,
    (new OptimalMotorCurrent(0,get("field_voltage")))->calculate(),//opt motor power
    mp,
    (new OptimalMotorPower(0,0))->calculate(),//motorshaftpower, motor eff
    (new AnnualEnergy(mp,get("fraction")))->calculate(),//motorpower
    (new AnnualEnergy(0,get("fraction")))->calculate(),//opt motorpower
    (new AnnualCost(0,get("cost")))->calculate(),//ex ann energy
    (new AnnualCost(0,get("cost")))->calculate(),//opt ann energy
    -1,
    (new AnnualSavingsPotential(0,0))->calculate(),//ex an cost, opt an cost
    -1,
    (new OptimizationRating(0,0))->calculate(),//ex an cost, opt an cost

    777//est fla; hp,class,v,speed
  });
  args.GetReturnValue().Set(r);
}

void init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "results", Results);
}

NODE_MODULE(bridge, init)

<commit_msg>no message<commit_after>#include <node.h>
#include <initializer_list>

#include "Pump.h"
#include "calculator/PumpEfficiency.h"
#include "calculator/OptimalPumpEfficiency.h"
#include "calculator/MotorRatedPower.h"
#include "calculator/OptimalMotorRatedPower.h"
#include "calculator/MotorShaftPower.h"
#include "calculator/OptimalMotorShaftPower.h"
#include "calculator/PumpShaftPower.h"
#include "calculator/OptimalPumpShaftPower.h"
#include "calculator/MotorEfficiency.h"
#include "calculator/OptimalMotorEfficiency.h"
#include "calculator/MotorPowerFactor.h"
#include "calculator/OptimalMotorPowerFactor.h"
#include "calculator/MotorCurrent.h"
#include "calculator/OptimalMotorCurrent.h"
#include "calculator/MotorPower.h"
#include "calculator/OptimalMotorPower.h"
#include "AnnualEnergy.h"
#include "AnnualCost.h"
#include "AnnualSavingsPotential.h"
#include "OptimizationRating.h"

using namespace v8;

Local<Array> r;
Isolate* iso;
Local<Object> inp;

void SetArgs(std::initializer_list <double> args) {
  for (auto d : args) {
    r->Set(r->Length(),Number::New(iso,d));
  }
}
double Get(const char *nm) {
  return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue();
}
void Results(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  r = Array::New(iso);
  inp = args[0]->ToObject();

  auto drive = static_cast<Pump::Drive>(Get("drive"));
  auto effCls = static_cast<Motor::EfficiencyClass>(Get("efficiency_class"));

  auto loadMeth = FieldData::LoadEstimationMethod::POWER;
  double mp = Get("motor_field_power");
  double mc = Get("motor_field_current");
  if (mc>0) {
    loadMeth = FieldData::LoadEstimationMethod::CURRENT;
    mp = (new MotorPower(0,mc,0,Get("field_voltage")))->calculate();//motor power (makes no sense, it IS motor power), motor a, motorpf
  } else {
    mc = (new MotorCurrent(Get("motor_rated_power"),mp,Get("motor_rated_speed"),effCls)/*Get("field_voltage")*/)->calculate();//motor a, motor power, recursive arg!!
  }
  SetArgs({
    (new PumpEfficiency(Get("specific_gravity"),Get("flow"),Get("head"),0))->calculate(),//pumpShaftPower
    (new OptimalPumpEfficiency(static_cast<Pump::Style>(Get("style")),
      Get("pump_rated_speed"),Get("viscosity"),Get("stages"),Get("flow"),Get("head"),static_cast<Pump::Speed>(!Get("speed"))))->calculate(),//
    mp,
    (new OptimalMotorRatedPower(0,Get("margin")))->calculate(),//motorshaftpower
    (new MotorShaftPower(0,mp,Get("motor_rated_speed"),effCls))->calculate(),//motor eff
    (new OptimalMotorShaftPower(0,drive))->calculate(),//pumpshaftpower
    (new PumpShaftPower(0,drive))->calculate(),//motorshaftpower
    (new OptimalPumpShaftPower(Get("flow"),Get("head"),Get("specific_gravity"),0))->calculate(),//pumpeff
    (new MotorEfficiency(Get("line"),Get("motor_rated_speed"),effCls,Get("motor_rated_power"),
      loadMeth,0,mc,Get("field_voltage"),0,0))->calculate(),//motorKwh??
    (new OptimalMotorEfficiency(Get("motor_rated_power"),0))->calculate(),//motor shaft power
    (new MotorPowerFactor(Get("line"),Get("rpm"),effCls,Get("power_rating"),
      loadMeth,0,mc,Get("field_voltage")))->calculate(),//motor kwh
    (new OptimalMotorPowerFactor(Get("motor_rated_power"),0))->calculate(),//opt motor power?
    mc,
    (new OptimalMotorCurrent(0,Get("field_voltage")))->calculate(),//opt motor power
    mp,
    (new OptimalMotorPower(0,0))->calculate(),//motorshaftpower, motor eff
    (new AnnualEnergy(mp,Get("fraction")))->calculate(),//motorpower
    (new AnnualEnergy(0,Get("fraction")))->calculate(),//opt motorpower
    (new AnnualCost(0,Get("cost")))->calculate(),//ex ann energy
    (new AnnualCost(0,Get("cost")))->calculate(),//opt ann energy
    -1,
    (new AnnualSavingsPotential(0,0))->calculate(),//ex an cost, opt an cost
    -1,
    (new OptimizationRating(0,0))->calculate(),//ex an cost, opt an cost

    777//est fla; hp,class,v,speed
  });
  args.GetReturnValue().Set(r);
}

void Init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "results", Results);
}

NODE_MODULE(bridge, Init)

<|endoftext|>


<commit_before>#include <node.h>
#include <node_buffer.h>

#include "LauncherShared.h"

void LaunchGame(v8::FunctionCallbackInfo<v8::Value> const& args)
{
    v8::Isolate* isolate = args.GetIsolate();
    v8::HandleScope scope(isolate);

    if (args.Length() < 5)
    {
        isolate->ThrowException(v8::Exception::TypeError(v8::String::NewFromUtf8(isolate, "Wrong number of arguments, expected 5")));
        return;
    }

    if (!args[0]->IsString() || !args[1]->IsBoolean() || !args[2]->IsString() || !args[3]->IsString() || !args[4]->IsString())
    {
        isolate->ThrowException(v8::Exception::TypeError(v8::String::NewFromUtf8(isolate,
                "Wrong arguments types, expected (gameInstallDir: string, use64Bit: boolean, portal: string, loginTicket: string, gameAccount: string)")));
        return;
    }

    v8::String::Utf8Value gameInstallDir(args[0]->ToString(isolate));
    bool use64Bit = args[1]->BooleanValue();
    v8::String::Utf8Value portal(args[2]->ToString(isolate));
    v8::String::Utf8Value loginTicket(args[3]->ToString(isolate));
    v8::String::Utf8Value gameAccount(args[4]->ToString(isolate));

    bool success = false;
    if (StoreLoginTicket(*portal, *loginTicket, *gameAccount))
        if (LaunchGameWithLogin(*gameInstallDir, use64Bit))
            success = true;

    args.GetReturnValue().Set(v8::Boolean::New(isolate, success));
}

void EncryptJsString(v8::FunctionCallbackInfo<v8::Value> const& args)
{
    v8::Isolate* isolate = args.GetIsolate();
    v8::HandleScope scope(isolate);

    if (args.Length() != 1)
    {
        isolate->ThrowException(v8::Exception::TypeError(v8::String::NewFromUtf8(isolate, "Wrong number of arguments, expected 1")));
        return;
    }

    if (!args[0]->IsString())
    {
        isolate->ThrowException(v8::Exception::TypeError(v8::String::NewFromUtf8(isolate,
            "Wrong arguments types, expected (inputString: string)")));
        return;
    }

    v8::String::Utf8Value inputString(args[0]->ToString(isolate));
    std::unique_ptr<std::vector<uint8_t>> encryptedString = std::make_unique<std::vector<uint8_t>>();

    if (!EncryptString(*inputString, encryptedString.get()))
    {
        isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, "Encryption failed")));
        return;
    }

    char* data = reinterpret_cast<char*>(encryptedString->data());
    size_t length = encryptedString->size();
    node::Buffer::FreeCallback deleter = [](char*, void* hint) { delete reinterpret_cast<std::vector<uint8_t>*>(hint); };
    v8::Local<v8::Object> returnBuffer;
    if (node::Buffer::New(isolate, data, length, deleter, encryptedString.release()).ToLocal(&returnBuffer))
        args.GetReturnValue().Set(returnBuffer);
    else
        isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, "Output buffer creation failed")));
}

void DecryptJsString(v8::FunctionCallbackInfo<v8::Value> const& args)
{
    v8::Isolate* isolate = args.GetIsolate();
    v8::HandleScope scope(isolate);

    if (args.Length() != 1)
    {
        isolate->ThrowException(v8::Exception::TypeError(v8::String::NewFromUtf8(isolate, "Wrong number of arguments, expected 1")));
        return;
    }

    if (!args[0]->IsObject())
    {
        isolate->ThrowException(v8::Exception::TypeError(v8::String::NewFromUtf8(isolate,
            "Wrong arguments types, expected (encryptedString: Buffer)")));
        return;
    }

    v8::Local<v8::Object> encryptedString = args[0]->ToObject(isolate);
    uint8_t* data = reinterpret_cast<uint8_t*>(node::Buffer::Data(encryptedString));
    size_t length = node::Buffer::Length(encryptedString);
    std::string outputString;

    if (!DecryptString(std::vector<uint8_t>(data, data + length), &outputString))
    {
        isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, "Decryption failed")));
        return;
    }

    v8::Local<v8::String> returnString;
    if (v8::String::NewFromUtf8(isolate, outputString.c_str(), v8::NewStringType::kNormal, outputString.length()).ToLocal(&returnString))
        args.GetReturnValue().Set(returnString);
    else
        isolate->ThrowException(v8::Exception::TypeError(v8::String::NewFromUtf8(isolate, "Output string creation failed")));
}

void Init(v8::Handle<v8::Object> exports)
{
    NODE_SET_METHOD(exports, "launchGame", LaunchGame);
    NODE_SET_METHOD(exports, "encryptString", EncryptJsString);
    NODE_SET_METHOD(exports, "decryptString", DecryptJsString);
}

NODE_MODULE(tc_launcher, Init)
<commit_msg>Build fix<commit_after>#include <node.h>
#include <node_buffer.h>

#include "LauncherShared.h"
#include <memory>

void LaunchGame(v8::FunctionCallbackInfo<v8::Value> const& args)
{
    v8::Isolate* isolate = args.GetIsolate();
    v8::HandleScope scope(isolate);

    if (args.Length() < 5)
    {
        isolate->ThrowException(v8::Exception::TypeError(v8::String::NewFromUtf8(isolate, "Wrong number of arguments, expected 5")));
        return;
    }

    if (!args[0]->IsString() || !args[1]->IsBoolean() || !args[2]->IsString() || !args[3]->IsString() || !args[4]->IsString())
    {
        isolate->ThrowException(v8::Exception::TypeError(v8::String::NewFromUtf8(isolate,
                "Wrong arguments types, expected (gameInstallDir: string, use64Bit: boolean, portal: string, loginTicket: string, gameAccount: string)")));
        return;
    }

    v8::String::Utf8Value gameInstallDir(args[0]->ToString(isolate));
    bool use64Bit = args[1]->BooleanValue();
    v8::String::Utf8Value portal(args[2]->ToString(isolate));
    v8::String::Utf8Value loginTicket(args[3]->ToString(isolate));
    v8::String::Utf8Value gameAccount(args[4]->ToString(isolate));

    bool success = false;
    if (StoreLoginTicket(*portal, *loginTicket, *gameAccount))
        if (LaunchGameWithLogin(*gameInstallDir, use64Bit))
            success = true;

    args.GetReturnValue().Set(v8::Boolean::New(isolate, success));
}

void EncryptJsString(v8::FunctionCallbackInfo<v8::Value> const& args)
{
    v8::Isolate* isolate = args.GetIsolate();
    v8::HandleScope scope(isolate);

    if (args.Length() != 1)
    {
        isolate->ThrowException(v8::Exception::TypeError(v8::String::NewFromUtf8(isolate, "Wrong number of arguments, expected 1")));
        return;
    }

    if (!args[0]->IsString())
    {
        isolate->ThrowException(v8::Exception::TypeError(v8::String::NewFromUtf8(isolate,
            "Wrong arguments types, expected (inputString: string)")));
        return;
    }

    v8::String::Utf8Value inputString(args[0]->ToString(isolate));
    std::unique_ptr<std::vector<uint8_t>> encryptedString = std::make_unique<std::vector<uint8_t>>();

    if (!EncryptString(*inputString, encryptedString.get()))
    {
        isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, "Encryption failed")));
        return;
    }

    char* data = reinterpret_cast<char*>(encryptedString->data());
    size_t length = encryptedString->size();
    node::Buffer::FreeCallback deleter = [](char*, void* hint) { delete reinterpret_cast<std::vector<uint8_t>*>(hint); };
    v8::Local<v8::Object> returnBuffer;
    if (node::Buffer::New(isolate, data, length, deleter, encryptedString.release()).ToLocal(&returnBuffer))
        args.GetReturnValue().Set(returnBuffer);
    else
        isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, "Output buffer creation failed")));
}

void DecryptJsString(v8::FunctionCallbackInfo<v8::Value> const& args)
{
    v8::Isolate* isolate = args.GetIsolate();
    v8::HandleScope scope(isolate);

    if (args.Length() != 1)
    {
        isolate->ThrowException(v8::Exception::TypeError(v8::String::NewFromUtf8(isolate, "Wrong number of arguments, expected 1")));
        return;
    }

    if (!args[0]->IsObject())
    {
        isolate->ThrowException(v8::Exception::TypeError(v8::String::NewFromUtf8(isolate,
            "Wrong arguments types, expected (encryptedString: Buffer)")));
        return;
    }

    v8::Local<v8::Object> encryptedString = args[0]->ToObject(isolate);
    uint8_t* data = reinterpret_cast<uint8_t*>(node::Buffer::Data(encryptedString));
    size_t length = node::Buffer::Length(encryptedString);
    std::string outputString;

    if (!DecryptString(std::vector<uint8_t>(data, data + length), &outputString))
    {
        isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, "Decryption failed")));
        return;
    }

    v8::Local<v8::String> returnString;
    if (v8::String::NewFromUtf8(isolate, outputString.c_str(), v8::NewStringType::kNormal, outputString.length()).ToLocal(&returnString))
        args.GetReturnValue().Set(returnString);
    else
        isolate->ThrowException(v8::Exception::TypeError(v8::String::NewFromUtf8(isolate, "Output string creation failed")));
}

void Init(v8::Handle<v8::Object> exports)
{
    NODE_SET_METHOD(exports, "launchGame", LaunchGame);
    NODE_SET_METHOD(exports, "encryptString", EncryptJsString);
    NODE_SET_METHOD(exports, "decryptString", DecryptJsString);
}

NODE_MODULE(tc_launcher, Init)
<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include "emulator.h"
#include "register.h"
#include "insndata.h"
#include "instruction.h"
#include "instruction16.h"
#include "instruction32.h"
#include "../../device/pic.h"
#include "../../device/keyboard.h"

using namespace std;

namespace x86{

void Emulator::InitInstructions(){
	// 起動時は16bitリアルモード
	idata = new InsnData(this);
	insn16 = new Instruction16(this, idata);
	insn32 = new Instruction32(this, idata);
	insn16->Init();
	insn32->Init();
	insn = insn16;
	mode = 16;
}

void Emulator::InitRegisters(){
	pc.SetName("EIP");
	eflags.SetName("EFLAGS");

	reg = std::vector<x86::Register32>(REG_COUNT);
	const char* reg_name[REG_COUNT] = {
		"EAX", "ECX", "EDX", "EBX", "ESP", "EBP", "ESI", "EDI",
	};
	for(size_t i=0;i<REG_COUNT;i++){
		reg[i].SetName(reg_name[i]);
	}

	sreg = std::vector<x86::SRegister>(SREG_COUNT);
	const char* sreg_name[SREG_COUNT] = {
		"ES", "CS", "SS", "DS", "FS", "GS",
	};
	for(size_t i=0;i<SREG_COUNT;i++)
		sreg[i].SetName(sreg_name[i]);

	GDTR.SetName("GDTR");
	IDTR.SetName("IDTR");
	TR.SetName("  TR");
	LDTR.SetName("LDTR");
	GDTR.SetSize(sizeof(uint64_t)*3/4);
	IDTR.SetSize(sizeof(uint64_t)*3/4);

// all_regへの登録
	all_reg.push_back(&pc);
	all_reg.push_back(&eflags);
	for(size_t i=0;i<REG_COUNT;i++)
		all_reg.push_back(&reg[i]);
	for(size_t i=0;i<SREG_COUNT;i++)
		all_reg.push_back(&sreg[i]);
	all_reg.push_back(&GDTR);
	all_reg.push_back(&IDTR);
	all_reg.push_back(&TR);
	all_reg.push_back(&LDTR);
}

void Emulator::InitMemory(){
	memory->endian = ENDIAN::LITTLE;
}

void Emulator::InitIO(){
	io = new IO();
	auto pic = new Device::PIC();
	io->port[0x20] = io->port[0x21] = io->port[0xa0] = io->port[0xa1] = pic;

	auto keyboard = new Device::Keyboard();
	io->port[0x60] = io->port[0x64] = keyboard;
}

void Emulator::RunStep(){
	bool is_16 = IsMode16();

	insn->Fetch();
	idata->chsiz_addr = !(is_16 ^ idata->chsiz_addr);
	if(is_16 ^  idata->chsiz_op){
		insn16->Decode();
		insn16->Exec();
	}else{
		insn32->Decode();
		insn32->Exec();
	}

	DOUT(std::endl);
}

}
<commit_msg>[ADD] initialize memory management registers<commit_after>#include <iostream>
#include <sstream>
#include "emulator.h"
#include "register.h"
#include "insndata.h"
#include "instruction.h"
#include "instruction16.h"
#include "instruction32.h"
#include "../../device/pic.h"
#include "../../device/keyboard.h"

using namespace std;

namespace x86{

void Emulator::InitInstructions(){
	// 起動時は16bitリアルモード
	idata = new InsnData(this);
	insn16 = new Instruction16(this, idata);
	insn32 = new Instruction32(this, idata);
	insn16->Init();
	insn32->Init();
	insn = insn16;
	mode = 16;
}

void Emulator::InitRegisters(){
	pc.SetName("EIP");
	eflags.SetName("EFLAGS");

	reg = std::vector<x86::Register32>(REG_COUNT);
	const char* reg_name[REG_COUNT] = {
		"EAX", "ECX", "EDX", "EBX", "ESP", "EBP", "ESI", "EDI",
	};
	for(size_t i=0;i<REG_COUNT;i++){
		reg[i].SetName(reg_name[i]);
	}

	sreg = std::vector<x86::SRegister>(SREG_COUNT);
	const char* sreg_name[SREG_COUNT] = {
		"ES", "CS", "SS", "DS", "FS", "GS",
	};
	for(size_t i=0;i<SREG_COUNT;i++)
		sreg[i].SetName(sreg_name[i]);

	GDTR.SetName("GDTR");
	IDTR.SetName("IDTR");
	TR.SetName("  TR");
	LDTR.SetName("LDTR");
	GDTR.SetSize(sizeof(uint64_t)*3/4);
	IDTR.SetSize(sizeof(uint64_t)*3/4);

	LDTR.selector = 0x00;
	GDTR.base  = IDTR.base = TR.base = LDTR.base	= 0x00;
	GDTR.limit = IDTR.limit = TR.limit = LDTR.limit	= 0xffff;

// all_regへの登録
	all_reg.push_back(&pc);
	all_reg.push_back(&eflags);
	for(size_t i=0;i<REG_COUNT;i++)
		all_reg.push_back(&reg[i]);
	for(size_t i=0;i<SREG_COUNT;i++)
		all_reg.push_back(&sreg[i]);
	all_reg.push_back(&GDTR);
	all_reg.push_back(&IDTR);
	all_reg.push_back(&TR);
	all_reg.push_back(&LDTR);
}

void Emulator::InitMemory(){
	memory->endian = ENDIAN::LITTLE;
}

void Emulator::InitIO(){
	io = new IO();
	auto pic = new Device::PIC();
	io->port[0x20] = io->port[0x21] = io->port[0xa0] = io->port[0xa1] = pic;

	auto keyboard = new Device::Keyboard();
	io->port[0x60] = io->port[0x64] = keyboard;
}

void Emulator::RunStep(){
	bool is_16 = IsMode16();

	insn->Fetch();
	idata->chsiz_addr = !(is_16 ^ idata->chsiz_addr);
	if(is_16 ^  idata->chsiz_op){
		insn16->Decode();
		insn16->Exec();
	}else{
		insn32->Decode();
		insn32->Exec();
	}

	DOUT(std::endl);
}

}
<|endoftext|>


<commit_before>#include "nbt/nbt.h"

#include <iostream>

using namespace std;

void begin_compound(void*, nbt::String name) {
  cout << "BEGIN Compound(" << name << ")" << endl;
}

void end_compound(void*, nbt::String name) {
  cout << "END Compound(" << name << ")" << endl;
}

void begin_list(void*, nbt::String name, nbt::Byte type, nbt::Int length) {
  cout << "BEGIN List(" << name << ", 0x" << hex << (int)type << ", " << length << ")" << endl;
}

void end_list(void*, nbt::String name) {
  cout << "END List(" << name << ")" << endl;
}

void register_string(void*, nbt::String name, nbt::String value) {
  cout << "String(" << name << "): " << value << endl;
}

void register_short(void*, nbt::String name, nbt::Short value) {
  cout << "Short(" << name << "): " << value << endl;
}

void register_long(void*, nbt::String name, nbt::Long value) {
  cout << "Long(" << name << "): " << value << endl;
}

void register_int(void*, nbt::String name, nbt::Int value) {
  cout << "Int(" << name << "): " << value << endl;
}

void register_byte_array(void*, nbt::String name, nbt::ByteArray* value) {
  cout << "ByteArray(" << name << "): " << value->length << endl;
}

int main(int argc, char* argv[]) {
  if (argc < 2) {
    return 1;
  }

  nbt::Parser<void> parser(NULL);
  parser.begin_compound = begin_compound;
  parser.end_compound = end_compound;
  parser.begin_list = begin_list;
  parser.end_list = end_list;
  parser.register_string = register_string;
  parser.register_short = register_short;
  parser.register_long = register_long;
  parser.register_int = register_int;
  parser.register_byte_array = register_byte_array;
  parser.parse_file(argv[1]);
}
<commit_msg>Added better inspection<commit_after>#include "nbt/nbt.h"

#include <iostream>
#include <iomanip>

using namespace std;

struct inspect_context {
  int width;
};

void begin_compound(inspect_context* inspect, nbt::String name) {
  cout << setw(inspect->width) << ""
       << "BEGIN Compound(" << name << ")" << endl;
  inspect->width += 2;
}

void end_compound(inspect_context* inspect, nbt::String name) {
  inspect->width -= 2;
  cout << setw(inspect->width) << ""
       << "END Compound(" << name << ")" << endl;
}

void begin_list(inspect_context* inspect, nbt::String name, nbt::Byte type, nbt::Int length) {
  cout << setw(inspect->width) << ""
       << "BEGIN List(" << name << ", 0x" << hex << (int)type << ", " << length << ")" << endl;
  inspect->width += 2;
}

void end_list(inspect_context* inspect, nbt::String name) {
  inspect->width -= 2;
  cout << setw(inspect->width) << ""
       << "END List(" << name << ")" << endl;
}

void register_long(inspect_context* inspect, nbt::String name, nbt::Long value) {
  cout << setw(inspect->width) << ""
       << "Long(" << name << "): " << dec << value << endl;
}

void register_short(inspect_context* inspect, nbt::String name, nbt::Short value) {
  cout << setw(inspect->width) << ""
       << "Short(" << name << "): " << value << endl;
}

void register_string(inspect_context* inspect, nbt::String name, nbt::String value) {
  cout << setw(inspect->width) << ""
       << "String(" << name << "): " << value << endl;
}

void register_float(inspect_context* inspect, nbt::String name, nbt::Float value) {
  cout << setw(inspect->width) << ""
       << "Float(" << name << "): " << value << endl;
}

void register_double(inspect_context* inspect, nbt::String name, nbt::Double value) {
  cout << setw(inspect->width) << ""
       << "Double(" << name << "): " << value << endl;
}

void register_int(inspect_context* inspect, nbt::String name, nbt::Int value) {
  cout << setw(inspect->width) << ""
       << "Int(" << name << "): " << value << endl;
}

void register_byte(inspect_context* inspect, nbt::String name, nbt::Byte value) {
  cout << setw(inspect->width) << ""
       << "Byte(" << name << "): 0x" << hex << (int)value << endl;
}

void register_byte_array(inspect_context* inspect, nbt::String name, nbt::ByteArray* value) {
  cout << setw(inspect->width) << ""
       << "ByteArray(" << name << "): " << "(binary blob)" << endl;
}

int main(int argc, char* argv[]) {
  if (argc < 2) {
    return 1;
  }

  inspect_context ctx;
  ctx.width = 0;

  nbt::Parser<inspect_context> parser(&ctx);
  parser.begin_compound = begin_compound;
  parser.end_compound = end_compound;
  parser.begin_list = begin_list;
  parser.end_list = end_list;
  parser.register_long = register_long;
  parser.register_short = register_short;
  parser.register_string = register_string;
  parser.register_float = register_float;
  parser.register_double = register_double;
  parser.register_int = register_int;
  parser.register_byte = register_byte;
  parser.register_byte_array = register_byte_array;
  parser.parse_file(argv[1]);
}
<|endoftext|>


<commit_before>#include "user-env.hh"
#include "util.hh"
#include "derivations.hh"
#include "store-api.hh"
#include "globals.hh"
#include "shared.hh"
#include "eval.hh"
#include "eval-inline.hh"
#include "profiles.hh"

namespace nix {

DrvInfos queryInstalled(EvalState & state, const Path & userEnv)
{
    DrvInfos elems;
    Path manifestFile = userEnv + "/manifest.nix";
    if (pathExists(manifestFile)) {
        Value v;
        state.evalFile(manifestFile, v);
        Bindings bindings;
        getDerivations(state, v, "", bindings, elems, false);
    }
    return elems;
}

bool createUserEnv(EvalState & state, DrvInfos & elems,
    const Path & profile, bool keepDerivations,
    const string & lockToken)
{
    /* Build the components in the user environment, if they don't
       exist already. */
    PathSet drvsToBuild;
    foreach (DrvInfos::iterator, i, elems)
        if (i->queryDrvPath() != "")
            drvsToBuild.insert(i->queryDrvPath());

    debug(format("building user environment dependencies"));
    store->buildPaths(drvsToBuild, state.repair ? bmRepair : bmNormal);

    /* Construct the whole top level derivation. */
    PathSet references;
    Value manifest;
    state.mkList(manifest, elems.size());
    unsigned int n = 0;
    foreach (DrvInfos::iterator, i, elems) {
        /* Create a pseudo-derivation containing the name, system,
           output paths, and optionally the derivation path, as well
           as the meta attributes. */
        Path drvPath = keepDerivations ? i->queryDrvPath() : "";

        Value & v(*state.allocValue());
        manifest.list.elems[n++] = &v;
        state.mkAttrs(v, 16);

        mkString(*state.allocAttr(v, state.sType), "derivation");
        mkString(*state.allocAttr(v, state.sName), i->name);
        if (!i->system.empty())
            mkString(*state.allocAttr(v, state.sSystem), i->system);
        mkString(*state.allocAttr(v, state.sOutPath), i->queryOutPath());
        if (drvPath != "")
            mkString(*state.allocAttr(v, state.sDrvPath), i->queryDrvPath());

        // Copy each output.
        DrvInfo::Outputs outputs = i->queryOutputs();
        Value & vOutputs = *state.allocAttr(v, state.sOutputs);
        state.mkList(vOutputs, outputs.size());
        unsigned int m = 0;
        foreach (DrvInfo::Outputs::iterator, j, outputs) {
            mkString(*(vOutputs.list.elems[m++] = state.allocValue()), j->first);
            Value & vOutputs = *state.allocAttr(v, state.symbols.create(j->first));
            state.mkAttrs(vOutputs, 2);
            mkString(*state.allocAttr(vOutputs, state.sOutPath), j->second);

            /* This is only necessary when installing store paths, e.g.,
               `nix-env -i /nix/store/abcd...-foo'. */
            store->addTempRoot(j->second);
            store->ensurePath(j->second);

            references.insert(j->second);
        }

        // Copy the meta attributes.
        Value & vMeta = *state.allocAttr(v, state.sMeta);
        state.mkAttrs(vMeta, 16);
        StringSet metaNames = i->queryMetaNames();
        foreach (StringSet::iterator, j, metaNames) {
            Value * v = i->queryMeta(*j);
            if (!v) continue;
            vMeta.attrs->push_back(Attr(state.symbols.create(*j), v));
        }
        v.attrs->sort();

        if (drvPath != "") references.insert(drvPath);
    }

    /* Also write a copy of the list of user environment elements to
       the store; we need it for future modifications of the
       environment. */
    Path manifestFile = store->addTextToStore("env-manifest.nix",
        (format("%1%") % manifest).str(), references);

    /* Get the environment builder expression. */
    Value envBuilder;
    state.evalFile(state.findFile("nix/buildenv.nix"), envBuilder);

    /* Construct a Nix expression that calls the user environment
       builder with the manifest as argument. */
    Value args, topLevel;
    state.mkAttrs(args, 3);
    mkString(*state.allocAttr(args, state.symbols.create("manifest")),
        manifestFile, singleton<PathSet>(manifestFile));
    args.attrs->push_back(Attr(state.symbols.create("derivations"), &manifest));
    args.attrs->sort();
    mkApp(topLevel, envBuilder, args);

    /* Evaluate it. */
    debug("evaluating user environment builder");
    state.forceValue(topLevel);
    PathSet context;
    Path topLevelDrv = state.coerceToPath(*topLevel.attrs->find(state.sDrvPath)->value, context);
    Path topLevelOut = state.coerceToPath(*topLevel.attrs->find(state.sOutPath)->value, context);

    /* Realise the resulting store expression. */
    debug("building user environment");
    store->buildPaths(singleton<PathSet>(topLevelDrv), state.repair ? bmRepair : bmNormal);

    /* Switch the current user environment to the output path. */
    PathLocks lock;
    lockProfile(lock, profile);

    Path lockTokenCur = optimisticLockProfile(profile);
    if (lockToken != lockTokenCur) {
        printMsg(lvlError, format("profile `%1%' changed while we were busy; restarting") % profile);
        return false;
    }

    debug(format("switching to new user environment"));
    Path generation = createGeneration(profile, topLevelOut);
    switchLink(profile, generation);

    return true;
}

}
<commit_msg>Fix passing meta attribute to buildenv.nix<commit_after>#include "user-env.hh"
#include "util.hh"
#include "derivations.hh"
#include "store-api.hh"
#include "globals.hh"
#include "shared.hh"
#include "eval.hh"
#include "eval-inline.hh"
#include "profiles.hh"

namespace nix {

DrvInfos queryInstalled(EvalState & state, const Path & userEnv)
{
    DrvInfos elems;
    Path manifestFile = userEnv + "/manifest.nix";
    if (pathExists(manifestFile)) {
        Value v;
        state.evalFile(manifestFile, v);
        Bindings bindings;
        getDerivations(state, v, "", bindings, elems, false);
    }
    return elems;
}

bool createUserEnv(EvalState & state, DrvInfos & elems,
    const Path & profile, bool keepDerivations,
    const string & lockToken)
{
    /* Build the components in the user environment, if they don't
       exist already. */
    PathSet drvsToBuild;
    foreach (DrvInfos::iterator, i, elems)
        if (i->queryDrvPath() != "")
            drvsToBuild.insert(i->queryDrvPath());

    debug(format("building user environment dependencies"));
    store->buildPaths(drvsToBuild, state.repair ? bmRepair : bmNormal);

    /* Construct the whole top level derivation. */
    PathSet references;
    Value manifest;
    state.mkList(manifest, elems.size());
    unsigned int n = 0;
    foreach (DrvInfos::iterator, i, elems) {
        /* Create a pseudo-derivation containing the name, system,
           output paths, and optionally the derivation path, as well
           as the meta attributes. */
        Path drvPath = keepDerivations ? i->queryDrvPath() : "";

        Value & v(*state.allocValue());
        manifest.list.elems[n++] = &v;
        state.mkAttrs(v, 16);

        mkString(*state.allocAttr(v, state.sType), "derivation");
        mkString(*state.allocAttr(v, state.sName), i->name);
        if (!i->system.empty())
            mkString(*state.allocAttr(v, state.sSystem), i->system);
        mkString(*state.allocAttr(v, state.sOutPath), i->queryOutPath());
        if (drvPath != "")
            mkString(*state.allocAttr(v, state.sDrvPath), i->queryDrvPath());

        // Copy each output.
        DrvInfo::Outputs outputs = i->queryOutputs();
        Value & vOutputs = *state.allocAttr(v, state.sOutputs);
        state.mkList(vOutputs, outputs.size());
        unsigned int m = 0;
        foreach (DrvInfo::Outputs::iterator, j, outputs) {
            mkString(*(vOutputs.list.elems[m++] = state.allocValue()), j->first);
            Value & vOutputs = *state.allocAttr(v, state.symbols.create(j->first));
            state.mkAttrs(vOutputs, 2);
            mkString(*state.allocAttr(vOutputs, state.sOutPath), j->second);

            /* This is only necessary when installing store paths, e.g.,
               `nix-env -i /nix/store/abcd...-foo'. */
            store->addTempRoot(j->second);
            store->ensurePath(j->second);

            references.insert(j->second);
        }

        // Copy the meta attributes.
        Value & vMeta = *state.allocAttr(v, state.sMeta);
        state.mkAttrs(vMeta, 16);
        StringSet metaNames = i->queryMetaNames();
        foreach (StringSet::iterator, j, metaNames) {
            Value * v = i->queryMeta(*j);
            if (!v) continue;
            vMeta.attrs->push_back(Attr(state.symbols.create(*j), v));
        }
        vMeta.attrs->sort();
        v.attrs->sort();

        if (drvPath != "") references.insert(drvPath);
    }

    /* Also write a copy of the list of user environment elements to
       the store; we need it for future modifications of the
       environment. */
    Path manifestFile = store->addTextToStore("env-manifest.nix",
        (format("%1%") % manifest).str(), references);

    /* Get the environment builder expression. */
    Value envBuilder;
    state.evalFile(state.findFile("nix/buildenv.nix"), envBuilder);

    /* Construct a Nix expression that calls the user environment
       builder with the manifest as argument. */
    Value args, topLevel;
    state.mkAttrs(args, 3);
    mkString(*state.allocAttr(args, state.symbols.create("manifest")),
        manifestFile, singleton<PathSet>(manifestFile));
    args.attrs->push_back(Attr(state.symbols.create("derivations"), &manifest));
    args.attrs->sort();
    mkApp(topLevel, envBuilder, args);

    /* Evaluate it. */
    debug("evaluating user environment builder");
    state.forceValue(topLevel);
    PathSet context;
    Path topLevelDrv = state.coerceToPath(*topLevel.attrs->find(state.sDrvPath)->value, context);
    Path topLevelOut = state.coerceToPath(*topLevel.attrs->find(state.sOutPath)->value, context);

    /* Realise the resulting store expression. */
    debug("building user environment");
    store->buildPaths(singleton<PathSet>(topLevelDrv), state.repair ? bmRepair : bmNormal);

    /* Switch the current user environment to the output path. */
    PathLocks lock;
    lockProfile(lock, profile);

    Path lockTokenCur = optimisticLockProfile(profile);
    if (lockToken != lockTokenCur) {
        printMsg(lvlError, format("profile `%1%' changed while we were busy; restarting") % profile);
        return false;
    }

    debug(format("switching to new user environment"));
    Path generation = createGeneration(profile, topLevelOut);
    switchLink(profile, generation);

    return true;
}

}
<|endoftext|>


<commit_before>// Copyright (c) 2018-2019 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <llmq/quorums_init.h>

#include <llmq/quorums.h>
#include <llmq/quorums_blockprocessor.h>
#include <llmq/quorums_commitment.h>
#include <llmq/quorums_debug.h>
#include <llmq/quorums_dkgsessionmgr.h>
#include <llmq/quorums_signing.h>
#include <llmq/quorums_signing_shares.h>
#include <llmq/quorums_chainlocks.h>
#include <consensus/validation.h>
#include <dbwrapper.h>
#include <net.h>
namespace llmq
{

CBLSWorker* blsWorker;

CDBWrapper* llmqDb;

void InitLLMQSystem(bool unitTests, CConnman& connman, BanMan& banman, PeerManager& peerman, bool fWipe)
{
    llmqDb = new CDBWrapper(unitTests ? "" : (gArgs.GetDataDirNet() / "llmq"), 1 << 20, unitTests, fWipe);
    blsWorker = new CBLSWorker();

    quorumDKGDebugManager = new CDKGDebugManager();
    quorumBlockProcessor = new CQuorumBlockProcessor(connman);
    quorumDKGSessionManager = new CDKGSessionManager(*llmqDb, *blsWorker, connman, peerman);
    quorumManager = new CQuorumManager(*blsWorker, *quorumDKGSessionManager);
    quorumSigSharesManager = new CSigSharesManager(connman, banman, peerman);
    quorumSigningManager = new CSigningManager(*llmqDb, unitTests, connman, peerman);
    chainLocksHandler = new CChainLocksHandler(connman, peerman);
}

void DestroyLLMQSystem()
{
    delete chainLocksHandler;
    chainLocksHandler = nullptr;
    delete quorumSigningManager;
    quorumSigningManager = nullptr;
    delete quorumSigSharesManager;
    quorumSigSharesManager = nullptr;
    delete quorumManager;
    quorumManager = nullptr;
    delete quorumDKGSessionManager;
    quorumDKGSessionManager = nullptr;
    delete quorumBlockProcessor;
    quorumBlockProcessor = nullptr;
    delete quorumDKGDebugManager;
    quorumDKGDebugManager = nullptr;
    delete blsWorker;
    blsWorker = nullptr;
    delete llmqDb;
    llmqDb = nullptr;
}

void StartLLMQSystem()
{
    if (blsWorker) {
        blsWorker->Start();
    }
    if (quorumDKGSessionManager) {
        quorumDKGSessionManager->StartThreads();
    }
    if (quorumManager) {
        quorumManager->Start();
    }
    if (quorumSigSharesManager) {
        quorumSigSharesManager->RegisterAsRecoveredSigsListener();
        quorumSigSharesManager->StartWorkerThread();
    }
    if (chainLocksHandler) {
        chainLocksHandler->Start();
    }
}

void StopLLMQSystem()
{
    if (chainLocksHandler) {
        chainLocksHandler->Stop();
    }
    if (quorumSigSharesManager) {
        quorumSigSharesManager->StopWorkerThread();
        quorumSigSharesManager->UnregisterAsRecoveredSigsListener();
    }
    if (quorumManager) {
        quorumManager->Stop();
    }
    if (quorumDKGSessionManager) {
        quorumDKGSessionManager->StopThreads();
    }
    if (blsWorker) {
        blsWorker->Stop();
    }
}

void InterruptLLMQSystem()
{
    if (quorumSigSharesManager) {
        quorumSigSharesManager->InterruptWorkerThread();
    }
}

} // namespace llmq
<commit_msg>llmq: Bump llmq leveldb cache size to 8 MiB<commit_after>// Copyright (c) 2018-2019 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <llmq/quorums_init.h>

#include <llmq/quorums.h>
#include <llmq/quorums_blockprocessor.h>
#include <llmq/quorums_commitment.h>
#include <llmq/quorums_debug.h>
#include <llmq/quorums_dkgsessionmgr.h>
#include <llmq/quorums_signing.h>
#include <llmq/quorums_signing_shares.h>
#include <llmq/quorums_chainlocks.h>
#include <consensus/validation.h>
#include <dbwrapper.h>
#include <net.h>
namespace llmq
{

CBLSWorker* blsWorker;

CDBWrapper* llmqDb;

void InitLLMQSystem(bool unitTests, CConnman& connman, BanMan& banman, PeerManager& peerman, bool fWipe)
{
    llmqDb = new CDBWrapper(unitTests ? "" : (gArgs.GetDataDirNet() / "llmq"), 8 << 20, unitTests, fWipe);
    blsWorker = new CBLSWorker();

    quorumDKGDebugManager = new CDKGDebugManager();
    quorumBlockProcessor = new CQuorumBlockProcessor(connman);
    quorumDKGSessionManager = new CDKGSessionManager(*llmqDb, *blsWorker, connman, peerman);
    quorumManager = new CQuorumManager(*blsWorker, *quorumDKGSessionManager);
    quorumSigSharesManager = new CSigSharesManager(connman, banman, peerman);
    quorumSigningManager = new CSigningManager(*llmqDb, unitTests, connman, peerman);
    chainLocksHandler = new CChainLocksHandler(connman, peerman);
}

void DestroyLLMQSystem()
{
    delete chainLocksHandler;
    chainLocksHandler = nullptr;
    delete quorumSigningManager;
    quorumSigningManager = nullptr;
    delete quorumSigSharesManager;
    quorumSigSharesManager = nullptr;
    delete quorumManager;
    quorumManager = nullptr;
    delete quorumDKGSessionManager;
    quorumDKGSessionManager = nullptr;
    delete quorumBlockProcessor;
    quorumBlockProcessor = nullptr;
    delete quorumDKGDebugManager;
    quorumDKGDebugManager = nullptr;
    delete blsWorker;
    blsWorker = nullptr;
    delete llmqDb;
    llmqDb = nullptr;
}

void StartLLMQSystem()
{
    if (blsWorker) {
        blsWorker->Start();
    }
    if (quorumDKGSessionManager) {
        quorumDKGSessionManager->StartThreads();
    }
    if (quorumManager) {
        quorumManager->Start();
    }
    if (quorumSigSharesManager) {
        quorumSigSharesManager->RegisterAsRecoveredSigsListener();
        quorumSigSharesManager->StartWorkerThread();
    }
    if (chainLocksHandler) {
        chainLocksHandler->Start();
    }
}

void StopLLMQSystem()
{
    if (chainLocksHandler) {
        chainLocksHandler->Stop();
    }
    if (quorumSigSharesManager) {
        quorumSigSharesManager->StopWorkerThread();
        quorumSigSharesManager->UnregisterAsRecoveredSigsListener();
    }
    if (quorumManager) {
        quorumManager->Stop();
    }
    if (quorumDKGSessionManager) {
        quorumDKGSessionManager->StopThreads();
    }
    if (blsWorker) {
        blsWorker->Stop();
    }
}

void InterruptLLMQSystem()
{
    if (quorumSigSharesManager) {
        quorumSigSharesManager->InterruptWorkerThread();
    }
}

} // namespace llmq
<|endoftext|>


<commit_before>#include <disir/cli/command.h>
#include <disir/cli/cli.h>

#include <iostream>

using namespace disir;

Command::Command (std::string name)
    : m_name (name)
{
}

void
Command::setup_parser (args::ArgumentParser& parser)
{
    parser.helpParams.progindent = 0;
    parser.helpParams.progtailindent = 2;
    parser.helpParams.descriptionindent = 2;
    parser.helpParams.flagindent = 2;
    parser.helpParams.eachgroupindent = 0;
    parser.helpParams.helpindent = 28;
    parser.helpParams.showTerminator = false;
}

int
Command::list_configs (std::set<std::string>& list)
{
    enum disir_status status;
    struct disir_entry *config_entries;
    struct disir_entry *next;
    struct disir_entry *current;

    status = disir_config_entries (m_cli->disir(), m_cli->group_id().c_str(), &config_entries);
    if (status != DISIR_STATUS_OK)
    {
        std::cerr << "error querying available configs: "
                  << disir_error (m_cli->disir()) << std::endl;
        return (-1);
    }

    current = config_entries;
    while (current != NULL)
    {
        next = current->next;

        list.insert (std::string(current->de_entry_name));

        disir_entry_finished (&current);
        current = next;
    }

    return (0);
}

int
Command::setup_group (std::string id)
{
    int code;
    std::list<std::string> groups;

    m_cli->list_groups (groups);

    if (std::find (groups.begin(), groups.end(), id) == groups.end())
    {
        // invalid entry
        std::cerr << "error: invalid group selected - " << id << std::endl;
        std::cerr << "Select one of the following:" << std::endl;
        for (auto& g : groups)
        {
            std::cerr << "  " << g << std::endl;
        }

        code = 1;
    }
    else
    {
        m_cli->group_id (id);
        m_cli->verbose() << "Setting user-provided group id to: " << m_cli->group_id << std::endl;
        code = 0;
    }

    return (code);
}
<commit_msg>fix cli: method missing parenthesis<commit_after>#include <disir/cli/command.h>
#include <disir/cli/cli.h>

#include <iostream>

using namespace disir;

Command::Command (std::string name)
    : m_name (name)
{
}

void
Command::setup_parser (args::ArgumentParser& parser)
{
    parser.helpParams.progindent = 0;
    parser.helpParams.progtailindent = 2;
    parser.helpParams.descriptionindent = 2;
    parser.helpParams.flagindent = 2;
    parser.helpParams.eachgroupindent = 0;
    parser.helpParams.helpindent = 28;
    parser.helpParams.showTerminator = false;
}

int
Command::list_configs (std::set<std::string>& list)
{
    enum disir_status status;
    struct disir_entry *config_entries;
    struct disir_entry *next;
    struct disir_entry *current;

    status = disir_config_entries (m_cli->disir(), m_cli->group_id().c_str(), &config_entries);
    if (status != DISIR_STATUS_OK)
    {
        std::cerr << "error querying available configs: "
                  << disir_error (m_cli->disir()) << std::endl;
        return (-1);
    }

    current = config_entries;
    while (current != NULL)
    {
        next = current->next;

        list.insert (std::string(current->de_entry_name));

        disir_entry_finished (&current);
        current = next;
    }

    return (0);
}

int
Command::setup_group (std::string id)
{
    int code;
    std::list<std::string> groups;

    m_cli->list_groups (groups);

    if (std::find (groups.begin(), groups.end(), id) == groups.end())
    {
        // invalid entry
        std::cerr << "error: invalid group selected - " << id << std::endl;
        std::cerr << "Select one of the following:" << std::endl;
        for (auto& g : groups)
        {
            std::cerr << "  " << g << std::endl;
        }

        code = 1;
    }
    else
    {
        m_cli->group_id (id);
        m_cli->verbose() << "Setting user-provided group id to: "
                         << m_cli->group_id() << std::endl;
        code = 0;
    }

    return (code);
}
<|endoftext|>


<commit_before>/** @file
    @brief Implementation

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

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

// Internal Includes
#include <osvr/ClientKit/Context.h>
#include <osvr/Common/ClientContext.h>
#include <osvr/Common/PathTreeFull.h>
#include <osvr/Common/ResolveFullTree.h>
#include <osvr/Util/TreeTraversalVisitor.h>
#include <osvr/Common/PathElementTypes.h>
#include <osvr/Common/PathElementTools.h>
#include <osvr/Common/ApplyPathNodeVisitor.h>
#include <osvr/Common/PathNode.h>
#include <osvr/Util/IndentingStream.h>
#include <osvr/Util/ProgramOptionsToggleFlags.h>

// Library/third-party includes
#include <boost/program_options.hpp>
#include <boost/noncopyable.hpp>
#include <boost/variant.hpp>

// Standard includes
#include <iostream>
#include <iomanip>
#include <thread>
#include <chrono>

struct Options {
    bool showAliasSource;
    bool showAliasPriority;
    bool showDeviceDetails;
    bool showDeviceDescriptor;
    bool showSensors;
    bool showStringData;
};

using osvr::common::PathNode;
namespace elements = osvr::common::elements;

/// This functor is applied at each node to get the (type-safe variant) value
/// out of it (hence the numerous overloads of the function call operator - one
/// for each node element type we want to treat differently.)
///
/// As a "visitor", this visitor visits just a single node - it's used by a
/// simple lambda to visit every node in the path tree.
class TreeNodePrinter : public boost::static_visitor<>, boost::noncopyable {
  public:
    /// @brief Constructor
    TreeNodePrinter(Options opts)
        : boost::static_visitor<>(), m_opts(opts),
          m_maxTypeLen(elements::getMaxTypeNameLength()), m_os(std::cout),
          m_indentStream{m_maxTypeLen + 2 + 1 + 2, m_os} {
        // Computation for initializing the indent stream above:
        // Indents type name size, +2 for the brackets, +1 for the space, and +2
        // so it doesn't line up with the path.

        // Some initial space to set the output off.
        m_os << "\n\n";
    }

    /// @brief print nothing for a null element.
    void operator()(PathNode const &, elements::NullElement const &) {}

    /// @brief We might print something for a sensor element.
    void operator()(PathNode const &node, elements::SensorElement const &elt) {
        if (m_opts.showSensors) {
            outputBasics(node, elt) << "\n";
        }
    }

    /// @brief Print aliases
    void operator()(PathNode const &node, elements::AliasElement const &elt) {
        outputBasics(node, elt) << std::endl;
        if (m_opts.showAliasSource) {
            m_indentStream << "-> " << elt.getSource() << std::endl;
        }
        if (m_opts.showAliasPriority) {
            m_indentStream << "Priority: "
                           << osvr::common::outputPriority(elt.priority())
                           << std::endl;
        }
    }
    /// @brief Print Devices
    void operator()(PathNode const &node, elements::DeviceElement const &elt) {
        outputBasics(node, elt) << std::endl;
        if (m_opts.showDeviceDetails) {
            m_indentStream << "- corresponds to " << elt.getFullDeviceName()
                           << std::endl;
        }
        if (m_opts.showDeviceDescriptor) {
            m_indentStream << "- Descriptor: "
                           << elt.getDescriptor().toStyledString() << std::endl;
        }
    }

    /// @brief We might print something for a sensor element.
    void operator()(PathNode const &node, elements::StringElement const &elt) {
        outputBasics(node, elt) << std::endl;
        if (m_opts.showStringData) {
            m_indentStream << "- Contained value: " << elt.getString()
                           << std::endl;
        }
    }

    /// @brief Catch-all for other element types.
    template <typename T> void operator()(PathNode const &node, T const &elt) {
        outputBasics(node, elt) << "\n";
    }

  private:
    /// @brief shared implementation: prints type name in brackets padded to
    /// fixed width, then the full path.
    template <typename T>
    std::ostream &outputBasics(PathNode const &node, T const &elt) {
        m_os << "[" << std::setw(m_maxTypeLen) << osvr::common::getTypeName(elt)
             << "] " << osvr::common::getFullPath(node);
        return m_os;
    }
    Options m_opts;
    size_t m_maxTypeLen;
    std::ostream &m_os;
    osvr::util::IndentingStream m_indentStream;
};

int main(int argc, char *argv[]) {
    Options opts;
    namespace po = boost::program_options;
    // clang-format off
    po::options_description desc("Options");
    desc.add_options()
        ("help,h", "produce help message")
        ("alias-source", po::value<bool>(&opts.showAliasSource)->default_value(true), "Whether or not to show the source associated with each alias")
        ("alias-priority", po::value<bool>(&opts.showAliasPriority)->default_value(false), "Whether or not to show the priority associated with each alias")
        ("device-details", po::value<bool>(&opts.showDeviceDetails)->default_value(true), "Whether or not to show the basic details associated with each device")
        ("device-descriptors", po::value<bool>(&opts.showDeviceDescriptor)->default_value(false), "Whether or not to show the JSON descriptors associated with each device")
        ("sensors", po::value<bool>(&opts.showSensors)->default_value(true), "Whether or not to show the 'sensor' nodes")
        ("string-data", po::value<bool>(&opts.showStringData)->default_value(true), "Whether or not to show the data in 'string' nodes")
        ;
    // clang-format on
    po::variables_map vm;
    bool usage = false;
    try {
        po::store(po::command_line_parser(argc, argv)
                      .options(desc)
                      .extra_parser(
                          osvr::util::convertProgramOptionShowHideIntoTrueFalse)
                      .run(),
                  vm);
        po::notify(vm);
    } catch (std::exception &e) {
        std::cerr << "\nError parsing command line: " << e.what() << "\n\n";
        usage = true;
    }
    if (usage || vm.count("help")) {
        std::cerr << "\nTraverses the path tree and outputs it as text for "
                     "human consumption. See\nPathTreeExport for structured "
                     "output for graphical display.\n";
        std::cerr << "Usage: " << argv[0] << " [options]\n\n";
        std::cerr << "All options are shown as being --option 1/0 (true/false) "
                     "but may be expressed\nas --show-option or --hide-option "
                     "instead (e.g. --show-alias-priority)\n\n";
        std::cerr << desc << "\n";
        return 1;
    }

    osvr::common::PathTree pathTree;
    {
        /// We only actually need the client open for long enough to get the
        /// path tree and clone it.
        osvr::clientkit::ClientContext context("org.osvr.tools.printtree");

        if (!context.checkStatus()) {
            std::cerr << "Client context has not yet started up - waiting. "
                         "Make sure the server is running."
                      << std::endl;
            do {
                std::this_thread::sleep_for(std::chrono::milliseconds(1));
                context.update();
            } while (!context.checkStatus());
            std::cerr << "OK, client context ready. Proceeding." << std::endl;
        }
        /// Get a non-const copy of the path tree.
        osvr::common::clonePathTree(context.get()->getPathTree(), pathTree);
        /// Resolve all aliases
        osvr::common::resolveFullTree(pathTree);
    }

    TreeNodePrinter printer{opts};
    /// Now traverse for output - traverse every node in the path tree and apply
    /// the node visitor to get the type-safe variant data out of the nodes. The
    /// lambda will be called (and thus the TreeNodePrinter applied) at every
    /// PathNode in the tree.
    osvr::util::traverseWith(
        pathTree.getRoot(), [&printer](PathNode const &node) {
            osvr::common::applyPathNodeVisitor(printer, node);
        });

    return 0;
}
<commit_msg>Have OSVR print tree report aliases that don't fully resolve.<commit_after>/** @file
    @brief Implementation

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

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

// Internal Includes
#include <osvr/ClientKit/Context.h>
#include <osvr/Common/ClientContext.h>
#include <osvr/Common/PathTreeFull.h>
#include <osvr/Common/ResolveFullTree.h>
#include <osvr/Util/TreeTraversalVisitor.h>
#include <osvr/Common/PathElementTypes.h>
#include <osvr/Common/PathElementTools.h>
#include <osvr/Common/ApplyPathNodeVisitor.h>
#include <osvr/Common/PathNode.h>
#include <osvr/Util/IndentingStream.h>
#include <osvr/Util/ProgramOptionsToggleFlags.h>

// Library/third-party includes
#include <boost/program_options.hpp>
#include <boost/noncopyable.hpp>
#include <boost/variant.hpp>

// Standard includes
#include <iostream>
#include <iomanip>
#include <thread>
#include <chrono>
#include <vector>
#include <string>
#include <unordered_set>

struct Options {
    bool showAliasSource;
    bool showAliasPriority;
    bool showDeviceDetails;
    bool showDeviceDescriptor;
    bool showSensors;
    bool showStringData;
};

using osvr::common::PathNode;
namespace elements = osvr::common::elements;

/// This functor is applied at each node to get the (type-safe variant) value
/// out of it (hence the numerous overloads of the function call operator - one
/// for each node element type we want to treat differently.)
///
/// As a "visitor", this visitor visits just a single node - it's used by a
/// simple lambda to visit every node in the path tree.
class TreeNodePrinter : public boost::static_visitor<>, boost::noncopyable {
  public:
    /// @brief Constructor
    TreeNodePrinter(Options opts, std::vector<std::string> const &badAliases)
        : boost::static_visitor<>(), m_opts(opts),
          m_maxTypeLen(elements::getMaxTypeNameLength()), m_os(std::cout),
          m_indentStream(m_maxTypeLen + 2 + 1 + 2, m_os),
          m_badAliases(begin(badAliases), end(badAliases)) {
        // Computation for initializing the indent stream above:
        // Indents type name size, +2 for the brackets, +1 for the space, and +2
        // so it doesn't line up with the path.

        // Some initial space to set the output off.
        m_os << "\n\n";
    }

    /// @brief print nothing for a null element.
    void operator()(PathNode const &, elements::NullElement const &) {}

    /// @brief We might print something for a sensor element.
    void operator()(PathNode const &node, elements::SensorElement const &elt) {
        if (m_opts.showSensors) {
            outputBasics(node, elt) << "\n";
        }
    }

    /// @brief Print aliases
    void operator()(PathNode const &node, elements::AliasElement const &elt) {
        outputBasics(node, elt) << std::endl;

        /// Check to see if this alias fully resolved, and warn if it didn't.
        auto fullPath = osvr::common::getFullPath(node);
        if (m_badAliases.find(fullPath) != m_badAliases.end()) {
            m_indentStream << "WARNING: this alias does not fully resolve to a "
                              "device/sensor!\n";
        }

        if (m_opts.showAliasSource) {
            m_indentStream << "-> " << elt.getSource() << std::endl;
        }
        if (m_opts.showAliasPriority) {
            m_indentStream << "Priority: "
                           << osvr::common::outputPriority(elt.priority())
                           << std::endl;
        }
    }
    /// @brief Print Devices
    void operator()(PathNode const &node, elements::DeviceElement const &elt) {
        outputBasics(node, elt) << std::endl;
        if (m_opts.showDeviceDetails) {
            m_indentStream << "- corresponds to " << elt.getFullDeviceName()
                           << std::endl;
        }
        if (m_opts.showDeviceDescriptor) {
            m_indentStream << "- Descriptor: "
                           << elt.getDescriptor().toStyledString() << std::endl;
        }
    }

    /// @brief We might print something for a sensor element.
    void operator()(PathNode const &node, elements::StringElement const &elt) {
        outputBasics(node, elt) << std::endl;
        if (m_opts.showStringData) {
            m_indentStream << "- Contained value: " << elt.getString()
                           << std::endl;
        }
    }

    /// @brief Catch-all for other element types.
    template <typename T> void operator()(PathNode const &node, T const &elt) {
        outputBasics(node, elt) << "\n";
    }

  private:
    /// @brief shared implementation: prints type name in brackets padded to
    /// fixed width, then the full path.
    template <typename T>
    std::ostream &outputBasics(PathNode const &node, T const &elt) {
        m_os << "[" << std::setw(m_maxTypeLen) << osvr::common::getTypeName(elt)
             << "] " << osvr::common::getFullPath(node);
        return m_os;
    }
    Options m_opts;
    size_t m_maxTypeLen;
    std::ostream &m_os;
    osvr::util::IndentingStream m_indentStream;

    /// The set of paths that are aliases that don't completely resolve.
    std::unordered_set<std::string> m_badAliases;
};

int main(int argc, char *argv[]) {
    Options opts;
    namespace po = boost::program_options;
    // clang-format off
    po::options_description desc("Options");
    desc.add_options()
        ("help,h", "produce help message")
        ("alias-source", po::value<bool>(&opts.showAliasSource)->default_value(true), "Whether or not to show the source associated with each alias")
        ("alias-priority", po::value<bool>(&opts.showAliasPriority)->default_value(false), "Whether or not to show the priority associated with each alias")
        ("device-details", po::value<bool>(&opts.showDeviceDetails)->default_value(true), "Whether or not to show the basic details associated with each device")
        ("device-descriptors", po::value<bool>(&opts.showDeviceDescriptor)->default_value(false), "Whether or not to show the JSON descriptors associated with each device")
        ("sensors", po::value<bool>(&opts.showSensors)->default_value(true), "Whether or not to show the 'sensor' nodes")
        ("string-data", po::value<bool>(&opts.showStringData)->default_value(true), "Whether or not to show the data in 'string' nodes")
        ;
    // clang-format on
    po::variables_map vm;
    bool usage = false;
    try {
        po::store(po::command_line_parser(argc, argv)
                      .options(desc)
                      .extra_parser(
                          osvr::util::convertProgramOptionShowHideIntoTrueFalse)
                      .run(),
                  vm);
        po::notify(vm);
    } catch (std::exception &e) {
        std::cerr << "\nError parsing command line: " << e.what() << "\n\n";
        usage = true;
    }
    if (usage || vm.count("help")) {
        std::cerr << "\nTraverses the path tree and outputs it as text for "
                     "human consumption. See\nPathTreeExport for structured "
                     "output for graphical display.\n";
        std::cerr << "Usage: " << argv[0] << " [options]\n\n";
        std::cerr << "All options are shown as being --option 1/0 (true/false) "
                     "but may be expressed\nas --show-option or --hide-option "
                     "instead (e.g. --show-alias-priority)\n\n";
        std::cerr << desc << "\n";
        return 1;
    }

    osvr::common::PathTree pathTree;
    std::vector<std::string> badAliases;

    {
        /// We only actually need the client open for long enough to get the
        /// path tree and clone it.
        osvr::clientkit::ClientContext context("org.osvr.tools.printtree");

        if (!context.checkStatus()) {
            std::cerr << "Client context has not yet started up - waiting. "
                         "Make sure the server is running."
                      << std::endl;
            do {
                std::this_thread::sleep_for(std::chrono::milliseconds(1));
                context.update();
            } while (!context.checkStatus());
            std::cerr << "OK, client context ready. Proceeding." << std::endl;
        }
        /// Get a non-const copy of the path tree.
        osvr::common::clonePathTree(context.get()->getPathTree(), pathTree);
        /// Resolve all aliases, keeping track of those that don't fully
        /// resolve.
        badAliases = osvr::common::resolveFullTree(pathTree);
    }

    TreeNodePrinter printer{opts, badAliases};
    /// Now traverse for output - traverse every node in the path tree and apply
    /// the node visitor to get the type-safe variant data out of the nodes. The
    /// lambda will be called (and thus the TreeNodePrinter applied) at every
    /// PathNode in the tree.
    osvr::util::traverseWith(
        pathTree.getRoot(), [&printer](PathNode const &node) {
            osvr::common::applyPathNodeVisitor(printer, node);
        });

    return 0;
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2016, José María Foces Vivancos
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 <organization> 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 ESTEBAN PELLEGRINO 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 <pattern/Pattern.h>

Pattern::Pattern(std::string bpf,std::string regex,std::string replacement_regex, std::string raw_replacement):
	bpf_string(bpf),
	regex(regex),
	replacement_regex(replacement_regex),
	raw_replacement(raw_replacement){

	init_pcap_bpf();
}
void Pattern::init_pcap_bpf(){
	//pcap = pcap_open_dead(DLT_EN10MB,65535);//Allocs mem.
	pcap = pcap_open_dead(DLT_RAW,65535);//Allocs mem.
	bpf_compiled = (struct bpf_program* ) malloc(sizeof(bpf_program));
	if (pcap_compile(pcap,bpf_compiled,bpf_string.c_str(),0,PCAP_NETMASK_UNKNOWN) < 0 ){
		BOOST_LOG_TRIVIAL(error) << "Error compiling " << pcap_geterr(pcap);
		BOOST_LOG_TRIVIAL(error) << "Cannot compile BPF "<< bpf_string;
		throw BPF_ERR;
	}

}
Pattern::Pattern(boost::property_tree::ptree ptree) {
	boost::property_tree::ptree match = ptree.get_child(CONF_KEY_MATCH);
	boost::property_tree::ptree replacement = ptree.get_child(CONF_KEY_REPLACEMENT);
	bpf_string = match.get_child(CONF_KEY_BPF).data();
	regex = boost::regex(match.get_child(CONF_KEY_REGEX).data());
	replacement_regex =	boost::regex(replacement.get_child(CONF_KEY_REGEX).data());
	raw_replacement = replacement.get_child(CONF_KEY_REPLACEMENT).data();
	init_pcap_bpf();
}
Pattern::~Pattern() {
	delete bpf_compiled;
	pcap_close(pcap);//Releases mem.
}

bool Pattern::check(Crafter::Packet *packet){
	BOOST_LOG_TRIVIAL(debug) << "Pattern" << print() << "checking packet..." ;
	bool ret_value = false;
	size_t size = packet->GetSize();
	uint8_t* raw_packet= (uint8_t*) malloc(
		size
	);
	size = packet->GetData(raw_packet);
	BOOST_LOG_TRIVIAL(trace) << "PACKET DATA" <<  hexa_print((unsigned char* ) raw_packet, size);
	/*uint32_t bpf_exec_result = bpf_filter( //if 0 then  matches
		bpf_compiled->bf_insns,
		(unsigned char*) raw_packet,
		size,
		size
	);*/
	pcap_pkthdr pkt_hdr;
	pkt_hdr.caplen = size;
	pkt_hdr.len = size;
	int bpf_exec_result = pcap_offline_filter(
		bpf_compiled,
		&pkt_hdr,
		raw_packet
	);

	BOOST_LOG_TRIVIAL(trace) << "BPF Program exit code: " << bpf_exec_result;
	std::string raw_pack_str((const char*)raw_packet,size);
	if(bpf_exec_result != 0){
		//FIXME
		BOOST_LOG_TRIVIAL(debug) << "BPF Match "<< bpf_string;
		ret_value = match_regex(raw_pack_str,regex);
	}
	if(ret_value)BOOST_LOG_TRIVIAL(info) << "Pattern" << print() << "Matched!";
	free(raw_packet);
	return ret_value;
}

int32_t Pattern::applyReplacement(Crafter::Layer *layer){
	BOOST_LOG_TRIVIAL(debug) << "Pattern" << print() << "Updating packet contents..." ;
	std::string payload = layer->GetStringPayload();
	std::ostringstream t(std::ios::out | std::ios::binary);
	std::ostream_iterator<char, char> oi(t);
	BOOST_LOG_TRIVIAL(trace) << "BASE PAYLOAD " << hexa_print(payload.c_str(),payload.size());
	//boost::regex_replace(oi, payload.begin(),payload.end(),regex, format, boost::match_default | boost::format_all);
	std::string payload_mod =  boost::regex_replace(
		payload,
		replacement_regex,
		raw_replacement,
		boost::match_default | boost::format_first_only
	);

	layer->SetPayload((unsigned char*)payload_mod.c_str(),payload_mod.size());
	BOOST_LOG_TRIVIAL(trace) << "Payload mod PAYLOAD " << hexa_print(layer->GetStringPayload().c_str(),layer->GetStringPayload().size());

	if (payload != payload_mod) BOOST_LOG_TRIVIAL(info) << "Pattern" << print() << "Updated packet content" ;
	return (payload_mod.size() - payload.size());
}
<commit_msg>Update Pattern.cpp<commit_after>/*
Copyright (c) 2016, José María Foces Vivancos
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 <organization> 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 ESTEBAN PELLEGRINO 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 <pattern/Pattern.h>

Pattern::Pattern(std::string bpf,std::string regex,std::string replacement_regex, std::string raw_replacement):
	bpf_string(bpf),
	regex(regex),
	replacement_regex(replacement_regex),
	raw_replacement(raw_replacement){

	init_pcap_bpf();
}
void Pattern::init_pcap_bpf(){
	//pcap = pcap_open_dead(DLT_EN10MB,65535);//Allocs mem.
	pcap = pcap_open_dead(DLT_RAW,65535);//Allocs mem.
	bpf_compiled = (struct bpf_program* ) malloc(sizeof(bpf_program));
	if (pcap_compile(pcap,bpf_compiled,bpf_string.c_str(),0,PCAP_NETMASK_UNKNOWN) < 0 ){
		BOOST_LOG_TRIVIAL(error) << "Error compiling " << pcap_geterr(pcap);
		BOOST_LOG_TRIVIAL(error) << "Cannot compile BPF "<< bpf_string;
		throw BPF_ERR;
	}

}
Pattern::Pattern(boost::property_tree::ptree ptree) {
	boost::property_tree::ptree match = ptree.get_child(CONF_KEY_MATCH);
	boost::property_tree::ptree replacement = ptree.get_child(CONF_KEY_REPLACEMENT);
	bpf_string = match.get_child(CONF_KEY_BPF).data();
	regex = boost::regex(match.get_child(CONF_KEY_REGEX).data());
	replacement_regex =	boost::regex(replacement.get_child(CONF_KEY_REGEX).data());
	raw_replacement = replacement.get_child(CONF_KEY_REPLACEMENT).data();
	init_pcap_bpf();
}
Pattern::~Pattern() {
	delete bpf_compiled;
	pcap_close(pcap);//Releases mem.
}

bool Pattern::check(Crafter::Packet *packet){
	BOOST_LOG_TRIVIAL(debug) << "Pattern" << print() << "checking packet..." ;
	bool ret_value = false;
	size_t size = packet->GetSize();
	uint8_t* raw_packet= (uint8_t*) malloc(
		size
	);
	size = packet->GetData(raw_packet);
	BOOST_LOG_TRIVIAL(trace) << "PACKET DATA" <<  hexa_print((unsigned char* ) raw_packet, size);

	pcap_pkthdr pkt_hdr;
	pkt_hdr.caplen = size;
	pkt_hdr.len = size;
	int bpf_exec_result = pcap_offline_filter(
		bpf_compiled,
		&pkt_hdr,
		raw_packet
	);

	BOOST_LOG_TRIVIAL(trace) << "BPF Program exit code: " << bpf_exec_result;
	std::string raw_pack_str((const char*)raw_packet,size);
	if(bpf_exec_result != 0){
		//FIXME
		BOOST_LOG_TRIVIAL(debug) << "BPF Match "<< bpf_string;
		ret_value = match_regex(raw_pack_str,regex);
	}
	if(ret_value)BOOST_LOG_TRIVIAL(info) << "Pattern" << print() << "Matched!";
	free(raw_packet);
	return ret_value;
}

int32_t Pattern::applyReplacement(Crafter::Layer *layer){
	BOOST_LOG_TRIVIAL(debug) << "Pattern" << print() << "Updating packet contents..." ;
	std::string payload = layer->GetStringPayload();
	std::ostringstream t(std::ios::out | std::ios::binary);
	std::ostream_iterator<char, char> oi(t);
	BOOST_LOG_TRIVIAL(trace) << "BASE PAYLOAD " << hexa_print(payload.c_str(),payload.size());
	//boost::regex_replace(oi, payload.begin(),payload.end(),regex, format, boost::match_default | boost::format_all);
	std::string payload_mod =  boost::regex_replace(
		payload,
		replacement_regex,
		raw_replacement,
		boost::match_default | boost::format_first_only
	);

	layer->SetPayload((unsigned char*)payload_mod.c_str(),payload_mod.size());
	BOOST_LOG_TRIVIAL(trace) << "Payload mod PAYLOAD " << hexa_print(layer->GetStringPayload().c_str(),layer->GetStringPayload().size());

	if (payload != payload_mod) BOOST_LOG_TRIVIAL(info) << "Pattern" << print() << "Updated packet content" ;
	return (payload_mod.size() - payload.size());
}
<|endoftext|>


<commit_before>
/*
 * Copyright 2010 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkData.h"
#include "SkFlate.h"
#include "SkPDFCatalog.h"
#include "SkPDFStream.h"
#include "SkStream.h"

static bool skip_compression(SkPDFCatalog* catalog) {
    return SkToBool(catalog->getDocumentFlags() &
                    SkPDFDocument::kFavorSpeedOverSize_Flags);
}

SkPDFStream::SkPDFStream(SkStream* stream)
    : fState(kUnused_State),
      fData(stream) {
    SkSafeRef(stream);
}

SkPDFStream::SkPDFStream(SkData* data) : fState(kUnused_State) {
    setData(data);
}

SkPDFStream::SkPDFStream(const SkPDFStream& pdfStream)
        : SkPDFDict(),
          fState(kUnused_State),
          fData(pdfStream.fData.get()) {
    fData.get()->ref();
    bool removeLength = true;
    // Don't uncompress an already compressed stream, but we could.
    if (pdfStream.fState == kCompressed_State) {
        fState = kCompressed_State;
        removeLength = false;
    }
    SkPDFDict::Iter dict(pdfStream);
    SkPDFName* key;
    SkPDFObject* value;
    SkPDFName lengthName("Length");
    for (key = dict.next(&value); key != NULL; key = dict.next(&value)) {
        if (removeLength && *key == lengthName) {
            continue;
        }
        this->insert(key, value);
    }
}

SkPDFStream::~SkPDFStream() {}

void SkPDFStream::emitObject(SkWStream* stream, SkPDFCatalog* catalog,
                             bool indirect) {
    if (indirect) {
        return emitIndirectObject(stream, catalog);
    }
    if (!this->populate(catalog)) {
        return fSubstitute->emitObject(stream, catalog, indirect);
    }

    this->INHERITED::emitObject(stream, catalog, false);
    stream->writeText(" stream\n");
    stream->write(fData->getMemoryBase(), fData->getLength());
    stream->writeText("\nendstream");
}

size_t SkPDFStream::getOutputSize(SkPDFCatalog* catalog, bool indirect) {
    if (indirect) {
        return getIndirectOutputSize(catalog);
    }
    if (!this->populate(catalog)) {
        return fSubstitute->getOutputSize(catalog, indirect);
    }

    return this->INHERITED::getOutputSize(catalog, false) +
        strlen(" stream\n\nendstream") + fData->getLength();
}

SkPDFStream::SkPDFStream() : fState(kUnused_State) {}

void SkPDFStream::setData(SkData* data) {
    SkMemoryStream* stream = new SkMemoryStream;
    stream->setData(data);
    fData.reset(stream);  // Transfer ownership.
}

void SkPDFStream::setData(SkStream* stream) {
    fData.reset(stream);
    SkSafeRef(stream);
}

bool SkPDFStream::populate(SkPDFCatalog* catalog) {
    if (fState == kUnused_State) {
        if (!skip_compression(catalog) && SkFlate::HaveFlate()) {
            SkDynamicMemoryWStream compressedData;

            SkAssertResult(SkFlate::Deflate(fData.get(), &compressedData));
            if (compressedData.getOffset() < fData->getLength()) {
                SkMemoryStream* stream = new SkMemoryStream;
                stream->setData(compressedData.copyToData())->unref();
                fData.reset(stream);  // Transfer ownership.
                insertName("Filter", "FlateDecode");
            }
            fState = kCompressed_State;
        } else {
            fState = kNoCompression_State;
        }
        insertInt("Length", fData->getLength());
    } else if (fState == kNoCompression_State && !skip_compression(catalog) &&
               SkFlate::HaveFlate()) {
        if (!fSubstitute.get()) {
            fSubstitute.reset(new SkPDFStream(*this));
            catalog->setSubstitute(this, fSubstitute.get());
        }
        return false;
    }
    return true;
}
<commit_msg>[PDF] Fix printing crashes caused by font streams that don't support getMemoryBase().<commit_after>
/*
 * Copyright 2010 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkData.h"
#include "SkFlate.h"
#include "SkPDFCatalog.h"
#include "SkPDFStream.h"
#include "SkStream.h"

static bool skip_compression(SkPDFCatalog* catalog) {
    return SkToBool(catalog->getDocumentFlags() &
                    SkPDFDocument::kFavorSpeedOverSize_Flags);
}

SkPDFStream::SkPDFStream(SkStream* stream)
    : fState(kUnused_State),
      fData(stream) {
    SkSafeRef(stream);
}

SkPDFStream::SkPDFStream(SkData* data) : fState(kUnused_State) {
    setData(data);
}

SkPDFStream::SkPDFStream(const SkPDFStream& pdfStream)
        : SkPDFDict(),
          fState(kUnused_State),
          fData(pdfStream.fData.get()) {
    fData.get()->ref();
    bool removeLength = true;
    // Don't uncompress an already compressed stream, but we could.
    if (pdfStream.fState == kCompressed_State) {
        fState = kCompressed_State;
        removeLength = false;
    }
    SkPDFDict::Iter dict(pdfStream);
    SkPDFName* key;
    SkPDFObject* value;
    SkPDFName lengthName("Length");
    for (key = dict.next(&value); key != NULL; key = dict.next(&value)) {
        if (removeLength && *key == lengthName) {
            continue;
        }
        this->insert(key, value);
    }
}

SkPDFStream::~SkPDFStream() {}

void SkPDFStream::emitObject(SkWStream* stream, SkPDFCatalog* catalog,
                             bool indirect) {
    if (indirect) {
        return emitIndirectObject(stream, catalog);
    }
    if (!this->populate(catalog)) {
        return fSubstitute->emitObject(stream, catalog, indirect);
    }

    this->INHERITED::emitObject(stream, catalog, false);
    stream->writeText(" stream\n");
    stream->writeStream(fData.get(), fData->getLength());
    stream->writeText("\nendstream");
}

size_t SkPDFStream::getOutputSize(SkPDFCatalog* catalog, bool indirect) {
    if (indirect) {
        return getIndirectOutputSize(catalog);
    }
    if (!this->populate(catalog)) {
        return fSubstitute->getOutputSize(catalog, indirect);
    }

    return this->INHERITED::getOutputSize(catalog, false) +
        strlen(" stream\n\nendstream") + fData->getLength();
}

SkPDFStream::SkPDFStream() : fState(kUnused_State) {}

void SkPDFStream::setData(SkData* data) {
    SkMemoryStream* stream = new SkMemoryStream;
    stream->setData(data);
    fData.reset(stream);  // Transfer ownership.
}

void SkPDFStream::setData(SkStream* stream) {
    fData.reset(stream);
    SkSafeRef(stream);
}

bool SkPDFStream::populate(SkPDFCatalog* catalog) {
    if (fState == kUnused_State) {
        if (!skip_compression(catalog) && SkFlate::HaveFlate()) {
            SkDynamicMemoryWStream compressedData;

            SkAssertResult(SkFlate::Deflate(fData.get(), &compressedData));
            if (compressedData.getOffset() < fData->getLength()) {
                SkMemoryStream* stream = new SkMemoryStream;
                stream->setData(compressedData.copyToData())->unref();
                fData.reset(stream);  // Transfer ownership.
                insertName("Filter", "FlateDecode");
            }
            fState = kCompressed_State;
        } else {
            fState = kNoCompression_State;
        }
        insertInt("Length", fData->getLength());
    } else if (fState == kNoCompression_State && !skip_compression(catalog) &&
               SkFlate::HaveFlate()) {
        if (!fSubstitute.get()) {
            fSubstitute.reset(new SkPDFStream(*this));
            catalog->setSubstitute(this, fSubstitute.get());
        }
        return false;
    }
    return true;
}
<|endoftext|>