<commit_before>/*!
 * SteamID Parser
 *
 * Copyright 2014 Mukunda Johnson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#pragma once
#ifndef _STEAMID_
#define _STEAMID_

#include <string>
#include <cctype>

/** ---------------------------------------------------------------------------
 * SteamID
 *
 * Contains a User Steam ID.
 *
 * @author Mukunda Johnson
 */
class SteamID {

public:
	enum class Formats : int {
		AUTO = 0,		// Auto-detect format --- this also supports
						// other unlisted formats such as
						// full profile URLs.
		STEAMID32 = 1,	// Classic STEAM_x:y:zzzzzz | x = 0/1
		STEAMID64 = 2,	// SteamID64: 7656119xxxxxxxxxx
		STEAMID3 = 3,	// SteamID3 format: [U:1:xxxxxx]
		S32 = 4,		// Raw 32-bit SIGNED format.
						// this is a raw steamid index that overflows
						// into negative bitspace.
						// This is the format that SourceMod returns
						// with GetSteamAccountID, and will always
						// fit into a 32-bit signed variable. (e.g.
						// a 32-bit PHP integer).
		RAW = 5,		// Raw index. like 64-bit minus the base value.

	};

	// 64-bit type.
	using bigint = long long;
	using uint = unsigned int;

	// base constant of 64-bit Steam IDs
	static const bigint STEAMID64_BASE = 76561197960265728L;

	// max allowed value. (sanity check)
	// 2^36; update this in approx 2,400,000 years
	static const bigint MAX_VALUE = 68719476736L;

	/** -----------------------------------------------------------------------
	 * Parse a Steam ID.
	 *
	 * @param input      Input to parse.
	 *
	 * @param format     Input formatting, see Format constants.
	 *                   Defaults to Format::AUTO which detects the format.
	 *
	 * @param detect_raw Detect and parse RAW values. (only used with
	 *                   Format::AUTO. e.g "123" will resolve to the
	 *                   SteamID with the raw value 123.
	 *                   Default option set with ParseRawDefault.
	 *
	 * @returns SteamID instance or an empty SteamID if the parsing fails.
	 */
	static SteamID Parse( const std::string &input,
						  Formats format = Formats::AUTO,
						  int detect_raw = ParseRawDefault() ) {

		if( input.empty() ) return SteamID(); // no input...

		namespace rc = std::regex_constants;

		try {
			switch( format ) {

			//-----------------------------------------------------------------
			case Formats::STEAMID32: {

				// regex is slow as fuck for some reason.
				if( input.size() < 11  || input[0] != 'S' || input[1] != 'T'
					|| input[2] != 'E' || input[3] != 'A' || input[4] != 'M'
					|| input[5] != '_' || !Is01(input,6)  || input[7] != ':'
					|| !Is01(input,8)  || input[9] != ':' ) return SteamID();

				// STEAM_X:Y:Z'
//				static const std::regex r(
//					R"--(^STEAM_[0-1]:[0-1]:[0-9]+$)--",
//					rc::icase | rc::optimize );
//
//				if( !std::regex_match( input, r ) ) return SteamID();

				bigint z = std::stoll( input.substr( 10 ) );
				z = (z << 1) + (input[8] - '0');

				SteamID result(z);
				//result.Cache( Format::STEAMID32, input );
				return result;

			//-----------------------------------------------------------------
			} case Formats::STEAMID64: {

				// allow digits only
				if( !IsDigits( input ) ) return SteamID();

				// convert to raw (subtract base)
				SteamID result( std::stoll( input ) - STEAMID64_BASE );
				//result.Cache( Format::STEAMID64, input );
				return result;

			//-----------------------------------------------------------------
			} case Formats::STEAMID3: {

				// [U:1:xxxxxx]
				if( input.size() < 7   || input[0] != '[' || input[1] != 'U'
					|| input[2] != ':' || input[3] != '1' || input[4] != ':'
					|| input[input.size()-1] != ']'
					|| !IsDigits( input, 5, input.size() - 1 - 5 ) ) {

					return SteamID();
				}

				// slow.
//				static const std::regex r( R"--(^\[U:1:[0-9]+\]$)--",
//						rc::optimize );
//				if( !std::regex_match( input, r ) ) return SteamID();

				SteamID result( std::stoll(
						input.substr( 5, input.size() - 1 - 5 )));

				//result.Cache( Format::STEAMID3, input );
				return result;

			//-----------------------------------------------------------------
			} case Formats::S32: {

				// signed digits
				if( !IsDigits( input, input[0] == '-' ? 1:0 ) ) {
					return SteamID();
				}

				bigint a = std::stoll( input );

				if( a < 0 ) a += 4294967296L;

				SteamID result( a );
				//result.Cache( Format::S32, input );
				return result;

			//-----------------------------------------------------------------
			} case Formats::RAW: {

				// validate digits only
				if( !IsDigits( input ) ) return SteamID();

				return SteamID( std::stoll( input ));
			}}
		} catch( std::out_of_range& ) {

			// integer conversion out of range...
			return SteamID();
		}
		// Auto detect format:

		std::string cleaned = TrimString(input);
		SteamID result;
		result = Parse( cleaned, Formats::STEAMID32 );
		if( *result ) return result;
		result = Parse( cleaned, Formats::STEAMID64 );
		if( *result ) return result;
		result = Parse( cleaned, Formats::STEAMID3 );
		if( *result ) return result;

		result = TryConvertProfileURL( cleaned );
		if( *result ) return result;

	//		static const std::regex r_url(
	//			R"--(^(?:https?:\/\/)?(?:www.)?steamcommunity.com\/profiles\/([0-9]+)$)--",
	//			rc::icase | rc::optimize );

	//		std::smatch matches;
	//		if( std::regex_match( cleaned, matches, r_url ) ) {
	//			result = Parse( matches[1], Formats::STEAMID64  );
	//			if( *result ) return result;
	//		}

		if( detect_raw ) {
			result = Parse( input, Formats::S32 );
			if( *result ) return result;
			result = Parse( input, Formats::RAW );
			if( *result ) return result;
		}

		// unknown stem
		return SteamID();
	}

	/** -----------------------------------------------------------------------
	 * Format this SteamID to a string.
	 *
	 * @param format Output format. See Format constants.
	 * @returns      Formatted Steam ID, or an empty string if an invalid
	 *                      format is given or the desired format cannot
	 *                      contain the SteamID.
	 */
	std::string Format( Formats format ) const {

		switch( format ) {
		case Formats::STEAMID32: {
			bigint z = m_value >> 1;
			int y = m_value & 1;
			return std::string("STEAM_1:") + std::to_string(y)
						+ ":" + std::to_string(z);

		} case Formats::STEAMID64: {
			return std::to_string( m_value + STEAMID64_BASE );

		} case Formats::STEAMID3: {
			return std::string( "[U:1:" ) +
					std::to_string(m_value) + ']';

		} case Formats::S32: {
			if( m_value >= 4294967296L ) {
				return ""; // too large for s32.
			}

			if( m_value >= 2147483648L ) {
				return std::to_string( m_value - 4294967296L );
			}

			// -->
		} case Formats::RAW: {
			return std::to_string( m_value );
		}}

		return "";
	}

	/** -----------------------------------------------------------------------
	 * Set the default setting for detect_raw for Parse()
	 *
	 * @param detect_raw Default detect_raw value, see Parse function.
	 * @returns Current or updated setting.
	 */
	static bool ParseRawDefault( int detect_raw = -1 ) {
		static int option = false;
		if( detect_raw == -1 ) return !!option;
		option = !!detect_raw;
		return !!option;
	}

	/** -----------------------------------------------------------------------
	 * Overload for Format.
	 */
	std::string operator[]( Formats format ) const {
		return Format( format );
	}

	/** -----------------------------------------------------------------------
	 * Get raw value. 0 = empty
	 */
	bigint Value() const {
		return m_value;
	}

	/** -----------------------------------------------------------------------
	 * Get raw value. 0 = empty
	 */
	bigint operator*() const {
		return m_value;
	}

	/** -----------------------------------------------------------------------
	 * Returns true if this SteamID is empty/invalid.
	 */
	bool operator!() {
		return m_value == 0;
	}

	/** -----------------------------------------------------------------------
	 * Returns true if this SteamID is empty/invalid.
	 */
	bool Empty() const {
		return m_value == 0;
	}

	/** -----------------------------------------------------------------------
	 * Get 64-bit Steam ID.
	 */
	bigint To64() {
		return m_value + STEAMID64_BASE;
	}

	/** -----------------------------------------------------------------------
	 * Parsing shortcut.
	 */
	SteamID( const std::string &input, Formats format = Formats::AUTO,
			 int detect_raw = ParseRawDefault() )
			 : SteamID( Parse( input, format, detect_raw )) {
	}

	/** -----------------------------------------------------------------------
	 * Construct a Steam ID.
	 *
	 * @param raw RAW value of Steam ID.
	 */
	SteamID( bigint raw )
			: m_value( (raw > 0 && raw <= MAX_VALUE) ? raw : 0 ) {
	}

	/** -----------------------------------------------------------------------
	 * An empty steam id.
	 */
	SteamID() : m_value(0) {
	}

	SteamID( const SteamID& o ) = default;
	SteamID( SteamID&& o ) {
		m_value = o.m_value;
	}
	SteamID& operator=( const SteamID& o ) = default;
	SteamID& operator=( SteamID&& o ) {
		m_value = o.m_value;
		return *this;
	}

private:

	bigint m_value;	// RAW Steam ID value.

	//-------------------------------------------------------------------------
	static bool IsDigits( const std::string &str, size_t start = 0,
						  size_t length = 9000 ) {

		for( size_t i = start; i != (start+length) && str[i]; i++ ) {
			if( str[i] < '0' || str[i] > '9' ) return false;
		}
		return true;
	}

	//-------------------------------------------------------------------------
	static bool Is01( const std::string &str, size_t index ) {
		return str[index] == '0' || str[index] == '1';
	}

	//-------------------------------------------------------------------------
	static std::string TrimString( const std::string &input ) {

		int start = 0, end = (int)input.size()-1;
		if( end < 0 ) return "";

		while( std::isspace( input[start] )) {
			start++;
			if( start == input.size() ) return "";
		}

		while( std::isspace( input[end] )) {
			end--;
		}

		return input.substr( start, 1+end-start );
	}

	//-------------------------------------------------------------------------
	static SteamID TryConvertProfileURL( std::string &str ) {
		if( str[0] != 'h' && str[0] != 'w' && str[0] != 's' ) return SteamID();

		int lastslash = str.find_last_of( '/' );
		if( lastslash == std::string::npos ) return SteamID();
		if( lastslash == str.size()-1 ) {
			str.pop_back();
			lastslash = str.find_last_of( '/' );
			if( lastslash == std::string::npos ) return SteamID();
		}

		if( CheckProfilePrefix( str, lastslash ) ) {
			return Parse( str.substr( lastslash+1 ) );
		}
		return SteamID();
	}

	static bool CheckProfilePrefix( std::string &str, int end ) {
		// possible prefixes:
		// 0123456789012345678901234567890123456789
		// https://www.steamcommunity.com/profiles/
		// http://www.steamcommunity.com/profiles/
		// https://steamcommunity.com/profiles/
		// http://steamcommunity.com/profiles/
		// www.steamcommunity.com/profiles/
		// steamcommunity.com/profiles/

		if( end == 39 ) {
			return str.compare( 0, 1+end,
					"https://www.steamcommunity.com/profiles/" ) == 0;
		} else if( end == 38 ) {
			return str.compare( 0, 1+end,
					"http://www.steamcommunity.com/profiles/" ) == 0;
		} else if( end == 35 ) {
			return str.compare( 0, 1+end,
					"https://steamcommunity.com/profiles/" ) == 0;
		} else if( end == 34 ) {
			return str.compare( 0, 1+end,
					"http://steamcommunity.com/profiles/" ) == 0;
		} else if( end == 31 ) {
			return str.compare( 0, 1+end,
					"www.steamcommunity.com/profiles/" ) == 0;
		} else if( end == 27 ) {
			return str.compare( 0, 1+end,
					"steamcommunity.com/profiles/" ) == 0;
		}
		return false;
	}
};

#endif
<commit_msg>c++ functions<commit_after>/*!
 * SteamID Parser
 *
 * Copyright 2014 Mukunda Johnson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#pragma once
#ifndef _STEAMID_
#define _STEAMID_

#include <string>
#include <cctype>

/** ---------------------------------------------------------------------------
 * SteamID
 *
 * Contains a User Steam ID.
 *
 * @author Mukunda Johnson
 */
class SteamID {

public:
	enum class Formats : int {
		AUTO = 0,		// Auto-detect format --- this also supports
						// other unlisted formats such as
						// full profile URLs.
		STEAMID32 = 1,	// Classic STEAM_x:y:zzzzzz | x = 0/1
		STEAMID64 = 2,	// SteamID64: 7656119xxxxxxxxxx
		STEAMID3 = 3,	// SteamID3 format: [U:1:xxxxxx]
		S32 = 4,		// Raw 32-bit SIGNED format.
						// this is a raw steamid index that overflows
						// into negative bitspace.
						// This is the format that SourceMod returns
						// with GetSteamAccountID, and will always
						// fit into a 32-bit signed variable. (e.g.
						// a 32-bit PHP integer).
		RAW = 5,		// Raw index. like 64-bit minus the base value.

	};

	// 64-bit type.
	using bigint = long long;
	using uint = unsigned int;

	// base constant of 64-bit Steam IDs
	static const bigint STEAMID64_BASE = 76561197960265728L;

	// max allowed value. (sanity check)
	// 2^36; update this in approx 2,400,000 years
	static const bigint MAX_VALUE = 68719476736L;

	/** -----------------------------------------------------------------------
	 * Parse a Steam ID.
	 *
	 * @param input      Input to parse.
	 *
	 * @param format     Input formatting, see Format constants.
	 *                   Defaults to Format::AUTO which detects the format.
	 *
	 * @param detect_raw Detect and parse RAW values. (only used with
	 *                   Format::AUTO. e.g "123" will resolve to the
	 *                   SteamID with the raw value 123.
	 *                   Default option set with ParseRawDefault.
	 *
	 * @returns SteamID instance or an empty SteamID if the parsing fails.
	 */
	static SteamID Parse( const std::string &input,
						  Formats format = Formats::AUTO,
						  int detect_raw = ParseRawDefault() ) {

		if( input.empty() ) return SteamID(); // no input...

		namespace rc = std::regex_constants;

		try {
			switch( format ) {

			//-----------------------------------------------------------------
			case Formats::STEAMID32: {

				// regex is slow as fuck for some reason.
				if( input.size() < 11  || input[0] != 'S' || input[1] != 'T'
					|| input[2] != 'E' || input[3] != 'A' || input[4] != 'M'
					|| input[5] != '_' || !Is01(input,6)  || input[7] != ':'
					|| !Is01(input,8)  || input[9] != ':' ) return SteamID();

				// STEAM_X:Y:Z'
//				static const std::regex r(
//					R"--(^STEAM_[0-1]:[0-1]:[0-9]+$)--",
//					rc::icase | rc::optimize );
//
//				if( !std::regex_match( input, r ) ) return SteamID();

				bigint z = std::stoll( input.substr( 10 ) );
				z = (z << 1) + (input[8] - '0');

				SteamID result(z);
				//result.Cache( Format::STEAMID32, input );
				return result;

			//-----------------------------------------------------------------
			} case Formats::STEAMID64: {

				// allow digits only
				if( !IsDigits( input ) ) return SteamID();

				// convert to raw (subtract base)
				SteamID result( std::stoll( input ) - STEAMID64_BASE );
				//result.Cache( Format::STEAMID64, input );
				return result;

			//-----------------------------------------------------------------
			} case Formats::STEAMID3: {

				// [U:1:xxxxxx]
				if( input.size() < 7   || input[0] != '[' || input[1] != 'U'
					|| input[2] != ':' || input[3] != '1' || input[4] != ':'
					|| input[input.size()-1] != ']'
					|| !IsDigits( input, 5, input.size() - 1 - 5 ) ) {

					return SteamID();
				}

				// slow.
//				static const std::regex r( R"--(^\[U:1:[0-9]+\]$)--",
//						rc::optimize );
//				if( !std::regex_match( input, r ) ) return SteamID();

				SteamID result( std::stoll(
						input.substr( 5, input.size() - 1 - 5 )));

				//result.Cache( Format::STEAMID3, input );
				return result;

			//-----------------------------------------------------------------
			} case Formats::S32: {

				// signed digits
				if( !IsDigits( input, input[0] == '-' ? 1:0 ) ) {
					return SteamID();
				}

				bigint a = std::stoll( input );
				if( a < 0 ) a += 4294967296L;

				SteamID result( a );
				//result.Cache( Format::S32, input );
				return result;

			//-----------------------------------------------------------------
			} case Formats::RAW: {

				// validate digits only
				if( !IsDigits( input ) ) return SteamID();

				return SteamID( std::stoll( input ));
			}}
		} catch( std::out_of_range& ) {

			// integer conversion out of range...
			return SteamID();
		}
		// Auto detect format:

		std::string cleaned = TrimString(input);
		SteamID result;
		result = Parse( cleaned, Formats::STEAMID32 );
		if( *result ) return result;
		result = Parse( cleaned, Formats::STEAMID64 );
		if( *result ) return result;
		result = Parse( cleaned, Formats::STEAMID3 );
		if( *result ) return result;

		result = TryConvertProfileURL( cleaned );
		if( *result ) return result;

	//		static const std::regex r_url(
	//			R"--(^(?:https?:\/\/)?(?:www.)?steamcommunity.com\/profiles\/([0-9]+)$)--",
	//			rc::icase | rc::optimize );

	//		std::smatch matches;
	//		if( std::regex_match( cleaned, matches, r_url ) ) {
	//			result = Parse( matches[1], Formats::STEAMID64  );
	//			if( *result ) return result;
	//		}

		if( detect_raw ) {
			result = Parse( input, Formats::S32 );
			if( *result ) return result;
			result = Parse( input, Formats::RAW );
			if( *result ) return result;
		}

		// unknown stem
		return SteamID();
	}

	/** -----------------------------------------------------------------------
	 * Format this SteamID to a string.
	 *
	 * @param format Output format. See Format constants.
	 * @returns      Formatted Steam ID, or an empty string if an invalid
	 *                      format is given or the desired format cannot
	 *                      contain the SteamID.
	 */
	std::string Format( Formats format ) const {

		switch( format ) {
		case Formats::STEAMID32: {
			bigint z = m_value >> 1;
			int y = m_value & 1;
			return std::string("STEAM_1:") + std::to_string(y)
						+ ":" + std::to_string(z);

		} case Formats::STEAMID64: {
			return std::to_string( m_value + STEAMID64_BASE );

		} case Formats::STEAMID3: {
			return std::string( "[U:1:" ) +
					std::to_string(m_value) + ']';

		} case Formats::S32: {
			if( m_value >= 4294967296L ) {
				return ""; // too large for s32.
			}

			if( m_value >= 2147483648L ) {
				return std::to_string( m_value - 4294967296L );
			}

			// -->
		} case Formats::RAW: {
			return std::to_string( m_value );
		}}

		return "";
	}

	/** -----------------------------------------------------------------------
	 * Set the default setting for detect_raw for Parse()
	 *
	 * @param detect_raw Default detect_raw value, see Parse function.
	 * @returns Current or updated setting.
	 */
	static bool ParseRawDefault( int detect_raw = -1 ) {
		static int option = false;
		if( detect_raw == -1 ) return !!option;
		option = !!detect_raw;
		return !!option;
	}

	/** -----------------------------------------------------------------------
	 * Overload for Format.
	 */
	std::string operator[]( Formats format ) const {
		return Format( format );
	}

	/** -----------------------------------------------------------------------
	 * Get raw value. 0 = empty
	 */
	bigint Value() const {
		return m_value;
	}

	/** -----------------------------------------------------------------------
	 * Get raw value. 0 = empty
	 */
	bigint operator*() const {
		return m_value;
	}

	/** -----------------------------------------------------------------------
	 * Returns true if this SteamID is empty/invalid.
	 */
	bool operator!() {
		return m_value == 0;
	}

	/** -----------------------------------------------------------------------
	 * Returns true if this SteamID is empty/invalid.
	 */
	bool Empty() const {
		return m_value == 0;
	}

	/** -----------------------------------------------------------------------
	 * Get 64-bit Steam ID.
	 */
	bigint To64() {
		return m_value + STEAMID64_BASE;
	}

	/** -----------------------------------------------------------------------
	 * Get raw value, same as operator*.
	 */
	bigint ToRaw() {
		return m_value;
	}

	/** -----------------------------------------------------------------------
	 * Get 32-bit value cast to signed.
	 */
	int ToS32() {
		if( m_value > 0xFFFFFFFF ) {
			return 0;
		}
		return (int)m_value;
	}

	/** -----------------------------------------------------------------------
	 * Parsing shortcut.
	 */
	SteamID( const std::string &input, Formats format = Formats::AUTO,
			 int detect_raw = ParseRawDefault() )
			 : SteamID( Parse( input, format, detect_raw )) {
	}

	/** -----------------------------------------------------------------------
	 * Construct a Steam ID.
	 *
	 * @param raw RAW value of Steam ID.
	 */
	SteamID( bigint raw )
			: m_value( (raw > 0 && raw <= MAX_VALUE) ? raw : 0 ) {
	}

	/** -----------------------------------------------------------------------
	 * An empty steam id.
	 */
	SteamID() : m_value(0) {
	}

	SteamID( const SteamID& o ) = default;
	SteamID( SteamID&& o ) {
		m_value = o.m_value;
	}
	SteamID& operator=( const SteamID& o ) = default;
	SteamID& operator=( SteamID&& o ) {
		m_value = o.m_value;
		return *this;
	}

private:

	bigint m_value;	// RAW Steam ID value.

	//-------------------------------------------------------------------------
	static bool IsDigits( const std::string &str, size_t start = 0,
						  size_t length = 9000 ) {

		for( size_t i = start; i != (start+length) && str[i]; i++ ) {
			if( str[i] < '0' || str[i] > '9' ) return false;
		}
		return true;
	}

	//-------------------------------------------------------------------------
	static bool Is01( const std::string &str, size_t index ) {
		return str[index] == '0' || str[index] == '1';
	}

	//-------------------------------------------------------------------------
	static std::string TrimString( const std::string &input ) {

		int start = 0, end = (int)input.size()-1;
		if( end < 0 ) return "";

		while( std::isspace( input[start] )) {
			start++;
			if( start == input.size() ) return "";
		}

		while( std::isspace( input[end] )) {
			end--;
		}

		return input.substr( start, 1+end-start );
	}

	//-------------------------------------------------------------------------
	static SteamID TryConvertProfileURL( std::string &str ) {
		if( str[0] != 'h' && str[0] != 'w' && str[0] != 's' ) return SteamID();

		int lastslash = str.find_last_of( '/' );
		if( lastslash == std::string::npos ) return SteamID();
		if( lastslash == str.size()-1 ) {
			str.pop_back();
			lastslash = str.find_last_of( '/' );
			if( lastslash == std::string::npos ) return SteamID();
		}

		if( CheckProfilePrefix( str, lastslash ) ) {
			return Parse( str.substr( lastslash+1 ) );
		}
		return SteamID();
	}

	static bool CheckProfilePrefix( std::string &str, int end ) {
		// possible prefixes:
		// 0123456789012345678901234567890123456789
		// https://www.steamcommunity.com/profiles/
		// http://www.steamcommunity.com/profiles/
		// https://steamcommunity.com/profiles/
		// http://steamcommunity.com/profiles/
		// www.steamcommunity.com/profiles/
		// steamcommunity.com/profiles/

		if( end == 39 ) {
			return str.compare( 0, 1+end,
					"https://www.steamcommunity.com/profiles/" ) == 0;
		} else if( end == 38 ) {
			return str.compare( 0, 1+end,
					"http://www.steamcommunity.com/profiles/" ) == 0;
		} else if( end == 35 ) {
			return str.compare( 0, 1+end,
					"https://steamcommunity.com/profiles/" ) == 0;
		} else if( end == 34 ) {
			return str.compare( 0, 1+end,
					"http://steamcommunity.com/profiles/" ) == 0;
		} else if( end == 31 ) {
			return str.compare( 0, 1+end,
					"www.steamcommunity.com/profiles/" ) == 0;
		} else if( end == 27 ) {
			return str.compare( 0, 1+end,
					"steamcommunity.com/profiles/" ) == 0;
		}
		return false;
	}
};

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.

#ifndef MFEM_ODE2
#define MFEM_ODE2

#include "../config/config.hpp"
#include "operator.hpp"

namespace mfem
{

/// Abstract class for solving systems of ODEs: d2x/dt2 = f(x,dxdt,t)
class ODE2Solver
{
protected:
   /// Pointer to the associated TimeDependent2Operator.
   TimeDependent2Operator *f;  // f(.,t) : R^n --> R^n

public:
   ODE2Solver() : f(NULL) { }

   virtual void PrintProperties(std::ostream &out = mfem::out) {}

   /// Associate a TimeDependentOperator with the ODE solver.
   /** This method has to be called:
       - Before the first call to Step().
       - When the dimensions of the associated TimeDependentOperator change.
       - When a time stepping sequence has to be restarted.
       - To change the associated TimeDependent2Operator. */
   virtual void Init(TimeDependent2Operator &f)
   {
      this->f = &f;
   }

   /** @brief Perform a time step from time @a t [in] to time @a t [out] based
       on the requested step size @a dt [in]. */
   /** @param[in,out] x    Approximate solution.
       @param[in,out] dxdt Approximate rate.
       @param[in,out] t    Time associated with the approximate solution @a x.
       @param[in,out] dt   Time step size.

       The following rules describe the common behavior of the method:
       - The input @a x [in] is the approximate solution for the input time
         @a t [in].
       - The input @a dxdt [in] is the approximate rate for the input time
         @a t [in].
       - The input @a dt [in] is the desired time step size, defining the desired
         target time: t [target] = @a t [in] + @a dt [in].
       - The output @a x [out] is the approximate solution for the output time
         @a t [out].
       - The output @a dxdt [out] is the approximate rate for the output time
         @a t [out].
       - The output @a dt [out] is the last time step taken by the method which
         may be smaller or larger than the input @a dt [in] value, e.g. because
         of time step control.
       - The method may perform more than one time step internally; in this case
         @a dt [out] is the last internal time step size.
       - The output value of @a t [out] may be smaller or larger than
         t [target], however, it is not smaller than @a t [in] + @a dt [out], if
         at least one internal time step was performed.
       - The values @a x [out] and @a dxdt [out] may be obtained by interpolation
         using internally stored data.
       - In some cases, the contents of @a x [in] or @a dxdt [in] may not be used,
         e.g. when @a x [out] or @a dxdt [out] from a previous Step() call was
         obtained by interpolation.
       - In consecutive calls to this method, the output @a t [out] of one
         Step() call has to be the same as the input @a t [in] to the next
         Step() call.
       - If the previous rule has to be broken, e.g. to restart a time stepping
         sequence, then the ODE solver must be re-initialized by calling Init()
         between the two Step() calls. */
   virtual void Step(Vector &x, Vector &dxdt, double &t, double &dt) = 0;

   /// Perform time integration from time @a t [in] to time @a tf [in].
   /** @param[in,out] x    Approximate solution.
       @param[in,out] dxdt Approximate solution.
       @param[in,out] t    Time associated with the approximate solution @a x.
       @param[in,out] dt   Time step size.
       @param[in]     tf   Requested final time.

       The default implementation makes consecutive calls to Step() until
       reaching @a tf.
       The following rules describe the common behavior of the method:
       - The input @a x [in] is the approximate solution for the input time
         @a t [in].
       - The input @a dxdt [in] is the approximate rate for the input time
         @a t [in].
       - The input @a dt [in] is the initial time step size.
       - The output @a dt [out] is the last time step taken by the method which
         may be smaller or larger than the input @a dt [in] value, e.g. because
         of time step control.
       - The output value of @a t [out] is not smaller than @a tf [in]. */
   virtual void Run(Vector &x, Vector &dxdt, double &t, double &dt, double tf)
   {
      while (t < tf) { Step(x, dxdt, t, dt); }
   }

   virtual ~ODE2Solver() { }
};

/// The classical midpoint method.
class AverageAccelerationSolver : public ODE2Solver
{
private:
   Vector d2xdt2;

public:
   AverageAccelerationSolver() { };

   virtual void Init(TimeDependent2Operator &_f);

   virtual void Step(Vector &x, Vector &dxdt, double &t, double &dt);

};

/// The classical newmark method.
/// Newmark, N. M. (1959) A method of computation for structural dynamics.
/// Journal of Engineering Mechanics, ASCE, 85 (EM3) 67-94.
class NewmarkSolver : public ODE2Solver
{
private:
   Vector d2xdt2;

   double beta, gamma;
   bool first;

public:
   NewmarkSolver(double beta_ = 0.25, double gamma_ = 0.5) { beta = beta_; gamma = gamma_; };

   virtual void PrintProperties(std::ostream &out = mfem::out);

   virtual void Init(TimeDependent2Operator &_f);

   virtual void Step(Vector &x, Vector &dxdt, double &t, double &dt);
};

class LinearAccelerationSolver : public NewmarkSolver
{
public:
   LinearAccelerationSolver() : NewmarkSolver(1.0/6.0, 0.5) { };
};

class CentralDifferenceSolver : public NewmarkSolver
{
public:
   CentralDifferenceSolver() : NewmarkSolver(0.0, 0.5) { };
};

class FoxGoodwinSolver : public NewmarkSolver
{
public:
   FoxGoodwinSolver() : NewmarkSolver(1.0/12.0, 0.5) { };
};

/// Generalized-alpha ODE solver
/// A Time Integration Algorithm for Structural Dynamics With Improved Numerical Dissipation: The Generalized-α Method
/// J.Chung and G.M. Hulbert,  J. Appl. Mech 60(2), 371-375, 1993
/// https://doi.org/10.1115/1.2900803
class GeneralizedAlpha2Solver : public ODE2Solver
{
protected:
   Vector xa,va,aa,d2xdt2;
   double alpha_f, alpha_m, beta, gamma;
   bool first;

public:
   GeneralizedAlpha2Solver(double rho_inf = 1.0)
   {
      rho_inf = (rho_inf > 1.0) ? 1.0 : rho_inf;
      rho_inf = (rho_inf < 0.0) ? 0.0 : rho_inf;

      alpha_m = (2.0 - rho_inf)/(1.0 + rho_inf);
      alpha_f = 1.0/(1.0 + rho_inf);
      beta    = 0.25*pow(1.0 + alpha_m - alpha_f,2);
      gamma   = 0.5 + alpha_m - alpha_f;
   };

   virtual void PrintProperties(std::ostream &out = mfem::out);

   virtual void Init(TimeDependent2Operator &_f);

   virtual void Step(Vector &x, Vector &dxdt, double &t, double &dt);
};

/// HHT-alpha ODE solver
/// Improved numerical dissipation for time integration algorithms in structural dynamics
/// H.M. Hilber, T.J.R. Hughes and R.L. Taylor 1977
/// https://doi.org/10.1002/eqe.4290050306
class HHTAlphaSolver : public GeneralizedAlpha2Solver
{
public:
   HHTAlphaSolver(double rho_inf = 1.0)
   {
      rho_inf = (rho_inf > 1.0) ? 1.0 : rho_inf;
      rho_inf = (rho_inf < 0.0) ? 0.0 : rho_inf;

      alpha_m = 1.0;
      alpha_f = 2.0*rho_inf/(1.0 + rho_inf);
      beta    = 0.25*pow(1.0 + alpha_m - alpha_f,2);
      gamma   = 0.5 + alpha_m - alpha_f;
   };

};

/// WBZ-alpha ODE solver
/// An alpha modification of Newmark's method
/// W.L. Wood, M. Bossak and O.C. Zienkiewicz 1980
/// https://doi.org/10.1002/nme.1620151011
class WBZAlphaSolver : public GeneralizedAlpha2Solver
{
public:
   WBZAlphaSolver(double rho_inf = 1.0)
   {
      rho_inf = (rho_inf > 1.0) ? 1.0 : rho_inf;
      rho_inf = (rho_inf < 0.0) ? 0.0 : rho_inf;

      alpha_f = 1.0;
      alpha_m = 2.0/(1.0 + rho_inf);
      beta    = 0.25*pow(1.0 + alpha_m - alpha_f,2);
      gamma   = 0.5 + alpha_m - alpha_f;
   };

};

}

#endif
<commit_msg>Update ode2.hpp<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.

#ifndef MFEM_ODE2
#define MFEM_ODE2

#include "../config/config.hpp"
#include "operator.hpp"

namespace mfem
{

/// Abstract class for solving systems of ODEs: d2x/dt2 = f(x,dxdt,t)
class ODE2Solver
{
protected:
   /// Pointer to the associated TimeDependent2Operator.
   TimeDependent2Operator *f;  // f(.,t) : R^n --> R^n

public:
   ODE2Solver() : f(NULL) { }

   virtual void PrintProperties(std::ostream &out = mfem::out) {}

   /// Associate a TimeDependentOperator with the ODE solver.
   /** This method has to be called:
       - Before the first call to Step().
       - When the dimensions of the associated TimeDependentOperator change.
       - When a time stepping sequence has to be restarted.
       - To change the associated TimeDependent2Operator. */
   virtual void Init(TimeDependent2Operator &f)
   {
      this->f = &f;
   }

   /** @brief Perform a time step from time @a t [in] to time @a t [out] based
       on the requested step size @a dt [in]. */
   /** @param[in,out] x    Approximate solution.
       @param[in,out] dxdt Approximate rate.
       @param[in,out] t    Time associated with the approximate solution @a x.
       @param[in,out] dt   Time step size.

       The following rules describe the common behavior of the method:
       - The input @a x [in] is the approximate solution for the input time
         @a t [in].
       - The input @a dxdt [in] is the approximate rate for the input time
         @a t [in].
       - The input @a dt [in] is the desired time step size, defining the desired
         target time: t [target] = @a t [in] + @a dt [in].
       - The output @a x [out] is the approximate solution for the output time
         @a t [out].
       - The output @a dxdt [out] is the approximate rate for the output time
         @a t [out].
       - The output @a dt [out] is the last time step taken by the method which
         may be smaller or larger than the input @a dt [in] value, e.g. because
         of time step control.
       - The method may perform more than one time step internally; in this case
         @a dt [out] is the last internal time step size.
       - The output value of @a t [out] may be smaller or larger than
         t [target], however, it is not smaller than @a t [in] + @a dt [out], if
         at least one internal time step was performed.
       - The values @a x [out] and @a dxdt [out] may be obtained by interpolation
         using internally stored data.
       - In some cases, the contents of @a x [in] or @a dxdt [in] may not be used,
         e.g. when @a x [out] or @a dxdt [out] from a previous Step() call was
         obtained by interpolation.
       - In consecutive calls to this method, the output @a t [out] of one
         Step() call has to be the same as the input @a t [in] to the next
         Step() call.
       - If the previous rule has to be broken, e.g. to restart a time stepping
         sequence, then the ODE solver must be re-initialized by calling Init()
         between the two Step() calls. */
   virtual void Step(Vector &x, Vector &dxdt, double &t, double &dt) = 0;

   /// Perform time integration from time @a t [in] to time @a tf [in].
   /** @param[in,out] x    Approximate solution.
       @param[in,out] dxdt Approximate solution.
       @param[in,out] t    Time associated with the approximate solution @a x.
       @param[in,out] dt   Time step size.
       @param[in]     tf   Requested final time.

       The default implementation makes consecutive calls to Step() until
       reaching @a tf.
       The following rules describe the common behavior of the method:
       - The input @a x [in] is the approximate solution for the input time
         @a t [in].
       - The input @a dxdt [in] is the approximate rate for the input time
         @a t [in].
       - The input @a dt [in] is the initial time step size.
       - The output @a dt [out] is the last time step taken by the method which
         may be smaller or larger than the input @a dt [in] value, e.g. because
         of time step control.
       - The output value of @a t [out] is not smaller than @a tf [in]. */
   virtual void Run(Vector &x, Vector &dxdt, double &t, double &dt, double tf)
   {
      while (t < tf) { Step(x, dxdt, t, dt); }
   }

   virtual ~ODE2Solver() { }
};

/// The classical newmark method.
/// Newmark, N. M. (1959) A method of computation for structural dynamics.
/// Journal of Engineering Mechanics, ASCE, 85 (EM3) 67-94.
class NewmarkSolver : public ODE2Solver
{
private:
   Vector d2xdt2;

   double beta, gamma;
   bool first;

public:
   NewmarkSolver(double beta_ = 0.25, double gamma_ = 0.5) { beta = beta_; gamma = gamma_; };

   virtual void PrintProperties(std::ostream &out = mfem::out);

   virtual void Init(TimeDependent2Operator &_f);

   virtual void Step(Vector &x, Vector &dxdt, double &t, double &dt);
};

class LinearAccelerationSolver : public NewmarkSolver
{
public:
   LinearAccelerationSolver() : NewmarkSolver(1.0/6.0, 0.5) { };
};

class CentralDifferenceSolver : public NewmarkSolver
{
public:
   CentralDifferenceSolver() : NewmarkSolver(0.0, 0.5) { };
};

class FoxGoodwinSolver : public NewmarkSolver
{
public:
   FoxGoodwinSolver() : NewmarkSolver(1.0/12.0, 0.5) { };
};

/// Generalized-alpha ODE solver
/// A Time Integration Algorithm for Structural Dynamics With Improved Numerical Dissipation: The Generalized-α Method
/// J.Chung and G.M. Hulbert,  J. Appl. Mech 60(2), 371-375, 1993
/// https://doi.org/10.1115/1.2900803
class GeneralizedAlpha2Solver : public ODE2Solver
{
protected:
   Vector xa,va,aa,d2xdt2;
   double alpha_f, alpha_m, beta, gamma;
   bool first;

public:
   GeneralizedAlpha2Solver(double rho_inf = 1.0)
   {
      rho_inf = (rho_inf > 1.0) ? 1.0 : rho_inf;
      rho_inf = (rho_inf < 0.0) ? 0.0 : rho_inf;

      alpha_m = (2.0 - rho_inf)/(1.0 + rho_inf);
      alpha_f = 1.0/(1.0 + rho_inf);
      beta    = 0.25*pow(1.0 + alpha_m - alpha_f,2);
      gamma   = 0.5 + alpha_m - alpha_f;
   };

   virtual void PrintProperties(std::ostream &out = mfem::out);

   virtual void Init(TimeDependent2Operator &_f);

   virtual void Step(Vector &x, Vector &dxdt, double &t, double &dt);
};

/// The classical midpoint method.
class AverageAccelerationSolver : public GeneralizedAlpha2Solver
{
public:
   AverageAccelerationSolver()
   {
      alpha_m = 0.5;
      alpha_f = 0.5;
      beta    = 0.25;
      gamma   = 0.5;
   };
};

/// HHT-alpha ODE solver
/// Improved numerical dissipation for time integration algorithms in structural dynamics
/// H.M. Hilber, T.J.R. Hughes and R.L. Taylor 1977
/// https://doi.org/10.1002/eqe.4290050306
class HHTAlphaSolver : public GeneralizedAlpha2Solver
{
public:
   HHTAlphaSolver(double rho_inf = 1.0)
   {
      rho_inf = (rho_inf > 1.0) ? 1.0 : rho_inf;
      rho_inf = (rho_inf < 0.0) ? 0.0 : rho_inf;

      alpha_m = 1.0;
      alpha_f = 2.0*rho_inf/(1.0 + rho_inf);
      beta    = 0.25*pow(1.0 + alpha_m - alpha_f,2);
      gamma   = 0.5 + alpha_m - alpha_f;
   };

};

/// WBZ-alpha ODE solver
/// An alpha modification of Newmark's method
/// W.L. Wood, M. Bossak and O.C. Zienkiewicz 1980
/// https://doi.org/10.1002/nme.1620151011
class WBZAlphaSolver : public GeneralizedAlpha2Solver
{
public:
   WBZAlphaSolver(double rho_inf = 1.0)
   {
      rho_inf = (rho_inf > 1.0) ? 1.0 : rho_inf;
      rho_inf = (rho_inf < 0.0) ? 0.0 : rho_inf;

      alpha_f = 1.0;
      alpha_m = 2.0/(1.0 + rho_inf);
      beta    = 0.25*pow(1.0 + alpha_m - alpha_f,2);
      gamma   = 0.5 + alpha_m - alpha_f;
   };

};

}

#endif
<|endoftext|>


<commit_before>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QtQml>
#include <QSettings>
#include "Models/container.h"
#include "Models/passwordstrengthchecker.h"
#include "Models/randomseedgenerator.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QQmlApplicationEngine engine;

    // app.setOrganizationName("TODO");
    // app.setOrganizationDomain("TODO");
    // app.setApplicationName("TODO");

    QCoreApplication::setOrganizationName("tempest");
    QCoreApplication::setOrganizationDomain("tempest.com");
    QCoreApplication::setApplicationName("tempest GUI");

    // Model example: http://www.vladest.org/qttipsandtricks/qsettings-and-qml.html
    QSettings settings;
    engine.rootContext()->setContextProperty("_settings", &settings);

    ContainerModel containerModel;
    engine.rootContext()->setContextProperty("_containerModel", &containerModel);

    PasswordStrengthCheckerModel pwStrengthCheckerModel;
    engine.rootContext()->setContextProperty("_pwStrengthCheckerModel", &pwStrengthCheckerModel);

    //RandomSeedGeneratorModel randomSeedGeneratorModel;
    //engine.rootContext()->setContextProperty("_randomSeedGeneratorModel", &randomSeedGeneratorModel);

    qmlRegisterType<ContainerObject>("tempest.Container", 1, 0, "Container");
    qmlRegisterType<RandomSeedGeneratorModel>("tempest.RandomSeedGenerator", 1, 0, "RandomSeedGenerator");

    //#ifdef Q_OS_OSX
    //#endif
    // #ifdef Q_OS_WIN
    // #ifdef Q_OS_LINUX

    engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));
    return app.exec();
}
<commit_msg>Global (and environment) variables added<commit_after>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QtQml>
#include <QSettings>
#include "Models/container.h"
#include "Models/passwordstrengthchecker.h"
#include "Models/randomseedgenerator.h"

#include "stdlib.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QQmlApplicationEngine engine;

    // app.setOrganizationName("TODO");
    // app.setOrganizationDomain("TODO");
    // app.setApplicationName("TODO");

    QCoreApplication::setOrganizationName("tempest");
    QCoreApplication::setOrganizationDomain("tempest.com");
    QCoreApplication::setApplicationName("tempest GUI");

    engine.rootContext()->setContextProperty("_applicationDirPath", QApplication::applicationDirPath());
    engine.rootContext()->setContextProperty("_homeDirPath", getenv("HOME"));

    // Model example: http://www.vladest.org/qttipsandtricks/qsettings-and-qml.html
    QSettings settings;
    engine.rootContext()->setContextProperty("_settings", &settings);

    ContainerModel containerModel;
    engine.rootContext()->setContextProperty("_containerModel", &containerModel);

    PasswordStrengthCheckerModel pwStrengthCheckerModel;
    engine.rootContext()->setContextProperty("_pwStrengthCheckerModel", &pwStrengthCheckerModel);

    //RandomSeedGeneratorModel randomSeedGeneratorModel;
    //engine.rootContext()->setContextProperty("_randomSeedGeneratorModel", &randomSeedGeneratorModel);

    qmlRegisterType<ContainerObject>("tempest.Container", 1, 0, "Container");
    qmlRegisterType<RandomSeedGeneratorModel>("tempest.RandomSeedGenerator", 1, 0, "RandomSeedGenerator");

    //#ifdef Q_OS_OSX
    //#endif
    // #ifdef Q_OS_WIN
    // #ifdef Q_OS_LINUX

    engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));
    return app.exec();
}
<|endoftext|>


<commit_before>// da3.cpp (skeleton)
// Arsh Chauhan
// 10/11/2013
// For CS 311 Fall 2013
// Source file for Assignment 3

#include "da3.h"

int collatz(int n)
{
	while (n != 1)
	{

		if( n % 2 == 0)
	{
		n = n/2;
		return 1+collatz(n);
	}
	else
	{
		n = (3*n)+1;
		return 1+collatz(n);
	}
	}
	return 0;
      // Dummy return, so that it compiles
               // Eliminate this return statement!
    // WRITE THIS!!!
}
<commit_msg>Optimized collatz(int) return statement. After compiling i noticed it didn't matter since the compiler was anyways automatically optimizing it.<commit_after>// da3.cpp (skeleton)
// Arsh Chauhan
// 10/11/2013
// For CS 311 Fall 2013
// Source file for Assignment 3

#include "da3.h"

int collatz(int n)
{
	while (n != 1)
	{

		if( n % 2 == 0)
	{
		return 1+collatz(n/2);
	}
	else
	{
		return 1+collatz((3*n)+1);
	}
	}
	return 0;
      // Dummy return, so that it compiles
               // Eliminate this return statement!
    // WRITE THIS!!!
}
<|endoftext|>


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

int main() {
  List<int> l;
  l.push_front(10); // 10
  l.push_front(11); // 11, 10
  l.push_back(9); // 11, 10, 9

  List<int>::iterator it;
  for(it = l.begin(); it!=l.end(); ++it)
    std::cout << *it << std::endl;

  it = l.begin();
  l.insert(it, 0); // 0, 11, 10, 9
  ++it;
  l.insert(it, 100); // 0, 11, 100, 10, 9

  // normal for loop
  std::cout << std::endl;
  for(it = l.begin(); it!=l.end(); ++it)
    std::cout << *it << std::endl;

  // ranged for loop
  std::cout << std::endl;
  for(int i : l)
    std::cout << i << std::endl;
  return 0;
}
<commit_msg>Added ranged list incrementer<commit_after>#include <iostream>
#include "List.h"

int main() {
  List<int> l;
  l.push_front(10); // 10
  l.push_front(11); // 11, 10
  l.push_back(9); // 11, 10, 9

  List<int>::iterator it;
  for(it = l.begin(); it!=l.end(); ++it)
    std::cout << *it << std::endl;

  it = l.begin();
  l.insert(it, 0); // 0, 11, 10, 9
  ++it;
  l.insert(it, 100); // 0, 11, 100, 10, 9

  // normal for loop
  std::cout << std::endl;
  for(it = l.begin(); it!=l.end(); ++it)
    std::cout << *it << std::endl;

  // ranged increment of list
  for(int &i : l)
    i++;

  // ranged for loop
  std::cout << std::endl;
  for(int i : l)
    std::cout << i << std::endl;
  return 0;
}
<|endoftext|>


<commit_before>// Do not remove the include below, I use it in Eclipse(http://www.baeyens.it/eclipse/)
#include "Midi_to_Fan.h" // you dont need this in Arduino Sketchbook IDE
#include <MIDI.h>  // Add Midi Library (http://sourceforge.net/projects/arduinomidilib/)
#define LED 13    // Arduino Board LED is on Pin 13
int speakerPin1 = 8;
int speakerPin2 = 4;
int muteFrquenzy = 30000;//The Fan should move even when there is no Sound you can hear

volatile byte lastTone1 = 0;
volatile byte lastTone2 = 0;

//?
volatile int curentFreuq;

//Deklarieren
int getTone(int noteByte);
void playTone(int noteByte);

void MyHandleNoteOff(byte channel, byte pitch, byte velocity) {
	if (pitch == lastTone1) {
		tone(speakerPin1, muteFrquenzy);
		lastTone1 = 0;
	}
	if (pitch == lastTone2) {
		tone(speakerPin2, muteFrquenzy);
		lastTone2 = 0;
	}

	digitalWrite(LED, LOW); //Turn LED off
}

// Below is my function that will be called by the Midi Library
// when a MIDI NOTE ON message is received.
// It will be passed bytes for Channel, Pitch, and Velocity
void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
	digitalWrite(LED, HIGH);  //Turn LED on
	if (velocity == 0) { //A NOTE ON message with a velocity = Zero is actually a NOTE OFF
		MyHandleNoteOff(channel, pitch, velocity);
	}

	if (pitch > 64) {
		playTone(pitch);
	}
}

void setup() {
	pinMode(LED, OUTPUT); // Set Arduino board pin 13 to output
	MIDI.begin(MIDI_CHANNEL_OMNI); // Initialize the Midi Library.
// OMNI sets it to listen to all channels.. MIDI.begin(2) would set it
// to respond to channel 2 notes only.
	MIDI.setHandleNoteOn(MyHandleNoteOn); // This is important!! This command
	// tells the Midi Library which function I want called when a Note ON command
	// is received. in this case it's "MyHandleNoteOn".
	MIDI.setHandleNoteOff(MyHandleNoteOff);
}

void playTone(int noteByte);
void loop() { // Main loop

	MIDI.read(); // Continually check what Midi Commands have been received.
	//MakeSample();
	//PlaySample();
}
//MIDI
void playTone(int noteByte) {
	if (lastTone1 == 0) {
		lastTone1 = noteByte;
		tone(speakerPin1, getTone(noteByte));
		return;
	}

	if (lastTone2 == 0) {
		lastTone2 = noteByte;
		tone(speakerPin2, getTone(noteByte));
	}
	return;
}

int getTone(int noteByte) {

	//an Octave
	static const int tones[] = {
			8372 / 2,//c
			8870 / 2,//c#
			9397 / 2,//d
			9956 / 2, //d#
			10548/ 2,//e
			11175 / 2,//f
			11840 / 2,//f#
			12544 / 2,//g
			13290 / 2,//g#
			14080 / 2, //a
			14917/ 2,//a#
			15804 / 2 //h
			};

	//find the right octave, then calculate the Frequency
	if (noteByte >= 120)
		return tones[noteByte - 120];
	//8
	if (noteByte >= 108)
		return tones[noteByte - 108] / 2;
	//7
	if (noteByte >= 96)
		return tones[noteByte - 96] / 4;
	//6
	if (noteByte >= 84)
		return tones[noteByte - 84] / 8;
	//5
	if (noteByte >= 72)
		return tones[noteByte - 72] / 16;
	//4
	if (noteByte >= 60)
		return tones[noteByte - 60] / 32;
	//3
	if (noteByte >= 48)
		return tones[noteByte - 48] / 64;
	//2
	if (noteByte >= 36)
		return tones[noteByte - 36] / 128;
	//1
	if (noteByte >= 24)
		return tones[noteByte - 24] / 256;
	//0
	if (noteByte >= 12)
		return tones[noteByte - 12] / 512;
	//-1
	if (noteByte >= 0)
		return tones[noteByte - 0] / 1024;
	return 0;

}

<commit_msg>Improved octave calculation<commit_after>// Do not remove the include below, I use it in Eclipse(http://www.baeyens.it/eclipse/)
#include "Midi_to_Fan.h" // you dont need this in Arduino Sketchbook IDE
#include <MIDI.h>  // Add Midi Library (http://sourceforge.net/projects/arduinomidilib/)
#define LED 13    // Arduino Board LED is on Pin 13
int speakerPin1 = 8;
int speakerPin2 = 4;
int muteFrquenzy = 30000;//The Fan should move even when there is no Sound you can hear

volatile byte lastTone1 = 0;
volatile byte lastTone2 = 0;

//Prototypesn
int getTone(int noteByte);
void playTone(int noteByte);

void MyHandleNoteOff(byte channel, byte pitch, byte velocity) {
	if (pitch == lastTone1) {
		tone(speakerPin1, muteFrquenzy);
		lastTone1 = 0;
	}
	if (pitch == lastTone2) {
		tone(speakerPin2, muteFrquenzy);
		lastTone2 = 0;
	}

	digitalWrite(LED, LOW); //Turn LED off
}

// Below is my function that will be called by the Midi Library
// when a MIDI NOTE ON message is received.
// It will be passed bytes for Channel, Pitch, and Velocity
void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
	digitalWrite(LED, HIGH);  //Turn LED on
	if (velocity == 0) { //A NOTE ON message with a velocity = Zero is actually a NOTE OFF
		MyHandleNoteOff(channel, pitch, velocity);
	}

	if (pitch > 64) {
		playTone(pitch);
	}
}

void setup() {
	pinMode(LED, OUTPUT); // Set Arduino board pin 13 to output
	MIDI.begin(MIDI_CHANNEL_OMNI); // Initialize the Midi Library.
// OMNI sets it to listen to all channels.. MIDI.begin(2) would set it
// to respond to channel 2 notes only.
	MIDI.setHandleNoteOn(MyHandleNoteOn); // This is important!! This command
	// tells the Midi Library which function I want called when a Note ON command
	// is received. in this case it's "MyHandleNoteOn".
	MIDI.setHandleNoteOff(MyHandleNoteOff);
}

void loop() { // Main loop

	MIDI.read(); // Continually check what Midi Commands have been received.
	//MakeSample();
	//PlaySample();
}

//MIDI
void playTone(int noteByte) {
	if (lastTone1 == 0) {
		lastTone1 = noteByte;
		tone(speakerPin1, getTone(noteByte));
		return;
	}

	if (lastTone2 == 0) {
		lastTone2 = noteByte;
		tone(speakerPin2, getTone(noteByte));
	}
	return;
}

int getTone(int noteByte) {

	//an Octave
	static const int tones[] = {
			8372 / 2,//c
			8870 / 2,//c#
			9397 / 2,//d
			9956 / 2, //d#
			10548/ 2,//e
			11175 / 2,//f
			11840 / 2,//f#
			12544 / 2,//g
			13290 / 2,//g#
			14080 / 2, //a
			14917/ 2,//a#
			15804 / 2 //h
			};

    int divisor = 1;
    for(int i=120,i>=0,i-=12) {
        if(noteByte >=i)
            return tones[noteByte - i] / divisor;
        divisor <<=1;
    }
	return 0;

}

<|endoftext|>


<commit_before>//===-- PlatformMacOSX.cpp --------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "PlatformMacOSX.h"
#include "lldb/Host/Config.h"

#include <sstream>

#include "lldb/Breakpoint/BreakpointLocation.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleList.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"
#include "lldb/Utility/DataBufferHeap.h"
#include "lldb/Utility/FileSpec.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/StreamString.h"

using namespace lldb;
using namespace lldb_private;

static uint32_t g_initialize_count = 0;

void PlatformMacOSX::Initialize() {
  PlatformDarwin::Initialize();

  if (g_initialize_count++ == 0) {
#if defined(__APPLE__)
    PlatformSP default_platform_sp(new PlatformMacOSX(true));
    default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture());
    Platform::SetHostPlatform(default_platform_sp);
#endif
    PluginManager::RegisterPlugin(PlatformMacOSX::GetPluginNameStatic(false),
                                  PlatformMacOSX::GetDescriptionStatic(false),
                                  PlatformMacOSX::CreateInstance);
  }
}

void PlatformMacOSX::Terminate() {
  if (g_initialize_count > 0) {
    if (--g_initialize_count == 0) {
      PluginManager::UnregisterPlugin(PlatformMacOSX::CreateInstance);
    }
  }

  PlatformDarwin::Terminate();
}

PlatformSP PlatformMacOSX::CreateInstance(bool force, const ArchSpec *arch) {
  Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
  if (log) {
    const char *arch_name;
    if (arch && arch->GetArchitectureName())
      arch_name = arch->GetArchitectureName();
    else
      arch_name = "<null>";

    const char *triple_cstr =
        arch ? arch->GetTriple().getTriple().c_str() : "<null>";

    log->Printf("PlatformMacOSX::%s(force=%s, arch={%s,%s})", __FUNCTION__,
                force ? "true" : "false", arch_name, triple_cstr);
  }

  // The only time we create an instance is when we are creating a remote
  // macosx platform
  const bool is_host = false;

  bool create = force;
  if (!create && arch && arch->IsValid()) {
    const llvm::Triple &triple = arch->GetTriple();
    switch (triple.getVendor()) {
    case llvm::Triple::Apple:
      create = true;
      break;

#if defined(__APPLE__)
    // Only accept "unknown" for vendor if the host is Apple and it "unknown"
    // wasn't specified (it was just returned because it was NOT specified)
    case llvm::Triple::UnknownVendor:
      create = !arch->TripleVendorWasSpecified();
      break;
#endif
    default:
      break;
    }

    if (create) {
      switch (triple.getOS()) {
      case llvm::Triple::Darwin: // Deprecated, but still support Darwin for
                                 // historical reasons
      case llvm::Triple::MacOSX:
        break;
#if defined(__APPLE__)
      // Only accept "vendor" for vendor if the host is Apple and it "unknown"
      // wasn't specified (it was just returned because it was NOT specified)
      case llvm::Triple::UnknownOS:
        create = !arch->TripleOSWasSpecified();
        break;
#endif
      default:
        create = false;
        break;
      }
    }
  }
  if (create) {
    if (log)
      log->Printf("PlatformMacOSX::%s() creating platform", __FUNCTION__);
    return PlatformSP(new PlatformMacOSX(is_host));
  }

  if (log)
    log->Printf("PlatformMacOSX::%s() aborting creation of platform",
                __FUNCTION__);

  return PlatformSP();
}

lldb_private::ConstString PlatformMacOSX::GetPluginNameStatic(bool is_host) {
  if (is_host) {
    static ConstString g_host_name(Platform::GetHostPlatformName());
    return g_host_name;
  } else {
    static ConstString g_remote_name("remote-macosx");
    return g_remote_name;
  }
}

const char *PlatformMacOSX::GetDescriptionStatic(bool is_host) {
  if (is_host)
    return "Local Mac OS X user platform plug-in.";
  else
    return "Remote Mac OS X user platform plug-in.";
}

//------------------------------------------------------------------
/// Default Constructor
//------------------------------------------------------------------
PlatformMacOSX::PlatformMacOSX(bool is_host) : PlatformDarwin(is_host) {}

//------------------------------------------------------------------
/// Destructor.
///
/// The destructor is virtual since this class is designed to be
/// inherited from by the plug-in instance.
//------------------------------------------------------------------
PlatformMacOSX::~PlatformMacOSX() {}

ConstString PlatformMacOSX::GetSDKDirectory(lldb_private::Target &target) {
  ModuleSP exe_module_sp(target.GetExecutableModule());
  if (exe_module_sp) {
    ObjectFile *objfile = exe_module_sp->GetObjectFile();
    if (objfile) {
      std::string xcode_contents_path;
      std::string default_xcode_sdk;
      FileSpec fspec;
      uint32_t versions[2];
      if (objfile->GetSDKVersion(versions, sizeof(versions))) {
        fspec = HostInfo::GetShlibDir();
        if (fspec) {
          std::string path;
          xcode_contents_path = fspec.GetPath();
          size_t pos = xcode_contents_path.find("/Xcode.app/Contents/");
          if (pos != std::string::npos) {
            // LLDB.framework is inside an Xcode app bundle, we can locate the
            // SDK from here
            xcode_contents_path.erase(pos + strlen("/Xcode.app/Contents/"));
          } else {
            xcode_contents_path.clear();
            // Use the selected Xcode
            int status = 0;
            int signo = 0;
            std::string output;
            const char *command = "xcrun -sdk macosx --show-sdk-path";
            lldb_private::Status error = RunShellCommand(
                command, // shell command to run
                NULL,    // current working directory
                &status, // Put the exit status of the process in here
                &signo,  // Put the signal that caused the process to exit in
                         // here
                &output, // Get the output from the command and place it in this
                         // string
                std::chrono::seconds(3));
            if (status == 0 && !output.empty()) {
              size_t first_non_newline = output.find_last_not_of("\r\n");
              if (first_non_newline != std::string::npos)
                output.erase(first_non_newline + 1);
              default_xcode_sdk = output;

              pos = default_xcode_sdk.find("/Xcode.app/Contents/");
              if (pos != std::string::npos)
                xcode_contents_path = default_xcode_sdk.substr(
                    0, pos + strlen("/Xcode.app/Contents/"));
            }
          }
        }

        if (!xcode_contents_path.empty()) {
          StreamString sdk_path;
          sdk_path.Printf("%sDeveloper/Platforms/MacOSX.platform/Developer/"
                          "SDKs/MacOSX%u.%u.sdk",
                          xcode_contents_path.c_str(), versions[0],
                          versions[1]);
          fspec.SetFile(sdk_path.GetString(), FileSpec::Style::native);
          if (FileSystem::Instance().Exists(fspec))
            return ConstString(sdk_path.GetString());
        }

        if (!default_xcode_sdk.empty()) {
          fspec.SetFile(default_xcode_sdk, FileSpec::Style::native);
          if (FileSystem::Instance().Exists(fspec))
            return ConstString(default_xcode_sdk);
        }
      }
    }
  }
  return ConstString();
}

Status PlatformMacOSX::GetSymbolFile(const FileSpec &platform_file,
                                     const UUID *uuid_ptr,
                                     FileSpec &local_file) {
  if (IsRemote()) {
    if (m_remote_platform_sp)
      return m_remote_platform_sp->GetFileWithUUID(platform_file, uuid_ptr,
                                                   local_file);
  }

  // Default to the local case
  local_file = platform_file;
  return Status();
}

lldb_private::Status
PlatformMacOSX::GetFileWithUUID(const lldb_private::FileSpec &platform_file,
                                const lldb_private::UUID *uuid_ptr,
                                lldb_private::FileSpec &local_file) {
  if (IsRemote() && m_remote_platform_sp) {
    std::string local_os_build;
#if !defined(__linux__)
    HostInfo::GetOSBuildString(local_os_build);
#endif
    std::string remote_os_build;
    m_remote_platform_sp->GetOSBuildString(remote_os_build);
    if (local_os_build == remote_os_build) {
      // same OS version: the local file is good enough
      local_file = platform_file;
      return Status();
    } else {
      // try to find the file in the cache
      std::string cache_path(GetLocalCacheDirectory());
      std::string module_path(platform_file.GetPath());
      cache_path.append(module_path);
      FileSpec module_cache_spec(cache_path);
      if (FileSystem::Instance().Exists(module_cache_spec)) {
        local_file = module_cache_spec;
        return Status();
      }
      // bring in the remote module file
      FileSpec module_cache_folder =
          module_cache_spec.CopyByRemovingLastPathComponent();
      // try to make the local directory first
      Status err(
          llvm::sys::fs::create_directory(module_cache_folder.GetPath()));
      if (err.Fail())
        return err;
      err = GetFile(platform_file, module_cache_spec);
      if (err.Fail())
        return err;
      if (FileSystem::Instance().Exists(module_cache_spec)) {
        local_file = module_cache_spec;
        return Status();
      } else
        return Status("unable to obtain valid module file");
    }
  }
  local_file = platform_file;
  return Status();
}

bool PlatformMacOSX::GetSupportedArchitectureAtIndex(uint32_t idx,
                                                     ArchSpec &arch) {
#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
  return ARMGetSupportedArchitectureAtIndex(idx, arch);
#else
  return x86GetSupportedArchitectureAtIndex(idx, arch);
#endif
}

lldb_private::Status PlatformMacOSX::GetSharedModule(
    const lldb_private::ModuleSpec &module_spec, Process *process,
    lldb::ModuleSP &module_sp,
    const lldb_private::FileSpecList *module_search_paths_ptr,
    lldb::ModuleSP *old_module_sp_ptr, bool *did_create_ptr) {
  Status error = GetSharedModuleWithLocalCache(
      module_spec, module_sp, module_search_paths_ptr, old_module_sp_ptr,
      did_create_ptr);

  if (module_sp) {
    if (module_spec.GetArchitecture().GetCore() ==
        ArchSpec::eCore_x86_64_x86_64h) {
      ObjectFile *objfile = module_sp->GetObjectFile();
      if (objfile == NULL) {
        // We didn't find an x86_64h slice, fall back to a x86_64 slice
        ModuleSpec module_spec_x86_64(module_spec);
        module_spec_x86_64.GetArchitecture() = ArchSpec("x86_64-apple-macosx");
        lldb::ModuleSP x86_64_module_sp;
        lldb::ModuleSP old_x86_64_module_sp;
        bool did_create = false;
        Status x86_64_error = GetSharedModuleWithLocalCache(
            module_spec_x86_64, x86_64_module_sp, module_search_paths_ptr,
            &old_x86_64_module_sp, &did_create);
        if (x86_64_module_sp && x86_64_module_sp->GetObjectFile()) {
          module_sp = x86_64_module_sp;
          if (old_module_sp_ptr)
            *old_module_sp_ptr = old_x86_64_module_sp;
          if (did_create_ptr)
            *did_create_ptr = did_create;
          return x86_64_error;
        }
      }
    }
  }

  if (!module_sp) {
      error = FindBundleBinaryInExecSearchPaths (module_spec, process, module_sp, module_search_paths_ptr, old_module_sp_ptr, did_create_ptr);
  }
  return error;
}
<commit_msg>Fix a stack-smasher in PlatformMacOSX::GetSDKDirectory()<commit_after>//===-- PlatformMacOSX.cpp --------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "PlatformMacOSX.h"
#include "lldb/Host/Config.h"

#include <sstream>

#include "lldb/Breakpoint/BreakpointLocation.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleList.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"
#include "lldb/Utility/DataBufferHeap.h"
#include "lldb/Utility/FileSpec.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/StreamString.h"

using namespace lldb;
using namespace lldb_private;

static uint32_t g_initialize_count = 0;

void PlatformMacOSX::Initialize() {
  PlatformDarwin::Initialize();

  if (g_initialize_count++ == 0) {
#if defined(__APPLE__)
    PlatformSP default_platform_sp(new PlatformMacOSX(true));
    default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture());
    Platform::SetHostPlatform(default_platform_sp);
#endif
    PluginManager::RegisterPlugin(PlatformMacOSX::GetPluginNameStatic(false),
                                  PlatformMacOSX::GetDescriptionStatic(false),
                                  PlatformMacOSX::CreateInstance);
  }
}

void PlatformMacOSX::Terminate() {
  if (g_initialize_count > 0) {
    if (--g_initialize_count == 0) {
      PluginManager::UnregisterPlugin(PlatformMacOSX::CreateInstance);
    }
  }

  PlatformDarwin::Terminate();
}

PlatformSP PlatformMacOSX::CreateInstance(bool force, const ArchSpec *arch) {
  Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
  if (log) {
    const char *arch_name;
    if (arch && arch->GetArchitectureName())
      arch_name = arch->GetArchitectureName();
    else
      arch_name = "<null>";

    const char *triple_cstr =
        arch ? arch->GetTriple().getTriple().c_str() : "<null>";

    log->Printf("PlatformMacOSX::%s(force=%s, arch={%s,%s})", __FUNCTION__,
                force ? "true" : "false", arch_name, triple_cstr);
  }

  // The only time we create an instance is when we are creating a remote
  // macosx platform
  const bool is_host = false;

  bool create = force;
  if (!create && arch && arch->IsValid()) {
    const llvm::Triple &triple = arch->GetTriple();
    switch (triple.getVendor()) {
    case llvm::Triple::Apple:
      create = true;
      break;

#if defined(__APPLE__)
    // Only accept "unknown" for vendor if the host is Apple and it "unknown"
    // wasn't specified (it was just returned because it was NOT specified)
    case llvm::Triple::UnknownVendor:
      create = !arch->TripleVendorWasSpecified();
      break;
#endif
    default:
      break;
    }

    if (create) {
      switch (triple.getOS()) {
      case llvm::Triple::Darwin: // Deprecated, but still support Darwin for
                                 // historical reasons
      case llvm::Triple::MacOSX:
        break;
#if defined(__APPLE__)
      // Only accept "vendor" for vendor if the host is Apple and it "unknown"
      // wasn't specified (it was just returned because it was NOT specified)
      case llvm::Triple::UnknownOS:
        create = !arch->TripleOSWasSpecified();
        break;
#endif
      default:
        create = false;
        break;
      }
    }
  }
  if (create) {
    if (log)
      log->Printf("PlatformMacOSX::%s() creating platform", __FUNCTION__);
    return PlatformSP(new PlatformMacOSX(is_host));
  }

  if (log)
    log->Printf("PlatformMacOSX::%s() aborting creation of platform",
                __FUNCTION__);

  return PlatformSP();
}

lldb_private::ConstString PlatformMacOSX::GetPluginNameStatic(bool is_host) {
  if (is_host) {
    static ConstString g_host_name(Platform::GetHostPlatformName());
    return g_host_name;
  } else {
    static ConstString g_remote_name("remote-macosx");
    return g_remote_name;
  }
}

const char *PlatformMacOSX::GetDescriptionStatic(bool is_host) {
  if (is_host)
    return "Local Mac OS X user platform plug-in.";
  else
    return "Remote Mac OS X user platform plug-in.";
}

//------------------------------------------------------------------
/// Default Constructor
//------------------------------------------------------------------
PlatformMacOSX::PlatformMacOSX(bool is_host) : PlatformDarwin(is_host) {}

//------------------------------------------------------------------
/// Destructor.
///
/// The destructor is virtual since this class is designed to be
/// inherited from by the plug-in instance.
//------------------------------------------------------------------
PlatformMacOSX::~PlatformMacOSX() {}

ConstString PlatformMacOSX::GetSDKDirectory(lldb_private::Target &target) {
  ModuleSP exe_module_sp(target.GetExecutableModule());
  if (exe_module_sp) {
    ObjectFile *objfile = exe_module_sp->GetObjectFile();
    if (objfile) {
      std::string xcode_contents_path;
      std::string default_xcode_sdk;
      FileSpec fspec;
      uint32_t versions[2];
      if (objfile->GetSDKVersion(versions, 2)) {
        fspec = HostInfo::GetShlibDir();
        if (fspec) {
          std::string path;
          xcode_contents_path = fspec.GetPath();
          size_t pos = xcode_contents_path.find("/Xcode.app/Contents/");
          if (pos != std::string::npos) {
            // LLDB.framework is inside an Xcode app bundle, we can locate the
            // SDK from here
            xcode_contents_path.erase(pos + strlen("/Xcode.app/Contents/"));
          } else {
            xcode_contents_path.clear();
            // Use the selected Xcode
            int status = 0;
            int signo = 0;
            std::string output;
            const char *command = "xcrun -sdk macosx --show-sdk-path";
            lldb_private::Status error = RunShellCommand(
                command, // shell command to run
                NULL,    // current working directory
                &status, // Put the exit status of the process in here
                &signo,  // Put the signal that caused the process to exit in
                         // here
                &output, // Get the output from the command and place it in this
                         // string
                std::chrono::seconds(3));
            if (status == 0 && !output.empty()) {
              size_t first_non_newline = output.find_last_not_of("\r\n");
              if (first_non_newline != std::string::npos)
                output.erase(first_non_newline + 1);
              default_xcode_sdk = output;

              pos = default_xcode_sdk.find("/Xcode.app/Contents/");
              if (pos != std::string::npos)
                xcode_contents_path = default_xcode_sdk.substr(
                    0, pos + strlen("/Xcode.app/Contents/"));
            }
          }
        }

        if (!xcode_contents_path.empty()) {
          StreamString sdk_path;
          sdk_path.Printf("%sDeveloper/Platforms/MacOSX.platform/Developer/"
                          "SDKs/MacOSX%u.%u.sdk",
                          xcode_contents_path.c_str(), versions[0],
                          versions[1]);
          fspec.SetFile(sdk_path.GetString(), FileSpec::Style::native);
          if (FileSystem::Instance().Exists(fspec))
            return ConstString(sdk_path.GetString());
        }

        if (!default_xcode_sdk.empty()) {
          fspec.SetFile(default_xcode_sdk, FileSpec::Style::native);
          if (FileSystem::Instance().Exists(fspec))
            return ConstString(default_xcode_sdk);
        }
      }
    }
  }
  return ConstString();
}

Status PlatformMacOSX::GetSymbolFile(const FileSpec &platform_file,
                                     const UUID *uuid_ptr,
                                     FileSpec &local_file) {
  if (IsRemote()) {
    if (m_remote_platform_sp)
      return m_remote_platform_sp->GetFileWithUUID(platform_file, uuid_ptr,
                                                   local_file);
  }

  // Default to the local case
  local_file = platform_file;
  return Status();
}

lldb_private::Status
PlatformMacOSX::GetFileWithUUID(const lldb_private::FileSpec &platform_file,
                                const lldb_private::UUID *uuid_ptr,
                                lldb_private::FileSpec &local_file) {
  if (IsRemote() && m_remote_platform_sp) {
    std::string local_os_build;
#if !defined(__linux__)
    HostInfo::GetOSBuildString(local_os_build);
#endif
    std::string remote_os_build;
    m_remote_platform_sp->GetOSBuildString(remote_os_build);
    if (local_os_build == remote_os_build) {
      // same OS version: the local file is good enough
      local_file = platform_file;
      return Status();
    } else {
      // try to find the file in the cache
      std::string cache_path(GetLocalCacheDirectory());
      std::string module_path(platform_file.GetPath());
      cache_path.append(module_path);
      FileSpec module_cache_spec(cache_path);
      if (FileSystem::Instance().Exists(module_cache_spec)) {
        local_file = module_cache_spec;
        return Status();
      }
      // bring in the remote module file
      FileSpec module_cache_folder =
          module_cache_spec.CopyByRemovingLastPathComponent();
      // try to make the local directory first
      Status err(
          llvm::sys::fs::create_directory(module_cache_folder.GetPath()));
      if (err.Fail())
        return err;
      err = GetFile(platform_file, module_cache_spec);
      if (err.Fail())
        return err;
      if (FileSystem::Instance().Exists(module_cache_spec)) {
        local_file = module_cache_spec;
        return Status();
      } else
        return Status("unable to obtain valid module file");
    }
  }
  local_file = platform_file;
  return Status();
}

bool PlatformMacOSX::GetSupportedArchitectureAtIndex(uint32_t idx,
                                                     ArchSpec &arch) {
#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
  return ARMGetSupportedArchitectureAtIndex(idx, arch);
#else
  return x86GetSupportedArchitectureAtIndex(idx, arch);
#endif
}

lldb_private::Status PlatformMacOSX::GetSharedModule(
    const lldb_private::ModuleSpec &module_spec, Process *process,
    lldb::ModuleSP &module_sp,
    const lldb_private::FileSpecList *module_search_paths_ptr,
    lldb::ModuleSP *old_module_sp_ptr, bool *did_create_ptr) {
  Status error = GetSharedModuleWithLocalCache(
      module_spec, module_sp, module_search_paths_ptr, old_module_sp_ptr,
      did_create_ptr);

  if (module_sp) {
    if (module_spec.GetArchitecture().GetCore() ==
        ArchSpec::eCore_x86_64_x86_64h) {
      ObjectFile *objfile = module_sp->GetObjectFile();
      if (objfile == NULL) {
        // We didn't find an x86_64h slice, fall back to a x86_64 slice
        ModuleSpec module_spec_x86_64(module_spec);
        module_spec_x86_64.GetArchitecture() = ArchSpec("x86_64-apple-macosx");
        lldb::ModuleSP x86_64_module_sp;
        lldb::ModuleSP old_x86_64_module_sp;
        bool did_create = false;
        Status x86_64_error = GetSharedModuleWithLocalCache(
            module_spec_x86_64, x86_64_module_sp, module_search_paths_ptr,
            &old_x86_64_module_sp, &did_create);
        if (x86_64_module_sp && x86_64_module_sp->GetObjectFile()) {
          module_sp = x86_64_module_sp;
          if (old_module_sp_ptr)
            *old_module_sp_ptr = old_x86_64_module_sp;
          if (did_create_ptr)
            *did_create_ptr = did_create;
          return x86_64_error;
        }
      }
    }
  }

  if (!module_sp) {
      error = FindBundleBinaryInExecSearchPaths (module_spec, process, module_sp, module_search_paths_ptr, old_module_sp_ptr, did_create_ptr);
  }
  return error;
}
<|endoftext|>


<commit_before>// RUN: %clang_cc1 -triple armv7-apple-darwin9 -emit-llvm -o - %s -Wno-return-type-c-linkage | FileCheck %s

// This isn't really testing anything ARM-specific; it's just a convenient
// 32-bit platform.

#define SWIFTCALL __attribute__((swiftcall))
#define OUT __attribute__((swift_indirect_result))
#define ERROR __attribute__((swift_error_result))
#define CONTEXT __attribute__((swift_context))

/*****************************************************************************/
/********************************** LOWERING *********************************/
/*****************************************************************************/

#define TEST(TYPE)                                  \
  extern "C" SWIFTCALL TYPE return_##TYPE(void) {   \
    TYPE result = {};                               \
    return result;                                  \
  }                                                 \
  extern "C" SWIFTCALL void take_##TYPE(TYPE v) {   \
  }                                                 \
  extern "C" void test_##TYPE() {                   \
    take_##TYPE(return_##TYPE());                   \
  }

/*****************************************************************************/
/*********************************** STRUCTS *********************************/
/*****************************************************************************/

typedef struct {
} struct_empty;
TEST(struct_empty);
// CHECK-LABEL: define {{.*}} @return_struct_empty()
// CHECK:   ret void
// CHECK-LABEL: define {{.*}} @take_struct_empty()
// CHECK:   ret void

// This is only properly testable in C++ because it relies on empty structs
// actually taking up space in a structure without requiring any extra data
// to be passed.
typedef struct {
  int x;
  struct_empty padding[2];
  char c1;
  float f0;
  float f1;
} struct_1;
TEST(struct_1);
// CHECK-LABEL: define {{.*}} @return_struct_1()
// CHECK:   [[RET:%.*]] = alloca [[REC:%.*]], align 4
// CHECK:   @llvm.memset
// CHECK:   [[CAST_TMP:%.*]] = bitcast [[REC]]* [[RET]] to [[AGG:{ i32, \[2 x i8\], i8, \[1 x i8\], float, float }]]*
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK:   [[FIRST:%.*]] = load i32, i32* [[T0]], align 4
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 2
// CHECK:   [[SECOND:%.*]] = load i8, i8* [[T0]], align 2
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 4
// CHECK:   [[THIRD:%.*]] = load float, float* [[T0]], align 4
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 5
// CHECK:   [[FOURTH:%.*]] = load float, float* [[T0]], align 4
// CHECK:   [[T0:%.*]] = insertvalue [[UAGG:{ i32, i8, float, float }]] undef, i32 [[FIRST]], 0
// CHECK:   [[T1:%.*]] = insertvalue [[UAGG]] [[T0]], i8 [[SECOND]], 1
// CHECK:   [[T2:%.*]] = insertvalue [[UAGG]] [[T1]], float [[THIRD]], 2
// CHECK:   [[T3:%.*]] = insertvalue [[UAGG]] [[T2]], float [[FOURTH]], 3
// CHECK:   ret [[UAGG]] [[T3]]
// CHECK-LABEL: define {{.*}} @take_struct_1(i32, i8, float, float)
// CHECK:   [[V:%.*]] = alloca [[REC]], align 4
// CHECK:   [[CAST_TMP:%.*]] = bitcast [[REC]]* [[V]] to [[AGG]]*
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK:   store i32 %0, i32* [[T0]], align 4
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 2
// CHECK:   store i8 %1, i8* [[T0]], align 2
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 4
// CHECK:   store float %2, float* [[T0]], align 4
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 5
// CHECK:   store float %3, float* [[T0]], align 4
// CHECK:   ret void
// CHECK-LABEL: define void @test_struct_1()
// CHECK:   [[TMP:%.*]] = alloca [[REC]], align 4
// CHECK:   [[CALL:%.*]] = call [[SWIFTCC:swiftcc]] [[UAGG]] @return_struct_1()
// CHECK:   [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP]] to [[AGG]]*
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK:   [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 0
// CHECK:   store i32 [[T1]], i32* [[T0]], align 4
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 2
// CHECK:   [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 1
// CHECK:   store i8 [[T1]], i8* [[T0]], align 2
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 4
// CHECK:   [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 2
// CHECK:   store float [[T1]], float* [[T0]], align 4
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 5
// CHECK:   [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 3
// CHECK:   store float [[T1]], float* [[T0]], align 4
// CHECK:   [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP]] to [[AGG]]*
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK:   [[FIRST:%.*]] = load i32, i32* [[T0]], align 4
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 2
// CHECK:   [[SECOND:%.*]] = load i8, i8* [[T0]], align 2
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 4
// CHECK:   [[THIRD:%.*]] = load float, float* [[T0]], align 4
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 5
// CHECK:   [[FOURTH:%.*]] = load float, float* [[T0]], align 4
// CHECK:   call [[SWIFTCC]] void @take_struct_1(i32 [[FIRST]], i8 [[SECOND]], float [[THIRD]], float [[FOURTH]])
// CHECK:   ret void

struct struct_indirect_1 {
  int x;
  ~struct_indirect_1();
};
TEST(struct_indirect_1)

// CHECK-LABEL: define {{.*}} void @return_struct_indirect_1({{.*}} noalias sret

// Should not be byval.
// CHECK-LABEL: define {{.*}} void @take_struct_indirect_1({{.*}}*{{( %.*)?}})
<commit_msg>Make another test insensitive to the default C++ dialect.<commit_after>// RUN: %clang_cc1 -triple armv7-apple-darwin9 -emit-llvm -o - %s -Wno-return-type-c-linkage -std=c++03 | FileCheck %s -check-prefixes=CHECK

// This isn't really testing anything ARM-specific; it's just a convenient
// 32-bit platform.

#define SWIFTCALL __attribute__((swiftcall))
#define OUT __attribute__((swift_indirect_result))
#define ERROR __attribute__((swift_error_result))
#define CONTEXT __attribute__((swift_context))

/*****************************************************************************/
/********************************** LOWERING *********************************/
/*****************************************************************************/

#define TEST(TYPE)                                  \
  extern "C" SWIFTCALL TYPE return_##TYPE(void) {   \
    TYPE result = {};                               \
    return result;                                  \
  }                                                 \
  extern "C" SWIFTCALL void take_##TYPE(TYPE v) {   \
  }                                                 \
  extern "C" void test_##TYPE() {                   \
    take_##TYPE(return_##TYPE());                   \
  }

/*****************************************************************************/
/*********************************** STRUCTS *********************************/
/*****************************************************************************/

typedef struct {
} struct_empty;
TEST(struct_empty);
// CHECK-LABEL: define {{.*}} @return_struct_empty()
// CHECK:   ret void
// CHECK-LABEL: define {{.*}} @take_struct_empty()
// CHECK:   ret void

// This is only properly testable in C++ because it relies on empty structs
// actually taking up space in a structure without requiring any extra data
// to be passed.
typedef struct {
  int x;
  struct_empty padding[2];
  char c1;
  float f0;
  float f1;
} struct_1;
TEST(struct_1);
// CHECK-LABEL: define {{.*}} @return_struct_1()
// CHECK:   [[RET:%.*]] = alloca [[REC:%.*]], align 4
// CHECK:   @llvm.memset
// CHECK:   [[CAST_TMP:%.*]] = bitcast [[REC]]* [[RET]] to [[AGG:{ i32, \[2 x i8\], i8, \[1 x i8\], float, float }]]*
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK:   [[FIRST:%.*]] = load i32, i32* [[T0]], align 4
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 2
// CHECK:   [[SECOND:%.*]] = load i8, i8* [[T0]], align 2
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 4
// CHECK:   [[THIRD:%.*]] = load float, float* [[T0]], align 4
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 5
// CHECK:   [[FOURTH:%.*]] = load float, float* [[T0]], align 4
// CHECK:   [[T0:%.*]] = insertvalue [[UAGG:{ i32, i8, float, float }]] undef, i32 [[FIRST]], 0
// CHECK:   [[T1:%.*]] = insertvalue [[UAGG]] [[T0]], i8 [[SECOND]], 1
// CHECK:   [[T2:%.*]] = insertvalue [[UAGG]] [[T1]], float [[THIRD]], 2
// CHECK:   [[T3:%.*]] = insertvalue [[UAGG]] [[T2]], float [[FOURTH]], 3
// CHECK:   ret [[UAGG]] [[T3]]
// CHECK-LABEL: define {{.*}} @take_struct_1(i32, i8, float, float)
// CHECK:   [[V:%.*]] = alloca [[REC]], align 4
// CHECK:   [[CAST_TMP:%.*]] = bitcast [[REC]]* [[V]] to [[AGG]]*
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK:   store i32 %0, i32* [[T0]], align 4
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 2
// CHECK:   store i8 %1, i8* [[T0]], align 2
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 4
// CHECK:   store float %2, float* [[T0]], align 4
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 5
// CHECK:   store float %3, float* [[T0]], align 4
// CHECK:   ret void
// CHECK-LABEL: define void @test_struct_1()
// CHECK:   [[TMP:%.*]] = alloca [[REC]], align 4
// CHECK:   [[CALL:%.*]] = call [[SWIFTCC:swiftcc]] [[UAGG]] @return_struct_1()
// CHECK:   [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP]] to [[AGG]]*
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK:   [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 0
// CHECK:   store i32 [[T1]], i32* [[T0]], align 4
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 2
// CHECK:   [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 1
// CHECK:   store i8 [[T1]], i8* [[T0]], align 2
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 4
// CHECK:   [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 2
// CHECK:   store float [[T1]], float* [[T0]], align 4
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 5
// CHECK:   [[T1:%.*]] = extractvalue [[UAGG]] [[CALL]], 3
// CHECK:   store float [[T1]], float* [[T0]], align 4
// CHECK:   [[CAST_TMP:%.*]] = bitcast [[REC]]* [[TMP]] to [[AGG]]*
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 0
// CHECK:   [[FIRST:%.*]] = load i32, i32* [[T0]], align 4
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 2
// CHECK:   [[SECOND:%.*]] = load i8, i8* [[T0]], align 2
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 4
// CHECK:   [[THIRD:%.*]] = load float, float* [[T0]], align 4
// CHECK:   [[T0:%.*]] = getelementptr inbounds [[AGG]], [[AGG]]* [[CAST_TMP]], i32 0, i32 5
// CHECK:   [[FOURTH:%.*]] = load float, float* [[T0]], align 4
// CHECK:   call [[SWIFTCC]] void @take_struct_1(i32 [[FIRST]], i8 [[SECOND]], float [[THIRD]], float [[FOURTH]])
// CHECK:   ret void

struct struct_indirect_1 {
  int x;
  ~struct_indirect_1();
};
TEST(struct_indirect_1)

// CHECK-LABEL: define {{.*}} void @return_struct_indirect_1({{.*}} noalias sret

// Should not be byval.
// CHECK-LABEL: define {{.*}} void @take_struct_indirect_1({{.*}}*{{( %.*)?}})
<|endoftext|>


<commit_before>
#include <QApplication>
#include <QPainter>

#include <reflectionzeug/Property.h>

#include <propertyguizeug/PropertyEditor.h>

#include <propertyguizeug/ColorButton.h>
#include <propertyguizeug/PropertyPainter.h>

using namespace reflectionzeug;
namespace propertyguizeug
{

PropertyPainter::PropertyPainter()
:   m_drawn(false)
,   m_painter(nullptr)
{
}

PropertyPainter::~PropertyPainter()
{
}

void PropertyPainter::drawValue(QPainter * painter,
    const QStyleOptionViewItem & option, AbstractValueProperty & property)
{
    m_drawn = false;
    m_painter = painter;
    m_option = option;

    property.accept(this);

    std::string prefix = property.option<std::string>("prefix", "");
    std::string suffix = property.option<std::string>("suffix", "");

    if (!m_drawn)
        this->drawString(QString::fromStdString(prefix + property.toString() + suffix));
}

void PropertyPainter::drawString(const QString & string)
{
    const QWidget * widget = m_option.widget;
    QStyle * style = widget ? widget->style() : QApplication::style();

    m_option.text = string;
    style->drawControl(QStyle::CE_ItemViewItem, &m_option, m_painter, widget);
}

void PropertyPainter::drawItemViewBackground()
{
    const QWidget * widget = m_option.widget;
    QStyle * style = widget ? widget->style() : QApplication::style();
    style->drawControl(QStyle::CE_ItemViewItem, &m_option, m_painter, widget);
}

void PropertyPainter::visit(reflectionzeug::AbstractValueProperty * property)
{
    m_drawn = false;
}

void PropertyPainter::visit(Property<bool> * property)
{
    this->drawItemViewBackground();

    QStyleOptionButton opt;
    opt.state = property->value() ? QStyle::State_On : QStyle::State_Off;
    opt.state |= QStyle::State_Enabled;
    opt.rect = m_option.rect;
    opt.rect.setLeft(opt.rect.left()/* + PropertyEditor::s_horizontalMargin */);

    const QWidget * widget = m_option.widget;
    QStyle * style = widget ? widget->style() : QApplication::style();
    style->drawControl(QStyle::CE_CheckBox, &opt, m_painter, widget);

    m_drawn = true;
}

void PropertyPainter::visit(Property<Color> * property)
{
    this->drawItemViewBackground();

    const Color & color = property->value();

    QColor qcolor(color.red(),
                  color.green(),
                  color.blue(),
                  color.alpha());
    QPoint topLeft(m_option.rect.left(),
                   m_option.rect.top() + 4);

    ColorButton::paint(m_painter, topLeft, qcolor);

    QRect rect = m_option.rect;
    rect.setLeft(m_option.rect.left() +
                 ColorButton::s_fixedSize.width() + 4);

    const QWidget * widget = m_option.widget;
    QStyle * style = widget ? widget->style() : QApplication::style();
    style->drawItemText(m_painter,
                        rect,
                        Qt::AlignVCenter,
                        m_option.palette,
                        true,
                        QString::fromStdString(property->toString()),
                        QPalette::Text);

    m_drawn = true;
}

} // namespace propertyguizeug
<commit_msg>move code into conditional block<commit_after>
#include <QApplication>
#include <QPainter>

#include <reflectionzeug/Property.h>

#include <propertyguizeug/PropertyEditor.h>

#include <propertyguizeug/ColorButton.h>
#include <propertyguizeug/PropertyPainter.h>

using namespace reflectionzeug;
namespace propertyguizeug
{

PropertyPainter::PropertyPainter()
:   m_drawn(false)
,   m_painter(nullptr)
{
}

PropertyPainter::~PropertyPainter()
{
}

void PropertyPainter::drawValue(QPainter * painter,
    const QStyleOptionViewItem & option, AbstractValueProperty & property)
{
    m_drawn = false;
    m_painter = painter;
    m_option = option;

    property.accept(this);

    if (!m_drawn)
    {
        std::string prefix = property.option<std::string>("prefix", "");
        std::string suffix = property.option<std::string>("suffix", "");
        this->drawString(QString::fromStdString(prefix + property.toString() + suffix));
    }
}

void PropertyPainter::drawString(const QString & string)
{
    const QWidget * widget = m_option.widget;
    QStyle * style = widget ? widget->style() : QApplication::style();

    m_option.text = string;
    style->drawControl(QStyle::CE_ItemViewItem, &m_option, m_painter, widget);
}

void PropertyPainter::drawItemViewBackground()
{
    const QWidget * widget = m_option.widget;
    QStyle * style = widget ? widget->style() : QApplication::style();
    style->drawControl(QStyle::CE_ItemViewItem, &m_option, m_painter, widget);
}

void PropertyPainter::visit(reflectionzeug::AbstractValueProperty * property)
{
    m_drawn = false;
}

void PropertyPainter::visit(Property<bool> * property)
{
    this->drawItemViewBackground();

    QStyleOptionButton opt;
    opt.state = property->value() ? QStyle::State_On : QStyle::State_Off;
    opt.state |= QStyle::State_Enabled;
    opt.rect = m_option.rect;
    opt.rect.setLeft(opt.rect.left()/* + PropertyEditor::s_horizontalMargin */);

    const QWidget * widget = m_option.widget;
    QStyle * style = widget ? widget->style() : QApplication::style();
    style->drawControl(QStyle::CE_CheckBox, &opt, m_painter, widget);

    m_drawn = true;
}

void PropertyPainter::visit(Property<Color> * property)
{
    this->drawItemViewBackground();

    const Color & color = property->value();

    QColor qcolor(color.red(),
                  color.green(),
                  color.blue(),
                  color.alpha());
    QPoint topLeft(m_option.rect.left(),
                   m_option.rect.top() + 4);

    ColorButton::paint(m_painter, topLeft, qcolor);

    QRect rect = m_option.rect;
    rect.setLeft(m_option.rect.left() +
                 ColorButton::s_fixedSize.width() + 4);

    const QWidget * widget = m_option.widget;
    QStyle * style = widget ? widget->style() : QApplication::style();
    style->drawItemText(m_painter,
                        rect,
                        Qt::AlignVCenter,
                        m_option.palette,
                        true,
                        QString::fromStdString(property->toString()),
                        QPalette::Text);

    m_drawn = true;
}

} // namespace propertyguizeug
<|endoftext|>