<commit_before>/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
 */
#pragma once
#include <eosio/chain/types.hpp>

#include <numeric>

namespace eosio { namespace chain {

   struct permission_level {
      account_name    actor;
      permission_name permission;
   };

   /**
    *  An action is performed by an actor, aka an account. It may
    *  be created explicitly and authorized by signatures or might be
    *  generated implicitly by executing application code.
    *
    *  This follows the design pattern of React Flux where actions are
    *  named and then dispatched to one or more action handlers (aka stores).
    *  In the context of eosio, every action is dispatched to the handler defined
    *  by account 'scope' and function 'name', but the default handler may also
    *  forward the action to any number of additional handlers. Any application
    *  can write a handler for "scope::name" that will get executed if and only if
    *  this action is forwarded to that application.
    *
    *  Each action may require the permission of specific actors. Actors can define
    *  any number of permission levels. The actors and their respective permission
    *  levels are declared on the action and validated independently of the executing
    *  application code. An application code will check to see if the required authorization
    *  were properly declared when it executes.
    */
   struct action {
      account_name               account;
      action_name                name;
      vector<permission_level>   authorization;
      bytes                      data;

      action(){}

      template<typename T, std::enable_if_t<std::is_base_of<bytes, T>::value, int> = 1>
      action( vector<permission_level> auth, const T& value ) {
         account     = T::get_account();
         name        = T::get_name();
         authorization = move(auth);
         data.assign(value.data(), value.data() + value.size());
      }

      template<typename T, std::enable_if_t<!std::is_base_of<bytes, T>::value, int> = 1>
      action( vector<permission_level> auth, const T& value ) {
         account     = T::get_account();
         name        = T::get_name();
         authorization = move(auth);
         data        = fc::raw::pack(value);
      }

      action( vector<permission_level> auth, account_name account, action_name name, const bytes& data )
            : account(account), name(name), authorization(move(auth)), data(data) {
      }

      template<typename T>
      T data_as()const {
         FC_ASSERT( account == T::get_account() );
         FC_ASSERT( name == T::get_name()  );
         return fc::raw::unpack<T>(data);
      }
   };

   struct action_notice : public action {
      account_name receiver;
   };

   /**
    * When a transaction is referenced by a block it could imply one of several outcomes which
    * describe the state-transition undertaken by the block producer.
    */
   struct transaction_receipt {
      enum status_enum {
         executed  = 0, ///< succeed, no error handler executed
         soft_fail = 1, ///< objectively failed (not executed), error handler executed
         hard_fail = 2, ///< objectively failed and error handler objectively failed thus no state change
         delayed   = 3  ///< transaction delayed
      };

      transaction_receipt() : status(hard_fail) {}
      transaction_receipt( transaction_id_type tid ):status(executed),id(tid){}

      fc::enum_type<uint8_t,status_enum>  status;
      transaction_id_type                 id;
   };

   /**
    *  The transaction header contains the fixed-sized data
    *  associated with each transaction. It is separated from
    *  the transaction body to facilitate partial parsing of
    *  transactions without requiring dynamic memory allocation.
    *
    *  All transactions have an expiration time after which they
    *  may no longer be included in the blockchain. Once a block
    *  with a block_header::timestamp greater than expiration is
    *  deemed irreversible, then a user can safely trust the transaction
    *  will never be included.
    *

    *  Each region is an independent blockchain, it is included as routing
    *  information for inter-blockchain communication. A contract in this
    *  region might generate or authorize a transaction intended for a foreign
    *  region.
    */
   struct transaction_header {
      time_point_sec         expiration;   ///< the time at which a transaction expires
      uint16_t               region        = 0; ///< the computational memory region this transaction applies to.
      uint16_t               ref_block_num = 0; ///< specifies a block num in the last 2^16 blocks.
      uint32_t               ref_block_prefix = 0; ///< specifies the lower 32 bits of the blockid at get_ref_blocknum
      uint16_t               packed_bandwidth_words = 0; /// number of 8 byte words this transaction can compress into
      uint16_t               context_free_cpu_bandwidth = 0; /// number of CPU usage units to bill transaction for

      /**
       * @return the absolute block number given the relative ref_block_num
       */
      block_num_type get_ref_blocknum( block_num_type head_blocknum )const {
         return ((head_blocknum/0xffff)*0xffff) + head_blocknum%0xffff;
      }
      void set_reference_block( const block_id_type& reference_block );
      bool verify_reference_block( const block_id_type& reference_block )const;
   };

   /**
    *  A transaction consits of a set of messages which must all be applied or
    *  all are rejected. These messages have access to data within the given
    *  read and write scopes.
    */
   struct transaction : public transaction_header {
      vector<action>         context_free_actions;
      vector<action>         actions;

      transaction_id_type        id()const;
      digest_type                sig_digest( const chain_id_type& chain_id, const vector<bytes>& cfd = vector<bytes>() )const;
      flat_set<public_key_type>  get_signature_keys( const vector<signature_type>& signatures, const chain_id_type& chain_id, const vector<bytes>& cfd = vector<bytes>() )const;

   };

   struct signed_transaction : public transaction
   {
      signed_transaction() = default;
//      signed_transaction( const signed_transaction& ) = default;
//      signed_transaction( signed_transaction&& ) = default;
      signed_transaction( transaction&& trx, const vector<signature_type>& signatures, const vector<bytes>& context_free_data)
      : transaction(std::forward<transaction>(trx))
      , signatures(signatures)
      , context_free_data(context_free_data)
      {
      }

      vector<signature_type>    signatures;
      vector<bytes>             context_free_data; ///< for each context-free action, there is an entry here

      const signature_type&     sign(const private_key_type& key, const chain_id_type& chain_id);
      signature_type            sign(const private_key_type& key, const chain_id_type& chain_id)const;
      flat_set<public_key_type> get_signature_keys( const chain_id_type& chain_id )const;
   };

   struct packed_transaction {
      enum compression_type {
         none,
         zlib,
      };

      packed_transaction() = default;

      explicit packed_transaction(const transaction& t, compression_type _compression = none)
      {
         set_transaction(t, _compression);
      }

      explicit packed_transaction(const signed_transaction& t, compression_type _compression = none)
      :signatures(t.signatures)
      ,context_free_data(t.context_free_data)
      {
         set_transaction(t, _compression);
      }

      explicit packed_transaction(signed_transaction&& t, compression_type _compression = none)
      :signatures(std::move(t.signatures))
      ,context_free_data(std::move(t.context_free_data))
      {
         set_transaction(t, _compression);
      }

      vector<signature_type>    signatures;
      vector<bytes>             context_free_data;
      compression_type          compression;
      bytes                     data;

      bytes                     get_raw_transaction()const;
      transaction               get_transaction()const;
      signed_transaction        get_signed_transaction()const;
      void                      set_transaction(const transaction& t, compression_type _compression = none);

   };

   /**
    *  When a transaction is generated it can be scheduled to occur
    *  in the future. It may also fail to execute for some reason in
    *  which case the sender needs to be notified. When the sender
    *  sends a transaction they will assign it an ID which will be
    *  passed back to the sender if the transaction fails for some
    *  reason.
    */
   struct deferred_transaction : public transaction
   {
      uint64_t       sender_id; /// ID assigned by sender of generated, accessible via WASM api when executing normal or error
      account_name   sender; /// receives error handler callback
      time_point_sec execute_after; /// delayed exeuction

      deferred_transaction() = default;

      deferred_transaction(uint32_t sender_id, account_name sender, time_point_sec execute_after, const transaction& txn)
      : transaction(txn),
        sender_id(sender_id),
        sender(sender),
        execute_after(execute_after)
      {}
   };

   struct deferred_reference {
      deferred_reference( const account_name& sender, uint64_t sender_id)
      :sender(sender),sender_id(sender_id)
      {}

      account_name   sender;
      uint64_t       sender_id;
   };

   struct data_access_info {
      enum access_type {
         read = 0, ///< scope was read by this action
         write  = 1, ///< scope was (potentially) written to by this action
      };

      access_type                type;
      account_name               code;
      scope_name                 scope;

      uint64_t                   sequence;
   };

   struct action_trace {
      account_name               receiver;
      action                     act;
      string                     console;
      uint32_t                   region_id;
      uint32_t                   cycle_index;
      vector<data_access_info>   data_access;
   };

   struct transaction_trace : transaction_receipt {
      using transaction_receipt::transaction_receipt;

      vector<action_trace>          action_traces;
      vector<fc::static_variant<deferred_transaction, deferred_reference>> deferred_transaction_requests;
   };
} } // eosio::chain

FC_REFLECT( eosio::chain::permission_level, (actor)(permission) )
FC_REFLECT( eosio::chain::action, (account)(name)(authorization)(data) )
FC_REFLECT( eosio::chain::transaction_header, (expiration)(region)(ref_block_num)(ref_block_prefix)(packed_bandwidth_words)(context_free_cpu_bandwidth) )
FC_REFLECT_DERIVED( eosio::chain::transaction, (eosio::chain::transaction_header), (context_free_actions)(actions) )
FC_REFLECT_DERIVED( eosio::chain::signed_transaction, (eosio::chain::transaction), (signatures)(context_free_data) )
FC_REFLECT_ENUM( eosio::chain::packed_transaction::compression_type, (none)(zlib))
FC_REFLECT( eosio::chain::packed_transaction, (signatures)(compression)(data) )
FC_REFLECT_DERIVED( eosio::chain::deferred_transaction, (eosio::chain::transaction), (sender_id)(sender)(execute_after) )
FC_REFLECT( eosio::chain::deferred_reference, (sender_id)(sender) )
FC_REFLECT_ENUM( eosio::chain::data_access_info::access_type, (read)(write))
FC_REFLECT( eosio::chain::data_access_info, (type)(code)(scope)(sequence))
FC_REFLECT( eosio::chain::action_trace, (receiver)(act)(console)(region_id)(cycle_index)(data_access) )
FC_REFLECT( eosio::chain::transaction_receipt, (status)(id))
FC_REFLECT_ENUM( eosio::chain::transaction_receipt::status_enum, (executed)(soft_fail)(hard_fail)(delayed) )
FC_REFLECT_DERIVED( eosio::chain::transaction_trace, (eosio::chain::transaction_receipt), (action_traces)(deferred_transaction_requests) )

<commit_msg>Fix unpack packed_transaction struct error<commit_after>/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
 */
#pragma once
#include <eosio/chain/types.hpp>

#include <numeric>

namespace eosio { namespace chain {

   struct permission_level {
      account_name    actor;
      permission_name permission;
   };

   /**
    *  An action is performed by an actor, aka an account. It may
    *  be created explicitly and authorized by signatures or might be
    *  generated implicitly by executing application code.
    *
    *  This follows the design pattern of React Flux where actions are
    *  named and then dispatched to one or more action handlers (aka stores).
    *  In the context of eosio, every action is dispatched to the handler defined
    *  by account 'scope' and function 'name', but the default handler may also
    *  forward the action to any number of additional handlers. Any application
    *  can write a handler for "scope::name" that will get executed if and only if
    *  this action is forwarded to that application.
    *
    *  Each action may require the permission of specific actors. Actors can define
    *  any number of permission levels. The actors and their respective permission
    *  levels are declared on the action and validated independently of the executing
    *  application code. An application code will check to see if the required authorization
    *  were properly declared when it executes.
    */
   struct action {
      account_name               account;
      action_name                name;
      vector<permission_level>   authorization;
      bytes                      data;

      action(){}

      template<typename T, std::enable_if_t<std::is_base_of<bytes, T>::value, int> = 1>
      action( vector<permission_level> auth, const T& value ) {
         account     = T::get_account();
         name        = T::get_name();
         authorization = move(auth);
         data.assign(value.data(), value.data() + value.size());
      }

      template<typename T, std::enable_if_t<!std::is_base_of<bytes, T>::value, int> = 1>
      action( vector<permission_level> auth, const T& value ) {
         account     = T::get_account();
         name        = T::get_name();
         authorization = move(auth);
         data        = fc::raw::pack(value);
      }

      action( vector<permission_level> auth, account_name account, action_name name, const bytes& data )
            : account(account), name(name), authorization(move(auth)), data(data) {
      }

      template<typename T>
      T data_as()const {
         FC_ASSERT( account == T::get_account() );
         FC_ASSERT( name == T::get_name()  );
         return fc::raw::unpack<T>(data);
      }
   };

   struct action_notice : public action {
      account_name receiver;
   };

   /**
    * When a transaction is referenced by a block it could imply one of several outcomes which
    * describe the state-transition undertaken by the block producer.
    */
   struct transaction_receipt {
      enum status_enum {
         executed  = 0, ///< succeed, no error handler executed
         soft_fail = 1, ///< objectively failed (not executed), error handler executed
         hard_fail = 2, ///< objectively failed and error handler objectively failed thus no state change
         delayed   = 3  ///< transaction delayed
      };

      transaction_receipt() : status(hard_fail) {}
      transaction_receipt( transaction_id_type tid ):status(executed),id(tid){}

      fc::enum_type<uint8_t,status_enum>  status;
      transaction_id_type                 id;
   };

   /**
    *  The transaction header contains the fixed-sized data
    *  associated with each transaction. It is separated from
    *  the transaction body to facilitate partial parsing of
    *  transactions without requiring dynamic memory allocation.
    *
    *  All transactions have an expiration time after which they
    *  may no longer be included in the blockchain. Once a block
    *  with a block_header::timestamp greater than expiration is
    *  deemed irreversible, then a user can safely trust the transaction
    *  will never be included.
    *

    *  Each region is an independent blockchain, it is included as routing
    *  information for inter-blockchain communication. A contract in this
    *  region might generate or authorize a transaction intended for a foreign
    *  region.
    */
   struct transaction_header {
      time_point_sec         expiration;   ///< the time at which a transaction expires
      uint16_t               region        = 0; ///< the computational memory region this transaction applies to.
      uint16_t               ref_block_num = 0; ///< specifies a block num in the last 2^16 blocks.
      uint32_t               ref_block_prefix = 0; ///< specifies the lower 32 bits of the blockid at get_ref_blocknum
      uint16_t               packed_bandwidth_words = 0; /// number of 8 byte words this transaction can compress into
      uint16_t               context_free_cpu_bandwidth = 0; /// number of CPU usage units to bill transaction for

      /**
       * @return the absolute block number given the relative ref_block_num
       */
      block_num_type get_ref_blocknum( block_num_type head_blocknum )const {
         return ((head_blocknum/0xffff)*0xffff) + head_blocknum%0xffff;
      }
      void set_reference_block( const block_id_type& reference_block );
      bool verify_reference_block( const block_id_type& reference_block )const;
   };

   /**
    *  A transaction consits of a set of messages which must all be applied or
    *  all are rejected. These messages have access to data within the given
    *  read and write scopes.
    */
   struct transaction : public transaction_header {
      vector<action>         context_free_actions;
      vector<action>         actions;

      transaction_id_type        id()const;
      digest_type                sig_digest( const chain_id_type& chain_id, const vector<bytes>& cfd = vector<bytes>() )const;
      flat_set<public_key_type>  get_signature_keys( const vector<signature_type>& signatures, const chain_id_type& chain_id, const vector<bytes>& cfd = vector<bytes>() )const;

   };

   struct signed_transaction : public transaction
   {
      signed_transaction() = default;
//      signed_transaction( const signed_transaction& ) = default;
//      signed_transaction( signed_transaction&& ) = default;
      signed_transaction( transaction&& trx, const vector<signature_type>& signatures, const vector<bytes>& context_free_data)
      : transaction(std::forward<transaction>(trx))
      , signatures(signatures)
      , context_free_data(context_free_data)
      {
      }

      vector<signature_type>    signatures;
      vector<bytes>             context_free_data; ///< for each context-free action, there is an entry here

      const signature_type&     sign(const private_key_type& key, const chain_id_type& chain_id);
      signature_type            sign(const private_key_type& key, const chain_id_type& chain_id)const;
      flat_set<public_key_type> get_signature_keys( const chain_id_type& chain_id )const;
   };

   struct packed_transaction {
      enum compression_type {
         none,
         zlib,
      };

      packed_transaction() = default;

      explicit packed_transaction(const transaction& t, compression_type _compression = none)
      {
         set_transaction(t, _compression);
      }

      explicit packed_transaction(const signed_transaction& t, compression_type _compression = none)
      :signatures(t.signatures)
      ,context_free_data(t.context_free_data)
      {
         set_transaction(t, _compression);
      }

      explicit packed_transaction(signed_transaction&& t, compression_type _compression = none)
      :signatures(std::move(t.signatures))
      ,context_free_data(std::move(t.context_free_data))
      {
         set_transaction(t, _compression);
      }

      vector<signature_type>    signatures;
      vector<bytes>             context_free_data;
      compression_type          compression;
      bytes                     data;

      bytes                     get_raw_transaction()const;
      transaction               get_transaction()const;
      signed_transaction        get_signed_transaction()const;
      void                      set_transaction(const transaction& t, compression_type _compression = none);

   };

   /**
    *  When a transaction is generated it can be scheduled to occur
    *  in the future. It may also fail to execute for some reason in
    *  which case the sender needs to be notified. When the sender
    *  sends a transaction they will assign it an ID which will be
    *  passed back to the sender if the transaction fails for some
    *  reason.
    */
   struct deferred_transaction : public transaction
   {
      uint64_t       sender_id; /// ID assigned by sender of generated, accessible via WASM api when executing normal or error
      account_name   sender; /// receives error handler callback
      time_point_sec execute_after; /// delayed exeuction

      deferred_transaction() = default;

      deferred_transaction(uint32_t sender_id, account_name sender, time_point_sec execute_after, const transaction& txn)
      : transaction(txn),
        sender_id(sender_id),
        sender(sender),
        execute_after(execute_after)
      {}
   };

   struct deferred_reference {
      deferred_reference( const account_name& sender, uint64_t sender_id)
      :sender(sender),sender_id(sender_id)
      {}

      account_name   sender;
      uint64_t       sender_id;
   };

   struct data_access_info {
      enum access_type {
         read = 0, ///< scope was read by this action
         write  = 1, ///< scope was (potentially) written to by this action
      };

      access_type                type;
      account_name               code;
      scope_name                 scope;

      uint64_t                   sequence;
   };

   struct action_trace {
      account_name               receiver;
      action                     act;
      string                     console;
      uint32_t                   region_id;
      uint32_t                   cycle_index;
      vector<data_access_info>   data_access;
   };

   struct transaction_trace : transaction_receipt {
      using transaction_receipt::transaction_receipt;

      vector<action_trace>          action_traces;
      vector<fc::static_variant<deferred_transaction, deferred_reference>> deferred_transaction_requests;
   };
} } // eosio::chain

FC_REFLECT( eosio::chain::permission_level, (actor)(permission) )
FC_REFLECT( eosio::chain::action, (account)(name)(authorization)(data) )
FC_REFLECT( eosio::chain::transaction_header, (expiration)(region)(ref_block_num)(ref_block_prefix)(packed_bandwidth_words)(context_free_cpu_bandwidth) )
FC_REFLECT_DERIVED( eosio::chain::transaction, (eosio::chain::transaction_header), (context_free_actions)(actions) )
FC_REFLECT_DERIVED( eosio::chain::signed_transaction, (eosio::chain::transaction), (signatures)(context_free_data) )
FC_REFLECT_ENUM( eosio::chain::packed_transaction::compression_type, (none)(zlib))
FC_REFLECT( eosio::chain::packed_transaction, (signatures)(context_free_data)(compression)(data) )
FC_REFLECT_DERIVED( eosio::chain::deferred_transaction, (eosio::chain::transaction), (sender_id)(sender)(execute_after) )
FC_REFLECT( eosio::chain::deferred_reference, (sender_id)(sender) )
FC_REFLECT_ENUM( eosio::chain::data_access_info::access_type, (read)(write))
FC_REFLECT( eosio::chain::data_access_info, (type)(code)(scope)(sequence))
FC_REFLECT( eosio::chain::action_trace, (receiver)(act)(console)(region_id)(cycle_index)(data_access) )
FC_REFLECT( eosio::chain::transaction_receipt, (status)(id))
FC_REFLECT_ENUM( eosio::chain::transaction_receipt::status_enum, (executed)(soft_fail)(hard_fail)(delayed) )
FC_REFLECT_DERIVED( eosio::chain::transaction_trace, (eosio::chain::transaction_receipt), (action_traces)(deferred_transaction_requests) )

<|endoftext|>


<commit_before>#ifndef CPIMPL
#define CPIMPL
#include<memory>	//make_unique, unique_ptr
#include<utility>	//forward, move

namespace nTool
{
	template<class T>
	class CPimpl	//a class to help you use pimpl easily
	{
		std::unique_ptr<T> p_;
	public:
		CPimpl()
			:p_{std::make_unique<T>()}{}
		CPimpl(const CPimpl &val)
			:p_{std::make_unique<T>(val.get())}{}
		CPimpl(CPimpl &&rVal) noexcept
			:p_{std::move(rVal.p_)}{}
		//as smart pointer, use () instead of {}
		template<class ... Args>
		CPimpl(Args &&...args)
			:p_(std::make_unique<T>(std::forward<Args>(args)...)){}
		inline T& get() const noexcept
		{
			return *p_.get();
		}
		CPimpl& operator=(const CPimpl &val)
		{
			get()=val.get();
			return *this;
		}
		CPimpl& operator=(CPimpl &&rVal) noexcept
		{
			p_=std::move(rVal.p_);
			return *this;
		}
		explicit operator bool() const noexcept
		{
			return p_.operator bool();
		}
		~CPimpl(){}
	};
}

#endif<commit_msg>fix CPimpl::get<commit_after>#ifndef CPIMPL
#define CPIMPL
#include<memory>	//make_unique, unique_ptr
#include<utility>	//forward, move

namespace nTool
{
	template<class T>
	class CPimpl	//a class to help you use pimpl easily
	{
		std::unique_ptr<T> p_;
	public:
		CPimpl()
			:p_{std::make_unique<T>()}{}
		CPimpl(const CPimpl &val)
			:p_{std::make_unique<T>(val.get())}{}
		CPimpl(CPimpl &&rVal) noexcept
			:p_{std::move(rVal.p_)}{}
		//as smart pointer, use () instead of {}
		template<class ... Args>
		CPimpl(Args &&...args)
			:p_(std::make_unique<T>(std::forward<Args>(args)...)){}
		inline T& get() const noexcept
		{
			return *p_;
		}
		CPimpl& operator=(const CPimpl &val)
		{
			get()=val.get();
			return *this;
		}
		CPimpl& operator=(CPimpl &&rVal) noexcept
		{
			p_=std::move(rVal.p_);
			return *this;
		}
		explicit operator bool() const noexcept
		{
			return p_.operator bool();
		}
		~CPimpl(){}
	};
}

#endif<|endoftext|>


<commit_before>#include "qtdcmDataSourceSerieToolBox.h"

#include <QtDcmPreviewWidget.h>
#include <QtDcmSerieInfoWidget.h>
#include <QtDcmImportWidget.h>

#include <medPluginManager.h>

class qtdcmDataSourceSerieToolBoxPrivate
{
public:
    QWidget *parent;

    QtDcmPreviewWidget * preview;
    QtDcmSerieInfoWidget * serieInfoWidget;
    QtDcmImportWidget * importWidget;
};

qtdcmDataSourceSerieToolBox::qtdcmDataSourceSerieToolBox ( QWidget* parent ) : medToolBox ( parent ), d ( new qtdcmDataSourceSerieToolBoxPrivate )
{
    d->parent = parent;
    d->preview = new QtDcmPreviewWidget(this);
    //d->preview->previewGroupBox->setTitle("");

    d->serieInfoWidget = new QtDcmSerieInfoWidget(this);
    //d->serieInfoWidget->infosGroupBox->setTitle("");

    d->importWidget = new QtDcmImportWidget(this);

    this->addWidget(d->preview);
    this->addWidget(d->serieInfoWidget);
    this->addWidget(d->importWidget);
    this->setTitle("Series preview and import");

    // Add about plugin
    medPluginManager* pm = medPluginManager::instance();
    dtkPlugin* plugin = pm->plugin ( "qtdcmDataSourcePlugin" );
    setAboutPluginButton ( plugin );
    setAboutPluginVisibility( true );
}

qtdcmDataSourceSerieToolBox::~qtdcmDataSourceSerieToolBox()
{
    if (d)
        delete d;

    d = NULL;
}

QtDcmPreviewWidget* qtdcmDataSourceSerieToolBox::getPreviewWidget()
{
  return d->preview;
}

QtDcmSerieInfoWidget* qtdcmDataSourceSerieToolBox::getSerieInfoWidget()
{
    return d->serieInfoWidget;
}

QtDcmImportWidget* qtdcmDataSourceSerieToolBox::getImportWidget()
{
    return d->importWidget;
}
<commit_msg>Remove comments<commit_after>#include "qtdcmDataSourceSerieToolBox.h"

#include <QtDcmPreviewWidget.h>
#include <QtDcmSerieInfoWidget.h>
#include <QtDcmImportWidget.h>

#include <medPluginManager.h>

class qtdcmDataSourceSerieToolBoxPrivate
{
public:
    QWidget *parent;

    QtDcmPreviewWidget * preview;
    QtDcmSerieInfoWidget * serieInfoWidget;
    QtDcmImportWidget * importWidget;
};

qtdcmDataSourceSerieToolBox::qtdcmDataSourceSerieToolBox ( QWidget* parent ) : medToolBox ( parent ), d ( new qtdcmDataSourceSerieToolBoxPrivate )
{
    d->parent = parent;
    d->preview = new QtDcmPreviewWidget(this);

    d->serieInfoWidget = new QtDcmSerieInfoWidget(this);
    d->importWidget = new QtDcmImportWidget(this);

    this->addWidget(d->preview);
    this->addWidget(d->serieInfoWidget);
    this->addWidget(d->importWidget);
    this->setTitle("Series preview and import");

    // Add about plugin
    medPluginManager* pm = medPluginManager::instance();
    dtkPlugin* plugin = pm->plugin ( "qtdcmDataSourcePlugin" );
    setAboutPluginButton ( plugin );
    setAboutPluginVisibility( true );
}

qtdcmDataSourceSerieToolBox::~qtdcmDataSourceSerieToolBox()
{
    if (d)
        delete d;

    d = NULL;
}

QtDcmPreviewWidget* qtdcmDataSourceSerieToolBox::getPreviewWidget()
{
  return d->preview;
}

QtDcmSerieInfoWidget* qtdcmDataSourceSerieToolBox::getSerieInfoWidget()
{
    return d->serieInfoWidget;
}

QtDcmImportWidget* qtdcmDataSourceSerieToolBox::getImportWidget()
{
    return d->importWidget;
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 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 "remoting/host/capturer_mac.h"

#include <stddef.h>

#include <OpenGL/CGLMacro.h>

namespace remoting {

CapturerMac::CapturerMac(MessageLoop* message_loop)
    : Capturer(message_loop),
      cgl_context_(NULL),
      width_(0),
      height_(0),
      bytes_per_row_(0) {
  // TODO(dmaclach): move this initialization out into session_manager,
  // or at least have session_manager call into here to initialize it.
  CGError err =
      CGRegisterScreenRefreshCallback(CapturerMac::ScreenRefreshCallback,
                                      this);
  DCHECK_EQ(err, kCGErrorSuccess);
  err = CGScreenRegisterMoveCallback(CapturerMac::ScreenUpdateMoveCallback,
                                     this);
  DCHECK_EQ(err, kCGErrorSuccess);
  err = CGDisplayRegisterReconfigurationCallback(
      CapturerMac::DisplaysReconfiguredCallback, this);
  DCHECK_EQ(err, kCGErrorSuccess);
  ScreenConfigurationChanged();
}

CapturerMac::~CapturerMac() {
  ReleaseBuffers();
  CGUnregisterScreenRefreshCallback(CapturerMac::ScreenRefreshCallback, this);
  CGScreenUnregisterMoveCallback(CapturerMac::ScreenUpdateMoveCallback, this);
  CGDisplayRemoveReconfigurationCallback(
      CapturerMac::DisplaysReconfiguredCallback, this);
}

void CapturerMac::ReleaseBuffers() {
  if (cgl_context_) {
    CGLDestroyContext(cgl_context_);
    cgl_context_ = NULL;
  }
}

void CapturerMac::ScreenConfigurationChanged() {
  ReleaseBuffers();
  CGDirectDisplayID mainDevice = CGMainDisplayID();

  width_ = CGDisplayPixelsWide(mainDevice);
  height_ = CGDisplayPixelsHigh(mainDevice);
  pixel_format_ = media::VideoFrame::RGB32;
  bytes_per_row_ = width_ * sizeof(uint32_t);
  size_t buffer_size = height_ * bytes_per_row_;
  for (int i = 0; i < kNumBuffers; ++i) {
    buffers_[i].reset(new uint8[buffer_size]);
  }
  flip_buffer_.reset(new uint8[buffer_size]);
  CGLPixelFormatAttribute attributes[] = {
    kCGLPFAFullScreen,
    kCGLPFADisplayMask,
    (CGLPixelFormatAttribute)CGDisplayIDToOpenGLDisplayMask(mainDevice),
    (CGLPixelFormatAttribute)0
  };
  CGLPixelFormatObj pixel_format = NULL;
  GLint matching_pixel_format_count = 0;
  CGLError err = CGLChoosePixelFormat(attributes,
                                      &pixel_format,
                                      &matching_pixel_format_count);
  DCHECK_EQ(err, kCGLNoError);
  err = CGLCreateContext(pixel_format, NULL, &cgl_context_);
  DCHECK_EQ(err, kCGLNoError);
  CGLDestroyPixelFormat(pixel_format);
  CGLSetFullScreen(cgl_context_);
  CGLSetCurrentContext(cgl_context_);
}

void CapturerMac::CalculateInvalidRects() {
  // Since the Mac gets its list of invalid rects via calls to InvalidateRect(),
  // this step only needs to perform post-processing optimizations on the rect
  // list (if needed).
}

void CapturerMac::CaptureRects(const InvalidRects& rects,
                               CaptureCompletedCallback* callback) {
  CGLContextObj CGL_MACRO_CONTEXT = cgl_context_;
  glReadBuffer(GL_FRONT);
  glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);

  glPixelStorei(GL_PACK_ALIGNMENT, 4);  // Force 4-byte alignment.
  glPixelStorei(GL_PACK_ROW_LENGTH, 0);
  glPixelStorei(GL_PACK_SKIP_ROWS, 0);
  glPixelStorei(GL_PACK_SKIP_PIXELS, 0);

  // Read a block of pixels from the frame buffer.
  uint8* flip_buffer = flip_buffer_.get();
  uint8* current_buffer = buffers_[current_buffer_].get();
  glReadPixels(0, 0, width_, height_, GL_BGRA, GL_UNSIGNED_BYTE, flip_buffer);
  glPopClientAttrib();

  // OpenGL reads with a vertical flip, and sadly there is no optimized
  // way to get it flipped automatically.
  for (int y = 0; y < height_; ++y) {
    uint8* flip_row = &(flip_buffer[y * bytes_per_row_]);
    uint8* current_row =
        &(current_buffer[(height_ - (y + 1)) * bytes_per_row_]);
    memcpy(current_row, flip_row, bytes_per_row_);
  }

  DataPlanes planes;
  planes.data[0] = buffers_[current_buffer_].get();
  planes.strides[0] = bytes_per_row_;

  scoped_refptr<CaptureData> data(
      new CaptureData(planes, width_, height_, pixel_format()));
  data->mutable_dirty_rects() = rects;
  FinishCapture(data, callback);
}

void CapturerMac::ScreenRefresh(CGRectCount count, const CGRect *rect_array) {
  InvalidRects rects;
  for (CGRectCount i = 0; i < count; ++i) {
    CGRect rect = rect_array[i];
    rect.origin.y = height_ - rect.size.height;
    rects.insert(gfx::Rect(rect));
  }
  InvalidateRects(rects);
}

void CapturerMac::ScreenUpdateMove(CGScreenUpdateMoveDelta delta,
                                   size_t count,
                                   const CGRect *rect_array) {
  InvalidRects rects;
  for (CGRectCount i = 0; i < count; ++i) {
    CGRect rect = rect_array[i];
    rect.origin.y = height_ - rect.size.height;
    rects.insert(gfx::Rect(rect));
    rect = CGRectOffset(rect, delta.dX, delta.dY);
    rects.insert(gfx::Rect(rect));
  }
  InvalidateRects(rects);
}

void CapturerMac::ScreenRefreshCallback(CGRectCount count,
                                        const CGRect *rect_array,
                                        void *user_parameter) {
  CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
  capturer->ScreenRefresh(count, rect_array);
}

void CapturerMac::ScreenUpdateMoveCallback(CGScreenUpdateMoveDelta delta,
                                           size_t count,
                                           const CGRect *rect_array,
                                           void *user_parameter) {
  CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
  capturer->ScreenUpdateMove(delta, count, rect_array);
}

void CapturerMac::DisplaysReconfiguredCallback(
    CGDirectDisplayID display,
    CGDisplayChangeSummaryFlags flags,
    void *user_parameter) {
  if ((display == CGMainDisplayID()) &&
      !(flags & kCGDisplayBeginConfigurationFlag)) {
    CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
    capturer->ScreenConfigurationChanged();
  }
}

// static
Capturer* Capturer::Create(MessageLoop* message_loop) {
  return new CapturerMac(message_loop);
}

}  // namespace remoting
<commit_msg>Don't translate dirty rectangles in Mac capturer.<commit_after>// Copyright (c) 2010 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 "remoting/host/capturer_mac.h"

#include <stddef.h>

#include <OpenGL/CGLMacro.h>

namespace remoting {

CapturerMac::CapturerMac(MessageLoop* message_loop)
    : Capturer(message_loop),
      cgl_context_(NULL),
      width_(0),
      height_(0),
      bytes_per_row_(0) {
  // TODO(dmaclach): move this initialization out into session_manager,
  // or at least have session_manager call into here to initialize it.
  CGError err =
      CGRegisterScreenRefreshCallback(CapturerMac::ScreenRefreshCallback,
                                      this);
  DCHECK_EQ(err, kCGErrorSuccess);
  err = CGScreenRegisterMoveCallback(CapturerMac::ScreenUpdateMoveCallback,
                                     this);
  DCHECK_EQ(err, kCGErrorSuccess);
  err = CGDisplayRegisterReconfigurationCallback(
      CapturerMac::DisplaysReconfiguredCallback, this);
  DCHECK_EQ(err, kCGErrorSuccess);
  ScreenConfigurationChanged();
}

CapturerMac::~CapturerMac() {
  ReleaseBuffers();
  CGUnregisterScreenRefreshCallback(CapturerMac::ScreenRefreshCallback, this);
  CGScreenUnregisterMoveCallback(CapturerMac::ScreenUpdateMoveCallback, this);
  CGDisplayRemoveReconfigurationCallback(
      CapturerMac::DisplaysReconfiguredCallback, this);
}

void CapturerMac::ReleaseBuffers() {
  if (cgl_context_) {
    CGLDestroyContext(cgl_context_);
    cgl_context_ = NULL;
  }
}

void CapturerMac::ScreenConfigurationChanged() {
  ReleaseBuffers();
  CGDirectDisplayID mainDevice = CGMainDisplayID();

  width_ = CGDisplayPixelsWide(mainDevice);
  height_ = CGDisplayPixelsHigh(mainDevice);
  pixel_format_ = media::VideoFrame::RGB32;
  bytes_per_row_ = width_ * sizeof(uint32_t);
  size_t buffer_size = height_ * bytes_per_row_;
  for (int i = 0; i < kNumBuffers; ++i) {
    buffers_[i].reset(new uint8[buffer_size]);
  }
  flip_buffer_.reset(new uint8[buffer_size]);
  CGLPixelFormatAttribute attributes[] = {
    kCGLPFAFullScreen,
    kCGLPFADisplayMask,
    (CGLPixelFormatAttribute)CGDisplayIDToOpenGLDisplayMask(mainDevice),
    (CGLPixelFormatAttribute)0
  };
  CGLPixelFormatObj pixel_format = NULL;
  GLint matching_pixel_format_count = 0;
  CGLError err = CGLChoosePixelFormat(attributes,
                                      &pixel_format,
                                      &matching_pixel_format_count);
  DCHECK_EQ(err, kCGLNoError);
  err = CGLCreateContext(pixel_format, NULL, &cgl_context_);
  DCHECK_EQ(err, kCGLNoError);
  CGLDestroyPixelFormat(pixel_format);
  CGLSetFullScreen(cgl_context_);
  CGLSetCurrentContext(cgl_context_);
}

void CapturerMac::CalculateInvalidRects() {
  // Since the Mac gets its list of invalid rects via calls to InvalidateRect(),
  // this step only needs to perform post-processing optimizations on the rect
  // list (if needed).
}

void CapturerMac::CaptureRects(const InvalidRects& rects,
                               CaptureCompletedCallback* callback) {
  CGLContextObj CGL_MACRO_CONTEXT = cgl_context_;
  glReadBuffer(GL_FRONT);
  glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);

  glPixelStorei(GL_PACK_ALIGNMENT, 4);  // Force 4-byte alignment.
  glPixelStorei(GL_PACK_ROW_LENGTH, 0);
  glPixelStorei(GL_PACK_SKIP_ROWS, 0);
  glPixelStorei(GL_PACK_SKIP_PIXELS, 0);

  // Read a block of pixels from the frame buffer.
  uint8* flip_buffer = flip_buffer_.get();
  uint8* current_buffer = buffers_[current_buffer_].get();
  glReadPixels(0, 0, width_, height_, GL_BGRA, GL_UNSIGNED_BYTE, flip_buffer);
  glPopClientAttrib();

  // OpenGL reads with a vertical flip, and sadly there is no optimized
  // way to get it flipped automatically.
  for (int y = 0; y < height_; ++y) {
    uint8* flip_row = &(flip_buffer[y * bytes_per_row_]);
    uint8* current_row =
        &(current_buffer[(height_ - (y + 1)) * bytes_per_row_]);
    memcpy(current_row, flip_row, bytes_per_row_);
  }

  DataPlanes planes;
  planes.data[0] = buffers_[current_buffer_].get();
  planes.strides[0] = bytes_per_row_;

  scoped_refptr<CaptureData> data(
      new CaptureData(planes, width_, height_, pixel_format()));
  data->mutable_dirty_rects() = rects;
  FinishCapture(data, callback);
}

void CapturerMac::ScreenRefresh(CGRectCount count, const CGRect *rect_array) {
  InvalidRects rects;
  for (CGRectCount i = 0; i < count; ++i) {
    rects.insert(gfx::Rect(rect_array[i]));
  }
  InvalidateRects(rects);
}

void CapturerMac::ScreenUpdateMove(CGScreenUpdateMoveDelta delta,
                                   size_t count,
                                   const CGRect *rect_array) {
  InvalidRects rects;
  for (CGRectCount i = 0; i < count; ++i) {
    CGRect rect = rect_array[i];
    rects.insert(gfx::Rect(rect));
    rect = CGRectOffset(rect, delta.dX, delta.dY);
    rects.insert(gfx::Rect(rect));
  }
  InvalidateRects(rects);
}

void CapturerMac::ScreenRefreshCallback(CGRectCount count,
                                        const CGRect *rect_array,
                                        void *user_parameter) {
  CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
  capturer->ScreenRefresh(count, rect_array);
}

void CapturerMac::ScreenUpdateMoveCallback(CGScreenUpdateMoveDelta delta,
                                           size_t count,
                                           const CGRect *rect_array,
                                           void *user_parameter) {
  CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
  capturer->ScreenUpdateMove(delta, count, rect_array);
}

void CapturerMac::DisplaysReconfiguredCallback(
    CGDirectDisplayID display,
    CGDisplayChangeSummaryFlags flags,
    void *user_parameter) {
  if ((display == CGMainDisplayID()) &&
      !(flags & kCGDisplayBeginConfigurationFlag)) {
    CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
    capturer->ScreenConfigurationChanged();
  }
}

// static
Capturer* Capturer::Create(MessageLoop* message_loop) {
  return new CapturerMac(message_loop);
}

}  // namespace remoting
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 Opposite Renderer
 * For the full copyright and license information, please view the LICENSE.txt
 * file that was distributed with this source code.
*/

/*
 * This is the render server main entry. The render server accepts connections from clients
 * and will perform rendering per request
 */

#include <iostream>
#include <exception>
#include <QObject>
#include "gui/ServerWindow.hxx"
#include <QApplication>
#include <QMessageBox>
#include "server/RenderServer.hxx"
//#include <vld.h>

int main( int argc, char** argv )
{
    QApplication app(argc, argv);
    app.setOrganizationName("Opposite Renderer");
    app.setApplicationName("Opposite Renderer");

	try {
		RenderServer renderServer;
		ServerWindow serverWindow(NULL, renderServer);
		serverWindow.show();
		int appCode = app.exec();
		renderServer.wait();
		return appCode;
	} catch(std::exception ex){
		QString error = QString("An unexpected error ocurred during execution:\n\t%1\nApplication will now quit.").arg(ex.what());
		QMessageBox::critical(nullptr, "Critical", error);
		return 1;
	}
}
<commit_msg>Adds Optix error handling.<commit_after>/*
 * Copyright (c) 2013 Opposite Renderer
 * For the full copyright and license information, please view the LICENSE.txt
 * file that was distributed with this source code.
*/

/*
 * This is the render server main entry. The render server accepts connections from clients
 * and will perform rendering per request
 */

#include <iostream>
#include <exception>
#include <QObject>
#include "gui/ServerWindow.hxx"
#include <QApplication>
#include <QMessageBox>
#include "server/RenderServer.hxx"
#include <optix.h>

//#include <vld.h>

int main( int argc, char** argv )
{
    QApplication app(argc, argv);
    app.setOrganizationName("Opposite Renderer");
    app.setApplicationName("Opposite Renderer");

	try {
		RenderServer renderServer;
		ServerWindow serverWindow(NULL, renderServer);
		serverWindow.show();
		int appCode = app.exec();
		renderServer.wait();
		return appCode;
	} catch(optix::Exception ex){
		QString error = QString("An OptiX unexpected error ocurred during execution:\n\t%2(cod: %1)\nApplication will now quit.").arg(QString(ex.getErrorCode()), QString(ex.getErrorString().c_str()));
		QMessageBox::critical(nullptr, "Critical", error);
		return 1;
	} catch(std::exception ex){
		QString error = QString("An unexpected error ocurred during execution:\n\t%1\nApplication will now quit.").arg(ex.what());
		QMessageBox::critical(nullptr, "Critical", error);
		return 1;
	}
}
<|endoftext|>


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

/**
 * @file
 **/

#include "modules/planning/scenarios/side_pass/side_pass_stop_on_wait_point.h"

#include <algorithm>
#include <vector>

#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/speed_profile_generator.h"

namespace apollo {
namespace planning {
namespace scenario {
namespace side_pass {

using apollo::common::TrajectoryPoint;
using apollo::common::PathPoint;
using apollo::common::math::Vec2d;

constexpr double kExtraMarginforStopOnWaitPointStage = 3.0;

Stage::StageStatus SidePassStopOnWaitPoint::Process(
    const TrajectoryPoint& planning_start_point, Frame* frame) {
  const ReferenceLineInfo& reference_line_info =
      frame->reference_line_info().front();
  const ReferenceLine& reference_line = reference_line_info.reference_line();
  const PathDecision& path_decision = reference_line_info.path_decision();

  if (GetContext()->path_data_.discretized_path().path_points().empty()) {
    AERROR << "path data is empty.";
    return Stage::ERROR;
  }

  if (!GetContext()->path_data_.UpdateFrenetFramePath(&reference_line)) {
    return Stage::ERROR;
  }

  const auto adc_frenet_frame_point_ =
      reference_line.GetFrenetPoint(frame->PlanningStartPoint());

  if (!GetContext()->path_data_.LeftTrimWithRefS(adc_frenet_frame_point_.s(),
                                                 adc_frenet_frame_point_.l())) {
    return Stage::ERROR;
  }

  PathPoint first_path_point =
      GetContext()->path_data_.discretized_path().path_points().front();

  PathPoint last_path_point;
  if (!GetMoveForwardLastPathPoint(reference_line, &last_path_point)) {
    AERROR << "Fail to get move forward last path point.";
    return Stage::ERROR;
  }
  ADEBUG << "first_path_point: " << first_path_point.ShortDebugString();
  ADEBUG << "last_path_point : " << first_path_point.ShortDebugString();

  double move_forward_distance = last_path_point.s() - first_path_point.s();
  ADEBUG << "move_forward_distance: " << move_forward_distance;

  if (!IsFarAwayFromObstacles(reference_line, path_decision.obstacles(),
                              first_path_point, last_path_point)) {
    // wait here, do nothing this cycle.
    AINFO << "waiting until obstacles are far away.";
    return Stage::RUNNING;
  }

  // (1) call proceed with cautious
  constexpr double kSidePassCreepSpeed = 2.33;  // m/s
  auto& rfl_info = frame->mutable_reference_line_info()->front();
  *(rfl_info.mutable_speed_data()) =
      SpeedProfileGenerator::GenerateFixedDistanceCreepProfile(
          move_forward_distance, kSidePassCreepSpeed);

  // (2) combine path and speed.
  *(rfl_info.mutable_path_data()) = GetContext()->path_data_;

  rfl_info.set_trajectory_type(ADCTrajectory::NORMAL);
  DiscretizedTrajectory trajectory;
  if (!rfl_info.CombinePathAndSpeedProfile(
          frame->PlanningStartPoint().relative_time(),
          frame->PlanningStartPoint().path_point().s(), &trajectory)) {
    AERROR << "Fail to aggregate planning trajectory.";
    return Stage::RUNNING;
  }
  rfl_info.SetTrajectory(trajectory);
  rfl_info.SetDrivable(true);

  constexpr double kBuffer = 0.3;
  if (move_forward_distance < kBuffer) {
    next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY;
  }
  return Stage::FINISHED;
}

bool SidePassStopOnWaitPoint::IsFarAwayFromObstacles(
    const ReferenceLine& reference_line,
    const IndexedList<std::string, Obstacle>& indexed_obstacle_list,
    const PathPoint& first_path_point, const PathPoint& last_path_point) {
  common::SLPoint first_sl_point;
  if (!reference_line.XYToSL(Vec2d(first_path_point.x(), first_path_point.y()),
                             &first_sl_point)) {
    AERROR << "Failed to get the projection from TrajectoryPoint onto "
              "reference_line";
    return false;
  }
  common::SLPoint last_sl_point;
  if (!reference_line.XYToSL(Vec2d(last_path_point.x(), last_path_point.y()),
                             &last_sl_point)) {
    AERROR << "Failed to get the projection from TrajectoryPoint onto "
              "reference_line";
    return false;
  }

  // Go through every obstacle, check if there is any in the no_obs_zone,
  // which will used by the proceed_with_caution movement.
  for (const auto* obstacle : indexed_obstacle_list.Items()) {
    if (obstacle->IsVirtual()) {
      continue;
    }
    // Check the s-direction.
    double obs_start_s = obstacle->PerceptionSLBoundary().start_s();
    double obs_end_s = obstacle->PerceptionSLBoundary().end_s();
    if (obs_end_s < first_sl_point.s() ||
        obs_start_s > last_sl_point.s() + kExtraMarginforStopOnWaitPointStage) {
      continue;
    }
    // Check the l-direction.
    double lane_left_width_at_start_s = 0.0;
    double lane_left_width_at_end_s = 0.0;
    double lane_right_width_at_start_s = 0.0;
    double lane_right_width_at_end_s = 0.0;
    reference_line.GetLaneWidth(obs_start_s, &lane_left_width_at_start_s,
                                &lane_right_width_at_start_s);
    reference_line.GetLaneWidth(obs_end_s, &lane_left_width_at_end_s,
                                &lane_right_width_at_end_s);
    double lane_left_width = std::min(std::abs(lane_left_width_at_start_s),
                                      std::abs(lane_left_width_at_end_s));
    double lane_right_width = std::min(std::abs(lane_right_width_at_start_s),
                                       std::abs(lane_right_width_at_end_s));
    double obs_start_l = obstacle->PerceptionSLBoundary().start_l();
    double obs_end_l = obstacle->PerceptionSLBoundary().end_l();
    if (obs_start_l < lane_left_width && -obs_end_l < lane_right_width) {
      return false;
    }
  }
  return true;
}

bool SidePassStopOnWaitPoint::GetMoveForwardLastPathPoint(
    const ReferenceLine& reference_line,
    common::PathPoint* const last_path_point) {
  int count = 0;
  for (const auto& path_point :
       GetContext()->path_data_.discretized_path().path_points()) {
    // Get the four corner points ABCD of ADC at every path point,
    // and check if that's within the current lane until it reaches
    // out of current lane.
    const auto& vehicle_box =
        common::VehicleConfigHelper::Instance()->GetBoundingBox(path_point);
    std::vector<Vec2d> ABCDpoints = vehicle_box.GetAllCorners();
    bool is_out_of_curr_lane = false;
    for (size_t i = 0; i < ABCDpoints.size(); i++) {
      // For each corner point, project it onto reference_line
      common::SLPoint curr_point_sl;
      if (!reference_line.XYToSL(ABCDpoints[i], &curr_point_sl)) {
        AERROR << "Failed to get the projection from point onto "
                  "reference_line";
        return false;
      }
      // Get the lane width at the current s indicated by path_point
      double curr_point_left_width = 0.0;
      double curr_point_right_width = 0.0;
      reference_line.GetLaneWidth(curr_point_sl.s(), &curr_point_left_width,
                                  &curr_point_right_width);
      // Check if this corner point is within the lane:
      if (curr_point_sl.l() > std::abs(curr_point_left_width) ||
          curr_point_sl.l() < -std::abs(curr_point_right_width)) {
        is_out_of_curr_lane = true;
        break;
      }
    }
    if (is_out_of_curr_lane) {
      if (count == 0) {
        // The current ADC, without moving at all, is already at least
        // partially out of the current lane.
        return Stage::FINISHED;
      }
      break;
    } else {
      *last_path_point = path_point;
    }
    // check if the ego car on path_point will partially go into the
    // neighbor lane, and retain only those within-lane path-points.
    CHECK_GE(path_point.s(), 0.0);
    ++count;
  }
  return true;
}

}  // namespace side_pass
}  // namespace scenario
}  // namespace planning
}  // namespace apollo
<commit_msg>planning: side pass added traj output for stop on wait point.<commit_after>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file
 **/

#include "modules/planning/scenarios/side_pass/side_pass_stop_on_wait_point.h"

#include <algorithm>
#include <vector>

#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/speed_profile_generator.h"

namespace apollo {
namespace planning {
namespace scenario {
namespace side_pass {

using apollo::common::TrajectoryPoint;
using apollo::common::PathPoint;
using apollo::common::math::Vec2d;

constexpr double kExtraMarginforStopOnWaitPointStage = 3.0;

Stage::StageStatus SidePassStopOnWaitPoint::Process(
    const TrajectoryPoint& planning_start_point, Frame* frame) {
  const ReferenceLineInfo& reference_line_info =
      frame->reference_line_info().front();
  const ReferenceLine& reference_line = reference_line_info.reference_line();
  const PathDecision& path_decision = reference_line_info.path_decision();

  if (GetContext()->path_data_.discretized_path().path_points().empty()) {
    AERROR << "path data is empty.";
    return Stage::ERROR;
  }

  if (!GetContext()->path_data_.UpdateFrenetFramePath(&reference_line)) {
    return Stage::ERROR;
  }

  const auto adc_frenet_frame_point_ =
      reference_line.GetFrenetPoint(frame->PlanningStartPoint());

  if (!GetContext()->path_data_.LeftTrimWithRefS(adc_frenet_frame_point_.s(),
                                                 adc_frenet_frame_point_.l())) {
    return Stage::ERROR;
  }

  PathPoint first_path_point =
      GetContext()->path_data_.discretized_path().path_points().front();

  PathPoint last_path_point;
  if (!GetMoveForwardLastPathPoint(reference_line, &last_path_point)) {
    AERROR << "Fail to get move forward last path point.";
    return Stage::ERROR;
  }
  ADEBUG << "first_path_point: " << first_path_point.ShortDebugString();
  ADEBUG << "last_path_point : " << first_path_point.ShortDebugString();

  double move_forward_distance = last_path_point.s() - first_path_point.s();
  ADEBUG << "move_forward_distance: " << move_forward_distance;

  if (!IsFarAwayFromObstacles(reference_line, path_decision.obstacles(),
                              first_path_point, last_path_point)) {
    // wait here, do nothing this cycle.
    auto& rfl_info = frame->mutable_reference_line_info()->front();
    *(rfl_info.mutable_speed_data()) =
      SpeedProfileGenerator::GenerateFallbackSpeedProfile();
    rfl_info.set_trajectory_type(ADCTrajectory::NORMAL);
    DiscretizedTrajectory trajectory;
    if (!rfl_info.CombinePathAndSpeedProfile(
            frame->PlanningStartPoint().relative_time(),
            frame->PlanningStartPoint().path_point().s(), &trajectory)) {
      AERROR << "Fail to aggregate planning trajectory.";
      return Stage::RUNNING;
    }
    rfl_info.SetTrajectory(trajectory);
    rfl_info.SetDrivable(true);

    AINFO << "waiting until obstacles are far away.";
    return Stage::RUNNING;
  }

  // (1) call proceed with cautious
  constexpr double kSidePassCreepSpeed = 2.33;  // m/s
  auto& rfl_info = frame->mutable_reference_line_info()->front();
  *(rfl_info.mutable_speed_data()) =
      SpeedProfileGenerator::GenerateFixedDistanceCreepProfile(
          move_forward_distance, kSidePassCreepSpeed);

  // (2) combine path and speed.
  *(rfl_info.mutable_path_data()) = GetContext()->path_data_;

  rfl_info.set_trajectory_type(ADCTrajectory::NORMAL);
  DiscretizedTrajectory trajectory;
  if (!rfl_info.CombinePathAndSpeedProfile(
          frame->PlanningStartPoint().relative_time(),
          frame->PlanningStartPoint().path_point().s(), &trajectory)) {
    AERROR << "Fail to aggregate planning trajectory.";
    return Stage::RUNNING;
  }
  rfl_info.SetTrajectory(trajectory);
  rfl_info.SetDrivable(true);

  constexpr double kBuffer = 0.3;
  if (move_forward_distance < kBuffer) {
    next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY;
  }
  return Stage::FINISHED;
}

bool SidePassStopOnWaitPoint::IsFarAwayFromObstacles(
    const ReferenceLine& reference_line,
    const IndexedList<std::string, Obstacle>& indexed_obstacle_list,
    const PathPoint& first_path_point, const PathPoint& last_path_point) {
  common::SLPoint first_sl_point;
  if (!reference_line.XYToSL(Vec2d(first_path_point.x(), first_path_point.y()),
                             &first_sl_point)) {
    AERROR << "Failed to get the projection from TrajectoryPoint onto "
              "reference_line";
    return false;
  }
  common::SLPoint last_sl_point;
  if (!reference_line.XYToSL(Vec2d(last_path_point.x(), last_path_point.y()),
                             &last_sl_point)) {
    AERROR << "Failed to get the projection from TrajectoryPoint onto "
              "reference_line";
    return false;
  }

  // Go through every obstacle, check if there is any in the no_obs_zone,
  // which will used by the proceed_with_caution movement.
  for (const auto* obstacle : indexed_obstacle_list.Items()) {
    if (obstacle->IsVirtual()) {
      continue;
    }
    // Check the s-direction.
    double obs_start_s = obstacle->PerceptionSLBoundary().start_s();
    double obs_end_s = obstacle->PerceptionSLBoundary().end_s();
    if (obs_end_s < first_sl_point.s() ||
        obs_start_s > last_sl_point.s() + kExtraMarginforStopOnWaitPointStage) {
      continue;
    }
    // Check the l-direction.
    double lane_left_width_at_start_s = 0.0;
    double lane_left_width_at_end_s = 0.0;
    double lane_right_width_at_start_s = 0.0;
    double lane_right_width_at_end_s = 0.0;
    reference_line.GetLaneWidth(obs_start_s, &lane_left_width_at_start_s,
                                &lane_right_width_at_start_s);
    reference_line.GetLaneWidth(obs_end_s, &lane_left_width_at_end_s,
                                &lane_right_width_at_end_s);
    double lane_left_width = std::min(std::abs(lane_left_width_at_start_s),
                                      std::abs(lane_left_width_at_end_s));
    double lane_right_width = std::min(std::abs(lane_right_width_at_start_s),
                                       std::abs(lane_right_width_at_end_s));
    double obs_start_l = obstacle->PerceptionSLBoundary().start_l();
    double obs_end_l = obstacle->PerceptionSLBoundary().end_l();
    if (obs_start_l < lane_left_width && -obs_end_l < lane_right_width) {
      return false;
    }
  }
  return true;
}

bool SidePassStopOnWaitPoint::GetMoveForwardLastPathPoint(
    const ReferenceLine& reference_line,
    common::PathPoint* const last_path_point) {
  int count = 0;
  for (const auto& path_point :
       GetContext()->path_data_.discretized_path().path_points()) {
    // Get the four corner points ABCD of ADC at every path point,
    // and check if that's within the current lane until it reaches
    // out of current lane.
    const auto& vehicle_box =
        common::VehicleConfigHelper::Instance()->GetBoundingBox(path_point);
    std::vector<Vec2d> ABCDpoints = vehicle_box.GetAllCorners();
    bool is_out_of_curr_lane = false;
    for (size_t i = 0; i < ABCDpoints.size(); i++) {
      // For each corner point, project it onto reference_line
      common::SLPoint curr_point_sl;
      if (!reference_line.XYToSL(ABCDpoints[i], &curr_point_sl)) {
        AERROR << "Failed to get the projection from point onto "
                  "reference_line";
        return false;
      }
      // Get the lane width at the current s indicated by path_point
      double curr_point_left_width = 0.0;
      double curr_point_right_width = 0.0;
      reference_line.GetLaneWidth(curr_point_sl.s(), &curr_point_left_width,
                                  &curr_point_right_width);
      // Check if this corner point is within the lane:
      if (curr_point_sl.l() > std::abs(curr_point_left_width) ||
          curr_point_sl.l() < -std::abs(curr_point_right_width)) {
        is_out_of_curr_lane = true;
        break;
      }
    }
    if (is_out_of_curr_lane) {
      if (count == 0) {
        // The current ADC, without moving at all, is already at least
        // partially out of the current lane.
        return Stage::FINISHED;
      }
      break;
    } else {
      *last_path_point = path_point;
    }
    // check if the ego car on path_point will partially go into the
    // neighbor lane, and retain only those within-lane path-points.
    CHECK_GE(path_point.s(), 0.0);
    ++count;
  }
  return true;
}

}  // namespace side_pass
}  // namespace scenario
}  // namespace planning
}  // namespace apollo
<|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 "ash/system/ime/tray_ime.h"

#include <vector>

#include "ash/metrics/user_metrics_recorder.h"
#include "ash/root_window_controller.h"
#include "ash/shelf/shelf_widget.h"
#include "ash/shell.h"
#include "ash/system/system_notifier.h"
#include "ash/system/tray/hover_highlight_view.h"
#include "ash/system/tray/system_tray.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/system_tray_notifier.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_details_view.h"
#include "ash/system/tray/tray_item_more.h"
#include "ash/system/tray/tray_item_view.h"
#include "ash/system/tray/tray_utils.h"
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "grit/ash_resources.h"
#include "grit/ash_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/font.h"
#include "ui/gfx/image/image.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/notification.h"
#include "ui/message_center/notification_delegate.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/widget/widget.h"

using message_center::Notification;

namespace {

const char kIMENotificationId[] = "chrome://settings/ime";

}  // namespace

namespace ash {
namespace internal {
namespace tray {

class IMEDefaultView : public TrayItemMore {
 public:
  explicit IMEDefaultView(SystemTrayItem* owner)
      : TrayItemMore(owner, true) {
    ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();

    SetImage(bundle.GetImageNamed(
        IDR_AURA_UBER_TRAY_IME).ToImageSkia());

    IMEInfo info;
    Shell::GetInstance()->system_tray_delegate()->GetCurrentIME(&info);
    UpdateLabel(info);
  }

  virtual ~IMEDefaultView() {}

  void UpdateLabel(const IMEInfo& info) {
    SetLabel(info.name);
    SetAccessibleName(info.name);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(IMEDefaultView);
};

class IMEDetailedView : public TrayDetailsView,
                        public ViewClickListener {
 public:
  IMEDetailedView(SystemTrayItem* owner, user::LoginStatus login)
      : TrayDetailsView(owner),
        login_(login) {
    SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
    IMEInfoList list;
    delegate->GetAvailableIMEList(&list);
    IMEPropertyInfoList property_list;
    delegate->GetCurrentIMEProperties(&property_list);
    Update(list, property_list);
  }

  virtual ~IMEDetailedView() {}

  void Update(const IMEInfoList& list,
              const IMEPropertyInfoList& property_list) {
    Reset();

    AppendIMEList(list);
    if (!property_list.empty())
      AppendIMEProperties(property_list);
    if (login_ != user::LOGGED_IN_NONE && login_ != user::LOGGED_IN_LOCKED)
      AppendSettings();
    AppendHeaderEntry();

    Layout();
    SchedulePaint();
  }

 private:
  void AppendHeaderEntry() {
    CreateSpecialRow(IDS_ASH_STATUS_TRAY_IME, this);
  }

  void AppendIMEList(const IMEInfoList& list) {
    ime_map_.clear();
    CreateScrollableList();
    for (size_t i = 0; i < list.size(); i++) {
      HoverHighlightView* container = new HoverHighlightView(this);
      container->AddLabel(list[i].name,
          list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
      scroll_content()->AddChildView(container);
      ime_map_[container] = list[i].id;
    }
  }

  void AppendIMEProperties(const IMEPropertyInfoList& property_list) {
    property_map_.clear();
    for (size_t i = 0; i < property_list.size(); i++) {
      HoverHighlightView* container = new HoverHighlightView(this);
      container->AddLabel(
          property_list[i].name,
          property_list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
      if (i == 0)
        container->SetBorder(views::Border::CreateSolidSidedBorder(
            1, 0, 0, 0, kBorderLightColor));
      scroll_content()->AddChildView(container);
      property_map_[container] = property_list[i].key;
    }
  }

  void AppendSettings() {
    HoverHighlightView* container = new HoverHighlightView(this);
    container->AddLabel(ui::ResourceBundle::GetSharedInstance().
        GetLocalizedString(IDS_ASH_STATUS_TRAY_IME_SETTINGS),
        gfx::Font::NORMAL);
    AddChildView(container);
    settings_ = container;
  }

  // Overridden from ViewClickListener.
  virtual void OnViewClicked(views::View* sender) OVERRIDE {
    SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
    if (sender == footer()->content()) {
      TransitionToDefaultView();
    } else if (sender == settings_) {
      Shell::GetInstance()->metrics()->RecordUserMetricsAction(
          ash::UMA_STATUS_AREA_IME_SHOW_DETAILED);
      delegate->ShowIMESettings();
    } else {
      std::map<views::View*, std::string>::const_iterator ime_find;
      ime_find = ime_map_.find(sender);
      if (ime_find != ime_map_.end()) {
        Shell::GetInstance()->metrics()->RecordUserMetricsAction(
            ash::UMA_STATUS_AREA_IME_SWITCH_MODE);
        std::string ime_id = ime_find->second;
        delegate->SwitchIME(ime_id);
        GetWidget()->Close();
      } else {
        std::map<views::View*, std::string>::const_iterator prop_find;
        prop_find = property_map_.find(sender);
        if (prop_find != property_map_.end()) {
          const std::string key = prop_find->second;
          delegate->ActivateIMEProperty(key);
          GetWidget()->Close();
        }
      }
    }
  }

  user::LoginStatus login_;

  std::map<views::View*, std::string> ime_map_;
  std::map<views::View*, std::string> property_map_;
  views::View* settings_;

  DISALLOW_COPY_AND_ASSIGN(IMEDetailedView);
};

}  // namespace tray

TrayIME::TrayIME(SystemTray* system_tray)
    : SystemTrayItem(system_tray),
      tray_label_(NULL),
      default_(NULL),
      detailed_(NULL),
      message_shown_(false),
      weak_factory_(this) {
  Shell::GetInstance()->system_tray_notifier()->AddIMEObserver(this);
}

TrayIME::~TrayIME() {
  Shell::GetInstance()->system_tray_notifier()->RemoveIMEObserver(this);
  message_center::MessageCenter::Get()->RemoveNotification(
      kIMENotificationId, false /* by_user */);
}

void TrayIME::UpdateTrayLabel(const IMEInfo& current, size_t count) {
  if (tray_label_) {
    if (current.third_party) {
      tray_label_->label()->SetText(
          current.short_name + base::UTF8ToUTF16("*"));
    } else {
      tray_label_->label()->SetText(current.short_name);
    }
    tray_label_->SetVisible(count > 1);
    SetTrayLabelItemBorder(tray_label_, system_tray()->shelf_alignment());
    tray_label_->Layout();
  }
}

void TrayIME::UpdateOrCreateNotification() {
  message_center::MessageCenter* message_center =
      message_center::MessageCenter::Get();

  if (!message_center->HasNotification(kIMENotificationId) && message_shown_)
    return;

  SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
  IMEInfo current;
  delegate->GetCurrentIME(&current);

  ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
  scoped_ptr<Notification> notification(new Notification(
      message_center::NOTIFICATION_TYPE_SIMPLE,
      kIMENotificationId,
      // TODO(zork): Use IDS_ASH_STATUS_TRAY_THIRD_PARTY_IME_TURNED_ON_BUBBLE
      // for third party IMEs
      l10n_util::GetStringFUTF16(
          IDS_ASH_STATUS_TRAY_IME_TURNED_ON_BUBBLE,
          current.medium_name),
      base::string16(),  // message
      bundle.GetImageNamed(IDR_AURA_UBER_TRAY_IME),
      base::string16(),  // display_source
      message_center::NotifierId(
          message_center::NotifierId::SYSTEM_COMPONENT,
          system_notifier::kNotifierInputMethod),
      message_center::RichNotificationData(),
      new message_center::HandleNotificationClickedDelegate(
          base::Bind(&TrayIME::PopupDetailedView,
                     weak_factory_.GetWeakPtr(), 0, true))));
  message_center->AddNotification(notification.Pass());
  message_shown_ = true;
}

views::View* TrayIME::CreateTrayView(user::LoginStatus status) {
  CHECK(tray_label_ == NULL);
  tray_label_ = new TrayItemView(this);
  tray_label_->CreateLabel();
  SetupLabelForTray(tray_label_->label());
  // Hide IME tray when it is created, it will be updated when it is notified
  // for IME refresh event.
  tray_label_->SetVisible(false);
  return tray_label_;
}

views::View* TrayIME::CreateDefaultView(user::LoginStatus status) {
  SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
  IMEInfoList list;
  IMEPropertyInfoList property_list;
  delegate->GetAvailableIMEList(&list);
  delegate->GetCurrentIMEProperties(&property_list);
  if (list.size() <= 1 && property_list.size() <= 1)
    return NULL;
  CHECK(default_ == NULL);
  default_ = new tray::IMEDefaultView(this);
  return default_;
}

views::View* TrayIME::CreateDetailedView(user::LoginStatus status) {
  CHECK(detailed_ == NULL);
  detailed_ = new tray::IMEDetailedView(this, status);
  return detailed_;
}

void TrayIME::DestroyTrayView() {
  tray_label_ = NULL;
}

void TrayIME::DestroyDefaultView() {
  default_ = NULL;
}

void TrayIME::DestroyDetailedView() {
  detailed_ = NULL;
}

void TrayIME::UpdateAfterLoginStatusChange(user::LoginStatus status) {
}

void TrayIME::UpdateAfterShelfAlignmentChange(ShelfAlignment alignment) {
  SetTrayLabelItemBorder(tray_label_, alignment);
  tray_label_->Layout();
}

void TrayIME::OnIMERefresh(bool show_message) {
  SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
  IMEInfoList list;
  IMEInfo current;
  IMEPropertyInfoList property_list;
  delegate->GetCurrentIME(&current);
  delegate->GetAvailableIMEList(&list);
  delegate->GetCurrentIMEProperties(&property_list);

  UpdateTrayLabel(current, list.size());

  if (default_)
    default_->UpdateLabel(current);
  if (detailed_)
    detailed_->Update(list, property_list);

  if (list.size() > 1 && show_message)
    UpdateOrCreateNotification();
}

}  // namespace internal
}  // namespace ash
<commit_msg>Do not change IME label in tray before hiding it.<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 "ash/system/ime/tray_ime.h"

#include <vector>

#include "ash/metrics/user_metrics_recorder.h"
#include "ash/root_window_controller.h"
#include "ash/shelf/shelf_widget.h"
#include "ash/shell.h"
#include "ash/system/system_notifier.h"
#include "ash/system/tray/hover_highlight_view.h"
#include "ash/system/tray/system_tray.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/system_tray_notifier.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_details_view.h"
#include "ash/system/tray/tray_item_more.h"
#include "ash/system/tray/tray_item_view.h"
#include "ash/system/tray/tray_utils.h"
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "grit/ash_resources.h"
#include "grit/ash_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/font.h"
#include "ui/gfx/image/image.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/notification.h"
#include "ui/message_center/notification_delegate.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/widget/widget.h"

using message_center::Notification;

namespace {

const char kIMENotificationId[] = "chrome://settings/ime";

}  // namespace

namespace ash {
namespace internal {
namespace tray {

class IMEDefaultView : public TrayItemMore {
 public:
  explicit IMEDefaultView(SystemTrayItem* owner)
      : TrayItemMore(owner, true) {
    ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();

    SetImage(bundle.GetImageNamed(
        IDR_AURA_UBER_TRAY_IME).ToImageSkia());

    IMEInfo info;
    Shell::GetInstance()->system_tray_delegate()->GetCurrentIME(&info);
    UpdateLabel(info);
  }

  virtual ~IMEDefaultView() {}

  void UpdateLabel(const IMEInfo& info) {
    SetLabel(info.name);
    SetAccessibleName(info.name);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(IMEDefaultView);
};

class IMEDetailedView : public TrayDetailsView,
                        public ViewClickListener {
 public:
  IMEDetailedView(SystemTrayItem* owner, user::LoginStatus login)
      : TrayDetailsView(owner),
        login_(login) {
    SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
    IMEInfoList list;
    delegate->GetAvailableIMEList(&list);
    IMEPropertyInfoList property_list;
    delegate->GetCurrentIMEProperties(&property_list);
    Update(list, property_list);
  }

  virtual ~IMEDetailedView() {}

  void Update(const IMEInfoList& list,
              const IMEPropertyInfoList& property_list) {
    Reset();

    AppendIMEList(list);
    if (!property_list.empty())
      AppendIMEProperties(property_list);
    if (login_ != user::LOGGED_IN_NONE && login_ != user::LOGGED_IN_LOCKED)
      AppendSettings();
    AppendHeaderEntry();

    Layout();
    SchedulePaint();
  }

 private:
  void AppendHeaderEntry() {
    CreateSpecialRow(IDS_ASH_STATUS_TRAY_IME, this);
  }

  void AppendIMEList(const IMEInfoList& list) {
    ime_map_.clear();
    CreateScrollableList();
    for (size_t i = 0; i < list.size(); i++) {
      HoverHighlightView* container = new HoverHighlightView(this);
      container->AddLabel(list[i].name,
          list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
      scroll_content()->AddChildView(container);
      ime_map_[container] = list[i].id;
    }
  }

  void AppendIMEProperties(const IMEPropertyInfoList& property_list) {
    property_map_.clear();
    for (size_t i = 0; i < property_list.size(); i++) {
      HoverHighlightView* container = new HoverHighlightView(this);
      container->AddLabel(
          property_list[i].name,
          property_list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
      if (i == 0)
        container->SetBorder(views::Border::CreateSolidSidedBorder(
            1, 0, 0, 0, kBorderLightColor));
      scroll_content()->AddChildView(container);
      property_map_[container] = property_list[i].key;
    }
  }

  void AppendSettings() {
    HoverHighlightView* container = new HoverHighlightView(this);
    container->AddLabel(ui::ResourceBundle::GetSharedInstance().
        GetLocalizedString(IDS_ASH_STATUS_TRAY_IME_SETTINGS),
        gfx::Font::NORMAL);
    AddChildView(container);
    settings_ = container;
  }

  // Overridden from ViewClickListener.
  virtual void OnViewClicked(views::View* sender) OVERRIDE {
    SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
    if (sender == footer()->content()) {
      TransitionToDefaultView();
    } else if (sender == settings_) {
      Shell::GetInstance()->metrics()->RecordUserMetricsAction(
          ash::UMA_STATUS_AREA_IME_SHOW_DETAILED);
      delegate->ShowIMESettings();
    } else {
      std::map<views::View*, std::string>::const_iterator ime_find;
      ime_find = ime_map_.find(sender);
      if (ime_find != ime_map_.end()) {
        Shell::GetInstance()->metrics()->RecordUserMetricsAction(
            ash::UMA_STATUS_AREA_IME_SWITCH_MODE);
        std::string ime_id = ime_find->second;
        delegate->SwitchIME(ime_id);
        GetWidget()->Close();
      } else {
        std::map<views::View*, std::string>::const_iterator prop_find;
        prop_find = property_map_.find(sender);
        if (prop_find != property_map_.end()) {
          const std::string key = prop_find->second;
          delegate->ActivateIMEProperty(key);
          GetWidget()->Close();
        }
      }
    }
  }

  user::LoginStatus login_;

  std::map<views::View*, std::string> ime_map_;
  std::map<views::View*, std::string> property_map_;
  views::View* settings_;

  DISALLOW_COPY_AND_ASSIGN(IMEDetailedView);
};

}  // namespace tray

TrayIME::TrayIME(SystemTray* system_tray)
    : SystemTrayItem(system_tray),
      tray_label_(NULL),
      default_(NULL),
      detailed_(NULL),
      message_shown_(false),
      weak_factory_(this) {
  Shell::GetInstance()->system_tray_notifier()->AddIMEObserver(this);
}

TrayIME::~TrayIME() {
  Shell::GetInstance()->system_tray_notifier()->RemoveIMEObserver(this);
  message_center::MessageCenter::Get()->RemoveNotification(
      kIMENotificationId, false /* by_user */);
}

void TrayIME::UpdateTrayLabel(const IMEInfo& current, size_t count) {
  if (tray_label_) {
    bool visible = count > 1;
    tray_label_->SetVisible(visible);
    // Do not change label before hiding because this change is noticeable.
    if (!visible)
      return;
    if (current.third_party) {
      tray_label_->label()->SetText(
          current.short_name + base::UTF8ToUTF16("*"));
    } else {
      tray_label_->label()->SetText(current.short_name);
    }
    SetTrayLabelItemBorder(tray_label_, system_tray()->shelf_alignment());
    tray_label_->Layout();
  }
}

void TrayIME::UpdateOrCreateNotification() {
  message_center::MessageCenter* message_center =
      message_center::MessageCenter::Get();

  if (!message_center->HasNotification(kIMENotificationId) && message_shown_)
    return;

  SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
  IMEInfo current;
  delegate->GetCurrentIME(&current);

  ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
  scoped_ptr<Notification> notification(new Notification(
      message_center::NOTIFICATION_TYPE_SIMPLE,
      kIMENotificationId,
      // TODO(zork): Use IDS_ASH_STATUS_TRAY_THIRD_PARTY_IME_TURNED_ON_BUBBLE
      // for third party IMEs
      l10n_util::GetStringFUTF16(
          IDS_ASH_STATUS_TRAY_IME_TURNED_ON_BUBBLE,
          current.medium_name),
      base::string16(),  // message
      bundle.GetImageNamed(IDR_AURA_UBER_TRAY_IME),
      base::string16(),  // display_source
      message_center::NotifierId(
          message_center::NotifierId::SYSTEM_COMPONENT,
          system_notifier::kNotifierInputMethod),
      message_center::RichNotificationData(),
      new message_center::HandleNotificationClickedDelegate(
          base::Bind(&TrayIME::PopupDetailedView,
                     weak_factory_.GetWeakPtr(), 0, true))));
  message_center->AddNotification(notification.Pass());
  message_shown_ = true;
}

views::View* TrayIME::CreateTrayView(user::LoginStatus status) {
  CHECK(tray_label_ == NULL);
  tray_label_ = new TrayItemView(this);
  tray_label_->CreateLabel();
  SetupLabelForTray(tray_label_->label());
  // Hide IME tray when it is created, it will be updated when it is notified
  // for IME refresh event.
  tray_label_->SetVisible(false);
  return tray_label_;
}

views::View* TrayIME::CreateDefaultView(user::LoginStatus status) {
  SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
  IMEInfoList list;
  IMEPropertyInfoList property_list;
  delegate->GetAvailableIMEList(&list);
  delegate->GetCurrentIMEProperties(&property_list);
  if (list.size() <= 1 && property_list.size() <= 1)
    return NULL;
  CHECK(default_ == NULL);
  default_ = new tray::IMEDefaultView(this);
  return default_;
}

views::View* TrayIME::CreateDetailedView(user::LoginStatus status) {
  CHECK(detailed_ == NULL);
  detailed_ = new tray::IMEDetailedView(this, status);
  return detailed_;
}

void TrayIME::DestroyTrayView() {
  tray_label_ = NULL;
}

void TrayIME::DestroyDefaultView() {
  default_ = NULL;
}

void TrayIME::DestroyDetailedView() {
  detailed_ = NULL;
}

void TrayIME::UpdateAfterLoginStatusChange(user::LoginStatus status) {
}

void TrayIME::UpdateAfterShelfAlignmentChange(ShelfAlignment alignment) {
  SetTrayLabelItemBorder(tray_label_, alignment);
  tray_label_->Layout();
}

void TrayIME::OnIMERefresh(bool show_message) {
  SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
  IMEInfoList list;
  IMEInfo current;
  IMEPropertyInfoList property_list;
  delegate->GetCurrentIME(&current);
  delegate->GetAvailableIMEList(&list);
  delegate->GetCurrentIMEProperties(&property_list);

  UpdateTrayLabel(current, list.size());

  if (default_)
    default_->UpdateLabel(current);
  if (detailed_)
    detailed_->Update(list, property_list);

  if (list.size() > 1 && show_message)
    UpdateOrCreateNotification();
}

}  // namespace internal
}  // namespace ash
<|endoftext|>


<commit_before>// $Id$
//
// Root macro that opens a mini GUI for running aliroot with Geant4.
//
//  To run aliroot with Geant4 using the g4menu.C:
//  aliroot
//  root [0] .x g4menu.C
//  --> First select "Geometry" to build geometry.root file
//  --> Then re-run aliroot and select "Run" button
//
// The Init button is kept for debugging purposes,
// it itializes MonteCarlo but it does not itialize
// completely ALICE framework. That's why to run simulation,
// you have to re-run aliroot and select Run button.
//
// The menu enables to start Geant4 interactive session:
//  --> Select "Geant4UI" button and use Geant4 interactive commands;
// To go back to Root UI, type exit.
//
// By I. Hrivnacova, IPN Orsay

#include <iostream>

void g4menu()
{

  // Load Geant4 libraries
  if (!gInterpreter->IsLoaded("$ALICE/geant4_vmc/examples/macro/g4libs.C"))
    gROOT->LoadMacro("$ALICE/geant4_vmc/examples/macro/g4libs.C");
  gInterpreter->ProcessLine("g4libs()");

  // Menu
  TControlBar* menu = new TControlBar("vertical","Alice Geant4 menu");

  menu->AddButton("Geometry", "MakeGeometry()",  "Generate Root geometry file");
  menu->AddButton("Run",      "RunSimulation()",  "Process Alice run");
  menu->AddButton("Init",     "Init()",  "Initialize Alice for simulation");
  menu->AddButton("Geant4UI", "StartGeant4UI()","Go to Geant4 Interactive session");
  menu->AddButton("AGDD",     "GenerateAGDD()","Generate XML (AGDD) file with geometry description");
  //menu->AddButton("GDML",     "GenerateGDML()","Generate XML (GDML) file with geometry description");
  menu->AddButton("Quit",     "Quit()", "Quit aliroot");
  gROOT->SaveContext();

  cout << endl
       << "**************************************************************" << endl
       << "  To run simulation:"                                           << endl
       << "  First select <Geometry> to build geometry.root file."         << endl
       << "  Then re-run aliroot and select <Run> button"                  << endl
       << endl
       << "  The <Init> button is kept for debugging purposes,"            << endl
       << "  it itializes MonteCarlo but it does not itialize"             << endl
       << "  completely ALICE framework. That's why to run simulation,"    << endl
       << "  you have to re-run aliroot and select Run button."            << endl
       << endl
       << "  The menu enables to start Geant4 interactive session:"        << endl
       << "  Select <Geant4UI> button and use Geant4 interactive commands" << endl
       << "  To go back to Root UI, type exit."                            << endl
       << "**************************************************************" << endl
       << endl;

  menu->Show();
}

void MakeGeometry()
{
  AliCDBManager* man = AliCDBManager::Instance();
  man->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  man->SetRun(1);
  gAlice->Init("$ALICE_ROOT/macros/g4ConfigGeometry.C");

  // Generate geometry file
  //
  gGeoManager->Export("geometry.root");

  cout << endl
       << "Geometry file geometry.root has been generated." << endl
       << "You have to re-run aliroot and choose Run in g4menu." << endl;

  exit(0);
}

void Init()
{
  AliCDBManager* man = AliCDBManager::Instance();
  man->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  man->SetRun(0);
  gAlice->Init("$ALICE_ROOT/macros/g4Config.C");

  cout << endl
       << "Only MonteCarlo initialization has been performed. " << endl
       << "To run simulation you have to re-run aliroot and choose Run in g4menu." << endl;
}

void RunSimulation()
{
  AliSimulation sim("$ALICE_ROOT/macros/g4Config.C");
  sim.SetMakeDigits("");
  sim.SetMakeSDigits("");
  sim.SetRunHLT("");
  sim.SetNumberOfEvents(1);
  TStopwatch timer;
  timer.Start();
  sim.Run(1);
  timer.Stop();
  timer.Print();
}

void StartGeant4UI()
{
  if (gMC) {
    // release Root terminal control

    // go into non-raw term mode
    Getlinem(kCleanUp, 0);

    // add test if gMC is TGeant4
    TGeant4* g4 = (TGeant4*)gMC;

    g4->StartGeantUI();

    // new Root prompt
    Getlinem(kInit, ((TRint*)gROOT->GetApplication())->GetPrompt());
  }
  else {
    cout << "Monte Carlo has not been yet created." << endl;
  }
}

void GenerateAGDD()
{
  if (gMC) {
    // release Root terminal control

    // go into non-raw term mode
    //Getlinem(kCleanUp, 0);

    // add test if gMC is TGeant4
    TGeant4* g4 = (TGeant4*)gMC;

    g4->ProcessGeantCommand("/vgm/generateAGDD");

    // new Root prompt
    //Getlinem(kInit, ((TRint*)gROOT->GetApplication())->GetPrompt());
  }
  else {
    cout << "Monte Carlo has not been yet created." << endl;
  }
}
/*
void GenerateGDML()
{
  if (gMC) {
    // release Root terminal control

    // go into non-raw term mode
    //Getlinem(kCleanUp, 0);

    // add test if gMC is TGeant4
    TGeant4* g4 = (TGeant4*)gMC;

    g4->ProcessGeantCommand("/vgm/generateGDML");

    // new Root prompt
    //Getlinem(kInit, ((TRint*)gROOT->GetApplication())->GetPrompt());
  }
  else {
    cout << "Monte Carlo has not been yet created." << endl;
  }
}
*/
void Quit()
{
  delete AliRunLoader::Instance();
  delete gAlice;

  exit(0);
}
<commit_msg>Updating g4menu.C macro for changes in STEER; calling gAlice->GetMCApp()->Init(); instead of gAlice->Init(), which is no more available. (I. Hrivnacova)<commit_after>// $Id$
//
// Root macro that opens a mini GUI for running aliroot with Geant4.
//
//  To run aliroot with Geant4 using the g4menu.C:
//  aliroot
//  root [0] .x g4menu.C
//  --> First select "Geometry" to build geometry.root file
//  --> Then re-run aliroot and select "Run" button
//
// The Init button is kept for debugging purposes,
// it itializes MonteCarlo but it does not itialize
// completely ALICE framework. That's why to run simulation,
// you have to re-run aliroot and select Run button.
//
// The menu enables to start Geant4 interactive session:
//  --> Select "Geant4UI" button and use Geant4 interactive commands;
// To go back to Root UI, type exit.
//
// By I. Hrivnacova, IPN Orsay

#include <iostream>

void g4menu()
{

  // Load Geant4 libraries
  if (!gInterpreter->IsLoaded("$ALICE/geant4_vmc/examples/macro/g4libs.C"))
    gROOT->LoadMacro("$ALICE/geant4_vmc/examples/macro/g4libs.C");
  gInterpreter->ProcessLine("g4libs()");

  // Menu
  TControlBar* menu = new TControlBar("vertical","Alice Geant4 menu");

  menu->AddButton("Geometry", "MakeGeometry()",  "Generate Root geometry file");
  menu->AddButton("Run",      "RunSimulation()",  "Process Alice run");
  menu->AddButton("Init",     "Init()",  "Initialize Alice for simulation");
  menu->AddButton("Geant4UI", "StartGeant4UI()","Go to Geant4 Interactive session");
  menu->AddButton("AGDD",     "GenerateAGDD()","Generate XML (AGDD) file with geometry description");
  //menu->AddButton("GDML",     "GenerateGDML()","Generate XML (GDML) file with geometry description");
  menu->AddButton("Quit",     "Quit()", "Quit aliroot");
  gROOT->SaveContext();

  cout << endl
       << "**************************************************************" << endl
       << "  To run simulation:"                                           << endl
       << "  First select <Geometry> to build geometry.root file."         << endl
       << "  Then re-run aliroot and select <Run> button"                  << endl
       << endl
       << "  The <Init> button is kept for debugging purposes,"            << endl
       << "  it itializes MonteCarlo but it does not itialize"             << endl
       << "  completely ALICE framework. That's why to run simulation,"    << endl
       << "  you have to re-run aliroot and select Run button."            << endl
       << endl
       << "  The menu enables to start Geant4 interactive session:"        << endl
       << "  Select <Geant4UI> button and use Geant4 interactive commands" << endl
       << "  To go back to Root UI, type exit."                            << endl
       << "**************************************************************" << endl
       << endl;

  menu->Show();
}

void MakeGeometry()
{
  AliCDBManager* man = AliCDBManager::Instance();
  man->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  man->SetRun(1);

  // MC application initialization
  TString configFileName = "$ALICE_ROOT/macros/g4ConfigGeometry.C";
  gROOT->LoadMacro(configFileName.Data());
  gInterpreter->ProcessLine(gAlice->GetConfigFunction());
  gAlice->GetMCApp()->Init();

  // Generate geometry file
  //
  gGeoManager->Export("geometry.root");

  cout << endl
       << "Geometry file geometry.root has been generated." << endl
       << "You have to re-run aliroot and choose Run in g4menu." << endl;

  exit(0);
}

void Init()
{
  AliCDBManager* man = AliCDBManager::Instance();
  man->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  man->SetRun(0);

  // MC application initialization
  TString configFileName = "$ALICE_ROOT/macros/g4Config.C";
  gROOT->LoadMacro(configFileName.Data());
  gInterpreter->ProcessLine(gAlice->GetConfigFunction());
  gAlice->GetMCApp()->Init();

  cout << endl
       << "Only MonteCarlo initialization has been performed. " << endl
       << "To run simulation you have to re-run aliroot and choose Run in g4menu." << endl;
}

void RunSimulation()
{
  AliSimulation sim("$ALICE_ROOT/macros/g4Config.C");
  sim.SetMakeDigits("");
  sim.SetMakeSDigits("");
  sim.SetRunHLT("");
  sim.SetNumberOfEvents(1);
  TStopwatch timer;
  timer.Start();
  sim.Run(1);
  timer.Stop();
  timer.Print();
}

void StartGeant4UI()
{
  if (gMC) {
    // release Root terminal control

    // go into non-raw term mode
    Getlinem(kCleanUp, 0);

    // add test if gMC is TGeant4
    TGeant4* g4 = (TGeant4*)gMC;

    g4->StartGeantUI();

    // new Root prompt
    Getlinem(kInit, ((TRint*)gROOT->GetApplication())->GetPrompt());
  }
  else {
    cout << "Monte Carlo has not been yet created." << endl;
  }
}

void GenerateAGDD()
{
  if (gMC) {
    // release Root terminal control

    // go into non-raw term mode
    //Getlinem(kCleanUp, 0);

    // add test if gMC is TGeant4
    TGeant4* g4 = (TGeant4*)gMC;

    g4->ProcessGeantCommand("/vgm/generateAGDD");

    // new Root prompt
    //Getlinem(kInit, ((TRint*)gROOT->GetApplication())->GetPrompt());
  }
  else {
    cout << "Monte Carlo has not been yet created." << endl;
  }
}
/*
void GenerateGDML()
{
  if (gMC) {
    // release Root terminal control

    // go into non-raw term mode
    //Getlinem(kCleanUp, 0);

    // add test if gMC is TGeant4
    TGeant4* g4 = (TGeant4*)gMC;

    g4->ProcessGeantCommand("/vgm/generateGDML");

    // new Root prompt
    //Getlinem(kInit, ((TRint*)gROOT->GetApplication())->GetPrompt());
  }
  else {
    cout << "Monte Carlo has not been yet created." << endl;
  }
}
*/
void Quit()
{
  delete AliRunLoader::Instance();
  delete gAlice;

  exit(0);
}
<|endoftext|>