<commit_before>
/*
 *  Movie.hpp
 *  sfeMovie project
 *
 *  Copyright (C) 2010-2012 Lucas Soltic
 *  soltic.lucas@gmail.com
 *
 *  This program 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; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 */

#ifndef MOVIE_HPP
#define MOVIE_HPP

#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Transformable.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/System/Clock.hpp>
#include <SFML/System/Mutex.hpp>
#include <SFML/System/Thread.hpp>
#include <SFML/Config.hpp>
#include <string>

////////////////////////////////////////////////////////////
// Define portable import / export macros
////////////////////////////////////////////////////////////
#if defined(SFML_SYSTEM_WINDOWS) && defined(_MSC_VER)
    #ifdef SFE_EXPORTS
        // From DLL side, we must export
        #define SFE_API __declspec(dllexport)
    #else
        // From client application side, we must import
        #define SFE_API __declspec(dllimport)
    #endif

    // For Visual C++ compilers, we also need to turn off this annoying C4251 warning.
    // You can read lots ot different things about it, but the point is the code will
    // just work fine, and so the simplest way to get rid of this warning is to disable it
    #ifdef _MSC_VER
        #pragma warning(disable : 4251)
    #endif
#else
	#define SFE_API
#endif

namespace sfe {
	class Movie_audio;
	class Movie_video;
	class Condition;

	class SFE_API Movie : public sf::Drawable, public sf::Transformable {
		friend class Movie_audio;
		friend class Movie_video;
	public:
		/** @brief Constants giving the movie playback status
		 */
		enum Status
		{
			Stopped, //!< Movie is stopped (ie. not playing and at the beginning)
			Paused,  //!< Movie is paused
			Playing  //!< Movie is playing
		};

		/** @brief Default constructor
		 */
		Movie(void);

		/** @brief Default destructor
		 */
		~Movie(void);

		/** @brief Attemps to open a media file (movie or audio)
		 *
		 * Opening can fails either because of a wrong filename,
		 * or because you tried to open a movie file that has unsupported
		 * video and audio format.
		 *
		 * @param filename the path to the movie file
		 * @return true on success, false otherwise
		 */
		bool openFromFile(const std::string& filename);

		/** @brief Starts the movie playback
		 */
		void play(void);

		/** @brief Pauses the movie playback
		 *
		 * If the movie playback is already paused,
		 * this does nothing, otherwise the playback is paused.
		 */
		void pause(void);

		/** @brief Stops the reading of the movie file. The playing offset is then reset to 0.
		 */
		void stop(void);

		/** @brief Returns whether the opened movie contains a video track (images)
		 *
		 * @return true if the opened movie contains a video track, false otherwise
		 */
		bool hasVideoTrack(void) const;

		/** @brief Returns whether the opened movie contains an audio track
		 *
		 * @return true if the opened movie contains an audio track, false otherwise
		 */
		bool hasAudioTrack(void) const;

		/** @brief Sets the sound's volume (default is 100)
		 *
		 * @param volume the volume in range [0, 100]
		 */
		void setVolume(float volume);

		/** @brief Returns the current sound's volume
		 *
		 * @return the sound's volume, in range [0, 100]
		 */
		float getVolume(void) const;

		/** @brief Returns the duration of the movie
		 *
		 * @return the duration in milliseconds
		 */
		sf::Time getDuration(void) const;

		/** @brief Returns the size (width/height) of the movie
		 *
		 * @return the size of the movie
		 */
		sf::Vector2i getSize(void) const;

		/** @see resizeToFrame(sf::IntRect, bool)
		 */
		void resizeToFrame(int x, int y, int width, int height, bool preserveRatio = true);

		/** @brief Scales the movie to fit the requested frame.
		 *
		 * If the ratio is preserved, the movie may be centered
		 * in the given frame. Thus the movie position may be different from
		 * the one you specified.
		 * @param frame the target frame in which you want to display the movie
		 * @param preserveRatio true to keep the original movie ratio, false otherwise
		 */
		void resizeToFrame(sf::IntRect frame, bool preserveRatio = true);

		/** @brief Returns the amount of video frames per second
		 *
		 * @return the video frame rate
		 */
		float getFramerate(void) const;

		/** @brief Returns the amount of audio samples per second
		 *
		 * @return the audio sample rate
		 */
		unsigned int getSampleRate(void) const;

		/** @brief Returns the count of audio channels
		 *
		 * @return the channels' count
		 */
		unsigned int getChannelCount(void) const;

		/** @brief Returns the current status of this movie
		 *
		 * @return See enum Status
		 */
		Status getStatus(void) const;

		/** @brief Sets the current playing position in the movie
		 *
		 * @return the playing position, in milliseconds
		 * NOTE: Not yet implemented!
		 */
		//void SetPlayingOffset(sf::Uint32 position);

		/** @brief Returns the current playing position in the movie
		 *
		 * @return the playing position
		 */
		sf::Time getPlayingOffset(void) const;

		/** @brief Returns a const reference to the movie texture currently being displayed.
		 * The returned image is a texture in VRAM.
		 *
		 * If the movie has no video track, this returns an empty image.
		 * @return the current image of the movie
		 */
		const sf::Texture& getCurrentFrame(void) const;

		//void SetLoop(bool Loop);
		//bool GetLoop() const;

		/** @brief Enables or disables the debug messages outputting
		 *
		 * When enabled, the following debug messages can be dispayed:
		 * - the attributes of the opened movie
		 * - a notification message when a frame was not decoded
		 * - a notification message when a frame has been skipped
		 * (because the movie playback was late)
		 *
		 * Disabling the debug messages does not prevent sfe::Movie from
		 * displaying the error messages.
		 * The debug messages are always sent to the cerr output stream.
		 *
		 * @param flag true to enable the debug messages outputting, false otherwise
		 */
		static void useDebugMessages(bool flag = true);

	private:

#ifndef LIBAVCODEC_VERSION
		typedef void *AVFormatContextRef;
		typedef void *AVPacketRef;
#else
		typedef AVFormatContext *AVFormatContextRef;
		typedef AVPacket *AVPacketRef;
#endif
		void internalStop(bool calledFromWatchThread);
		void draw(sf::RenderTarget& Target, sf::RenderStates states) const;

		static void outputError(int err, const std::string& fallbackMessage = "");
		void close(void);

		AVFormatContextRef getAVFormatContext(void);
		bool getEofReached();
		void setEofReached(bool flag);
		void setDuration(sf::Time duration);
		bool readFrameAndQueue(void);
		bool saveFrame(AVPacketRef frame);
		static bool usesDebugMessages(void);
		void starvation(void);
		void watch(void);

		AVFormatContextRef m_avFormatCtx;
		bool m_hasVideo;
		bool m_hasAudio;
		bool m_eofReached;
		sf::Mutex m_stopMutex;
		sf::Mutex m_readerMutex;
		sf::Thread m_watchThread;
		Condition *m_shouldStopCond;

		Status m_status;
		sf::Time m_duration;
		sf::Clock m_overallTimer;
		sf::Time m_progressAtPause;

		Movie_video *m_video;
		Movie_audio *m_audio;
	};

} // namespace sfe

#endif
<commit_msg>Updated Doxygen comments.<commit_after>
/*
 *  Movie.hpp
 *  sfeMovie project
 *
 *  Copyright (C) 2010-2012 Lucas Soltic
 *  soltic.lucas@gmail.com
 *
 *  This program 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; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 */

#ifndef MOVIE_HPP
#define MOVIE_HPP

#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Transformable.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/System/Clock.hpp>
#include <SFML/System/Mutex.hpp>
#include <SFML/System/Thread.hpp>
#include <SFML/Config.hpp>
#include <string>

////////////////////////////////////////////////////////////
// Define portable import / export macros
////////////////////////////////////////////////////////////
#if defined(SFML_SYSTEM_WINDOWS) && defined(_MSC_VER)
    #ifdef SFE_EXPORTS
        // From DLL side, we must export
        #define SFE_API __declspec(dllexport)
    #else
        // From client application side, we must import
        #define SFE_API __declspec(dllimport)
    #endif

    // For Visual C++ compilers, we also need to turn off this annoying C4251 warning.
    // You can read lots ot different things about it, but the point is the code will
    // just work fine, and so the simplest way to get rid of this warning is to disable it
    #ifdef _MSC_VER
        #pragma warning(disable : 4251)
    #endif
#else
	#define SFE_API
#endif

namespace sfe {
	class Movie_audio;
	class Movie_video;
	class Condition;

	class SFE_API Movie : public sf::Drawable, public sf::Transformable {
		friend class Movie_audio;
		friend class Movie_video;
	public:
		/** @brief Constants giving the movie playback status
		 */
		enum Status
		{
			Stopped, //!< Movie is stopped (ie. not playing and at the beginning)
			Paused,  //!< Movie is paused
			Playing  //!< Movie is playing
		};

		/** @brief Default constructor
		 */
		Movie(void);

		/** @brief Default destructor
		 */
		~Movie(void);

		/** @brief Attemps to open a media file (movie or audio)
		 *
		 * Opening can fails either because of a wrong filename,
		 * or because you tried to open a movie file that has unsupported
		 * video and audio format.
		 *
		 * @param filename the path to the movie file
		 * @return true on success, false otherwise
		 */
		bool openFromFile(const std::string& filename);

		/** @brief Starts the movie playback
		 */
		void play(void);

		/** @brief Pauses the movie playback
		 *
		 * If the movie playback is already paused,
		 * this does nothing, otherwise the playback is paused.
		 */
		void pause(void);

		/** @brief Stops the movie playback. The playing offset is reset to the beginning.
		 */
		void stop(void);

		/** @brief Returns whether the opened movie contains a video track (images)
		 *
		 * @return true if the opened movie contains a video track, false otherwise
		 */
		bool hasVideoTrack(void) const;

		/** @brief Returns whether the opened movie contains an audio track
		 *
		 * @return true if the opened movie contains an audio track, false otherwise
		 */
		bool hasAudioTrack(void) const;

		/** @brief Sets the sound's volume (default is 100)
		 *
		 * @param volume the volume in range [0, 100]
		 */
		void setVolume(float volume);

		/** @brief Returns the current sound's volume
		 *
		 * @return the sound's volume, in range [0, 100]
		 */
		float getVolume(void) const;

		/** @brief Returns the duration of the movie
		 *
		 * @return the duration in milliseconds
		 */
		sf::Time getDuration(void) const;

		/** @brief Returns the size (width, height) of the movie
		 *
		 * @return the size of the movie
		 */
		sf::Vector2i getSize(void) const;

		/** @brief See resizeToFrame(sf::IntRect, bool)
		 * @see resizeToFrame(sf::IntRect, bool)
		 */
		void resizeToFrame(int x, int y, int width, int height, bool preserveRatio = true);

		/** @brief Scales the movie to fit the requested frame.
		 *
		 * If the ratio is preserved, the movie may be centered
		 * in the given frame. Thus the movie position may be different from
		 * the one you specified.
		 * @param frame the target frame in which you want to display the movie
		 * @param preserveRatio true to keep the original movie ratio, false otherwise
		 */
		void resizeToFrame(sf::IntRect frame, bool preserveRatio = true);

		/** @brief Returns the amount of video frames per second
		 *
		 * @return the video frame rate
		 */
		float getFramerate(void) const;

		/** @brief Returns the amount of audio samples per second
		 *
		 * @return the audio sample rate
		 */
		unsigned int getSampleRate(void) const;

		/** @brief Returns the count of audio channels
		 *
		 * @return the channels' count
		 */
		unsigned int getChannelCount(void) const;

		/** @brief Returns the current status of the movie
		 *
		 * @return See enum Status
		 */
		Status getStatus(void) const;

		/* @brief Sets the current playing position in the movie
		 *
		 * @return the playing position, in milliseconds
		 * NOTE: Not yet implemented!
		 */
		//void SetPlayingOffset(sf::Uint32 position);

		/** @brief Returns the current playing position in the movie
		 *
		 * @return the playing position
		 */
		sf::Time getPlayingOffset(void) const;

		/** @brief Returns a const reference to the movie texture currently being displayed.
		 *
		 * The returned image is a texture in VRAM.
		 * Note: although the returned texture reference remains the same,
		 * getCurrentFrame() must be called for each new frame until you also use
		 * draw() ; otherwise the texture won't be updated.
		 *
		 * If the movie has no video track, this returns an empty image.
		 * @return the current image of the movie
		 */
		const sf::Texture& getCurrentFrame(void) const;

		//void SetLoop(bool Loop);
		//bool GetLoop() const;

		/** @brief Choose whether to print debug messages
		 *
		 * When enabled, the following debug messages can be dispayed:
		 * - the attributes of the opened movie
		 * - a notification message when a frame was not decoded
		 * - a notification message when a frame has been skipped
		 * (because the movie playback was late)
		 *
		 * Disabling the debug messages does not prevent sfe::Movie from
		 * displaying the error messages.
		 * The debug messages are always sent to the cerr output stream.
		 *
		 * @param flag true to enable the debug messages outputting, false otherwise
		 */
		static void useDebugMessages(bool flag = true);

	private:

#ifndef LIBAVCODEC_VERSION
		typedef void *AVFormatContextRef;
		typedef void *AVPacketRef;
#else
		typedef AVFormatContext *AVFormatContextRef;
		typedef AVPacket *AVPacketRef;
#endif
		void internalStop(bool calledFromWatchThread);
		void draw(sf::RenderTarget& Target, sf::RenderStates states) const;

		static void outputError(int err, const std::string& fallbackMessage = "");
		void close(void);

		AVFormatContextRef getAVFormatContext(void);
		bool getEofReached();
		void setEofReached(bool flag);
		void setDuration(sf::Time duration);
		bool readFrameAndQueue(void);
		bool saveFrame(AVPacketRef frame);
		static bool usesDebugMessages(void);
		void starvation(void);
		void watch(void);

		AVFormatContextRef m_avFormatCtx;
		bool m_hasVideo;
		bool m_hasAudio;
		bool m_eofReached;
		sf::Mutex m_stopMutex;
		sf::Mutex m_readerMutex;
		sf::Thread m_watchThread;
		Condition *m_shouldStopCond;

		Status m_status;
		sf::Time m_duration;
		sf::Clock m_overallTimer;
		sf::Time m_progressAtPause;

		Movie_video *m_video;
		Movie_audio *m_audio;
	};

} // namespace sfe

#endif
<|endoftext|>


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

#include "components/autofill/browser/wallet/wallet_service_url.h"

#include <string>

#include "base/command_line.h"
#include "components/autofill/common/autofill_switches.h"
#include "google_apis/gaia/gaia_urls.h"
#include "googleurl/src/gurl.h"
#include "net/base/url_util.h"

namespace {

const char kProdWalletServiceUrl[] = "https://wallet.google.com/";

// TODO(ahutter): Remove this once production is ready.
const char kSandboxWalletServiceUrl[] =
    "https://payments-form-dogfood.sandbox.google.com/";

// TODO(ahutter): Remove this once production is ready.
const char kSandboxWalletSecureServiceUrl[] =
    "https://wallet-web.sandbox.google.com/";

GURL GetWalletHostUrl() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  std::string wallet_service_hostname =
      command_line.GetSwitchValueASCII(switches::kWalletServiceUrl);
  if (!wallet_service_hostname.empty())
    return GURL(wallet_service_hostname);
  if (command_line.HasSwitch(switches::kWalletServiceUseProd))
    return GURL(kProdWalletServiceUrl);
  return GURL(kSandboxWalletServiceUrl);
}

GURL GetBaseWalletUrl() {
  return GetWalletHostUrl().Resolve("online/v2/");
}

GURL GetBaseAutocheckoutUrl() {
  return GetBaseWalletUrl().Resolve("wallet/autocheckout/v1/");
}

GURL GetBaseSecureUrl() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  std::string wallet_secure_url =
      command_line.GetSwitchValueASCII(switches::kWalletSecureServiceUrl);
  if (!wallet_secure_url.empty())
    return GURL(wallet_secure_url);
  if (command_line.HasSwitch(switches::kWalletServiceUseProd))
    return GURL(kProdWalletServiceUrl);
  return GURL(kSandboxWalletSecureServiceUrl);
}

}  // anonymous namespace

namespace autofill {
namespace wallet {

GURL GetGetWalletItemsUrl() {
  return GetBaseAutocheckoutUrl().Resolve("getWalletItemsJwtless");
}

GURL GetGetFullWalletUrl() {
  return GetBaseAutocheckoutUrl().Resolve("getFullWalletJwtless");
}

GURL GetAcceptLegalDocumentsUrl() {
  return GetBaseAutocheckoutUrl().Resolve("acceptLegalDocument");
}

GURL GetAuthenticateInstrumentUrl() {
  return GetBaseAutocheckoutUrl().Resolve("authenticateInstrument");
}

GURL GetSendStatusUrl() {
  return GetBaseAutocheckoutUrl().Resolve("reportStatus");
}

GURL GetSaveToWalletUrl() {
  return GetBaseAutocheckoutUrl().Resolve("saveToWallet");
}

GURL GetPassiveAuthUrl() {
  return GetBaseWalletUrl().Resolve("passiveauth");
}

GURL GetEncryptionUrl() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  // TODO(ahutter): Stop checking these switches once we switch over to prod.
  if (command_line.HasSwitch(switches::kWalletServiceUseProd) ||
      command_line.HasSwitch(switches::kWalletServiceUrl)) {
    return GetWalletHostUrl().Resolve(
        "online-secure/temporarydata/cvv?s7e=cvv");
  } else {
    return GetBaseSecureUrl().Resolve(
        "online-secure/temporarydata/cvv?s7e=cvv");
  }
}

GURL GetEscrowUrl() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  // TODO(ahutter): Stop checking these switches once we switch over to prod.
  if (command_line.HasSwitch(switches::kWalletServiceUseProd) ||
      command_line.HasSwitch(switches::kWalletServiceUrl)) {
    return GetBaseSecureUrl().Resolve("dehEfe?s7e=cardNumber%3Bcvv");
  } else {
    return GetBaseSecureUrl().Resolve("checkout/dehEfe?s7e=cardNumber%3Bcvv");
  }
}

GURL GetSignInUrl() {
  GURL url(GaiaUrls::GetInstance()->service_login_url());
  url = net::AppendQueryParameter(url, "service", "sierra");
  url = net::AppendQueryParameter(url, "btmpl", "popup");
  url = net::AppendQueryParameter(url,
                                  "continue",
                                  GetSignInContinueUrl().spec());
  return url;
}

// The continue url portion of the sign-in URL.
GURL GetSignInContinueUrl() {
  return GetPassiveAuthUrl();
}

bool IsSignInContinueUrl(const GURL& url) {
  GURL final_url = wallet::GetSignInContinueUrl();
  return url.SchemeIsSecure() &&
         url.host() == final_url.host() &&
         url.path() == final_url.path();
}

}  // namespace wallet
}  // namespace autofill
<commit_msg>Setting up Finch trial for using production Wallet service.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/autofill/browser/wallet/wallet_service_url.h"

#include <string>

#include "base/command_line.h"
#include "base/metrics/field_trial.h"
#include "components/autofill/common/autofill_switches.h"
#include "google_apis/gaia/gaia_urls.h"
#include "googleurl/src/gurl.h"
#include "net/base/url_util.h"

namespace {

const char kProdWalletServiceUrl[] = "https://wallet.google.com/";

// TODO(ahutter): Remove this once production is ready.
const char kSandboxWalletServiceUrl[] =
    "https://payments-form-dogfood.sandbox.google.com/";

// TODO(ahutter): Remove this once production is ready.
const char kSandboxWalletSecureServiceUrl[] =
    "https://wallet-web.sandbox.google.com/";

bool IsWalletProductionEnabled() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  return command_line.HasSwitch(switches::kWalletServiceUseProd) ||
         base::FieldTrialList::FindFullName("WalletProductionService") == "Yes";
}

GURL GetWalletHostUrl() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  std::string wallet_service_hostname =
      command_line.GetSwitchValueASCII(switches::kWalletServiceUrl);
  if (!wallet_service_hostname.empty())
    return GURL(wallet_service_hostname);
  if (IsWalletProductionEnabled())
    return GURL(kProdWalletServiceUrl);
  return GURL(kSandboxWalletServiceUrl);
}

GURL GetBaseWalletUrl() {
  return GetWalletHostUrl().Resolve("online/v2/");
}

GURL GetBaseAutocheckoutUrl() {
  return GetBaseWalletUrl().Resolve("wallet/autocheckout/v1/");
}

GURL GetBaseSecureUrl() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  std::string wallet_secure_url =
      command_line.GetSwitchValueASCII(switches::kWalletSecureServiceUrl);
  if (!wallet_secure_url.empty())
    return GURL(wallet_secure_url);
  if (IsWalletProductionEnabled())
    return GURL(kProdWalletServiceUrl);
  return GURL(kSandboxWalletSecureServiceUrl);
}

}  // anonymous namespace

namespace autofill {
namespace wallet {

GURL GetGetWalletItemsUrl() {
  return GetBaseAutocheckoutUrl().Resolve("getWalletItemsJwtless");
}

GURL GetGetFullWalletUrl() {
  return GetBaseAutocheckoutUrl().Resolve("getFullWalletJwtless");
}

GURL GetAcceptLegalDocumentsUrl() {
  return GetBaseAutocheckoutUrl().Resolve("acceptLegalDocument");
}

GURL GetAuthenticateInstrumentUrl() {
  return GetBaseAutocheckoutUrl().Resolve("authenticateInstrument");
}

GURL GetSendStatusUrl() {
  return GetBaseAutocheckoutUrl().Resolve("reportStatus");
}

GURL GetSaveToWalletUrl() {
  return GetBaseAutocheckoutUrl().Resolve("saveToWallet");
}

GURL GetPassiveAuthUrl() {
  return GetBaseWalletUrl().Resolve("passiveauth");
}

GURL GetEncryptionUrl() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  // TODO(ahutter): Stop checking these switches once we switch over to prod.
  if (IsWalletProductionEnabled() ||
      command_line.HasSwitch(switches::kWalletServiceUrl)) {
    return GetWalletHostUrl().Resolve(
        "online-secure/temporarydata/cvv?s7e=cvv");
  } else {
    return GetBaseSecureUrl().Resolve(
        "online-secure/temporarydata/cvv?s7e=cvv");
  }
}

GURL GetEscrowUrl() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  // TODO(ahutter): Stop checking these switches once we switch over to prod.
  if (IsWalletProductionEnabled() ||
      command_line.HasSwitch(switches::kWalletServiceUrl)) {
    return GetBaseSecureUrl().Resolve("dehEfe?s7e=cardNumber%3Bcvv");
  } else {
    return GetBaseSecureUrl().Resolve("checkout/dehEfe?s7e=cardNumber%3Bcvv");
  }
}

GURL GetSignInUrl() {
  GURL url(GaiaUrls::GetInstance()->service_login_url());
  url = net::AppendQueryParameter(url, "service", "sierra");
  url = net::AppendQueryParameter(url, "btmpl", "popup");
  url = net::AppendQueryParameter(url,
                                  "continue",
                                  GetSignInContinueUrl().spec());
  return url;
}

// The continue url portion of the sign-in URL.
GURL GetSignInContinueUrl() {
  return GetPassiveAuthUrl();
}

bool IsSignInContinueUrl(const GURL& url) {
  GURL final_url = wallet::GetSignInContinueUrl();
  return url.SchemeIsSecure() &&
         url.host() == final_url.host() &&
         url.path() == final_url.path();
}

}  // namespace wallet
}  // namespace autofill
<|endoftext|>


<commit_before>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/

//#include "stdafx.h"

#include "RhoClassfactory.h"
#include "sync/SyncThread.h"
#include "sync/ClientRegister.h"
#include "RhoCryptImpl.h"

static rho::common::CRhoClassFactory g_oRhoClassFactory;
rho::common::IRhoClassFactory* rho_get_RhoClassFactory()
{
    return &g_oRhoClassFactory;
}

namespace rho{
namespace common{

IRhoCrypt* CRhoClassFactory::createRhoCrypt()
{
    return new CRhoCryptImpl();
}

}
}

extern "C" {
void rho_clientregister_create(const char* szDevicePin)
{
	//rho::sync::CClientRegister::Create(szDevicePin);
}

};

<commit_msg>build fix<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/

//#include "stdafx.h"

#include "RhoClassfactory.h"
//#include "sync/SyncThread.h"
//#include "sync/ClientRegister.h"
#include "RhoCryptImpl.h"

static rho::common::CRhoClassFactory g_oRhoClassFactory;
rho::common::IRhoClassFactory* rho_get_RhoClassFactory()
{
    return &g_oRhoClassFactory;
}

namespace rho{
namespace common{

IRhoCrypt* CRhoClassFactory::createRhoCrypt()
{
    return new CRhoCryptImpl();
}

}
}

extern "C" {
void rho_clientregister_create(const char* szDevicePin)
{
	//rho::sync::CClientRegister::Create(szDevicePin);
}

};

<|endoftext|>


<commit_before>#include <mapnik/vertex.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/geometry_adapters.hpp>
#include <mapnik/vertex_processor.hpp>
#include "vector_tile_geometry_decoder.hpp"
#include "vector_tile_geometry_encoder.hpp"

namespace {

using namespace mapnik::geometry;

struct print
{
    void operator() (geometry_empty const&) const
    {
        std::cerr << "EMPTY" << std::endl;
    }
    template <typename T>
    void operator() (geometry_collection<T> const& collection) const
    {
    }
    template <typename T>
    void operator() (T const& geom) const
    {
        std::cerr << boost::geometry::wkt(geom) << std::endl;
    }
};

}

struct encode_geometry
{
    vector_tile::Tile_Feature & feature_;
    int32_t x_;
    int32_t y_;
    encode_geometry(vector_tile::Tile_Feature & feature) :
      feature_(feature),
      x_(0),
      y_(0) { }

    void operator() (geometry_empty const&)
    {
    }

    template <typename T>
    void operator()(T const& path)
    {
        mapnik::vector_tile_impl::encode_geometry(path,feature_,x_,y_);
    }

    void operator()(mapnik::geometry::multi_point<std::int64_t> const & path)
    {
        for (auto const& pt : path)
        {
            mapnik::vector_tile_impl::encode_geometry(pt,feature_,x_,y_);
        }
    }

    void operator()(mapnik::geometry::multi_line_string<std::int64_t> const & path)
    {
        for (auto const& ls : path)
        {
            mapnik::vector_tile_impl::encode_geometry(ls,feature_,x_,y_);
        }
    }

    void operator()(mapnik::geometry::multi_polygon<std::int64_t> const& path)
    {
        for (auto const& p : path)
        {
            mapnik::vector_tile_impl::encode_geometry(p,feature_,x_,y_);
        }
    }

    void operator()(mapnik::geometry::geometry_collection<std::int64_t> const& path)
    {
        for (auto const& p : path)
        {
            mapnik::util::apply_visitor((*this), p);
        }
    }
};

struct show_path
{
    std::string & str_;
    show_path(std::string & out) :
      str_(out) {}

    template <typename T>
    void operator()(T & path)
    {
        unsigned cmd = -1;
        double x = 0;
        double y = 0;
        std::ostringstream s;
        path.rewind(0);
        while ((cmd = path.vertex(&x, &y)) != mapnik::SEG_END)
        {
            switch (cmd)
            {
                case mapnik::SEG_MOVETO: s << "move_to("; break;
                case mapnik::SEG_LINETO: s << "line_to("; break;
                case mapnik::SEG_CLOSE: s << "close_path("; break;
                default: std::clog << "unhandled cmd " << cmd << "\n"; break;
            }
            s << x << "," << y << ")\n";
        }
        str_ += s.str();
    }
};

template <typename T>
vector_tile::Tile_Feature geometry_to_feature(mapnik::geometry::geometry<T> const& g)
{
    vector_tile::Tile_Feature feature;
    encode_geometry ap(feature);
    if (g.template is<mapnik::geometry::point<T> >() || g.template is<mapnik::geometry::multi_point<T> >())
    {
        feature.set_type(vector_tile::Tile_GeomType_POINT);
    }
    else if (g.template is<mapnik::geometry::line_string<T> >() || g.template is<mapnik::geometry::multi_line_string<T> >())
    {
        feature.set_type(vector_tile::Tile_GeomType_LINESTRING);
    }
    else if (g.template is<mapnik::geometry::polygon<T> >() || g.template is<mapnik::geometry::multi_polygon<T> >())
    {
        feature.set_type(vector_tile::Tile_GeomType_POLYGON);
    }
    else
    {
        throw std::runtime_error("could not detect valid geometry type");
    }
    mapnik::util::apply_visitor(ap,g);
    return feature;
}

template <typename T>
std::string decode_to_path_string(mapnik::geometry::geometry<T> const& g)
{
    //mapnik::util::apply_visitor(print(), g2);
    using decode_path_type = mapnik::geometry::vertex_processor<show_path>;
    std::string out;
    show_path sp(out);
    mapnik::util::apply_visitor(decode_path_type(sp), g);
    return out;
}

template <typename T>
std::string compare(mapnik::geometry::geometry<T> const& g)
{
    vector_tile::Tile_Feature feature = geometry_to_feature(g);
    mapnik::vector_tile_impl::Geometry geoms(feature,0.0,0.0,1.0,1.0);
    auto g2 = mapnik::vector_tile_impl::decode_geometry(geoms,feature.type());
    return decode_to_path_string(g2);
}
<commit_msg>print geometry collections<commit_after>#include <mapnik/vertex.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/geometry_adapters.hpp>
#include <mapnik/vertex_processor.hpp>
#include "vector_tile_geometry_decoder.hpp"
#include "vector_tile_geometry_encoder.hpp"

namespace {

using namespace mapnik::geometry;

struct print
{
    void operator() (geometry_empty const&) const
    {
        std::cerr << "EMPTY" << std::endl;
    }
    template <typename T>
    void operator() (geometry_collection<T> const&) const
    {
        std::cerr << "COLLECTION" << std::endl;
    }
    template <typename T>
    void operator() (T const& geom) const
    {
        std::cerr << boost::geometry::wkt(geom) << std::endl;
    }
};

}

struct encode_geometry
{
    vector_tile::Tile_Feature & feature_;
    int32_t x_;
    int32_t y_;
    encode_geometry(vector_tile::Tile_Feature & feature) :
      feature_(feature),
      x_(0),
      y_(0) { }

    void operator() (geometry_empty const&)
    {
    }

    template <typename T>
    void operator()(T const& path)
    {
        mapnik::vector_tile_impl::encode_geometry(path,feature_,x_,y_);
    }

    void operator()(mapnik::geometry::multi_point<std::int64_t> const & path)
    {
        for (auto const& pt : path)
        {
            mapnik::vector_tile_impl::encode_geometry(pt,feature_,x_,y_);
        }
    }

    void operator()(mapnik::geometry::multi_line_string<std::int64_t> const & path)
    {
        for (auto const& ls : path)
        {
            mapnik::vector_tile_impl::encode_geometry(ls,feature_,x_,y_);
        }
    }

    void operator()(mapnik::geometry::multi_polygon<std::int64_t> const& path)
    {
        for (auto const& p : path)
        {
            mapnik::vector_tile_impl::encode_geometry(p,feature_,x_,y_);
        }
    }

    void operator()(mapnik::geometry::geometry_collection<std::int64_t> const& path)
    {
        for (auto const& p : path)
        {
            mapnik::util::apply_visitor((*this), p);
        }
    }
};

struct show_path
{
    std::string & str_;
    show_path(std::string & out) :
      str_(out) {}

    template <typename T>
    void operator()(T & path)
    {
        unsigned cmd = -1;
        double x = 0;
        double y = 0;
        std::ostringstream s;
        path.rewind(0);
        while ((cmd = path.vertex(&x, &y)) != mapnik::SEG_END)
        {
            switch (cmd)
            {
                case mapnik::SEG_MOVETO: s << "move_to("; break;
                case mapnik::SEG_LINETO: s << "line_to("; break;
                case mapnik::SEG_CLOSE: s << "close_path("; break;
                default: std::clog << "unhandled cmd " << cmd << "\n"; break;
            }
            s << x << "," << y << ")\n";
        }
        str_ += s.str();
    }
};

template <typename T>
vector_tile::Tile_Feature geometry_to_feature(mapnik::geometry::geometry<T> const& g)
{
    vector_tile::Tile_Feature feature;
    encode_geometry ap(feature);
    if (g.template is<mapnik::geometry::point<T> >() || g.template is<mapnik::geometry::multi_point<T> >())
    {
        feature.set_type(vector_tile::Tile_GeomType_POINT);
    }
    else if (g.template is<mapnik::geometry::line_string<T> >() || g.template is<mapnik::geometry::multi_line_string<T> >())
    {
        feature.set_type(vector_tile::Tile_GeomType_LINESTRING);
    }
    else if (g.template is<mapnik::geometry::polygon<T> >() || g.template is<mapnik::geometry::multi_polygon<T> >())
    {
        feature.set_type(vector_tile::Tile_GeomType_POLYGON);
    }
    else
    {
        throw std::runtime_error("could not detect valid geometry type");
    }
    mapnik::util::apply_visitor(ap,g);
    return feature;
}

template <typename T>
std::string decode_to_path_string(mapnik::geometry::geometry<T> const& g)
{
    //mapnik::util::apply_visitor(print(), g2);
    using decode_path_type = mapnik::geometry::vertex_processor<show_path>;
    std::string out;
    show_path sp(out);
    mapnik::util::apply_visitor(decode_path_type(sp), g);
    return out;
}

template <typename T>
std::string compare(mapnik::geometry::geometry<T> const& g)
{
    vector_tile::Tile_Feature feature = geometry_to_feature(g);
    mapnik::vector_tile_impl::Geometry geoms(feature,0.0,0.0,1.0,1.0);
    auto g2 = mapnik::vector_tile_impl::decode_geometry(geoms,feature.type());
    return decode_to_path_string(g2);
}
<|endoftext|>


<commit_before>#include <util/Logger.h>
#include <util/foreach.h>
#include "LinearSolver.h"

static logger::LogChannel linearsolverlog("linearsolverlog", "[LinearSolver] ");

LinearSolver::LinearSolver(const LinearSolverBackendFactory& backendFactory) {

	registerInput(_objective, "objective");
	registerInput(_linearConstraints, "linear constraints");
	registerInput(_parameters, "parameters");
	registerOutput(_solution, "solution");

	// create solver backend
	_solver = backendFactory.createLinearSolverBackend();
}

LinearSolver::~LinearSolver() {

	delete _solver;
}

void
LinearSolver::updateOutputs() {

	updateLinearProgram();

	solve();
}

void
LinearSolver::updateLinearProgram() {

	_solver->initialize(
			getNumVariables(),
			(_parameters ? _parameters->getVariableType() : Continuous));

	_solver->setObjective(*_objective);

	_solver->setConstraints(*_linearConstraints);
}

void
LinearSolver::solve() {

	double value;

	std::string message;

	if (_solver->solve(*_solution, value, message))
		LOG_USER(linearsolverlog) << "optimal solution found" << std::endl;
	else
		LOG_ERROR(linearsolverlog) << "error: " << message << std::endl;
}

unsigned int
LinearSolver::getNumVariables() {

	unsigned int numVars = 0;

	// number of vars in the objective
	numVars = std::max<unsigned int>(numVars, _objective->getCoefficients().size());

	// numver of vars in the constraints
	typedef std::pair<unsigned int, double> lin_coef_type;
	foreach (const LinearConstraint& constraint, *_linearConstraints)
		foreach (const lin_coef_type& pair, constraint.getCoefficients())
			numVars = std::max(numVars, pair.first);

	return numVars;
}
<commit_msg>bugfix: inference - LinearSolver's variable count from constraints was off by one<commit_after>#include <util/Logger.h>
#include <util/foreach.h>
#include "LinearSolver.h"

static logger::LogChannel linearsolverlog("linearsolverlog", "[LinearSolver] ");

LinearSolver::LinearSolver(const LinearSolverBackendFactory& backendFactory) {

	registerInput(_objective, "objective");
	registerInput(_linearConstraints, "linear constraints");
	registerInput(_parameters, "parameters");
	registerOutput(_solution, "solution");

	// create solver backend
	_solver = backendFactory.createLinearSolverBackend();
}

LinearSolver::~LinearSolver() {

	delete _solver;
}

void
LinearSolver::updateOutputs() {

	updateLinearProgram();

	solve();
}

void
LinearSolver::updateLinearProgram() {

	_solver->initialize(
			getNumVariables(),
			(_parameters ? _parameters->getVariableType() : Continuous));

	_solver->setObjective(*_objective);

	_solver->setConstraints(*_linearConstraints);
}

void
LinearSolver::solve() {

	double value;

	std::string message;

	if (_solver->solve(*_solution, value, message))
		LOG_USER(linearsolverlog) << "optimal solution found" << std::endl;
	else
		LOG_ERROR(linearsolverlog) << "error: " << message << std::endl;
}

unsigned int
LinearSolver::getNumVariables() {

	LOG_ALL(linearsolverlog)
			<< "objective contains "
			<< _objective->getCoefficients().size()
			<< " variables" << std::endl;

	unsigned int numVars = _objective->getCoefficients().size();

	// number of vars in the constraints
	unsigned int varNum;
	double coef;
	foreach (const LinearConstraint& constraint, *_linearConstraints)
		foreach (boost::tie(varNum, coef), constraint.getCoefficients())
			numVars = std::max(numVars, varNum + 1);

	LOG_ALL(linearsolverlog)
			<< "together with the constraints, "
			<< numVars
			<< " variables are used" << std::endl;

	return numVars;
}
<|endoftext|>


<commit_before>int main()
{
  int *a = nullptr;
  return 0;
}
<commit_msg>const pointer<commit_after>#include <iostream>
using namespace std;

int main()
{
  int *a = nullptr;
  double b = 3.56;
  double *const bp = &b;
  *bp = .999;
  return 0;
}
<|endoftext|>


<commit_before>#include "glwidget.h"

#include <QtOpenGL>

#ifdef __APPLE__
    #include <GLUT/glut.h>
#else
    #include <glut.h>
#endif

#include <QDebug>

#include "db/database.h"
#include "algorithms/pathalgorithms.h"
#include "../stable.h"

GLWidget::GLWidget(QWidget *parent) :
    QGLWidget(parent)
{
    canvasWidth = 0;
    canvasHeight = 0;
    timer = new QTimer(this);
    camera = new GLCamera();

    isStop = true;
    isGLInitialized = false;

    startPoint = 0;
    endPoint = 0;

}

void GLWidget::initializeGL()
{
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
    glClearColor(0.329412, 0.329412, 0.329412, 1.0);
    glColor3f(1.0, 1.0, 1.0);

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
    glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);

    glEnable(GL_POINT_SMOOTH);

    //glEnable( GL_POINT_SPRITE );

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

    connect(timer, SIGNAL(timeout()), this, SLOT(updateLC()));
    this->setFocus();

    if(!glPOIPoints.empty())
    {
        for(int i = 0; i < glPOIPoints.size(); i++)
        {
            glPOIPoints[i]->texture = bindTexture(QPixmap(QString::fromStdString(glPOIPoints[i]->point->getIconPath())), GL_TEXTURE_2D);
        }
    }

    isGLInitialized = true;
}

void GLWidget::updateLC()
{
    // Do my update stuff

    //map->update();

    updateGL();
}

void GLWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();

    gluLookAt(camera->x, camera->y, camera->z,
              camera->look_x, camera->look_y, camera->look_z,
              0.0, 1.0, 0.0);

    glPushMatrix();

    glColor3f(1.0f, 1.0f, 1.0f);

    glLineWidth(1.0f);

    if(allWays == NULL)
        return;
    map<unsigned long int, Way*>::iterator wayIt;
    for(wayIt = allWays->begin(); wayIt != allWays->end(); ++wayIt)
    {
        Way* way = ((Way*)(*wayIt).second);
        switch(way->getWayType())
        {
            case ns_way::primary:
            default:
                glColor3f(1.0f, 1.0f, 1.0f);
                break;
            case ns_way::footway:
                glColor3f(1.0f, 1.0f, 0.0f);
                break;
            case ns_way::steps:
                glColor3f(0.0f, 1.0f, 1.0f);
                break;
            case ns_way::track:
                glColor3f(1.0f, 0.0f, 1.0f);
                break;
            case ns_way::raceway:
                glColor3f(1.0f, 0.5f, 0.0f);
                break;
            case ns_way::service:
                glColor3f(0.737255f, 0.560784f, 0.560784f);
                break;
        }

        glBegin(GL_LINE_STRIP);
        for (vector<Node*>::iterator nodeIt = way->getNodesBegin(); nodeIt != way->getNodesEnd(); nodeIt++){
            boost_xy_point& nodeGeoPos = (*nodeIt)->getGeoPosition();
            glVertex3f(nodeGeoPos.x() * 100, nodeGeoPos.y() * 100, 0.0f);
        }
        glEnd();
    }

    glLineWidth(5.0f);
    glColor3f(1.0f, 0.0f, 0.0f);
        glBegin(GL_LINES);
        if(startPoint != NULL && !path.empty())
        {
            glColor3f(0.0f, 0.0f, 1.0f);
            glVertex3f(startPoint->x() * 100.0f, startPoint->y() * 100.0f, 0.1f);
            WaySegment* waySegment = path[0];
            boost_xy_point& nodeGeoPosA = waySegment->getPointA()->getGeoPosition();
            glVertex3f(nodeGeoPosA.x() * 100.0f, nodeGeoPosA.y() * 100.0f, 0.1f);
        }
        glColor3f(1.0f, 0.0f, 0.0f);
        int i;
        for(i = 0; i < path.size(); i++)
        {
            WaySegment* waySegment = path[i];
            boost_xy_point& nodeGeoPosA = waySegment->getPointA()->getGeoPosition();
            boost_xy_point& nodeGeoPosB = waySegment->getPointB()->getGeoPosition();
            //glBegin(GL_LINES);
            //qDebug() << "A: " <<nodeGeoPosA.x() << "-" << nodeGeoPosA.y();
            //qDebug() << "B: " <<nodeGeoPosB.x() << "-" << nodeGeoPosB.y();
            glVertex3f(nodeGeoPosA.x() * 100.0f, nodeGeoPosA.y() * 100.0f, 0.1f);
            glVertex3f(nodeGeoPosB.x() * 100.0f, nodeGeoPosB.y() * 100.0f, 0.1f);
            //glEnd();
        }
        if(endPoint != NULL && !path.empty())
        {
            glColor3f(0.0f, 0.0f, 1.0f);
            WaySegment* waySegment = path[i-1];
            boost_xy_point& nodeGeoPosB = waySegment->getPointB()->getGeoPosition();
            glVertex3f(nodeGeoPosB.x() * 100.0f, nodeGeoPosB.y() * 100.0f, 0.1f);
            glVertex3f(endPoint->x() * 100.0f, endPoint->y() * 100.0f, 0.1f);
        }
        glEnd();

    if(startPoint != NULL)
    {
        glColor3f(0.0f, 1.0f, 0.0f);
        glPointSize(7.0f);
        glBegin(GL_POINTS);
        glVertex3f(startPoint->x() * 100.0f, startPoint->y() * 100.0f, 0.2f);
        glEnd();
    }

    if(endPoint != NULL)
    {
        glColor3f(1.0f, 0.0f, 0.0f);
        glPointSize(7.0f);
        glBegin(GL_POINTS);
        glVertex3f(endPoint->x() * 100.0f, endPoint->y() * 100.0f, 0.2f);
        glEnd();
    }

    glPushMatrix();
    //glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
    //glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
    glColor3f(0.3f, 0.3f, 0.3f);
    glEnable(GL_TEXTURE_2D);
    for(int i = 0; i < glPOIPoints.size(); i++)
    {
        if(!glPOIPoints[i]->texture)
            continue;
        glVertexPointer(3, GL_FLOAT, 0, glPOIPoints[i]->vertices.constData());
        glTexCoordPointer(2, GL_FLOAT, 0, glPOIPoints[i]->textureCoordinates.constData());
        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
        glBindTexture(GL_TEXTURE_2D, glPOIPoints[i]->texture);
        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
    }
    glDisable(GL_TEXTURE_2D);
    glPopMatrix();

    glPopMatrix();
}

void GLWidget::resizeGL(int w, int h)
{
    glViewport(0, 0, w, h);

    camera->canvasWidth = w;
    camera->canvasHeight = h;

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    float ratio = float(w) / float(h);

    glOrtho(camera->planeLeft,
            camera->planeRight,
            camera->planeBottom,
            camera->planeTop,
            camera->planeNear,
            camera->planeFar);

    //gluPerspective(60.0, ratio, 1.0, 100.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void GLWidget::keyPressEvent(QKeyEvent *event)
{
    switch (event->key())
    {
    case Qt::Key_C:
        camera->center();
        break;
    case Qt::Key_W:
        camera->up();
        break;
    case Qt::Key_A:
        camera->left();
        break;
    case Qt::Key_S:
        camera->down();
        break;
    case Qt::Key_D:
        camera->right();
        break;
    case Qt::Key_Q:
        camera->zoomIn();
        break;
    case Qt::Key_E:
        camera->zoomOut();
        break;
    case Qt::Key_Up:
        camera->up();
        break;
    case Qt::Key_Down:
        camera->down();
        break;
    case Qt::Key_Left:
        camera->left();
        break;
    case Qt::Key_Right:
        camera->right();
        break;
    case Qt::Key_Plus:
        camera->zoomIn();
        break;
    case Qt::Key_Minus:
        camera->zoomOut();
        break;
    case Qt::Key_Escape:
        this->parentWidget()->parentWidget()->close();
        break;
    default:
        break;
    }

    event->accept();
}

void GLWidget::wheelEvent(QWheelEvent *event)
{
    if(event->orientation() == Qt::Vertical)
    {
        if(event->delta() > 0)
            camera->zoomIn();
        else
            camera->zoomOut();
    }
    else
    {
        if(event->delta() > 0)
            camera->right();
        else
            camera->left();
    }

    event->accept();
}

void GLWidget::mousePressEvent(QMouseEvent *event)
{
    lastPos = event->pos();
    event->accept();
}

void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
    //qDebug() << "mouseMoveEvent"<<endl;
    int dx = event->x() - lastPos.x();
    int dy = event->y() - lastPos.y();

//    qDebug() << "lastPos.x: "<< lastPos.x() << " lastPost.y: " << lastPos.y() <<endl;
//    qDebug() << "event->x: "<< event->x() << " event->y: " << event->y() << endl;
//    qDebug() << "dx: "<< dx << " dy: " << dy << endl;
//    qDebug() << "===========================================" << endl;

    if (event->buttons() & Qt::LeftButton) {
        camera->move(dx, dy);
        //setXRotation(xRot + 8 * dy);
        //setYRotation(yRot + 8 * dx);
    } else if (event->buttons() & Qt::RightButton) {
        //setXRotation(xRot + 8 * dy);
        //setZRotation(zRot + 8 * dx);
    }

    lastPos = event->pos();
}

void GLWidget::startGL()
{
    isStop = false;
    timer->start(30);
}

void GLWidget::stopGL()
{
    isStop = true;
    timer->stop();
}

QPointF GLWidget::getGeoPosition(QPoint point)
{
    GLint viewport[4];
    GLdouble modelview[16];
    GLdouble projection[16];
    GLfloat winX, winY, winZ;
    GLdouble posX, posY, posZ;

    glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
    glGetDoublev(GL_PROJECTION_MATRIX, projection);
    glGetIntegerv(GL_VIEWPORT, viewport);

    winX = (float)point.x();
    winY = (float)viewport[3] - (float)point.y();
    glReadPixels(point.x(), int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);

    gluUnProject(winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);

    return QPointF(posX / 100.0, posY / 100.0);
}

void GLWidget::centerMap()
{
    camera->center();
}

void GLWidget::setMap(map<unsigned long int,Way*>* ways)
{
    allWays = ways;
}

void GLWidget::setPath(vector<WaySegment*> waySegments)
{
    path = waySegments;
}

void GLWidget::drawStartPoint(QPointF *startp)
{
    startPoint = startp;
}

void GLWidget::drawEndPoint(QPointF *endp)
{
    endPoint = endp;
}

void GLWidget::deleteStartPoint()
{
    startPoint = 0;
}

void GLWidget::deleteEndPoint()
{
    endPoint = 0;
}

void GLWidget::deletePath()
{
    path.clear();
}

void GLWidget::setPOIs(vector<POIPoint*> pois)
{
    glPOIPoints.clear();
    for(int i = 0; i < pois.size(); i++)
    {
        GLPOIPoint* poiPoint = new GLPOIPoint();
        poiPoint->point = pois[i];
        //qDebug() << "Icon Path: " << poiPoint->point->getIconPath();
        //qDebug() << "Icon Path: " << QString::fromStdString(poiPoint->point->getIconPath());
        if(isGLInitialized)
            poiPoint->texture = bindTexture(QPixmap(QString::fromStdString(poiPoint->point->getIconPath())), GL_TEXTURE_2D);
        poiPoint->setupVertices();
        glPOIPoints.push_back(poiPoint);
    }
}

void GLWidget::deletePOIs()
{
    glPOIPoints.clear();
}
<commit_msg>Fix Transparent POI Drawing<commit_after>#include "glwidget.h"

#include <QtOpenGL>

#ifdef __APPLE__
    #include <GLUT/glut.h>
#else
    #include <glut.h>
#endif

#include <QDebug>

#include "db/database.h"
#include "algorithms/pathalgorithms.h"
#include "../stable.h"

GLWidget::GLWidget(QWidget *parent) :
    QGLWidget(parent)
{
    canvasWidth = 0;
    canvasHeight = 0;
    timer = new QTimer(this);
    camera = new GLCamera();

    isStop = true;
    isGLInitialized = false;

    startPoint = 0;
    endPoint = 0;

}

void GLWidget::initializeGL()
{
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
    glClearColor(0.329412, 0.329412, 0.329412, 1.0);
    glColor3f(1.0, 1.0, 1.0);

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
    glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);

    glEnable(GL_POINT_SMOOTH);

    //glEnable( GL_POINT_SPRITE );

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    //glBlendFunc (GL_ONE, GL_ONE);
    //glBlendFunc(GL_ONE_MINUS_DST_ALPHA,GL_DST_ALPHA);
    glEnable(GL_ALPHA_TEST);
    glAlphaFunc(GL_GREATER, 0.5f);

    connect(timer, SIGNAL(timeout()), this, SLOT(updateLC()));
    this->setFocus();

    if(!glPOIPoints.empty())
    {
        for(int i = 0; i < glPOIPoints.size(); i++)
        {
            glPOIPoints[i]->texture = bindTexture(QPixmap(QString::fromStdString(glPOIPoints[i]->point->getIconPath())), GL_TEXTURE_2D);
        }
    }

    isGLInitialized = true;
}

void GLWidget::updateLC()
{
    // Do my update stuff

    //map->update();

    updateGL();
}

void GLWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();

    gluLookAt(camera->x, camera->y, camera->z,
              camera->look_x, camera->look_y, camera->look_z,
              0.0, 1.0, 0.0);

    glPushMatrix();

    glColor3f(1.0f, 1.0f, 1.0f);

    glLineWidth(1.0f);

    if(allWays == NULL)
        return;
    map<unsigned long int, Way*>::iterator wayIt;
    for(wayIt = allWays->begin(); wayIt != allWays->end(); ++wayIt)
    {
        Way* way = ((Way*)(*wayIt).second);
        switch(way->getWayType())
        {
            case ns_way::primary:
            default:
                glColor3f(1.0f, 1.0f, 1.0f);
                break;
            case ns_way::footway:
                glColor3f(1.0f, 1.0f, 0.0f);
                break;
            case ns_way::steps:
                glColor3f(0.0f, 1.0f, 1.0f);
                break;
            case ns_way::track:
                glColor3f(1.0f, 0.0f, 1.0f);
                break;
            case ns_way::raceway:
                glColor3f(1.0f, 0.5f, 0.0f);
                break;
            case ns_way::service:
                glColor3f(0.737255f, 0.560784f, 0.560784f);
                break;
        }

        glBegin(GL_LINE_STRIP);
        for (vector<Node*>::iterator nodeIt = way->getNodesBegin(); nodeIt != way->getNodesEnd(); nodeIt++){
            boost_xy_point& nodeGeoPos = (*nodeIt)->getGeoPosition();
            glVertex3f(nodeGeoPos.x() * 100, nodeGeoPos.y() * 100, 0.0f);
        }
        glEnd();
    }

    glLineWidth(5.0f);
    glColor3f(1.0f, 0.0f, 0.0f);
        glBegin(GL_LINES);
        if(startPoint != NULL && !path.empty())
        {
            glColor3f(0.0f, 0.0f, 1.0f);
            glVertex3f(startPoint->x() * 100.0f, startPoint->y() * 100.0f, 0.1f);
            WaySegment* waySegment = path[0];
            boost_xy_point& nodeGeoPosA = waySegment->getPointA()->getGeoPosition();
            glVertex3f(nodeGeoPosA.x() * 100.0f, nodeGeoPosA.y() * 100.0f, 0.1f);
        }
        glColor3f(1.0f, 0.0f, 0.0f);
        int i;
        for(i = 0; i < path.size(); i++)
        {
            WaySegment* waySegment = path[i];
            boost_xy_point& nodeGeoPosA = waySegment->getPointA()->getGeoPosition();
            boost_xy_point& nodeGeoPosB = waySegment->getPointB()->getGeoPosition();
            //glBegin(GL_LINES);
            //qDebug() << "A: " <<nodeGeoPosA.x() << "-" << nodeGeoPosA.y();
            //qDebug() << "B: " <<nodeGeoPosB.x() << "-" << nodeGeoPosB.y();
            glVertex3f(nodeGeoPosA.x() * 100.0f, nodeGeoPosA.y() * 100.0f, 0.1f);
            glVertex3f(nodeGeoPosB.x() * 100.0f, nodeGeoPosB.y() * 100.0f, 0.1f);
            //glEnd();
        }
        if(endPoint != NULL && !path.empty())
        {
            glColor3f(0.0f, 0.0f, 1.0f);
            WaySegment* waySegment = path[i-1];
            boost_xy_point& nodeGeoPosB = waySegment->getPointB()->getGeoPosition();
            glVertex3f(nodeGeoPosB.x() * 100.0f, nodeGeoPosB.y() * 100.0f, 0.1f);
            glVertex3f(endPoint->x() * 100.0f, endPoint->y() * 100.0f, 0.1f);
        }
        glEnd();

    if(startPoint != NULL)
    {
        glColor3f(0.0f, 1.0f, 0.0f);
        glPointSize(7.0f);
        glBegin(GL_POINTS);
        glVertex3f(startPoint->x() * 100.0f, startPoint->y() * 100.0f, 0.2f);
        glEnd();
    }

    if(endPoint != NULL)
    {
        glColor3f(1.0f, 0.0f, 0.0f);
        glPointSize(7.0f);
        glBegin(GL_POINTS);
        glVertex3f(endPoint->x() * 100.0f, endPoint->y() * 100.0f, 0.2f);
        glEnd();
    }

    glPushMatrix();
    //glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
    //glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
    glColor3f(0.3f, 0.3f, 0.3f);
    glEnable(GL_TEXTURE_2D);
    for(int i = 0; i < glPOIPoints.size(); i++)
    {
        if(!glPOIPoints[i]->texture)
            continue;
        glVertexPointer(3, GL_FLOAT, 0, glPOIPoints[i]->vertices.constData());
        glTexCoordPointer(2, GL_FLOAT, 0, glPOIPoints[i]->textureCoordinates.constData());
        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
        glBindTexture(GL_TEXTURE_2D, glPOIPoints[i]->texture);
        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
    }
    glDisable(GL_TEXTURE_2D);
    glPopMatrix();

    glPopMatrix();
}

void GLWidget::resizeGL(int w, int h)
{
    glViewport(0, 0, w, h);

    camera->canvasWidth = w;
    camera->canvasHeight = h;

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    float ratio = float(w) / float(h);

    glOrtho(camera->planeLeft,
            camera->planeRight,
            camera->planeBottom,
            camera->planeTop,
            camera->planeNear,
            camera->planeFar);

    //gluPerspective(60.0, ratio, 1.0, 100.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void GLWidget::keyPressEvent(QKeyEvent *event)
{
    switch (event->key())
    {
    case Qt::Key_C:
        camera->center();
        break;
    case Qt::Key_W:
        camera->up();
        break;
    case Qt::Key_A:
        camera->left();
        break;
    case Qt::Key_S:
        camera->down();
        break;
    case Qt::Key_D:
        camera->right();
        break;
    case Qt::Key_Q:
        camera->zoomIn();
        break;
    case Qt::Key_E:
        camera->zoomOut();
        break;
    case Qt::Key_Up:
        camera->up();
        break;
    case Qt::Key_Down:
        camera->down();
        break;
    case Qt::Key_Left:
        camera->left();
        break;
    case Qt::Key_Right:
        camera->right();
        break;
    case Qt::Key_Plus:
        camera->zoomIn();
        break;
    case Qt::Key_Minus:
        camera->zoomOut();
        break;
    case Qt::Key_Escape:
        this->parentWidget()->parentWidget()->close();
        break;
    default:
        break;
    }

    event->accept();
}

void GLWidget::wheelEvent(QWheelEvent *event)
{
    if(event->orientation() == Qt::Vertical)
    {
        if(event->delta() > 0)
            camera->zoomIn();
        else
            camera->zoomOut();
    }
    else
    {
        if(event->delta() > 0)
            camera->right();
        else
            camera->left();
    }

    event->accept();
}

void GLWidget::mousePressEvent(QMouseEvent *event)
{
    lastPos = event->pos();
    event->accept();
}

void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
    //qDebug() << "mouseMoveEvent"<<endl;
    int dx = event->x() - lastPos.x();
    int dy = event->y() - lastPos.y();

//    qDebug() << "lastPos.x: "<< lastPos.x() << " lastPost.y: " << lastPos.y() <<endl;
//    qDebug() << "event->x: "<< event->x() << " event->y: " << event->y() << endl;
//    qDebug() << "dx: "<< dx << " dy: " << dy << endl;
//    qDebug() << "===========================================" << endl;

    if (event->buttons() & Qt::LeftButton) {
        camera->move(dx, dy);
        //setXRotation(xRot + 8 * dy);
        //setYRotation(yRot + 8 * dx);
    } else if (event->buttons() & Qt::RightButton) {
        //setXRotation(xRot + 8 * dy);
        //setZRotation(zRot + 8 * dx);
    }

    lastPos = event->pos();
}

void GLWidget::startGL()
{
    isStop = false;
    timer->start(30);
}

void GLWidget::stopGL()
{
    isStop = true;
    timer->stop();
}

QPointF GLWidget::getGeoPosition(QPoint point)
{
    GLint viewport[4];
    GLdouble modelview[16];
    GLdouble projection[16];
    GLfloat winX, winY, winZ;
    GLdouble posX, posY, posZ;

    glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
    glGetDoublev(GL_PROJECTION_MATRIX, projection);
    glGetIntegerv(GL_VIEWPORT, viewport);

    winX = (float)point.x();
    winY = (float)viewport[3] - (float)point.y();
    glReadPixels(point.x(), int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);

    gluUnProject(winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);

    return QPointF(posX / 100.0, posY / 100.0);
}

void GLWidget::centerMap()
{
    camera->center();
}

void GLWidget::setMap(map<unsigned long int,Way*>* ways)
{
    allWays = ways;
}

void GLWidget::setPath(vector<WaySegment*> waySegments)
{
    path = waySegments;
}

void GLWidget::drawStartPoint(QPointF *startp)
{
    startPoint = startp;
}

void GLWidget::drawEndPoint(QPointF *endp)
{
    endPoint = endp;
}

void GLWidget::deleteStartPoint()
{
    startPoint = 0;
}

void GLWidget::deleteEndPoint()
{
    endPoint = 0;
}

void GLWidget::deletePath()
{
    path.clear();
}

void GLWidget::setPOIs(vector<POIPoint*> pois)
{
    glPOIPoints.clear();
    for(int i = 0; i < pois.size(); i++)
    {
        GLPOIPoint* poiPoint = new GLPOIPoint();
        poiPoint->point = pois[i];
        //qDebug() << "Icon Path: " << poiPoint->point->getIconPath();
        //qDebug() << "Icon Path: " << QString::fromStdString(poiPoint->point->getIconPath());
        if(isGLInitialized)
            poiPoint->texture = bindTexture(QPixmap(QString::fromStdString(poiPoint->point->getIconPath())), GL_TEXTURE_2D);
        poiPoint->setupVertices();
        glPOIPoints.push_back(poiPoint);
    }
}

void GLWidget::deletePOIs()
{
    glPOIPoints.clear();
}
<|endoftext|>


<commit_before>/*
    Copyright (C) 1997, 1998, 1999 by Alex Pfaffe
	(Digital Dawn Graphics Inc)

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
// For timing info.
#ifndef WIN32
#include <sys/types.h>
#include <sys/times.h>
#else
#include <time.h>
#endif
#include "sysdef.h"
#include "csterr/ddgutil.h"

// ----------------------------------------------------------------------
//
// ddgUtil:
//
//  See if we are running on a Pentium III.
//

bool ddgUtil::DetectSIMD(void)
{

#ifdef WIN32
bool found_simd;
_asm

{
pushfd
pop eax // get EFLAGS into eax
mov ebx,eax // keep a copy
xor eax,0x200000
// toggle CPUID bit

push eax
popfd // set new EFLAGS
pushfd
pop eax // EFLAGS back into eax

xor eax,ebx
// have we changed the ID bit?

je NO_SIMD
// No, no CPUID instruction

// we could toggle the
// ID bit so CPUID is present
mov eax,1

cpuid // get processor features
test edx,1<<25 // check the SIMD bit
jz NO_SIMD
mov found_simd,1
jmp DONE
NO_SIMD:
mov found_simd,0
DONE:
}

return found_simd;
#else
return false;
#endif

}

// ----------------------------------------------------------------------
float ddgAngle::_cosTable[180*ddgAngle_res];
float ddgAngle::pi = M_PI;
ddgAngle ddg_init;	// Ensure table gets initialized.

ddgAngle::ddgAngle()
{
  // Calculate from 0.0 to 180.0 degrees.
  for (int i = 0; i < (int)(180*ddgAngle_res); i++)
    {
    _cosTable[i] = ::cos(M_PI*(float)i/(float)(ddgAngle_res*180));
    }
}

// This should be inlined, but W32 wont let me use _cosTable in a DLL
// if it is inlined.
float ddgAngle::cos( float angle)
{
	float a = mod(angle);
	return a < 180.0f ?
		_cosTable[((int)a*ddgAngle_res)]:
		-_cosTable[((int)(a-180.0f)*ddgAngle_res)];
}

<commit_msg>Makeing sure it can be compiled for Mac OS.<commit_after>/*
    Copyright (C) 1997, 1998, 1999 by Alex Pfaffe
	(Digital Dawn Graphics Inc)

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
// For timing info.
#include "sysdef.h"
#ifdef WIN32
#include <time.h>
#elif OS_MACOS
#include <time.h>
#else
#include <sys/types.h>
#include <sys/times.h>
#endif
#include "csterr/ddgutil.h"

// ----------------------------------------------------------------------
//
// ddgUtil:
//
//  See if we are running on a Pentium III.
//

bool ddgUtil::DetectSIMD(void)
{

#ifdef WIN32
bool found_simd;
_asm

{
pushfd
pop eax // get EFLAGS into eax
mov ebx,eax // keep a copy
xor eax,0x200000
// toggle CPUID bit

push eax
popfd // set new EFLAGS
pushfd
pop eax // EFLAGS back into eax

xor eax,ebx
// have we changed the ID bit?

je NO_SIMD
// No, no CPUID instruction

// we could toggle the
// ID bit so CPUID is present
mov eax,1

cpuid // get processor features
test edx,1<<25 // check the SIMD bit
jz NO_SIMD
mov found_simd,1
jmp DONE
NO_SIMD:
mov found_simd,0
DONE:
}

return found_simd;
#else
return false;
#endif

}

// ----------------------------------------------------------------------
float ddgAngle::_cosTable[180*ddgAngle_res];
float ddgAngle::pi = M_PI;
ddgAngle ddg_init;	// Ensure table gets initialized.

ddgAngle::ddgAngle()
{
  // Calculate from 0.0 to 180.0 degrees.
  for (int i = 0; i < (int)(180*ddgAngle_res); i++)
    {
    _cosTable[i] = ::cos(M_PI*(float)i/(float)(ddgAngle_res*180));
    }
}

// This should be inlined, but W32 wont let me use _cosTable in a DLL
// if it is inlined.
float ddgAngle::cos( float angle)
{
	float a = mod(angle);
	return a < 180.0f ?
		_cosTable[((int)a*ddgAngle_res)]:
		-_cosTable[((int)(a-180.0f)*ddgAngle_res)];
}

<|endoftext|>


<commit_before>/*
    Copyright (C) 2001 by Jorrit Tyberghein

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "cstool/initapp.h"
#include "isys/system.h"
#include "iutil/eventh.h"
#include "iutil/comp.h"
#include "iutil/objreg.h"
#include "ivideo/graph3d.h"
#include "ivideo/graph2d.h"
#include "iengine/engine.h"
#include "ivaria/reporter.h"
#include "ivaria/stdrep.h"
#include "ivaria/conout.h"
#include "isys/vfs.h"
#include "imap/parser.h"
#include "isys/plugin.h"

bool csInitializeApplication (iObjectRegistry* object_reg, bool use_reporter,
	bool use_reporter_listener)
{
  iPluginManager* plugin_mgr = CS_QUERY_REGISTRY (object_reg, iPluginManager);

  iGraphics3D* g3d = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_VIDEO,
  	iGraphics3D);
  if (g3d)
  {
    object_reg->Register (g3d);
    if (g3d->GetDriver2D ())
      object_reg->Register (g3d->GetDriver2D ());
    g3d->DecRef ();
  }

  iEngine* engine = CS_QUERY_PLUGIN (plugin_mgr, iEngine);
  if (engine)
  {
    object_reg->Register (engine);
    engine->DecRef ();
  }

  iVFS* vfs = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_VFS, iVFS);
  if (vfs)
  {
    object_reg->Register (vfs);
    vfs->DecRef ();
  }

  iConsoleOutput* console = CS_QUERY_PLUGIN_ID (plugin_mgr,
  	CS_FUNCID_CONSOLE, iConsoleOutput);
  if (console)
  {
    object_reg->Register (console);
    console->DecRef ();
  }

  iLoader* loader = CS_QUERY_PLUGIN_ID (plugin_mgr,
  	CS_FUNCID_LVLLOADER, iLoader);
  if (loader)
  {
    object_reg->Register (loader);
    loader->DecRef ();
  }

  iReporter* reporter = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_REPORTER,
  	iReporter);
  if (!reporter && use_reporter)
  {
    reporter = CS_LOAD_PLUGIN (plugin_mgr, "crystalspace.utilities.reporter",
    	CS_FUNCID_REPORTER, iReporter);
    if (!reporter)
      return false;

    reporter->IncRef ();
  }
  if (reporter)
  {
    object_reg->Register (reporter);
    reporter->DecRef ();
  }

  iStandardReporterListener* stdrep = CS_QUERY_PLUGIN (plugin_mgr,
  	iStandardReporterListener);
  if (!stdrep && use_reporter_listener)
  {
    stdrep = CS_LOAD_PLUGIN (plugin_mgr, "crystalspace.utilities.stdrep",
    	"StdRep", iStandardReporterListener);
    if (!stdrep)
      return false;

    stdrep->IncRef ();
  }
  if (stdrep)
  {
    stdrep->SetDefaults ();
    object_reg->Register (stdrep);
    stdrep->DecRef ();
  }

  return true;
}

<commit_msg>removed the IncRef on the reporter related stuff. The CS_LOAD_PLUGIN already IncRef's it.<commit_after>/*
    Copyright (C) 2001 by Jorrit Tyberghein

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "cstool/initapp.h"
#include "isys/system.h"
#include "iutil/eventh.h"
#include "iutil/comp.h"
#include "iutil/objreg.h"
#include "ivideo/graph3d.h"
#include "ivideo/graph2d.h"
#include "iengine/engine.h"
#include "ivaria/reporter.h"
#include "ivaria/stdrep.h"
#include "ivaria/conout.h"
#include "isys/vfs.h"
#include "imap/parser.h"
#include "isys/plugin.h"

bool csInitializeApplication (iObjectRegistry* object_reg, bool use_reporter,
	bool use_reporter_listener)
{
  iPluginManager* plugin_mgr = CS_QUERY_REGISTRY (object_reg, iPluginManager);

  iGraphics3D* g3d = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_VIDEO,
  	iGraphics3D);
  if (g3d)
  {
    object_reg->Register (g3d);
    if (g3d->GetDriver2D ())
      object_reg->Register (g3d->GetDriver2D ());
    g3d->DecRef ();
  }

  iEngine* engine = CS_QUERY_PLUGIN (plugin_mgr, iEngine);
  if (engine)
  {
    object_reg->Register (engine);
    engine->DecRef ();
  }

  iVFS* vfs = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_VFS, iVFS);
  if (vfs)
  {
    object_reg->Register (vfs);
    vfs->DecRef ();
  }

  iConsoleOutput* console = CS_QUERY_PLUGIN_ID (plugin_mgr,
  	CS_FUNCID_CONSOLE, iConsoleOutput);
  if (console)
  {
    object_reg->Register (console);
    console->DecRef ();
  }

  iLoader* loader = CS_QUERY_PLUGIN_ID (plugin_mgr,
  	CS_FUNCID_LVLLOADER, iLoader);
  if (loader)
  {
    object_reg->Register (loader);
    loader->DecRef ();
  }

  iReporter* reporter = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_REPORTER,
  	iReporter);
  if (!reporter && use_reporter)
  {
    reporter = CS_LOAD_PLUGIN (plugin_mgr, "crystalspace.utilities.reporter",
    	CS_FUNCID_REPORTER, iReporter);
    if (!reporter)
      return false;

  }
  if (reporter)
  {
    object_reg->Register (reporter);
    reporter->DecRef ();
  }

  iStandardReporterListener* stdrep = CS_QUERY_PLUGIN (plugin_mgr,
  	iStandardReporterListener);
  if (!stdrep && use_reporter_listener)
  {
    stdrep = CS_LOAD_PLUGIN (plugin_mgr, "crystalspace.utilities.stdrep",
    	"StdRep", iStandardReporterListener);
    if (!stdrep)
      return false;

  }
  if (stdrep)
  {
    stdrep->SetDefaults ();
    object_reg->Register (stdrep);
    stdrep->DecRef ();
  }

  return true;
}

<|endoftext|>


<commit_before>/*
    Crystal Space: Named Object Vector class
    Copyright (C) 1998,1999 by Andrew Zabolotny <bit@eltech.ru>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csutil/nobjvec.h"
#include "csutil/csobject.h"

csObject *csNamedObjVector::FindByName (const char* name) const
{
  csObject* o;
  int i;
  for (i = Length () - 1; i >= 0; i--)
  {
    o = (csObject *)Get (i);
    const char* oname = o->GetName ();
    if (name == oname || (name && oname && !strcmp (oname, name)))
      return o;
  }
  return NULL;
}

int csNamedObjVector::Compare (csSome Item1, csSome Item2, int Mode) const
{
  (void)Mode;
  return (((csObject *)Item1)->GetName () == ((csObject *)Item2)->GetName ()) ? 0
       : strcmp (((csObject *)Item1)->GetName (), ((csObject *)Item2)->GetName ());
}

int csNamedObjVector::CompareKey (csSome Item, csConstSome Key, int Mode) const
{
  (void)Mode;
  return (((csObject *)Item)->GetName () == (char *)Key) ? 0
       : strcmp (((csObject *)Item)->GetName (), (char *)Key);
}

// ---------------------------------------------------------------------------

// @@@ is there a better way than doing QUERY_INTERFACE all the time?

int csNamedObjectVector::GetIndexByName (const char *name) const
{
  int i;
  for (i = 0; i < Length (); i++)
  {
    iObject *o = Get (i);
    if (!o) continue;
    const char* oname = o->GetName ();
    if (name == oname || (name && oname && !strcmp (oname, name)))
      return i;
  }
  return -1;
}

iObject *csNamedObjectVector::FindByName (const char* name) const
{
  int n = GetIndexByName (name);
  return (n == -1) ? NULL : Get (n);
}

int csNamedObjectVector::Find (iObject *obj) const
{
  int i;
  for (i = 0; i < Length (); i++)
  {
    iObject *o = Get (i);
    if (obj == o)
      return i;
  }
  return -1;
}

int csNamedObjectVector::Compare (csSome Item1, csSome Item2, int)
{
  iObject *obj1 = SCF_QUERY_INTERFACE_FAST (((iBase*)Item1), iObject);
  iObject *obj2 = SCF_QUERY_INTERFACE_FAST (((iBase*)Item2), iObject);

  return (obj1->GetName () == obj2->GetName ()) ? 0
       : strcmp (obj1->GetName (), obj2->GetName ());
}

int csNamedObjectVector::CompareKey (csSome Item, csConstSome Key, int)
{
  iObject *obj = SCF_QUERY_INTERFACE_FAST (((iBase*)Item), iObject);
  const char *name = (const char *)Key;

  return (obj->GetName () == name) ? 0
       : strcmp (obj->GetName (), name);
}
<commit_msg>the mother of all increfs has now been decref'ed<commit_after>/*
    Crystal Space: Named Object Vector class
    Copyright (C) 1998,1999 by Andrew Zabolotny <bit@eltech.ru>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csutil/nobjvec.h"
#include "csutil/csobject.h"

csObject *csNamedObjVector::FindByName (const char* name) const
{
  csObject* o;
  int i;
  for (i = Length () - 1; i >= 0; i--)
  {
    o = (csObject *)Get (i);
    const char* oname = o->GetName ();
    if (name == oname || (name && oname && !strcmp (oname, name)))
      return o;
  }
  return NULL;
}

int csNamedObjVector::Compare (csSome Item1, csSome Item2, int Mode) const
{
  (void)Mode;
  return (((csObject *)Item1)->GetName () == ((csObject *)Item2)->GetName ()) ? 0
       : strcmp (((csObject *)Item1)->GetName (), ((csObject *)Item2)->GetName ());
}

int csNamedObjVector::CompareKey (csSome Item, csConstSome Key, int Mode) const
{
  (void)Mode;
  return (((csObject *)Item)->GetName () == (char *)Key) ? 0
       : strcmp (((csObject *)Item)->GetName (), (char *)Key);
}

// ---------------------------------------------------------------------------

// @@@ is there a better way than doing QUERY_INTERFACE all the time?

int csNamedObjectVector::GetIndexByName (const char *name) const
{
  int i;
  for (i = 0; i < Length (); i++)
  {
    iObject *o = Get (i);
    if (!o) continue;
    const char* oname = o->GetName ();
    o->DecRef ();
    if (name == oname || (name && oname && !strcmp (oname, name)))
      return i;
  }
  return -1;
}

iObject *csNamedObjectVector::FindByName (const char* name) const
{
  int n = GetIndexByName (name);
  return (n == -1) ? NULL : Get (n);
}

int csNamedObjectVector::Find (iObject *obj) const
{
  int i;
  for (i = 0; i < Length (); i++)
  {
    iObject *o = Get (i);
    if (obj == o)
    {
      o->DecRef ();
      return i;
    }
    o->DecRef ();
  }
  return -1;
}

int csNamedObjectVector::Compare (csSome Item1, csSome Item2, int)
{
  iObject *obj1 = SCF_QUERY_INTERFACE_FAST (((iBase*)Item1), iObject);
  iObject *obj2 = SCF_QUERY_INTERFACE_FAST (((iBase*)Item2), iObject);

  int res = (obj1->GetName () == obj2->GetName ()) ? 0
       : strcmp (obj1->GetName (), obj2->GetName ());
  obj1->DecRef ();
  obj2->DecRef ();
  return res;
}

int csNamedObjectVector::CompareKey (csSome Item, csConstSome Key, int)
{
  iObject *obj = SCF_QUERY_INTERFACE_FAST (((iBase*)Item), iObject);
  const char *name = (const char *)Key;

  int res = (obj->GetName () == name) ? 0
       : strcmp (obj->GetName (), name);
  obj->DecRef ();
  return res;
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2010, Roger Light <roger@atchoo.org>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. Neither the name of mosquitto nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

#include <stdint.h>
#include <cstdlib>
#include <mosquitto.h>
#include <mosquittopp.h>

mosquittopp::mosquittopp()
{
}

mosquittopp::~mosquittopp()
{
}

int mosquittopp::connect(const char *host, int port)
{
	return 0;
}

int mosquittopp::disconnect()
{
	return 0;
}

int mosquittopp::publish(const char *topic, uint32_t payloadlen, const uint8_t *payload, int qos, bool retain)
{
	return 0;
}

int mosquittopp::subscribe(const char *sub, int qos)
{
	return 0;
}

int mosquittopp::unsubscribe(const char *sub)
{
	return 0;
}

int mosquittopp::loop()
{
	return 0;
}

int mosquittopp::read()
{
	return 0;
}

int mosquittopp::write()
{
	return 0;
}

<commit_msg>Call C functions from C++ class functions.<commit_after>/*
Copyright (c) 2010, Roger Light <roger@atchoo.org>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. Neither the name of mosquitto nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

#include <stdint.h>
#include <cstdlib>
#include <mosquitto.h>
#include <mosquittopp.h>

mosquittopp::mosquittopp()
{
}

mosquittopp::~mosquittopp()
{
}

int mosquittopp::connect(const char *host, int port)
{
	return mosquitto_connect(mosq, host, port);
}

int mosquittopp::disconnect()
{
	return mosquitto_disconnect(mosq);
}

int mosquittopp::publish(const char *topic, uint32_t payloadlen, const uint8_t *payload, int qos, bool retain)
{
	return mosquitto_publish(mosq, topic, payloadlen, payload, qos, retain);
}

int mosquittopp::subscribe(const char *sub, int qos)
{
	return mosquitto_subscribe(mosq, sub, qos);
}

int mosquittopp::unsubscribe(const char *sub)
{
	return mosquitto_unsubscribe(mosq, sub);
}

int mosquittopp::loop()
{
	return mosquitto_loop(mosq);
}

int mosquittopp::read()
{
	return mosquitto_read(mosq);
}

int mosquittopp::write()
{
	return mosquitto_write(mosq);
}

<|endoftext|>


<commit_before>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#include <regex>

#include "vast/concept/printable/to_string.hpp"
#include "vast/concept/printable/vast/pattern.hpp"
#include "vast/json.hpp"
#include "vast/pattern.hpp"

namespace vast {

pattern pattern::glob(std::string_view str) {
  std::string rx;
  std::regex_replace(std::back_inserter(rx), str.begin(), str.end(),
                     std::regex("\\."), "\\.");
  rx = std::regex_replace(rx, std::regex("\\*"), ".*");
  return pattern{std::regex_replace(rx, std::regex("\\?"), ".")};
}

pattern::pattern(std::string str) : str_(std::move(str)) {
}

bool pattern::match(std::string_view str) const {
  return std::regex_match(str.begin(), str.end(), std::regex{str_});
}

bool pattern::search(std::string_view str) const {
  return std::regex_search(str.begin(), str.end(), std::regex{str_});
}

const std::string& pattern::string() const {
  return str_;
}

pattern& pattern::operator+=(const pattern& other) {
  str_ += other.str_;
  return *this;
}

pattern& pattern::operator+=(std::string_view other) {
  str_ += other;
  return *this;
}

pattern& pattern::operator|=(const pattern& other) {
  return *this |= std::string_view{other.str_};
}

pattern& pattern::operator|=(std::string_view other) {
  str_.insert(str_.begin(), '(');
  str_ += ")|(";
  str_.append(other.begin(), other.end());
  str_ += ')';
  return *this;
}

pattern& pattern::operator&=(const pattern& other) {
  return *this &= std::string_view{other.str_};
}

pattern& pattern::operator&=(std::string_view other) {
  str_.insert(str_.begin(), '(');
  str_ += ")(";
  str_.append(other.begin(), other.end());
  str_ += ')';
  return *this;
}

pattern operator+(const pattern& x, std::string_view y) {
  return pattern{x.string() + std::string{y}};
}

pattern operator+(std::string_view x, const pattern& y) {
  return pattern{std::string{x} + y.string()};
}

pattern operator|(const pattern& x, std::string_view y) {
  pattern result{x};
  result |= y;
  return result;
}

pattern operator|(std::string_view x, const pattern& y) {
  pattern result{std::string{x}};
  result |= y;
  return result;
}

pattern operator&(const pattern& x, std::string_view y) {
  pattern result{x};
  result &= y;
  return result;
}

pattern operator&(std::string_view x, const pattern& y) {
  pattern result{std::string{x}};
  result &= y;
  return result;
}

bool operator==(const pattern& lhs, const pattern& rhs) {
  return lhs.str_ == rhs.str_;
}

bool operator<(const pattern& lhs, const pattern& rhs) {
  return lhs.str_ < rhs.str_;
}

bool convert(const pattern& p, json& j) {
  j = to_string(p);
  return true;
}

} // namespace vast
<commit_msg>Delegate operator+= to existing implementation<commit_after>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#include <regex>

#include "vast/concept/printable/to_string.hpp"
#include "vast/concept/printable/vast/pattern.hpp"
#include "vast/json.hpp"
#include "vast/pattern.hpp"

namespace vast {

pattern pattern::glob(std::string_view str) {
  std::string rx;
  std::regex_replace(std::back_inserter(rx), str.begin(), str.end(),
                     std::regex("\\."), "\\.");
  rx = std::regex_replace(rx, std::regex("\\*"), ".*");
  return pattern{std::regex_replace(rx, std::regex("\\?"), ".")};
}

pattern::pattern(std::string str) : str_(std::move(str)) {
}

bool pattern::match(std::string_view str) const {
  return std::regex_match(str.begin(), str.end(), std::regex{str_});
}

bool pattern::search(std::string_view str) const {
  return std::regex_search(str.begin(), str.end(), std::regex{str_});
}

const std::string& pattern::string() const {
  return str_;
}

pattern& pattern::operator+=(const pattern& other) {
  return *this += std::string_view{other.str_};
}

pattern& pattern::operator+=(std::string_view other) {
  str_ += other;
  return *this;
}

pattern& pattern::operator|=(const pattern& other) {
  return *this |= std::string_view{other.str_};
}

pattern& pattern::operator|=(std::string_view other) {
  str_.insert(str_.begin(), '(');
  str_ += ")|(";
  str_.append(other.begin(), other.end());
  str_ += ')';
  return *this;
}

pattern& pattern::operator&=(const pattern& other) {
  return *this &= std::string_view{other.str_};
}

pattern& pattern::operator&=(std::string_view other) {
  str_.insert(str_.begin(), '(');
  str_ += ")(";
  str_.append(other.begin(), other.end());
  str_ += ')';
  return *this;
}

pattern operator+(const pattern& x, std::string_view y) {
  return pattern{x.string() + std::string{y}};
}

pattern operator+(std::string_view x, const pattern& y) {
  return pattern{std::string{x} + y.string()};
}

pattern operator|(const pattern& x, std::string_view y) {
  pattern result{x};
  result |= y;
  return result;
}

pattern operator|(std::string_view x, const pattern& y) {
  pattern result{std::string{x}};
  result |= y;
  return result;
}

pattern operator&(const pattern& x, std::string_view y) {
  pattern result{x};
  result &= y;
  return result;
}

pattern operator&(std::string_view x, const pattern& y) {
  pattern result{std::string{x}};
  result &= y;
  return result;
}

bool operator==(const pattern& lhs, const pattern& rhs) {
  return lhs.str_ == rhs.str_;
}

bool operator<(const pattern& lhs, const pattern& rhs) {
  return lhs.str_ < rhs.str_;
}

bool convert(const pattern& p, json& j) {
  j = to_string(p);
  return true;
}

} // namespace vast
<|endoftext|>