CombinedText
stringlengths
8
3.42M
#include <iostream> #include <gtest/gtest.h> #include <thread> #include <chrono> #include <msgrpc/thrift_struct/thrift_codec.h> #include <msgrpc/frp/cell.h> #include <type_traits> #include <future> #include <atomic> using namespace std; using namespace std::chrono; #include "demo/demo_api_declare.h" //////////////////////////////////////////////////////////////////////////////// //TODO: check valgrind check results namespace msgrpc { template <typename T> struct Ret {}; typedef unsigned short msg_id_t; typedef unsigned short service_id_t; //TODO: how to deal with different service id types struct MsgChannel { //TODO: extract common channel interface //TODO: check common return value type virtual bool send_msg(const service_id_t& remote_service_id, msg_id_t msg_id, const char* buf, size_t len) const = 0; }; struct Config { void init_with(MsgChannel *msg_channel, msgrpc::msg_id_t request_msg_id, msgrpc::msg_id_t response_msg_id) { instance().msg_channel_ = msg_channel; request_msg_id_ = request_msg_id; response_msg_id_ = response_msg_id; } static inline Config& instance() { static thread_local Config instance; return instance; } MsgChannel* msg_channel_; msg_id_t request_msg_id_; msg_id_t response_msg_id_; }; } namespace msgrpc { typedef int32_t rpc_sequence_id_t; struct RpcSequenceId : msgrpc::Singleton<RpcSequenceId> { rpc_sequence_id_t get() { return ++sequence_id_; } private: atomic_uint sequence_id_ = {0}; }; } namespace msgrpc { typedef uint8_t method_index_t; typedef uint16_t iface_index_t; struct MsgHeader { uint8_t msgrpc_version_ = {0}; method_index_t method_index_in_interface_ = {0}; iface_index_t iface_index_in_service_ = {0}; rpc_sequence_id_t sequence_id_; //TODO: unsigned char feature_id_in_service_ = {0}; //TODO: TLV encoded varient length options //TODO: if not encoded/decode, how to deal hton and ntoh }; /*TODO: consider make msgHeader encoded through thrift*/ struct ReqMsgHeader : MsgHeader { }; enum class RpcResult : unsigned short { succeeded = 0 , deferred = 1 , failed = 2 , method_not_found = 3 , iface_not_found = 4 }; struct RspMsgHeader : MsgHeader { RpcResult rpc_result_ = { RpcResult::succeeded }; }; } //////////////////////////////////////////////////////////////////////////////// namespace msgrpc { struct RpcRspCellSink { virtual bool set_rpc_rsp(RspMsgHeader* rsp_header, const char* msg, size_t len) = 0; }; template<typename T> struct RpcRspCell : Cell<T>, RpcRspCellSink { void set_binded_context(RpcContext* context) { context_ = context; } RpcContext* context_; virtual bool set_rpc_rsp(RspMsgHeader* rsp_header, const char* msg, size_t len) override { //TODO: handle msg header status T rsp; if (! ThriftDecoder::decode(rsp, (uint8_t *) msg, len)) { cout << "decode failed on remote side." << endl; return false; } Cell<T>::set_value(std::move(rsp)); return true; } }; template<typename VT, typename... T> struct DerivedAction : Updatable { DerivedAction(bool is_final_action, std::function<VT(T...)> logic, T &&... args) : is_final_action_(is_final_action), bind_(logic, std::ref(args)...) { call_each_args(std::forward<T>(args)...); } DerivedAction(std::function<VT(T...)> logic, T &&... args) : bind_(logic, std::ref(args)...) { call_each_args(std::forward<T>(args)...); } template<typename C, typename... Ts> void call_each_args(C &&c, Ts &&... args) { c.register_listener(this); call_each_args(std::forward<Ts>(args)...); } template<typename C> void call_each_args(C &&c) { c.register_listener(this); if (is_final_action_) { if (c.context_) { c.context_->track_item_to_release(this); } assert(c.context_ != nullptr && "to release context, should bind not null context to final action."); context_ = c.context_; } } void update() override { bind_(); if (is_final_action_) { delete context_; } } bool is_final_action_ = {false}; RpcContext* context_; using bind_type = decltype(std::bind(std::declval<std::function<VT(T...)>>(), std::ref(std::declval<T>())...)); bind_type bind_; }; template<typename F, typename... Args> auto derive_action(F &&f, Args &&... args) -> DerivedAction<decltype(f(args...)), Args...>* { return new DerivedAction<decltype(f(args...)), Args...>(std::forward<F>(f), std::ref(args)...); } template<typename F, typename... Args> auto derive_final_action(F &&f, Args &&... args) -> DerivedAction<decltype(f(args...)), Args...>* { return new DerivedAction<decltype(f(args...)), Args...>(/*is_final_action=*/true, std::forward<F>(f), std::ref(args)...); } template<typename VT, typename... T> struct DerivedCell : RpcRspCell<VT> { DerivedCell(std::function<boost::optional<VT>(T...)> logic, T &&... args) : bind_(logic, std::ref(args)...) { call_each_args(std::forward<T>(args)...); } template<typename C, typename... Ts> void call_each_args(C &&c, Ts &&... args) { c->register_listener(this); call_each_args(std::forward<Ts>(args)...); } template<typename C> void call_each_args(C &&c) { c->register_listener(this); } void update() override { if (!Cell<VT>::cell_has_value_) { boost::optional<VT> value = bind_(); if (value) { Cell<VT>::set_value(std::move(value.value())); } } } using bind_type = decltype(std::bind(std::declval<std::function<boost::optional<VT>(T...)>>(), std::ref(std::declval<T>())...)); bind_type bind_; }; template<typename F, typename... Args> auto derive_cell(F &&f, Args &&... args) -> DerivedCell<typename decltype(f(args...))::value_type, Args...>* { return new DerivedCell<typename decltype(f(args...))::value_type, Args...>(std::forward<F>(f), std::ref(args)...); } struct RpcRspDispatcher : msgrpc::ThreadLocalSingleton<RpcRspDispatcher> { void register_rsp_Handler(rpc_sequence_id_t sequence_id, RpcRspCellSink* func) { assert(id_func_map_.find(sequence_id) == id_func_map_.end() && "should register with unique id."); id_func_map_[sequence_id] = func; } void handle_rpc_rsp(msgrpc::msg_id_t msg_id, const char *msg, size_t len) { //cout << "DEBUG: local received msg----------->: " << string(msg, len) << endl; if (len < sizeof(RspMsgHeader)) { cout << "WARNING: invalid rsp msg" << endl; return; } auto* rsp_header = (RspMsgHeader*)msg; auto iter = id_func_map_.find(rsp_header->sequence_id_); if (iter == id_func_map_.end()) { cout << "WARNING: can not find rsp handler" << endl; return; } (iter->second)->set_rpc_rsp(rsp_header, msg + sizeof(RspMsgHeader), len - sizeof(RspMsgHeader)); id_func_map_.erase(iter); } std::map<rpc_sequence_id_t, RpcRspCellSink*> id_func_map_; }; } //////////////////////////////////////////////////////////////////////////////// #include "test_util/UdpChannel.h" namespace demo { const msgrpc::service_id_t x_service_id = 2222; const msgrpc::service_id_t y_service_id = 3333; const msgrpc::msg_id_t k_msgrpc_request_msg_id = 101; const msgrpc::msg_id_t k_msgrpc_response_msg_id = 102; struct UdpMsgChannel : msgrpc::MsgChannel, msgrpc::Singleton<UdpMsgChannel> { virtual bool send_msg(const msgrpc::service_id_t& remote_service_id, msgrpc::msg_id_t msg_id, const char* buf, size_t len) const { cout << ((remote_service_id == x_service_id) ? "X <------ " : " ------> Y") << endl; size_t msg_len_with_msgid = sizeof(msgrpc::msg_id_t) + len; char* mem = (char*)malloc(msg_len_with_msgid); if (mem) { *(msgrpc::msg_id_t*)(mem) = msg_id; memcpy(mem + sizeof(msgrpc::msg_id_t), buf, len); g_msg_channel->send_msg_to_remote(string(mem, msg_len_with_msgid), udp::endpoint(udp::v4(), remote_service_id)); free(mem); } else { cout << "send msg failed: allocation failure." << endl; } return true; } }; } using namespace demo; //////////////////////////////////////////////////////////////////////////////// namespace msgrpc { struct IfaceImplBase { virtual msgrpc::RpcResult onRpcInvoke( const msgrpc::ReqMsgHeader& msg_header , const char* msg, size_t len , msgrpc::RspMsgHeader& rsp_header , msgrpc::service_id_t& sender_id) = 0; }; struct IfaceRepository : msgrpc::Singleton<IfaceRepository> { void add_iface_impl(iface_index_t ii, IfaceImplBase* iface) { assert(iface != nullptr && "interface implementation can not be null"); assert(___m.find(ii) == ___m.end() && "interface can only register once"); ___m[ii] = iface; } IfaceImplBase* get_iface_impl_by(iface_index_t ii) { auto iter = ___m.find(ii); return iter == ___m.end() ? nullptr : iter->second; } private: std::map<iface_index_t, IfaceImplBase*> ___m; }; struct MsgSender { static void send_msg_with_header(const msgrpc::service_id_t& service_id, const RspMsgHeader &rsp_header, const uint8_t *pout_buf, uint32_t out_buf_len) { if (pout_buf == nullptr || out_buf_len == 0) { Config::instance().msg_channel_->send_msg(service_id, k_msgrpc_response_msg_id, (const char*)&rsp_header, sizeof(rsp_header)); return; } size_t rsp_len_with_header = sizeof(rsp_header) + out_buf_len; char *mem = (char *) malloc(rsp_len_with_header); if (mem != nullptr) { memcpy(mem, &rsp_header, sizeof(rsp_header)); memcpy(mem + sizeof(rsp_header), pout_buf, out_buf_len); Config::instance().msg_channel_->send_msg(service_id, k_msgrpc_response_msg_id, mem, rsp_len_with_header); free(mem); } } }; struct RpcReqMsgHandler { static void on_rpc_req_msg(msgrpc::msg_id_t msg_id, const char *msg, size_t len) { assert(msg_id == k_msgrpc_request_msg_id && "invalid msg id for rpc"); if (len < sizeof(msgrpc::ReqMsgHeader)) { cout << "invalid msg: without sufficient msg header info." << endl; return; } auto *req_header = (msgrpc::ReqMsgHeader *) msg; msg += sizeof(msgrpc::ReqMsgHeader); msgrpc::RspMsgHeader rsp_header; rsp_header.msgrpc_version_ = req_header->msgrpc_version_; rsp_header.iface_index_in_service_ = req_header->iface_index_in_service_; rsp_header.method_index_in_interface_ = req_header->method_index_in_interface_; rsp_header.sequence_id_ = req_header->sequence_id_; msgrpc::service_id_t sender_id = req_header->iface_index_in_service_ == 2 ? x_service_id : y_service_id; IfaceImplBase *iface = IfaceRepository::instance().get_iface_impl_by(req_header->iface_index_in_service_); if (iface == nullptr) { rsp_header.rpc_result_ = RpcResult::iface_not_found; msgrpc::Config::instance().msg_channel_->send_msg(sender_id, k_msgrpc_response_msg_id, (const char *) &rsp_header, sizeof(rsp_header)); return; } RpcResult ret = iface->onRpcInvoke(*req_header, msg, len - sizeof(msgrpc::ReqMsgHeader), rsp_header, sender_id); if (ret == RpcResult::failed || ret == RpcResult::method_not_found) { return MsgSender::send_msg_with_header(sender_id, rsp_header, nullptr, 0); } //TODO: using pipelined processor to handling input/output msgheader and rpc statistics. } }; } //////////////////////////////////////////////////////////////////////////////// namespace msgrpc { //////////////////////////////////////////////////////////////////////////////// enum class MsgRpcRet : unsigned char { succeeded = 0, failed = 1, async_deferred = 2 }; template<typename RSP> static RpcResult send_rsp_cell_value(const service_id_t& sender_id, const RspMsgHeader &rsp_header, const RpcRspCell<RSP>& rsp_cell) { if (!rsp_cell.cell_has_value_) { return RpcResult::failed; } uint8_t* pout_buf = nullptr; uint32_t out_buf_len = 0; if (!ThriftEncoder::encode(rsp_cell.value_, &pout_buf, &out_buf_len)) { cout << "encode failed on remtoe side." << endl; return RpcResult::failed; } MsgSender::send_msg_with_header(sender_id, rsp_header, pout_buf, out_buf_len); return RpcResult::succeeded; } template<typename T, iface_index_t iface_index> struct InterfaceImplBaseT : IfaceImplBase { InterfaceImplBaseT() { IfaceRepository::instance().add_iface_impl(iface_index, this); } template<typename REQ, typename RSP> RpcResult invoke_templated_method(msgrpc::RpcRspCell<RSP>* (T::*method_impl)(const REQ&) , const char *msg, size_t len , msgrpc::service_id_t& sender_id , msgrpc::RspMsgHeader& rsp_header) { REQ req; if (! ThriftDecoder::decode(req, (uint8_t *) msg, len)) { cout << "decode failed on remote side." << endl; return RpcResult::failed; } msgrpc::RpcRspCell<RSP>* rsp_cell = ((T*)this->*method_impl)(req); if ( rsp_cell == nullptr ) { //TODO: log return RpcResult::failed; } if (rsp_cell->cell_has_value_) { RpcResult ret = send_rsp_cell_value(sender_id, rsp_header, *rsp_cell); delete rsp_cell; return ret; } //TODO: make args of lambda to be reference & ?? derive_final_action([sender_id, rsp_header](msgrpc::RpcRspCell<RSP>& r) { // if (r == nullptr) { // //TODO: log error // return; // } if (r.cell_has_value_) { send_rsp_cell_value(sender_id, rsp_header, r); } else { //TODO: handle error case where result do not contains value. maybe timeout? } }, *rsp_cell); return RpcResult::deferred; } }; } //////////////////////////////////////////////////////////////////////////////// namespace msgrpc { struct RpcStubBase { //TODO: split into .h and .cpp bool send_rpc_request_buf( msgrpc::iface_index_t iface_index, msgrpc::method_index_t method_index , const uint8_t *pbuf, uint32_t len, RpcRspCellSink* rpc_rsp_cell_sink) const { size_t msg_len_with_header = sizeof(msgrpc::ReqMsgHeader) + len; char *mem = (char *) malloc(msg_len_with_header); if (!mem) { cout << "alloc mem failed, during sending rpc request." << endl; return false; } auto seq_id = msgrpc::RpcSequenceId::instance().get(); msgrpc::RpcRspDispatcher::instance().register_rsp_Handler(seq_id, rpc_rsp_cell_sink); auto header = (msgrpc::ReqMsgHeader *) mem; header->msgrpc_version_ = 0; header->iface_index_in_service_ = iface_index; header->method_index_in_interface_ = method_index; header->sequence_id_ = seq_id; memcpy(header + 1, (const char *) pbuf, len); //cout << "stub sending msg with length: " << msg_len_with_header << endl; //TODO: find y_service_id by interface name "IBuzzMath" msgrpc::service_id_t service_id = iface_index == 1 ? x_service_id : y_service_id; bool send_ret = msgrpc::Config::instance().msg_channel_->send_msg(service_id, k_msgrpc_request_msg_id, mem, msg_len_with_header); free(mem); return send_ret; } template<typename T, typename U> RpcRspCell<U>* encode_request_and_send(msgrpc::iface_index_t iface_index, msgrpc::method_index_t method_index, const T &req) const { uint8_t* pbuf; uint32_t len; /*TODO: extract interface for encode/decode for other protocol adoption such as protobuf*/ if (!ThriftEncoder::encode(req, &pbuf, &len)) { /*TODO: how to do with log, maybe should extract logging interface*/ cout << "encode failed." << endl; return nullptr; //TODO: return false; } RpcRspCell<U>* rsp_cell = new RpcRspCell<U>(); if (! send_rpc_request_buf(iface_index, method_index, pbuf, len, rsp_cell)) { delete rsp_cell; return nullptr; } return rsp_cell; }; }; } //////////////////////////////////////////////////////////////////////////////// namespace msgrpc { template<typename T, typename U> struct MsgRpcSIBase { /*SI is short for service interaction*/ msgrpc::RpcRspCell<U> *run(const T &req) { msgrpc::RpcContext *ctxt = new msgrpc::RpcContext(); msgrpc::RpcRspCell<U> *result_cell = do_run(req, ctxt); result_cell->set_binded_context(ctxt); return result_cell; } virtual msgrpc::RpcRspCell<U> *do_run(const T &req, msgrpc::RpcContext *ctxt) = 0; }; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //constants for testing. const int k_req_init_value = 97; const int k__sync_y__delta = 1; const int k__sync_x__delta = 17; //////////////////////////////////////////////////////////////////////////////// //TODO: define following macros: #define declare_interface_on_consumer #define define_interface_on_consumer #define declare_interface_on_provider #define define_interface_on_provider //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //-----------generate by: declare and define stub macros struct InterfaceXStub : msgrpc::RpcStubBase { msgrpc::RpcRspCell<ResponseBar>* ______sync_x(const RequestFoo&); }; msgrpc::RpcRspCell<ResponseBar>* InterfaceXStub::______sync_x(const RequestFoo& req) { return encode_request_and_send<RequestFoo, ResponseBar>(1, 1, req); } //////////////////////////////////////////////////////////////////////////////// //---------------- generate this part by macros set: struct InterfaceXImpl : msgrpc::InterfaceImplBaseT<InterfaceXImpl, 1> { msgrpc::RpcRspCell<ResponseBar>* ______sync_x(const RequestFoo& req); virtual msgrpc::RpcResult onRpcInvoke(const msgrpc::ReqMsgHeader& msg_header , const char* msg, size_t len , msgrpc::RspMsgHeader& rsp_header , msgrpc::service_id_t& sender_id) override; }; //////////////////////////////////////////////////////////////////////////////// //---------------- generate this part by macros set: interface_implement_define.h InterfaceXImpl interfaceXImpl; msgrpc::RpcResult InterfaceXImpl::onRpcInvoke( const msgrpc::ReqMsgHeader& req_header, const char* msg , size_t len, msgrpc::RspMsgHeader& rsp_header , msgrpc::service_id_t& sender_id) { msgrpc::RpcResult ret; if (req_header.method_index_in_interface_ == 1) { ret = this->invoke_templated_method(&InterfaceXImpl::______sync_x, msg, len, sender_id, rsp_header); } else { rsp_header.rpc_result_ = msgrpc::RpcResult::method_not_found; return msgrpc::RpcResult::failed; } if (ret == msgrpc::RpcResult::failed) { rsp_header.rpc_result_ = msgrpc::RpcResult::failed; } return ret; } //////////////////////////////////////////////////////////////////////////////// //---------------- implement interface in here: msgrpc::RpcRspCell<ResponseBar>* InterfaceXImpl::______sync_x(const RequestFoo& req) { cout << " ______sync_x" << endl; auto* rsp_cell = new msgrpc::RpcRspCell<ResponseBar>(); rsp_cell->cell_has_value_ = true; rsp_cell->value_.__set_rspa(req.reqa + k__sync_x__delta); return rsp_cell; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //-----------generate by: declare and define stub macros struct InterfaceYStub : msgrpc::RpcStubBase { msgrpc::RpcRspCell<ResponseBar>* ______sync_y(const RequestFoo&); msgrpc::RpcRspCell<ResponseBar>* _____async_y(const RequestFoo&); }; msgrpc::RpcRspCell<ResponseBar>* InterfaceYStub::______sync_y(const RequestFoo& req) { return encode_request_and_send<RequestFoo, ResponseBar>(2, 1, req); } msgrpc::RpcRspCell<ResponseBar>* InterfaceYStub::_____async_y(const RequestFoo& req) { return encode_request_and_send<RequestFoo, ResponseBar>(2, 2, req); } //////////////////////////////////////////////////////////////////////////////// //---------------- generate this part by macros set: struct InterfaceYImpl : msgrpc::InterfaceImplBaseT<InterfaceYImpl, 2> { msgrpc::RpcRspCell<ResponseBar>* ______sync_y(const RequestFoo& req); msgrpc::RpcRspCell<ResponseBar>* _____async_y(const RequestFoo& req); virtual msgrpc::RpcResult onRpcInvoke( const msgrpc::ReqMsgHeader& msg_header , const char* msg, size_t len , msgrpc::RspMsgHeader& rsp_header , msgrpc::service_id_t& sender_id) override; }; //////////////////////////////////////////////////////////////////////////////// //---------------- generate this part by macros set: interface_implement_define.h InterfaceYImpl interfaceYImpl; msgrpc::RpcResult InterfaceYImpl::onRpcInvoke( const msgrpc::ReqMsgHeader& req_header, const char* msg , size_t len, msgrpc::RspMsgHeader& rsp_header , msgrpc::service_id_t& sender_id) { msgrpc::RpcResult ret; if (req_header.method_index_in_interface_ == 1) { ret = this->invoke_templated_method(&InterfaceYImpl::______sync_y, msg, len, sender_id, rsp_header); } else if (req_header.method_index_in_interface_ == 2) { ret = this->invoke_templated_method(&InterfaceYImpl::_____async_y, msg, len, sender_id, rsp_header); } else { rsp_header.rpc_result_ = msgrpc::RpcResult::method_not_found; return msgrpc::RpcResult::method_not_found; } if (ret == msgrpc::RpcResult::failed) { rsp_header.rpc_result_ = msgrpc::RpcResult::failed; } return ret; } //////////////////////////////////////////////////////////////////////////////// //---------------- implement interface in here: msgrpc::RpcRspCell<ResponseBar>* InterfaceYImpl::______sync_y(const RequestFoo& req) { cout << " ______sync_y" << endl; auto* rsp_cell = new msgrpc::RpcRspCell<ResponseBar>(); rsp_cell->cell_has_value_ = true; rsp_cell->value_.__set_rspa(req.reqa + k__sync_y__delta); return rsp_cell; } struct SI_____async_y : msgrpc::MsgRpcSIBase<RequestFoo, ResponseBar> { virtual msgrpc::RpcRspCell<ResponseBar>* do_run(const RequestFoo &req, msgrpc::RpcContext *ctxt) override { msgrpc::RpcRspCell<ResponseBar>* rsp_cell = InterfaceXStub().______sync_x(req); ctxt->track_item_to_release(rsp_cell); return rsp_cell; } }; msgrpc::RpcRspCell<ResponseBar>* InterfaceYImpl::_____async_y(const RequestFoo& req) { cout << " _____async_y" << endl; msgrpc::RpcRspCell<ResponseBar> *rsp_cell = SI_____async_y().run(req); return rsp_cell; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void save_rsp_from_other_services_to_db(msgrpc::RpcRspCell<ResponseBar>& r) { cout << "1/2 ----------------->>>> write db." << endl; }; void save_rsp_to_log(msgrpc::RpcRspCell<ResponseBar>& r) { cout << "2/2 ----------------->>>> save_log." << endl; }; struct SI_case1_x : msgrpc::MsgRpcSIBase<RequestFoo, ResponseBar> { virtual msgrpc::RpcRspCell<ResponseBar>* do_run(const RequestFoo &req, msgrpc::RpcContext *ctxt) override { msgrpc::RpcRspCell<ResponseBar>* rsp_cell = InterfaceYStub().______sync_y(req); ctxt->track_item_to_release(rsp_cell); ctxt->track_item_to_release(msgrpc::derive_action(save_rsp_from_other_services_to_db, *rsp_cell)); ctxt->track_item_to_release(msgrpc::derive_action(save_rsp_to_log, *rsp_cell)); return rsp_cell; } }; void x_main___case1() { std::this_thread::sleep_for(std::chrono::seconds(1)); RequestFoo foo; foo.reqa = k_req_init_value; msgrpc::RpcRspCell<ResponseBar> *rsp_cell = SI_case1_x().run(foo); if (rsp_cell != nullptr) { derive_final_action( [](msgrpc::RpcRspCell<ResponseBar>& rsp) { EXPECT_TRUE(rsp.cell_has_value_); EXPECT_EQ(k_req_init_value + k__sync_y__delta, rsp.value_.rspa); UdpChannel::close_all_channels(); }, *rsp_cell); } } struct SI_case2_x : msgrpc::MsgRpcSIBase<RequestFoo, ResponseBar> { virtual msgrpc::RpcRspCell<ResponseBar>* do_run(const RequestFoo &req, msgrpc::RpcContext *ctxt) override { msgrpc::RpcRspCell<ResponseBar>* rsp_cell = InterfaceYStub()._____async_y(req); ctxt->track_item_to_release(rsp_cell); return rsp_cell; } }; void x_main___case2() { std::this_thread::sleep_for(std::chrono::seconds(1)); RequestFoo foo; foo.reqa = k_req_init_value; msgrpc::RpcRspCell<ResponseBar> *rsp_cell = SI_case2_x().run(foo); if (rsp_cell != nullptr) { derive_final_action([](msgrpc::RpcRspCell<ResponseBar>& r) { EXPECT_TRUE(r.cell_has_value_); EXPECT_EQ(k_req_init_value + k__sync_x__delta, r.value_.rspa); UdpChannel::close_all_channels(); }, *rsp_cell); } } //////////////////////////////////////////////////////////////////////////////// void msgrpc_loop(unsigned short udp_port, std::function<void(void)> init_func) { msgrpc::Config::instance().init_with(&UdpMsgChannel::instance(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id); UdpChannel channel(udp_port, [&init_func](msgrpc::msg_id_t msg_id, const char* msg, size_t len) { if (0 == strcmp(msg, "init")) { return init_func(); } if (msg_id == msgrpc::Config::instance().request_msg_id_) { return msgrpc::RpcReqMsgHandler::on_rpc_req_msg(msg_id, msg, len); } if (msg_id == msgrpc::Config::instance().response_msg_id_) { return msgrpc::RpcRspDispatcher::instance().handle_rpc_rsp(msg_id, msg, len); } } ); } //////////////////////////////////////////////////////////////////////////////// TEST(async_rpc, should_able_to__support_simple_async_rpc_________x__rpc_to__sync_method_in__y__________case1) { // x ----(req)---->y (sync_y) // x <---(rsp)-----y std::thread thread_x(msgrpc_loop, x_service_id, x_main___case1); std::thread thread_y(msgrpc_loop, y_service_id, [](){}); thread_x.join(); thread_y.join(); } //////////////////////////////////////////////////////////////////////////////// TEST(async_rpc, should_able_to__support_simple_async_rpc_________x__rpc_to__async_method_in_y__________case2) { // x ----(req1)-------------------------->y (async_y) // y (sync_x) <=========(req2)=====y (async_y) // y (sync_x) ==========(rsp2)====>y (async_y) // x <---(rsp1)---------------------------y (async_y) std::thread thread_a(msgrpc_loop, x_service_id, x_main___case2); std::thread thread_b(msgrpc_loop, y_service_id, [](){}); thread_a.join(); thread_b.join(); } refactor test cases #include <iostream> #include <gtest/gtest.h> #include <thread> #include <chrono> #include <msgrpc/thrift_struct/thrift_codec.h> #include <msgrpc/frp/cell.h> #include <type_traits> #include <future> #include <atomic> using namespace std; using namespace std::chrono; #include "demo/demo_api_declare.h" //////////////////////////////////////////////////////////////////////////////// namespace msgrpc { template <typename T> struct Ret {}; typedef unsigned short msg_id_t; typedef unsigned short service_id_t; //TODO: how to deal with different service id types struct MsgChannel { //TODO: extract common channel interface //TODO: check common return value type virtual bool send_msg(const service_id_t& remote_service_id, msg_id_t msg_id, const char* buf, size_t len) const = 0; }; struct Config { void init_with(MsgChannel *msg_channel, msgrpc::msg_id_t request_msg_id, msgrpc::msg_id_t response_msg_id) { instance().msg_channel_ = msg_channel; request_msg_id_ = request_msg_id; response_msg_id_ = response_msg_id; } static inline Config& instance() { static thread_local Config instance; return instance; } MsgChannel* msg_channel_; msg_id_t request_msg_id_; msg_id_t response_msg_id_; }; } namespace msgrpc { typedef int32_t rpc_sequence_id_t; struct RpcSequenceId : msgrpc::Singleton<RpcSequenceId> { rpc_sequence_id_t get() { return ++sequence_id_; } private: atomic_uint sequence_id_ = {0}; }; } namespace msgrpc { typedef uint8_t method_index_t; typedef uint16_t iface_index_t; struct MsgHeader { uint8_t msgrpc_version_ = {0}; method_index_t method_index_in_interface_ = {0}; iface_index_t iface_index_in_service_ = {0}; rpc_sequence_id_t sequence_id_; //TODO: unsigned char feature_id_in_service_ = {0}; //TODO: TLV encoded varient length options //TODO: if not encoded/decode, how to deal hton and ntoh }; /*TODO: consider make msgHeader encoded through thrift*/ struct ReqMsgHeader : MsgHeader { }; enum class RpcResult : unsigned short { succeeded = 0 , deferred = 1 , failed = 2 , method_not_found = 3 , iface_not_found = 4 }; struct RspMsgHeader : MsgHeader { RpcResult rpc_result_ = { RpcResult::succeeded }; }; } //////////////////////////////////////////////////////////////////////////////// namespace msgrpc { struct RpcRspCellSink { virtual bool set_rpc_rsp(RspMsgHeader* rsp_header, const char* msg, size_t len) = 0; }; template<typename T> struct RpcRspCell : Cell<T>, RpcRspCellSink { void set_binded_context(RpcContext* context) { context_ = context; } RpcContext* context_; virtual bool set_rpc_rsp(RspMsgHeader* rsp_header, const char* msg, size_t len) override { //TODO: handle msg header status T rsp; if (! ThriftDecoder::decode(rsp, (uint8_t *) msg, len)) { cout << "decode failed on remote side." << endl; return false; } Cell<T>::set_value(std::move(rsp)); return true; } }; template<typename VT, typename... T> struct DerivedAction : Updatable { DerivedAction(bool is_final_action, std::function<VT(T...)> logic, T &&... args) : is_final_action_(is_final_action), bind_(logic, std::ref(args)...) { call_each_args(std::forward<T>(args)...); } DerivedAction(std::function<VT(T...)> logic, T &&... args) : bind_(logic, std::ref(args)...) { call_each_args(std::forward<T>(args)...); } template<typename C, typename... Ts> void call_each_args(C &&c, Ts &&... args) { c.register_listener(this); call_each_args(std::forward<Ts>(args)...); } template<typename C> void call_each_args(C &&c) { c.register_listener(this); if (is_final_action_) { if (c.context_) { c.context_->track_item_to_release(this); } assert(c.context_ != nullptr && "to release context, should bind not null context to final action."); context_ = c.context_; } } void update() override { bind_(); if (is_final_action_) { delete context_; } } bool is_final_action_ = {false}; RpcContext* context_; using bind_type = decltype(std::bind(std::declval<std::function<VT(T...)>>(), std::ref(std::declval<T>())...)); bind_type bind_; }; template<typename F, typename... Args> auto derive_action(F &&f, Args &&... args) -> DerivedAction<decltype(f(args...)), Args...>* { return new DerivedAction<decltype(f(args...)), Args...>(std::forward<F>(f), std::ref(args)...); } template<typename F, typename... Args> auto derive_final_action(F &&f, Args &&... args) -> DerivedAction<decltype(f(args...)), Args...>* { return new DerivedAction<decltype(f(args...)), Args...>(/*is_final_action=*/true, std::forward<F>(f), std::ref(args)...); } template<typename VT, typename... T> struct DerivedCell : RpcRspCell<VT> { DerivedCell(std::function<boost::optional<VT>(T...)> logic, T &&... args) : bind_(logic, std::ref(args)...) { call_each_args(std::forward<T>(args)...); } template<typename C, typename... Ts> void call_each_args(C &&c, Ts &&... args) { c->register_listener(this); call_each_args(std::forward<Ts>(args)...); } template<typename C> void call_each_args(C &&c) { c->register_listener(this); } void update() override { if (!Cell<VT>::cell_has_value_) { boost::optional<VT> value = bind_(); if (value) { Cell<VT>::set_value(std::move(value.value())); } } } using bind_type = decltype(std::bind(std::declval<std::function<boost::optional<VT>(T...)>>(), std::ref(std::declval<T>())...)); bind_type bind_; }; template<typename F, typename... Args> auto derive_cell(F &&f, Args &&... args) -> DerivedCell<typename decltype(f(args...))::value_type, Args...>* { return new DerivedCell<typename decltype(f(args...))::value_type, Args...>(std::forward<F>(f), std::ref(args)...); } struct RpcRspDispatcher : msgrpc::ThreadLocalSingleton<RpcRspDispatcher> { void register_rsp_Handler(rpc_sequence_id_t sequence_id, RpcRspCellSink* func) { assert(id_func_map_.find(sequence_id) == id_func_map_.end() && "should register with unique id."); id_func_map_[sequence_id] = func; } void handle_rpc_rsp(msgrpc::msg_id_t msg_id, const char *msg, size_t len) { //cout << "DEBUG: local received msg----------->: " << string(msg, len) << endl; if (len < sizeof(RspMsgHeader)) { cout << "WARNING: invalid rsp msg" << endl; return; } auto* rsp_header = (RspMsgHeader*)msg; auto iter = id_func_map_.find(rsp_header->sequence_id_); if (iter == id_func_map_.end()) { cout << "WARNING: can not find rsp handler" << endl; return; } (iter->second)->set_rpc_rsp(rsp_header, msg + sizeof(RspMsgHeader), len - sizeof(RspMsgHeader)); id_func_map_.erase(iter); } std::map<rpc_sequence_id_t, RpcRspCellSink*> id_func_map_; }; } //////////////////////////////////////////////////////////////////////////////// const msgrpc::service_id_t x_service_id = 2222; const msgrpc::service_id_t y_service_id = 3333; const msgrpc::msg_id_t k_msgrpc_request_msg_id = 101; const msgrpc::msg_id_t k_msgrpc_response_msg_id = 102; //////////////////////////////////////////////////////////////////////////////// namespace msgrpc { struct IfaceImplBase { virtual msgrpc::RpcResult onRpcInvoke( const msgrpc::ReqMsgHeader& msg_header , const char* msg, size_t len , msgrpc::RspMsgHeader& rsp_header , msgrpc::service_id_t& sender_id) = 0; }; struct IfaceRepository : msgrpc::Singleton<IfaceRepository> { void add_iface_impl(iface_index_t ii, IfaceImplBase* iface) { assert(iface != nullptr && "interface implementation can not be null"); assert(___m.find(ii) == ___m.end() && "interface can only register once"); ___m[ii] = iface; } IfaceImplBase* get_iface_impl_by(iface_index_t ii) { auto iter = ___m.find(ii); return iter == ___m.end() ? nullptr : iter->second; } private: std::map<iface_index_t, IfaceImplBase*> ___m; }; struct MsgSender { static void send_msg_with_header(const msgrpc::service_id_t& service_id, const RspMsgHeader &rsp_header, const uint8_t *pout_buf, uint32_t out_buf_len) { if (pout_buf == nullptr || out_buf_len == 0) { Config::instance().msg_channel_->send_msg(service_id, k_msgrpc_response_msg_id, (const char*)&rsp_header, sizeof(rsp_header)); return; } size_t rsp_len_with_header = sizeof(rsp_header) + out_buf_len; char *mem = (char *) malloc(rsp_len_with_header); if (mem != nullptr) { memcpy(mem, &rsp_header, sizeof(rsp_header)); memcpy(mem + sizeof(rsp_header), pout_buf, out_buf_len); Config::instance().msg_channel_->send_msg(service_id, k_msgrpc_response_msg_id, mem, rsp_len_with_header); free(mem); } } }; struct RpcReqMsgHandler { static void on_rpc_req_msg(msgrpc::msg_id_t msg_id, const char *msg, size_t len) { assert(msg_id == k_msgrpc_request_msg_id && "invalid msg id for rpc"); if (len < sizeof(msgrpc::ReqMsgHeader)) { cout << "invalid msg: without sufficient msg header info." << endl; return; } auto *req_header = (msgrpc::ReqMsgHeader *) msg; msg += sizeof(msgrpc::ReqMsgHeader); msgrpc::RspMsgHeader rsp_header; rsp_header.msgrpc_version_ = req_header->msgrpc_version_; rsp_header.iface_index_in_service_ = req_header->iface_index_in_service_; rsp_header.method_index_in_interface_ = req_header->method_index_in_interface_; rsp_header.sequence_id_ = req_header->sequence_id_; msgrpc::service_id_t sender_id = req_header->iface_index_in_service_ == 2 ? x_service_id : y_service_id; IfaceImplBase *iface = IfaceRepository::instance().get_iface_impl_by(req_header->iface_index_in_service_); if (iface == nullptr) { rsp_header.rpc_result_ = RpcResult::iface_not_found; msgrpc::Config::instance().msg_channel_->send_msg(sender_id, k_msgrpc_response_msg_id, (const char *) &rsp_header, sizeof(rsp_header)); return; } RpcResult ret = iface->onRpcInvoke(*req_header, msg, len - sizeof(msgrpc::ReqMsgHeader), rsp_header, sender_id); if (ret == RpcResult::failed || ret == RpcResult::method_not_found) { return MsgSender::send_msg_with_header(sender_id, rsp_header, nullptr, 0); } //TODO: using pipelined processor to handling input/output msgheader and rpc statistics. } }; } //////////////////////////////////////////////////////////////////////////////// namespace msgrpc { //////////////////////////////////////////////////////////////////////////////// enum class MsgRpcRet : unsigned char { succeeded = 0, failed = 1, async_deferred = 2 }; template<typename RSP> static RpcResult send_rsp_cell_value(const service_id_t& sender_id, const RspMsgHeader &rsp_header, const RpcRspCell<RSP>& rsp_cell) { if (!rsp_cell.cell_has_value_) { return RpcResult::failed; } uint8_t* pout_buf = nullptr; uint32_t out_buf_len = 0; if (!ThriftEncoder::encode(rsp_cell.value_, &pout_buf, &out_buf_len)) { cout << "encode failed on remtoe side." << endl; return RpcResult::failed; } MsgSender::send_msg_with_header(sender_id, rsp_header, pout_buf, out_buf_len); return RpcResult::succeeded; } template<typename T, iface_index_t iface_index> struct InterfaceImplBaseT : IfaceImplBase { InterfaceImplBaseT() { IfaceRepository::instance().add_iface_impl(iface_index, this); } template<typename REQ, typename RSP> RpcResult invoke_templated_method(msgrpc::RpcRspCell<RSP>* (T::*method_impl)(const REQ&) , const char *msg, size_t len , msgrpc::service_id_t& sender_id , msgrpc::RspMsgHeader& rsp_header) { REQ req; if (! ThriftDecoder::decode(req, (uint8_t *) msg, len)) { cout << "decode failed on remote side." << endl; return RpcResult::failed; } msgrpc::RpcRspCell<RSP>* rsp_cell = ((T*)this->*method_impl)(req); if ( rsp_cell == nullptr ) { //TODO: log return RpcResult::failed; } if (rsp_cell->cell_has_value_) { RpcResult ret = send_rsp_cell_value(sender_id, rsp_header, *rsp_cell); delete rsp_cell; return ret; } //TODO: make args of lambda to be reference & ?? derive_final_action([sender_id, rsp_header](msgrpc::RpcRspCell<RSP>& r) { if (r.cell_has_value_) { send_rsp_cell_value(sender_id, rsp_header, r); } else { //TODO: handle error case where result do not contains value. maybe timeout? } }, *rsp_cell); return RpcResult::deferred; } }; } //////////////////////////////////////////////////////////////////////////////// namespace msgrpc { struct RpcStubBase { //TODO: split into .h and .cpp bool send_rpc_request_buf( msgrpc::iface_index_t iface_index, msgrpc::method_index_t method_index , const uint8_t *pbuf, uint32_t len, RpcRspCellSink* rpc_rsp_cell_sink) const { size_t msg_len_with_header = sizeof(msgrpc::ReqMsgHeader) + len; char *mem = (char *) malloc(msg_len_with_header); if (!mem) { cout << "alloc mem failed, during sending rpc request." << endl; return false; } auto seq_id = msgrpc::RpcSequenceId::instance().get(); msgrpc::RpcRspDispatcher::instance().register_rsp_Handler(seq_id, rpc_rsp_cell_sink); auto header = (msgrpc::ReqMsgHeader *) mem; header->msgrpc_version_ = 0; header->iface_index_in_service_ = iface_index; header->method_index_in_interface_ = method_index; header->sequence_id_ = seq_id; memcpy(header + 1, (const char *) pbuf, len); //cout << "stub sending msg with length: " << msg_len_with_header << endl; //TODO: find y_service_id by interface name "IBuzzMath" msgrpc::service_id_t service_id = iface_index == 1 ? x_service_id : y_service_id; bool send_ret = msgrpc::Config::instance().msg_channel_->send_msg(service_id, k_msgrpc_request_msg_id, mem, msg_len_with_header); free(mem); return send_ret; } template<typename T, typename U> RpcRspCell<U>* encode_request_and_send(msgrpc::iface_index_t iface_index, msgrpc::method_index_t method_index, const T &req) const { uint8_t* pbuf; uint32_t len; /*TODO: extract interface for encode/decode for other protocol adoption such as protobuf*/ if (!ThriftEncoder::encode(req, &pbuf, &len)) { /*TODO: how to do with log, maybe should extract logging interface*/ cout << "encode failed." << endl; return nullptr; //TODO: return false; } RpcRspCell<U>* rsp_cell = new RpcRspCell<U>(); if (! send_rpc_request_buf(iface_index, method_index, pbuf, len, rsp_cell)) { delete rsp_cell; return nullptr; } return rsp_cell; }; }; } //////////////////////////////////////////////////////////////////////////////// namespace msgrpc { template<typename T, typename U> struct MsgRpcSIBase { /*SI is short for service interaction*/ msgrpc::RpcRspCell<U> *run(const T &req) { msgrpc::RpcContext *ctxt = new msgrpc::RpcContext(); msgrpc::RpcRspCell<U> *result_cell = do_run(req, ctxt); result_cell->set_binded_context(ctxt); return result_cell; } virtual msgrpc::RpcRspCell<U> *do_run(const T &req, msgrpc::RpcContext *ctxt) = 0; }; } //////////////////////////////////////////////////////////////////////////////// #include "test_util/UdpChannel.h" namespace demo { struct UdpMsgChannel : msgrpc::MsgChannel, msgrpc::Singleton<UdpMsgChannel> { virtual bool send_msg(const msgrpc::service_id_t& remote_service_id, msgrpc::msg_id_t msg_id, const char* buf, size_t len) const { cout << ((remote_service_id == x_service_id) ? "X <------ " : " ------> Y") << endl; size_t msg_len_with_msgid = sizeof(msgrpc::msg_id_t) + len; char* mem = (char*)malloc(msg_len_with_msgid); if (mem) { *(msgrpc::msg_id_t*)(mem) = msg_id; memcpy(mem + sizeof(msgrpc::msg_id_t), buf, len); g_msg_channel->send_msg_to_remote(string(mem, msg_len_with_msgid), udp::endpoint(udp::v4(), remote_service_id)); free(mem); } else { cout << "send msg failed: allocation failure." << endl; } return true; } }; } using namespace demo; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //constants for testing. const int k_req_init_value = 97; const int k__sync_y__delta = 1; const int k__sync_x__delta = 17; //////////////////////////////////////////////////////////////////////////////// void msgrpc_loop(unsigned short udp_port, std::function<void(void)> init_func) { msgrpc::Config::instance().init_with(&UdpMsgChannel::instance(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id); UdpChannel channel(udp_port, [&init_func](msgrpc::msg_id_t msg_id, const char* msg, size_t len) { if (0 == strcmp(msg, "init")) { return init_func(); } if (msg_id == msgrpc::Config::instance().request_msg_id_) { return msgrpc::RpcReqMsgHandler::on_rpc_req_msg(msg_id, msg, len); } if (msg_id == msgrpc::Config::instance().response_msg_id_) { return msgrpc::RpcRspDispatcher::instance().handle_rpc_rsp(msg_id, msg, len); } } ); } //////////////////////////////////////////////////////////////////////////////// template<typename SI> void rpc_main(std::function<void(msgrpc::RpcRspCell<ResponseBar>&)> f) { std::this_thread::sleep_for(std::chrono::seconds(1)); RequestFoo foo; foo.reqa = k_req_init_value; msgrpc::RpcRspCell<ResponseBar> *rsp_cell = SI().run(foo); if (rsp_cell != nullptr) { derive_final_action([f](msgrpc::RpcRspCell<ResponseBar>& r) { f(r); UdpChannel::close_all_channels(); }, *rsp_cell); } } //////////////////////////////////////////////////////////////////////////////// //TODO: define following macros: #define declare_interface_on_consumer #define define_interface_on_consumer #define declare_interface_on_provider #define define_interface_on_provider //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //-----------generate by: declare and define stub macros struct InterfaceXStub : msgrpc::RpcStubBase { msgrpc::RpcRspCell<ResponseBar>* ______sync_x(const RequestFoo&); }; msgrpc::RpcRspCell<ResponseBar>* InterfaceXStub::______sync_x(const RequestFoo& req) { return encode_request_and_send<RequestFoo, ResponseBar>(1, 1, req); } //////////////////////////////////////////////////////////////////////////////// //---------------- generate this part by macros set: struct InterfaceXImpl : msgrpc::InterfaceImplBaseT<InterfaceXImpl, 1> { msgrpc::RpcRspCell<ResponseBar>* ______sync_x(const RequestFoo& req); virtual msgrpc::RpcResult onRpcInvoke(const msgrpc::ReqMsgHeader& msg_header , const char* msg, size_t len , msgrpc::RspMsgHeader& rsp_header , msgrpc::service_id_t& sender_id) override; }; //////////////////////////////////////////////////////////////////////////////// //---------------- generate this part by macros set: interface_implement_define.h InterfaceXImpl interfaceXImpl; msgrpc::RpcResult InterfaceXImpl::onRpcInvoke( const msgrpc::ReqMsgHeader& req_header, const char* msg , size_t len, msgrpc::RspMsgHeader& rsp_header , msgrpc::service_id_t& sender_id) { msgrpc::RpcResult ret; if (req_header.method_index_in_interface_ == 1) { ret = this->invoke_templated_method(&InterfaceXImpl::______sync_x, msg, len, sender_id, rsp_header); } else { rsp_header.rpc_result_ = msgrpc::RpcResult::method_not_found; return msgrpc::RpcResult::failed; } if (ret == msgrpc::RpcResult::failed) { rsp_header.rpc_result_ = msgrpc::RpcResult::failed; } return ret; } //////////////////////////////////////////////////////////////////////////////// //---------------- implement interface in here: msgrpc::RpcRspCell<ResponseBar>* InterfaceXImpl::______sync_x(const RequestFoo& req) { cout << " ______sync_x" << endl; auto* rsp_cell = new msgrpc::RpcRspCell<ResponseBar>(); rsp_cell->cell_has_value_ = true; rsp_cell->value_.__set_rspa(req.reqa + k__sync_x__delta); return rsp_cell; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //-----------generate by: declare and define stub macros struct InterfaceYStub : msgrpc::RpcStubBase { msgrpc::RpcRspCell<ResponseBar>* ______sync_y(const RequestFoo&); msgrpc::RpcRspCell<ResponseBar>* _____async_y(const RequestFoo&); }; msgrpc::RpcRspCell<ResponseBar>* InterfaceYStub::______sync_y(const RequestFoo& req) { return encode_request_and_send<RequestFoo, ResponseBar>(2, 1, req); } msgrpc::RpcRspCell<ResponseBar>* InterfaceYStub::_____async_y(const RequestFoo& req) { return encode_request_and_send<RequestFoo, ResponseBar>(2, 2, req); } //////////////////////////////////////////////////////////////////////////////// //---------------- generate this part by macros set: struct InterfaceYImpl : msgrpc::InterfaceImplBaseT<InterfaceYImpl, 2> { msgrpc::RpcRspCell<ResponseBar>* ______sync_y(const RequestFoo& req); msgrpc::RpcRspCell<ResponseBar>* _____async_y(const RequestFoo& req); virtual msgrpc::RpcResult onRpcInvoke( const msgrpc::ReqMsgHeader& msg_header , const char* msg, size_t len , msgrpc::RspMsgHeader& rsp_header , msgrpc::service_id_t& sender_id) override; }; //////////////////////////////////////////////////////////////////////////////// //---------------- generate this part by macros set: interface_implement_define.h InterfaceYImpl interfaceYImpl; msgrpc::RpcResult InterfaceYImpl::onRpcInvoke( const msgrpc::ReqMsgHeader& req_header, const char* msg , size_t len, msgrpc::RspMsgHeader& rsp_header , msgrpc::service_id_t& sender_id) { msgrpc::RpcResult ret; if (req_header.method_index_in_interface_ == 1) { ret = this->invoke_templated_method(&InterfaceYImpl::______sync_y, msg, len, sender_id, rsp_header); } else if (req_header.method_index_in_interface_ == 2) { ret = this->invoke_templated_method(&InterfaceYImpl::_____async_y, msg, len, sender_id, rsp_header); } else { rsp_header.rpc_result_ = msgrpc::RpcResult::method_not_found; return msgrpc::RpcResult::method_not_found; } if (ret == msgrpc::RpcResult::failed) { rsp_header.rpc_result_ = msgrpc::RpcResult::failed; } return ret; } //////////////////////////////////////////////////////////////////////////////// //---------------- implement interface in here: msgrpc::RpcRspCell<ResponseBar>* InterfaceYImpl::______sync_y(const RequestFoo& req) { cout << " ______sync_y" << endl; auto* rsp_cell = new msgrpc::RpcRspCell<ResponseBar>(); rsp_cell->cell_has_value_ = true; rsp_cell->value_.__set_rspa(req.reqa + k__sync_y__delta); return rsp_cell; } struct SI_____async_y : msgrpc::MsgRpcSIBase<RequestFoo, ResponseBar> { virtual msgrpc::RpcRspCell<ResponseBar>* do_run(const RequestFoo &req, msgrpc::RpcContext *ctxt) override { msgrpc::RpcRspCell<ResponseBar>* rsp_cell = InterfaceXStub().______sync_x(req); ctxt->track_item_to_release(rsp_cell); return rsp_cell; } }; msgrpc::RpcRspCell<ResponseBar>* InterfaceYImpl::_____async_y(const RequestFoo& req) { cout << " _____async_y" << endl; msgrpc::RpcRspCell<ResponseBar> *rsp_cell = SI_____async_y().run(req); return rsp_cell; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void save_rsp_from_other_services_to_db(msgrpc::RpcRspCell<ResponseBar>& r) { cout << "1/2 ----------------->>>> write db." << endl; }; void save_rsp_to_log(msgrpc::RpcRspCell<ResponseBar>& r) { cout << "2/2 ----------------->>>> save_log." << endl; }; struct SI_case1_x : msgrpc::MsgRpcSIBase<RequestFoo, ResponseBar> { virtual msgrpc::RpcRspCell<ResponseBar>* do_run(const RequestFoo &req, msgrpc::RpcContext *ctxt) override { msgrpc::RpcRspCell<ResponseBar>* rsp_cell = InterfaceYStub().______sync_y(req); ctxt->track_item_to_release(rsp_cell); ctxt->track_item_to_release(msgrpc::derive_action(save_rsp_from_other_services_to_db, *rsp_cell)); ctxt->track_item_to_release(msgrpc::derive_action(save_rsp_to_log, *rsp_cell)); return rsp_cell; } }; TEST(async_rpc, should_able_to__support_simple_async_rpc_________x__rpc_to__sync_method_in__y__________case1) { // x ----(req)---->y (sync_y) // x <---(rsp)-----y auto then_check = [](msgrpc::RpcRspCell<ResponseBar>& ___r) { EXPECT_TRUE(___r.cell_has_value_); EXPECT_EQ(k_req_init_value + k__sync_y__delta, ___r.value_.rspa); }; std::thread thread_x(msgrpc_loop, x_service_id, [&]() {rpc_main<SI_case1_x>(then_check);}); std::thread thread_y(msgrpc_loop, y_service_id, [](){}); thread_x.join(); thread_y.join(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct SI_case2_x : msgrpc::MsgRpcSIBase<RequestFoo, ResponseBar> { virtual msgrpc::RpcRspCell<ResponseBar>* do_run(const RequestFoo &req, msgrpc::RpcContext *ctxt) override { msgrpc::RpcRspCell<ResponseBar>* rsp_cell = InterfaceYStub()._____async_y(req); ctxt->track_item_to_release(rsp_cell); return rsp_cell; } }; TEST(async_rpc, should_able_to__support_simple_async_rpc_________x__rpc_to__async_method_in_y__________case2) { // x ----(req1)-------------------------->y (async_y) // y (sync_x) <=========(req2)=====y (async_y) // y (sync_x) ==========(rsp2)====>y (async_y) // x <---(rsp1)---------------------------y (async_y) auto then_check = [](msgrpc::RpcRspCell<ResponseBar>& ___r) { EXPECT_TRUE(___r.cell_has_value_); EXPECT_EQ(k_req_init_value + k__sync_x__delta, ___r.value_.rspa); }; std::thread thread_x(msgrpc_loop, x_service_id, [&]() {rpc_main<SI_case2_x>(then_check);}); std::thread thread_y(msgrpc_loop, y_service_id, [](){}); thread_x.join(); thread_y.join(); }
namespace iox { template <uint64_t Capacity, typename ValueType> IndexQueue<Capacity, ValueType>::IndexQueue(ConstructEmpty_t) : m_readPosition(Index(Capacity)) , m_writePosition(Index(Capacity)) { } template <uint64_t Capacity, typename ValueType> IndexQueue<Capacity, ValueType>::IndexQueue(ConstructFull_t) : m_readPosition(Index(0)) , m_writePosition(Index(Capacity)) { for (uint64_t i = 0; i < Capacity; ++i) { m_cells[i].store(Index(i)); } } template <uint64_t Capacity, typename ValueType> constexpr uint64_t IndexQueue<Capacity, ValueType>::capacity() { return Capacity; } template <uint64_t Capacity, typename ValueType> void IndexQueue<Capacity, ValueType>::push(ValueType index) { // we need the CAS loop here since we may fail due to concurrent push operations // note that we are always able to succeed to publish since we have // enough capacity for all unique indices used // case analyis // (1) loaded value is exactly one cycle behind: // value is from the last cycle // we can try to publish // (2) loaded value has the same cycle: // some other push has published but not updated the write position // help updating the write position // (3) loaded value is more than one cycle behind: // this should only happen due to wrap around when push is interrupted for a long time // reload write position and try again // note that a complete wraparound can lead to a false detection of 1) (ABA problem) // but this is very unlikely with e.g. a 64 bit value type // (4) loaded value is some cycle ahead: // write position is outdated, there must have been other pushes concurrently // reload write position and try again constexpr bool notPublished = true; auto writePosition = loadNextWritePosition(); do { auto oldValue = loadValueAt(writePosition); auto isFreeToPublish = [&]() { return oldValue.isOneCycleBehind(writePosition); }; if (isFreeToPublish()) { // case (1) Index newValue(index, writePosition.getCycle()); // if publish fails, another thread has published before us if (tryToPublishAt(writePosition, oldValue, newValue)) { break; } } // even if we are not able to publish, we check whether some other push has already updated the writePosition // before trying again to publish auto writePositionWasNotUpdated = [&]() { return oldValue.getCycle() == writePosition.getCycle(); }; if (writePositionWasNotUpdated()) { // case (2) // the writePosition was not updated yet by another push but the value was already written // help with the update updateNextWritePosition(writePosition); } else { // case (3) and (4) // note: we do not call updateNextWritePosition here, the CAS is bound to fail anyway // (our value of writePosition is not up to date so needs to be loaded again) writePosition = loadNextWritePosition(); } } while (notPublished); updateNextWritePosition(writePosition); } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::pop(ValueType& index) { // we need the CAS loop here since we may fail due to concurrent pop operations // we leave when we detect an empty queue, otherwise we retry the pop operation // case analyis // (1) loaded value has the same cycle: // value was not popped before // try to get ownership // (2) loaded value is exactly one cycle behind: // value is from the last cycle which means the queue is empty // return false // (3) loaded value is more than one cycle behind: // this should only happen due to wrap around when push is interrupted for a long time // reload read position and try again // (4) loaded value is some cycle ahead: // read position is outdated, there must have been pushes concurrently // reload read position and try again constexpr bool ownerShipGained = true; Index value; auto readPosition = loadNextReadPosition(); do { value = loadValueAt(readPosition); // we only dequeue if value and readPosition are in the same cycle auto isValidToRead = [&]() { return readPosition.getCycle() == value.getCycle(); }; // readPosition is ahead by one cycle, queue was empty at loadValueAt(..) auto isEmpty = [&]() { return value.isOneCycleBehind(readPosition); }; if (isValidToRead()) { // case (1) if (tryToGainOwnershipAt(readPosition)) { break; // pop successful } else { // retry, readPosition was already updated via CAS in tryToGainOwnershipAt // todo: maybe refactor to eliminate the continue but still skip the reload of // readPosition continue; } } else if (isEmpty()) { // case (2) return false; } // else readPosition is outdated, retry operation // case (3) and (4) readPosition = loadNextReadPosition(); } while (!ownerShipGained); // we leave if we gain ownership of readPosition index = value.getIndex(); return true; } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::popIfFull(ValueType& index) { // we do NOT need a CAS loop here since if we detect that the queue is not full // someone else popped an element and we do not retry to check whether it was filled AGAIN // concurrently (which will usually not be the case and then we would return false anyway) // if it is filled again we can (and will) retry popIfFull from the call site // the queue is full if and only if write position and read position are the same but read position is // one cycle behind write position // unfortunately it seems impossible in this design to check this condition without loading // write posiion and read position (which causes more contention) auto writePosition = loadNextWritePosition(); auto readPosition = loadNextReadPosition(); auto value = loadValueAt(readPosition); auto isFull = [&]() { return writePosition.getIndex() == readPosition.getIndex() && readPosition.isOneCycleBehind(writePosition); }; if (isFull()) { if (tryToGainOwnershipAt(readPosition)) { index = value.getIndex(); return true; } } // else someone else has popped an index return false; } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::empty() { auto oldReadIndex = m_readPosition.load(std::memory_order_relaxed); auto value = m_cells[oldReadIndex.getIndex()].load(std::memory_order_relaxed); // if m_readPosition is ahead by one cycle compared to the value stored at head, // the queue was empty at the time of the loads above (but might not be anymore!) return value.isOneCycleBehind(oldReadIndex); } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::Index IndexQueue<Capacity, ValueType>::loadNextReadPosition() const { return m_readPosition.load(std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::Index IndexQueue<Capacity, ValueType>::loadNextWritePosition() const { return m_writePosition.load(std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::Index IndexQueue<Capacity, ValueType>::loadValueAt(typename IndexQueue<Capacity, ValueType>::Index position) const { return m_cells[position.getIndex()].load(std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::tryToPublishAt(typename IndexQueue<Capacity, ValueType>::Index writePosition, Index& oldValue, Index newValue) { return m_cells[writePosition.getIndex()].compare_exchange_strong( oldValue, newValue, std::memory_order_relaxed, std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> void IndexQueue<Capacity, ValueType>::updateNextWritePosition(Index& writePosition) { // compare_exchange updates writePosition if NOT successful Index newWritePosition(writePosition + 1); auto updateSucceeded = m_writePosition.compare_exchange_strong( writePosition, newWritePosition, std::memory_order_relaxed, std::memory_order_relaxed); // not needed in the successful case, we do not retry // if (updateSucceeded) // { // writePosition = newWritePosition; // } } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::tryToGainOwnershipAt(Index& oldReadPosition) { Index newReadPosition(oldReadPosition + 1); return m_readPosition.compare_exchange_strong( oldReadPosition, newReadPosition, std::memory_order_relaxed, std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> void IndexQueue<Capacity, ValueType>::push(const UniqueIndex& index) { push(*index); } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::UniqueIndex IndexQueue<Capacity, ValueType>::pop() { ValueType value; if (pop(value)) { return UniqueIndex(value); } return UniqueIndex::invalid; } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::UniqueIndex IndexQueue<Capacity, ValueType>::popIfFull() { ValueType value; if (popIfFull(value)) { return UniqueIndex(value); } return UniqueIndex::invalid; } } // namespace iox refactor code in index queue for comprehensibility Signed-off-by: Killat Matthias (CC-AD/ESW1) <fe1c406681586f2880f55b2d8223674cab4039ef@de.bosch.com> namespace iox { template <uint64_t Capacity, typename ValueType> IndexQueue<Capacity, ValueType>::IndexQueue(ConstructEmpty_t) : m_readPosition(Index(Capacity)) , m_writePosition(Index(Capacity)) { } template <uint64_t Capacity, typename ValueType> IndexQueue<Capacity, ValueType>::IndexQueue(ConstructFull_t) : m_readPosition(Index(0)) , m_writePosition(Index(Capacity)) { for (uint64_t i = 0; i < Capacity; ++i) { m_cells[i].store(Index(i)); } } template <uint64_t Capacity, typename ValueType> constexpr uint64_t IndexQueue<Capacity, ValueType>::capacity() { return Capacity; } template <uint64_t Capacity, typename ValueType> void IndexQueue<Capacity, ValueType>::push(ValueType index) { // we need the CAS loop here since we may fail due to concurrent push operations // note that we are always able to succeed to publish since we have // enough capacity for all unique indices used // case analyis // (1) loaded value is exactly one cycle behind: // value is from the last cycle // we can try to publish // (2) loaded value has the same cycle: // some other push has published but not updated the write position // help updating the write position // (3) loaded value is more than one cycle behind: // this should only happen due to wrap around when push is interrupted for a long time // reload write position and try again // note that a complete wraparound can lead to a false detection of 1) (ABA problem) // but this is very unlikely with e.g. a 64 bit value type // (4) loaded value is some cycle ahead: // write position is outdated, there must have been other pushes concurrently // reload write position and try again constexpr bool notPublished = true; auto writePosition = loadNextWritePosition(); do { auto oldValue = loadValueAt(writePosition); auto cellIsFree = oldValue.isOneCycleBehind(writePosition); if (cellIsFree) { // case (1) Index newValue(index, writePosition.getCycle()); // if publish fails, another thread has published before us if (tryToPublishAt(writePosition, oldValue, newValue)) { break; } } // even if we are not able to publish, we check whether some other push has already updated the writePosition // before trying again to publish auto writePositionRequiresUpdate = oldValue.getCycle() == writePosition.getCycle(); if (writePositionRequiresUpdate) { // case (2) // the writePosition was not updated yet by another push but the value was already written // help with the update updateNextWritePosition(writePosition); } else { // case (3) and (4) // note: we do not call updateNextWritePosition here, the CAS is bound to fail anyway // (since our value of writePosition is not up to date so needs to be loaded again) writePosition = loadNextWritePosition(); } } while (notPublished); updateNextWritePosition(writePosition); } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::pop(ValueType& index) { // we need the CAS loop here since we may fail due to concurrent pop operations // we leave when we detect an empty queue, otherwise we retry the pop operation // case analyis // (1) loaded value has the same cycle: // value was not popped before // try to get ownership // (2) loaded value is exactly one cycle behind: // value is from the last cycle which means the queue is empty // return false // (3) loaded value is more than one cycle behind: // this should only happen due to wrap around when push is interrupted for a long time // reload read position and try again // (4) loaded value is some cycle ahead: // read position is outdated, there must have been pushes concurrently // reload read position and try again constexpr bool ownerShipGained = true; Index value; auto readPosition = loadNextReadPosition(); do { value = loadValueAt(readPosition); // we only dequeue if value and readPosition are in the same cycle auto cellIsValidToRead = readPosition.getCycle() == value.getCycle(); if (cellIsValidToRead) { // case (1) if (tryToGainOwnershipAt(readPosition)) { break; // pop successful } // retry, readPosition was already updated via CAS in tryToGainOwnershipAt } else { // readPosition is ahead by one cycle, queue was empty at loadValueAt(..) auto isEmpty = value.isOneCycleBehind(readPosition); if (isEmpty) { // case (2) return false; } // case (3) and (4) requires loading readPosition again readPosition = loadNextReadPosition(); } // readPosition is outdated, retry operation } while (!ownerShipGained); // we leave if we gain ownership of readPosition index = value.getIndex(); return true; } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::popIfFull(ValueType& index) { // we do NOT need a CAS loop here since if we detect that the queue is not full // someone else popped an element and we do not retry to check whether it was filled AGAIN // concurrently (which will usually not be the case and then we would return false anyway) // if it is filled again we can (and will) retry popIfFull from the call site // the queue is full if and only if write position and read position are the same but read position is // one cycle behind write position // unfortunately it seems impossible in this design to check this condition without loading // write posiion and read position (which causes more contention) auto writePosition = loadNextWritePosition(); auto readPosition = loadNextReadPosition(); auto value = loadValueAt(readPosition); auto isFull = writePosition.getIndex() == readPosition.getIndex() && readPosition.isOneCycleBehind(writePosition); if (isFull) { if (tryToGainOwnershipAt(readPosition)) { index = value.getIndex(); return true; } } // otherwise someone else has dequeued an index and the queue was not full at the start of this popIfFull return false; } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::empty() { auto oldReadIndex = m_readPosition.load(std::memory_order_relaxed); auto value = m_cells[oldReadIndex.getIndex()].load(std::memory_order_relaxed); // if m_readPosition is ahead by one cycle compared to the value stored at head, // the queue was empty at the time of the loads above (but might not be anymore!) return value.isOneCycleBehind(oldReadIndex); } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::Index IndexQueue<Capacity, ValueType>::loadNextReadPosition() const { return m_readPosition.load(std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::Index IndexQueue<Capacity, ValueType>::loadNextWritePosition() const { return m_writePosition.load(std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::Index IndexQueue<Capacity, ValueType>::loadValueAt(typename IndexQueue<Capacity, ValueType>::Index position) const { return m_cells[position.getIndex()].load(std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::tryToPublishAt(typename IndexQueue<Capacity, ValueType>::Index writePosition, Index& oldValue, Index newValue) { return m_cells[writePosition.getIndex()].compare_exchange_strong( oldValue, newValue, std::memory_order_relaxed, std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> void IndexQueue<Capacity, ValueType>::updateNextWritePosition(Index& writePosition) { // compare_exchange updates writePosition if NOT successful Index newWritePosition(writePosition + 1); auto updateSucceeded = m_writePosition.compare_exchange_strong( writePosition, newWritePosition, std::memory_order_relaxed, std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::tryToGainOwnershipAt(Index& oldReadPosition) { Index newReadPosition(oldReadPosition + 1); return m_readPosition.compare_exchange_strong( oldReadPosition, newReadPosition, std::memory_order_relaxed, std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> void IndexQueue<Capacity, ValueType>::push(const UniqueIndex& index) { push(*index); } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::UniqueIndex IndexQueue<Capacity, ValueType>::pop() { ValueType value; if (pop(value)) { return UniqueIndex(value); } return UniqueIndex::invalid; } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::UniqueIndex IndexQueue<Capacity, ValueType>::popIfFull() { ValueType value; if (popIfFull(value)) { return UniqueIndex(value); } return UniqueIndex::invalid; } } // namespace iox
// @(#)root/cont:$Id$ // Author: Rene Brun 11/02/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // An array of clone (identical) objects. Memory for the objects // // stored in the array is allocated only once in the lifetime of the // // clones array. All objects must be of the same class. For the rest // // this class has the same properties as TObjArray. // // // // To reduce the very large number of new and delete calls in large // // loops like this (O(100000) x O(10000) times new/delete): // // // // TObjArray a(10000); // // while (TEvent *ev = (TEvent *)next()) { // O(100000) events // // for (int i = 0; i < ev->Ntracks; i++) { // O(10000) tracks // // a[i] = new TTrack(x,y,z,...); // // ... // // ... // // } // // ... // // a.Delete(); // // } // // // // One better uses a TClonesArray which reduces the number of // // new/delete calls to only O(10000): // // // // TClonesArray a("TTrack", 10000); // // while (TEvent *ev = (TEvent *)next()) { // O(100000) events // // for (int i = 0; i < ev->Ntracks; i++) { // O(10000) tracks // // new(a[i]) TTrack(x,y,z,...); // // ... // // ... // // } // // ... // // a.Delete(); // or a.Clear() or a.Clear("C") // // } // // // // To reduce the number of call to the constructor (especially useful // // if the user class requires memory allocation), the object can be // // added (and constructed when needed) using ConstructedAt which only // // calls the constructor once per slot. // // // // TClonesArray a("TTrack", 10000); // // while (TEvent *ev = (TEvent *)next()) { // O(100000) events // // for (int i = 0; i < ev->Ntracks; i++) { // O(10000) tracks // // TTrack *track = (TTrack*)a.ConstructedAt(i); // // track->Set(x,y,z,....); // // ... // // ... // // } // // ... // // a.Clear(); // or a.Clear("C"); // // } // // // // Note: the only supported way to add objects to a TClonesArray is // // via the new with placement method or the ConstructedAt method. // // The other Add() methods ofTObjArray and its base classes are not // // allowed. // // // // Considering that a new/delete costs about 70 mus on a 300 MHz HP, // // O(10^9) new/deletes will save about 19 hours. // // // // NOTE 1 // ====== // C/C++ offers the possibility of allocating and deleting memory. // Forgetting to delete allocated memory is a programming error called a // "memory leak", i.e. the memory of your process grows and eventually // your program crashes. Even if you *always* delete the allocated // memory, the recovered space may not be efficiently reused. The // process knows that there are portions of free memory, but when you // allocate it again, a fresh piece of memory is grabbed. Your program // is free from semantic errors, but the total memory of your process // still grows, because your program's memory is full of "holes" which // reduce the efficiency of memory access; this is called "memory // fragmentation". Moreover new / delete are expensive operations in // terms of CPU time. // // Without entering into technical details, TClonesArray allows you to // "reuse" the same portion of memory for new/delete avoiding memory // fragmentation and memory growth and improving the performance by // orders of magnitude. Every time the memory of the TClonesArray has // to be reused, the Clear() method is used. To provide its benefits, // each TClonesArray must be allocated *once* per process and disposed // of (deleted) *only when not needed any more*. // // So a job should see *only one* deletion for each TClonesArray, // which should be Clear()ed during the job several times. Deleting a // TClonesArray is a double waste. Not only you do not avoid memory // fragmentation, but you worsen it because the TClonesArray itself // is a rather heavy structure, and there is quite some code in the // destructor, so you have more memory fragmentation and slower code. // // NOTE 2 // ====== // // When investigating misuse of TClonesArray, please make sure of the following: // // * Use Clear() or Clear("C") instead of Delete(). This will improve // program execution time. // * TClonesArray object classes containing pointers allocate memory. // To avoid causing memory leaks, special Clear("C") must be used // for clearing TClonesArray. When option "C" is specified, ROOT // automatically executes the Clear() method (by default it is // empty contained in TObject). This method must be overridden in // the relevant TClonesArray object class, implementing the reset // procedure for pointer objects. // * If the objects are added using the placement new then the Clear must // deallocate the memory. // * If the objects are added using TClonesArray::ConstructedAt then the // heap-based memory can stay allocated and reused as the constructor is // not called for already constructed/added object. // * To reduce memory fragmentation, please make sure that the // TClonesArrays are not destroyed and created on every event. They // must only be constructed/destructed at the beginning/end of the // run. // ////////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include "TClonesArray.h" #include "TError.h" #include "TROOT.h" #include "TClass.h" #include "TObjectTable.h" ClassImp(TClonesArray) //______________________________________________________________________________ TClonesArray::TClonesArray() : TObjArray() { // Default Constructor. fClass = 0; fKeep = 0; } //______________________________________________________________________________ TClonesArray::TClonesArray(const char *classname, Int_t s, Bool_t) : TObjArray(s) { // Create an array of clone objects of classname. The class must inherit from // TObject. If the class defines its own operator delete(), make sure that // it looks like this: // // void MyClass::operator delete(void *vp) // { // if ((Long_t) vp != TObject::GetDtorOnly()) // ::operator delete(vp); // delete space // else // TObject::SetDtorOnly(0); // } // // The second argument s indicates an approximate number of objects // that will be entered in the array. If more than s objects are entered, // the array will be automatically expanded. // // The third argument is not used anymore and only there for backward // compatibility reasons. fKeep = 0; SetClass(classname,s); } //______________________________________________________________________________ TClonesArray::TClonesArray(const TClass *cl, Int_t s, Bool_t) : TObjArray(s) { // Create an array of clone objects of class cl. The class must inherit from // TObject. If the class defines an own operator delete(), make sure that // it looks like this: // // void MyClass::operator delete(void *vp) // { // if ((Long_t) vp != TObject::GetDtorOnly()) // ::operator delete(vp); // delete space // else // TObject::SetDtorOnly(0); // } // // The second argument, s, indicates an approximate number of objects // that will be entered in the array. If more than s objects are entered, // the array will be automatically expanded. // // The third argument is not used anymore and only there for backward // compatibility reasons. fKeep = 0; SetClass(cl,s); } //______________________________________________________________________________ TClonesArray::TClonesArray(const TClonesArray& tc): TObjArray(tc) { // Copy ctor. fKeep = new TObjArray(tc.fSize); fClass = tc.fClass; BypassStreamer(kTRUE); for (Int_t i = 0; i < fSize; i++) { if (tc.fCont[i]) fCont[i] = tc.fCont[i]->Clone(); fKeep->fCont[i] = fCont[i]; } } //______________________________________________________________________________ TClonesArray& TClonesArray::operator=(const TClonesArray& tc) { // Assignment operator. if (this == &tc) return *this; if (fClass != tc.fClass) { Error("operator=", "cannot copy TClonesArray's when classes are different"); return *this; } if (tc.fSize > fSize) Expand(TMath::Max(tc.fSize, GrowBy(fSize))); Int_t i; for (i = 0; i < fSize; i++) if (fKeep->fCont[i]) { if (TObject::GetObjectStat() && gObjectTable) gObjectTable->RemoveQuietly(fKeep->fCont[i]); ::operator delete(fKeep->fCont[i]); fKeep->fCont[i] = 0; fCont[i] = 0; } BypassStreamer(kTRUE); for (i = 0; i < tc.fSize; i++) { if (tc.fCont[i]) fKeep->fCont[i] = tc.fCont[i]->Clone(); fCont[i] = fKeep->fCont[i]; } fLast = tc.fLast; Changed(); return *this; } //______________________________________________________________________________ TClonesArray::~TClonesArray() { // Delete a clones array. if (fKeep) { for (Int_t i = 0; i < fKeep->fSize; i++) { TObject* p = fKeep->fCont[i]; if (p && p->TestBit(kNotDeleted)) { // -- The TObject destructor has not been called. fClass->Destructor(p); fKeep->fCont[i] = 0; } else { // -- The TObject destructor was called, just free memory. // // remove any possible entries from the ObjectTable if (TObject::GetObjectStat() && gObjectTable) { gObjectTable->RemoveQuietly(p); } ::operator delete(p); fKeep->fCont[i] = 0; } } } SafeDelete(fKeep); // Protect against erroneously setting of owner bit SetOwner(kFALSE); } //______________________________________________________________________________ void TClonesArray::BypassStreamer(Bool_t bypass) { // When the kBypassStreamer bit is set, the automatically // generated Streamer can call directly TClass::WriteBuffer. // Bypassing the Streamer improves the performance when writing/reading // the objects in the TClonesArray. However there is a drawback: // When a TClonesArray is written with split=0 bypassing the Streamer, // the StreamerInfo of the class in the array being optimized, // one cannot use later the TClonesArray with split>0. For example, // there is a problem with the following scenario: // 1- A class Foo has a TClonesArray of Bar objects // 2- The Foo object is written with split=0 to Tree T1. // In this case the StreamerInfo for the class Bar is created // in optimized mode in such a way that data members of the same type // are written as an array improving the I/O performance. // 3- In a new program, T1 is read and a new Tree T2 is created // with the object Foo in split>1 // 4- When the T2 branch is created, the StreamerInfo for the class Bar // is created with no optimization (mandatory for the split mode). // The optimized Bar StreamerInfo is going to be used to read // the TClonesArray in T1. The result will be Bar objects with // data member values not in the right sequence. // The solution to this problem is to call BypassStreamer(kFALSE) // for the TClonesArray. In this case, the normal Bar::Streamer function // will be called. The Bar::Streamer function works OK independently // if the Bar StreamerInfo had been generated in optimized mode or not. if (bypass) SetBit(kBypassStreamer); else ResetBit(kBypassStreamer); } //______________________________________________________________________________ void TClonesArray::Compress() { // Remove empty slots from array. Int_t j = 0, je = 0; TObject **tmp = new TObject* [fSize]; for (Int_t i = 0; i < fSize; i++) { if (fCont[i]) { fCont[j] = fCont[i]; fKeep->fCont[j] = fKeep->fCont[i]; j++; } else { tmp[je] = fKeep->fCont[i]; je++; } } fLast = j - 1; Int_t jf = 0; for ( ; j < fSize; j++) { fCont[j] = 0; fKeep->fCont[j] = tmp[jf]; jf++; } delete [] tmp; R__ASSERT(je == jf); } //______________________________________________________________________________ TObject *TClonesArray::ConstructedAt(Int_t idx) { // Get an object at index 'idx' that is guaranteed to have been constructed. // It might be either a freshly allocated object or one that had already been // allocated (and assumingly used). In the later case, it is the callers // responsability to insure that the object is returned to a known state, // usually by calling the Clear method on the TClonesArray. // // Tests to see if the destructor has been called on the object. // If so, or if the object has never been constructed the class constructor is called using // New(). If not, return a pointer to the correct memory location. // This explicitly to deal with TObject classes that allocate memory // which will be reset (but not deallocated) in their Clear() // functions. TObject *obj = (*this)[idx]; if ( obj && obj->TestBit(TObject::kNotDeleted) ) { return obj; } return (fClass) ? static_cast<TObject*>(fClass->New(obj)) : 0; } //______________________________________________________________________________ TObject *TClonesArray::ConstructedAt(Int_t idx, Option_t *clear_options) { // Get an object at index 'idx' that is guaranteed to have been constructed. // It might be either a freshly allocated object or one that had already been // allocated (and assumingly used). In the later case, the function Clear // will be called and passed the value of 'clear_options' // // Tests to see if the destructor has been called on the object. // If so, or if the object has never been constructed the class constructor is called using // New(). If not, return a pointer to the correct memory location. // This explicitly to deal with TObject classes that allocate memory // which will be reset (but not deallocated) in their Clear() // functions. TObject *obj = (*this)[idx]; if ( obj && obj->TestBit(TObject::kNotDeleted) ) { obj->Clear(clear_options); return obj; } return (fClass) ? static_cast<TObject*>(fClass->New(obj)) : 0; } //______________________________________________________________________________ void TClonesArray::Clear(Option_t *option) { // Clear the clones array. Only use this routine when your objects don't // allocate memory since it will not call the object dtors. // However, if the class in the TClonesArray implements the function // Clear(Option_t *option) and if option = "C" the function Clear() // is called for all objects in the array. In the function Clear(), one // can delete objects or dynamic arrays allocated in the class. // This procedure is much faster than calling TClonesArray::Delete(). // When the option starts with "C+", eg "C+xyz" the objects in the array // are in turn cleared with the option "xyz" if (option && option[0] == 'C') { const char *cplus = strstr(option,"+"); if (cplus) { cplus = cplus + 1; } else { cplus = ""; } Int_t n = GetEntriesFast(); for (Int_t i = 0; i < n; i++) { TObject *obj = UncheckedAt(i); if (obj) { obj->Clear(cplus); obj->ResetBit( kHasUUID ); obj->ResetBit( kIsReferenced ); obj->SetUniqueID( 0 ); } } } // Protect against erroneously setting of owner bit SetOwner(kFALSE); TObjArray::Clear(); } //______________________________________________________________________________ void TClonesArray::Delete(Option_t *) { // Clear the clones array. Use this routine when your objects allocate // memory (e.g. objects inheriting from TNamed or containing TStrings // allocate memory). If not you better use Clear() since if is faster. if ( fClass->TestBit(TClass::kIsEmulation) ) { // In case of emulated class, we can not use the delete operator // directly, it would use the wrong destructor. for (Int_t i = 0; i < fSize; i++) { if (fCont[i] && fCont[i]->TestBit(kNotDeleted)) { fClass->Destructor(fCont[i],kTRUE); } } } else { Long_t dtoronly = TObject::GetDtorOnly(); for (Int_t i = 0; i < fSize; i++) { if (fCont[i] && fCont[i]->TestBit(kNotDeleted)) { // Tell custom operator delete() not to delete space when // object fCont[i] is deleted. Only destructors are called // for this object. TObject::SetDtorOnly(fCont[i]); delete fCont[i]; } } // Restore the state. TObject::SetDtorOnly((void*)dtoronly); } // Protect against erroneously setting of owner bit. SetOwner(kFALSE); TObjArray::Clear(); } //______________________________________________________________________________ void TClonesArray::Expand(Int_t newSize) { // Expand or shrink the array to newSize elements. if (newSize < 0) { Error ("Expand", "newSize must be positive (%d)", newSize); return; } if (newSize == fSize) return; if (newSize < fSize) { // release allocated space in fKeep and set to 0 so // Expand() will shrink correctly for (int i = newSize; i < fSize; i++) if (fKeep->fCont[i]) { if (TObject::GetObjectStat() && gObjectTable) gObjectTable->RemoveQuietly(fKeep->fCont[i]); ::operator delete(fKeep->fCont[i]); fKeep->fCont[i] = 0; } } TObjArray::Expand(newSize); fKeep->Expand(newSize); } //______________________________________________________________________________ void TClonesArray::ExpandCreate(Int_t n) { // Expand or shrink the array to n elements and create the clone // objects by calling their default ctor. If n is less than the current size // the array is shrunk and the allocated space is freed. // This routine is typically used to create a clonesarray into which // one can directly copy object data without going via the // "new (arr[i]) MyObj()" (i.e. the vtbl is already set correctly). if (n < 0) { Error("ExpandCreate", "n must be positive (%d)", n); return ; } if (n > fSize) Expand(TMath::Max(n, GrowBy(fSize))); Int_t i; for (i = 0; i < n; i++) { if (!fKeep->fCont[i]) { fKeep->fCont[i] = (TObject*)fClass->New(); } else if (!fKeep->fCont[i]->TestBit(kNotDeleted)) { // The object has been deleted (or never initialized) fClass->New(fKeep->fCont[i]); } fCont[i] = fKeep->fCont[i]; } for (i = n; i < fSize; i++) if (fKeep->fCont[i]) { if (TObject::GetObjectStat() && gObjectTable) gObjectTable->RemoveQuietly(fKeep->fCont[i]); ::operator delete(fKeep->fCont[i]); fKeep->fCont[i] = 0; fCont[i] = 0; } fLast = n - 1; Changed(); } //______________________________________________________________________________ void TClonesArray::ExpandCreateFast(Int_t n) { // Expand or shrink the array to n elements and create the clone // objects by calling their default ctor. If n is less than the current size // the array is shrinked but the allocated space is _not_ freed. // This routine is typically used to create a clonesarray into which // one can directly copy object data without going via the // "new (arr[i]) MyObj()" (i.e. the vtbl is already set correctly). // This is a simplified version of ExpandCreate used in the TTree mechanism. if (n > fSize) Expand(TMath::Max(n, GrowBy(fSize))); Int_t i; for (i = 0; i < n; i++) { if (!fKeep->fCont[i]) { fKeep->fCont[i] = (TObject*)fClass->New(); } else if (!fKeep->fCont[i]->TestBit(kNotDeleted)) { // The object has been deleted (or never initialized) fClass->New(fKeep->fCont[i]); } fCont[i] = fKeep->fCont[i]; } if (fLast >= n) { memset(fCont + n, 0, (fLast - n + 1) * sizeof(TObject*)); } fLast = n - 1; Changed(); } //______________________________________________________________________________ TObject *TClonesArray::RemoveAt(Int_t idx) { // Remove object at index idx. if (!BoundsOk("RemoveAt", idx)) return 0; int i = idx-fLowerBound; if (fCont[i] && fCont[i]->TestBit(kNotDeleted)) { // Tell custom operator delete() not to delete space when // object fCont[i] is deleted. Only destructors are called // for this object. Long_t dtoronly = TObject::GetDtorOnly(); TObject::SetDtorOnly(fCont[i]); delete fCont[i]; TObject::SetDtorOnly((void*)dtoronly); } if (fCont[i]) { fCont[i] = 0; // recalculate array size if (i == fLast) do { fLast--; } while (fLast >= 0 && fCont[fLast] == 0); Changed(); } return 0; } //______________________________________________________________________________ TObject *TClonesArray::Remove(TObject *obj) { // Remove object from array. if (!obj) return 0; Int_t i = IndexOf(obj) - fLowerBound; if (i == -1) return 0; if (fCont[i] && fCont[i]->TestBit(kNotDeleted)) { // Tell custom operator delete() not to delete space when // object fCont[i] is deleted. Only destructors are called // for this object. Long_t dtoronly = TObject::GetDtorOnly(); TObject::SetDtorOnly(fCont[i]); delete fCont[i]; TObject::SetDtorOnly((void*)dtoronly); } fCont[i] = 0; // recalculate array size if (i == fLast) do { fLast--; } while (fLast >= 0 && fCont[fLast] == 0); Changed(); return obj; } //______________________________________________________________________________ void TClonesArray::RemoveRange(Int_t idx1, Int_t idx2) { // Remove objects from index idx1 to idx2 included. if (!BoundsOk("RemoveRange", idx1)) return; if (!BoundsOk("RemoveRange", idx2)) return; Long_t dtoronly = TObject::GetDtorOnly(); idx1 -= fLowerBound; idx2 -= fLowerBound; Bool_t change = kFALSE; for (TObject **obj=fCont+idx1; obj<=fCont+idx2; obj++) { if (!*obj) continue; if ((*obj)->TestBit(kNotDeleted)) { // Tell custom operator delete() not to delete space when // object fCont[i] is deleted. Only destructors are called // for this object. TObject::SetDtorOnly(*obj); delete *obj; } *obj = 0; change = kTRUE; } TObject::SetDtorOnly((void*)dtoronly); // recalculate array size if (change) Changed(); if (idx1 < fLast || fLast > idx2) return; do { fLast--; } while (fLast >= 0 && fCont[fLast] == 0); } //______________________________________________________________________________ void TClonesArray::SetClass(const TClass *cl, Int_t s) { // Create an array of clone objects of class cl. The class must inherit from // TObject. If the class defines an own operator delete(), make sure that // it looks like this: // // void MyClass::operator delete(void *vp) // { // if ((Long_t) vp != TObject::GetDtorOnly()) // ::operator delete(vp); // delete space // else // TObject::SetDtorOnly(0); // } // // The second argument s indicates an approximate number of objects // that will be entered in the array. If more than s objects are entered, // the array will be automatically expanded. // // NB: This function should not be called in the TClonesArray is already // initialized with a class. if (fKeep) { Error("SetClass", "TClonesArray already initialized with another class"); return; } fClass = (TClass*)cl; if (!fClass) { MakeZombie(); Error("SetClass", "called with a null pointer"); return; } const char *classname = fClass->GetName(); if (!fClass->IsTObject()) { MakeZombie(); Error("SetClass", "%s does not inherit from TObject", classname); return; } if (fClass->GetBaseClassOffset(TObject::Class())!=0) { MakeZombie(); Error("SetClass", "%s must inherit from TObject as the left most base class.", classname); return; } Int_t nch = strlen(classname)+2; char *name = new char[nch]; snprintf(name,nch, "%ss", classname); SetName(name); delete [] name; fKeep = new TObjArray(s); BypassStreamer(kTRUE); } //______________________________________________________________________________ void TClonesArray::SetClass(const char *classname, Int_t s) { //see TClonesArray::SetClass(const TClass*) SetClass(TClass::GetClass(classname),s); } //______________________________________________________________________________ void TClonesArray::SetOwner(Bool_t /* enable */) { // A TClonesArray is always the owner of the object it contains. // However the collection its inherits from (TObjArray) does not. // Hence this member function needs to be a nop for TClonesArray. // Nothing to be done. } //______________________________________________________________________________ void TClonesArray::Sort(Int_t upto) { // If objects in array are sortable (i.e. IsSortable() returns true // for all objects) then sort array. Int_t nentries = GetAbsLast()+1; if (nentries <= 0 || fSorted) return; for (Int_t i = 0; i < fSize; i++) if (fCont[i]) { if (!fCont[i]->IsSortable()) { Error("Sort", "objects in array are not sortable"); return; } } QSort(fCont, fKeep->fCont, 0, TMath::Min(nentries, upto-fLowerBound)); fLast = -2; fSorted = kTRUE; } //_______________________________________________________________________ void TClonesArray::Streamer(TBuffer &b) { // Write all objects in array to the I/O buffer. ATTENTION: empty slots // are also stored (using one byte per slot). If you don't want this // use a TOrdCollection or TList. // Important Note: if you modify this function, remember to also modify // TConvertClonesArrayToProxy accordingly Int_t nobjects; char nch; TString s, classv; UInt_t R__s, R__c; if (b.IsReading()) { Version_t v = b.ReadVersion(&R__s, &R__c); if (v == 3) { const Int_t kOldBypassStreamer = BIT(14); if (TestBit(kOldBypassStreamer)) BypassStreamer(); } if (v > 2) TObject::Streamer(b); if (v > 1) fName.Streamer(b); s.Streamer(b); classv = s; Int_t clv = 0; Ssiz_t pos = s.Index(";"); if (pos != kNPOS) { classv = s(0, pos); s = s(pos+1, s.Length()-pos-1); clv = s.Atoi(); } TClass *cl = TClass::GetClass(classv); if (!cl) { printf("TClonesArray::Streamer expecting class %s\n", classv.Data()); b.CheckByteCount(R__s, R__c,TClonesArray::IsA()); return; } b >> nobjects; if (nobjects < 0) nobjects = -nobjects; // still there for backward compatibility b >> fLowerBound; if (fClass == 0 && fKeep == 0) { fClass = cl; fKeep = new TObjArray(fSize); Expand(nobjects); } if (cl != fClass) { fClass = cl; //this case may happen when switching from an emulated class to the real class //may not be an error. fClass may point to a deleted object //Error("Streamer", "expecting objects of type %s, finding objects" // " of type %s", fClass->GetName(), cl->GetName()); //return; } // make sure there are enough slots in the fKeep array if (fKeep->GetSize() < nobjects) Expand(nobjects); //reset fLast. nobjects may be 0 Int_t oldLast = fLast; fLast = nobjects-1; //TStreamerInfo *sinfo = fClass->GetStreamerInfo(clv); if (CanBypassStreamer() && !b.TestBit(TBuffer::kCannotHandleMemberWiseStreaming)) { for (Int_t i = 0; i < nobjects; i++) { if (!fKeep->fCont[i]) { fKeep->fCont[i] = (TObject*)fClass->New(); } else if (!fKeep->fCont[i]->TestBit(kNotDeleted)) { // The object has been deleted (or never initialized) fClass->New(fKeep->fCont[i]); } fCont[i] = fKeep->fCont[i]; } //sinfo->ReadBufferClones(b,this,nobjects,-1,0); b.ReadClones(this,nobjects,clv); } else { for (Int_t i = 0; i < nobjects; i++) { b >> nch; if (nch) { if (!fKeep->fCont[i]) fKeep->fCont[i] = (TObject*)fClass->New(); else if (!fKeep->fCont[i]->TestBit(kNotDeleted)) { // The object has been deleted (or never initialized) fClass->New(fKeep->fCont[i]); } fCont[i] = fKeep->fCont[i]; b.StreamObject(fKeep->fCont[i]); } } } for (Int_t i = TMath::Max(nobjects,0); i < oldLast+1; ++i) fCont[i] = 0; Changed(); b.CheckByteCount(R__s, R__c,TClonesArray::IsA()); } else { //Make sure TStreamerInfo is not optimized, otherwise it will not be //possible to support schema evolution in read mode. //In case the StreamerInfo has already been computed and optimized, //one must disable the option BypassStreamer b.ForceWriteInfoClones(this); // make sure the status of bypass streamer is part of the buffer // (bits in TObject), so that when reading the object the right // mode is used, independent of the method (e.g. written via // TMessage, received and stored to a file and then later read via // TBufferFile) Bool_t bypass = kFALSE; if (b.TestBit(TBuffer::kCannotHandleMemberWiseStreaming)) { bypass = CanBypassStreamer(); BypassStreamer(kFALSE); } R__c = b.WriteVersion(TClonesArray::IsA(), kTRUE); TObject::Streamer(b); fName.Streamer(b); s.Form("%s;%d", fClass->GetName(), fClass->GetClassVersion()); s.Streamer(b); nobjects = GetEntriesFast(); b << nobjects; b << fLowerBound; if (CanBypassStreamer()) { b.WriteClones(this,nobjects); } else { for (Int_t i = 0; i < nobjects; i++) { if (!fCont[i]) { nch = 0; b << nch; } else { nch = 1; b << nch; b.StreamObject(fCont[i]); } } } b.SetByteCount(R__c, kTRUE); if (bypass) BypassStreamer(); } } //______________________________________________________________________________ TObject *&TClonesArray::operator[](Int_t idx) { // Return pointer to reserved area in which a new object of clones // class can be constructed. This operator should not be used for // lefthand side assignments, like a[2] = xxx. Only like, // new (a[2]) myClass, or xxx = a[2]. Of course right hand side usage // is only legal after the object has been constructed via the // new operator or via the New() method. To remove elements from // the clones array use Remove() or RemoveAt(). if (idx < 0) { Error("operator[]", "out of bounds at %d in %lx", idx, (Long_t)this); return fCont[0]; } if (!fClass) { Error("operator[]", "invalid class specified in TClonesArray ctor"); return fCont[0]; } if (idx >= fSize) Expand(TMath::Max(idx+1, GrowBy(fSize))); if (!fKeep->fCont[idx]) { fKeep->fCont[idx] = (TObject*) TStorage::ObjectAlloc(fClass->Size()); // Reset the bit so that: // obj = myClonesArray[i]; // obj->TestBit(TObject::kNotDeleted) // will behave correctly. // TObject::kNotDeleted is one of the higher bit that is not settable via the public // interface. But luckily we are its friend. fKeep->fCont[idx]->fBits &= ~kNotDeleted; } fCont[idx] = fKeep->fCont[idx]; fLast = TMath::Max(idx, GetAbsLast()); Changed(); return fCont[idx]; } //______________________________________________________________________________ TObject *TClonesArray::operator[](Int_t idx) const { // Return the object at position idx. Returns 0 if idx is out of bounds. if (idx < 0 || idx >= fSize) { Error("operator[]", "out of bounds at %d in %lx", idx, (Long_t)this); return 0; } return fCont[idx]; } //______________________________________________________________________________ TObject *TClonesArray::New(Int_t idx) { // Create an object of type fClass with the default ctor at the specified // index. Returns 0 in case of error. if (idx < 0) { Error("New", "out of bounds at %d in %lx", idx, (Long_t)this); return 0; } if (!fClass) { Error("New", "invalid class specified in TClonesArray ctor"); return 0; } return (TObject *)fClass->New(operator[](idx)); } //______________________________________________________________________________ // // The following functions are utilities implemented by Jason Detwiler // (jadetwiler@lbl.gov) // //______________________________________________________________________________ void TClonesArray::AbsorbObjects(TClonesArray *tc) { // Directly move the object pointers from tc without cloning (copying). // This TClonesArray takes over ownership of all of tc's object // pointers. The tc array is left empty upon return. // tests if (tc == 0 || tc == this || tc->GetEntriesFast() == 0) return; if (fClass != tc->fClass) { Error("AbsorbObjects", "cannot absorb objects when classes are different"); return; } // cache the sorted status Bool_t wasSorted = IsSorted() && tc->IsSorted() && (Last() == 0 || Last()->Compare(tc->First()) == -1); // expand this Int_t oldSize = GetEntriesFast(); Int_t newSize = oldSize + tc->GetEntriesFast(); if(newSize > fSize) Expand(newSize); // move for (Int_t i = 0; i < tc->GetEntriesFast(); ++i) { fCont[oldSize+i] = tc->fCont[i]; (*fKeep)[oldSize+i] = (*(tc->fKeep))[i]; tc->fCont[i] = 0; (*(tc->fKeep))[i] = 0; } // cleanup fLast = newSize-1; tc->fLast = -1; if (!wasSorted) Changed(); } //______________________________________________________________________________ void TClonesArray::AbsorbObjects(TClonesArray *tc, Int_t idx1, Int_t idx2) { // Directly move the range of object pointers from tc without cloning // (copying). // This TClonesArray takes over ownership of all of tc's object pointers // from idx1 to idx2. The tc array is re-arranged by return. // tests if (tc == 0 || tc == this || tc->GetEntriesFast() == 0) return; if (fClass != tc->fClass) { Error("AbsorbObjects", "cannot absorb objects when classes are different"); return; } if (idx1 > idx2) { Error("AbsorbObjects", "range is not valid: idx1>idx2"); return; } // cache the sorted status Bool_t wasSorted = IsSorted() && tc->IsSorted() && (Last() == 0 || Last()->Compare(tc->First()) == -1); // expand this Int_t oldSize = GetEntriesFast(); Int_t newSize = oldSize + (idx2-idx1+1); if(newSize > fSize) Expand(newSize); // move for (Int_t i = idx1; i <= idx2; i++) { Int_t newindex = oldSize+i -idx1; fCont[newindex] = tc->fCont[i]; ::operator delete(fKeep->fCont[newindex]); (*fKeep)[newindex] = (*(tc->fKeep))[i]; tc->fCont[i] = 0; (*(tc->fKeep))[i] = 0; } // cleanup for (Int_t i = idx2+1; i < tc->GetEntriesFast(); i++) { tc->fCont[i-(idx2-idx1+1)] = tc->fCont[i]; (*(tc->fKeep))[i-(idx2-idx1+1)] = (*(tc->fKeep))[i]; tc->fCont[i] = 0; (*(tc->fKeep))[i] = 0; } tc->fLast = tc->GetEntriesFast() - 2 - (idx2 - idx1); fLast = newSize-1; if (!wasSorted) Changed(); } //______________________________________________________________________________ void TClonesArray::MultiSort(Int_t nTCs, TClonesArray** tcs, Int_t upto) { // Sort multiple TClonesArrays simultaneously with this array. // If objects in array are sortable (i.e. IsSortable() returns true // for all objects) then sort array. Int_t nentries = GetAbsLast()+1; if (nentries <= 1 || fSorted) return; Bool_t sortedCheck = kTRUE; for (Int_t i = 0; i < fSize; i++) { if (fCont[i]) { if (!fCont[i]->IsSortable()) { Error("MultiSort", "objects in array are not sortable"); return; } } if (sortedCheck && i > 1) { if (ObjCompare(fCont[i], fCont[i-1]) < 0) sortedCheck = kFALSE; } } if (sortedCheck) { fSorted = kTRUE; return; } for (int i = 0; i < nTCs; i++) { if (tcs[i] == this) { Error("MultiSort", "tcs[%d] = \"this\"", i); return; } if (tcs[i]->GetEntriesFast() != GetEntriesFast()) { Error("MultiSort", "tcs[%d] has length %d != length of this (%d)", i, tcs[i]->GetEntriesFast(), this->GetEntriesFast()); return; } } int nBs = nTCs*2+1; TObject*** b = new TObject**[nBs]; for (int i = 0; i < nTCs; i++) { b[2*i] = tcs[i]->fCont; b[2*i+1] = tcs[i]->fKeep->fCont; } b[nBs-1] = fKeep->fCont; QSort(fCont, nBs, b, 0, TMath::Min(nentries, upto-fLowerBound)); delete [] b; fLast = -2; fSorted = kTRUE; } Avoid unitialized read in TClonesArray::ExpandCreateFast. This fixes ROOT-7046. // @(#)root/cont:$Id$ // Author: Rene Brun 11/02/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // An array of clone (identical) objects. Memory for the objects // // stored in the array is allocated only once in the lifetime of the // // clones array. All objects must be of the same class. For the rest // // this class has the same properties as TObjArray. // // // // To reduce the very large number of new and delete calls in large // // loops like this (O(100000) x O(10000) times new/delete): // // // // TObjArray a(10000); // // while (TEvent *ev = (TEvent *)next()) { // O(100000) events // // for (int i = 0; i < ev->Ntracks; i++) { // O(10000) tracks // // a[i] = new TTrack(x,y,z,...); // // ... // // ... // // } // // ... // // a.Delete(); // // } // // // // One better uses a TClonesArray which reduces the number of // // new/delete calls to only O(10000): // // // // TClonesArray a("TTrack", 10000); // // while (TEvent *ev = (TEvent *)next()) { // O(100000) events // // for (int i = 0; i < ev->Ntracks; i++) { // O(10000) tracks // // new(a[i]) TTrack(x,y,z,...); // // ... // // ... // // } // // ... // // a.Delete(); // or a.Clear() or a.Clear("C") // // } // // // // To reduce the number of call to the constructor (especially useful // // if the user class requires memory allocation), the object can be // // added (and constructed when needed) using ConstructedAt which only // // calls the constructor once per slot. // // // // TClonesArray a("TTrack", 10000); // // while (TEvent *ev = (TEvent *)next()) { // O(100000) events // // for (int i = 0; i < ev->Ntracks; i++) { // O(10000) tracks // // TTrack *track = (TTrack*)a.ConstructedAt(i); // // track->Set(x,y,z,....); // // ... // // ... // // } // // ... // // a.Clear(); // or a.Clear("C"); // // } // // // // Note: the only supported way to add objects to a TClonesArray is // // via the new with placement method or the ConstructedAt method. // // The other Add() methods ofTObjArray and its base classes are not // // allowed. // // // // Considering that a new/delete costs about 70 mus on a 300 MHz HP, // // O(10^9) new/deletes will save about 19 hours. // // // // NOTE 1 // ====== // C/C++ offers the possibility of allocating and deleting memory. // Forgetting to delete allocated memory is a programming error called a // "memory leak", i.e. the memory of your process grows and eventually // your program crashes. Even if you *always* delete the allocated // memory, the recovered space may not be efficiently reused. The // process knows that there are portions of free memory, but when you // allocate it again, a fresh piece of memory is grabbed. Your program // is free from semantic errors, but the total memory of your process // still grows, because your program's memory is full of "holes" which // reduce the efficiency of memory access; this is called "memory // fragmentation". Moreover new / delete are expensive operations in // terms of CPU time. // // Without entering into technical details, TClonesArray allows you to // "reuse" the same portion of memory for new/delete avoiding memory // fragmentation and memory growth and improving the performance by // orders of magnitude. Every time the memory of the TClonesArray has // to be reused, the Clear() method is used. To provide its benefits, // each TClonesArray must be allocated *once* per process and disposed // of (deleted) *only when not needed any more*. // // So a job should see *only one* deletion for each TClonesArray, // which should be Clear()ed during the job several times. Deleting a // TClonesArray is a double waste. Not only you do not avoid memory // fragmentation, but you worsen it because the TClonesArray itself // is a rather heavy structure, and there is quite some code in the // destructor, so you have more memory fragmentation and slower code. // // NOTE 2 // ====== // // When investigating misuse of TClonesArray, please make sure of the following: // // * Use Clear() or Clear("C") instead of Delete(). This will improve // program execution time. // * TClonesArray object classes containing pointers allocate memory. // To avoid causing memory leaks, special Clear("C") must be used // for clearing TClonesArray. When option "C" is specified, ROOT // automatically executes the Clear() method (by default it is // empty contained in TObject). This method must be overridden in // the relevant TClonesArray object class, implementing the reset // procedure for pointer objects. // * If the objects are added using the placement new then the Clear must // deallocate the memory. // * If the objects are added using TClonesArray::ConstructedAt then the // heap-based memory can stay allocated and reused as the constructor is // not called for already constructed/added object. // * To reduce memory fragmentation, please make sure that the // TClonesArrays are not destroyed and created on every event. They // must only be constructed/destructed at the beginning/end of the // run. // ////////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include "TClonesArray.h" #include "TError.h" #include "TROOT.h" #include "TClass.h" #include "TObjectTable.h" ClassImp(TClonesArray) //______________________________________________________________________________ TClonesArray::TClonesArray() : TObjArray() { // Default Constructor. fClass = 0; fKeep = 0; } //______________________________________________________________________________ TClonesArray::TClonesArray(const char *classname, Int_t s, Bool_t) : TObjArray(s) { // Create an array of clone objects of classname. The class must inherit from // TObject. If the class defines its own operator delete(), make sure that // it looks like this: // // void MyClass::operator delete(void *vp) // { // if ((Long_t) vp != TObject::GetDtorOnly()) // ::operator delete(vp); // delete space // else // TObject::SetDtorOnly(0); // } // // The second argument s indicates an approximate number of objects // that will be entered in the array. If more than s objects are entered, // the array will be automatically expanded. // // The third argument is not used anymore and only there for backward // compatibility reasons. fKeep = 0; SetClass(classname,s); } //______________________________________________________________________________ TClonesArray::TClonesArray(const TClass *cl, Int_t s, Bool_t) : TObjArray(s) { // Create an array of clone objects of class cl. The class must inherit from // TObject. If the class defines an own operator delete(), make sure that // it looks like this: // // void MyClass::operator delete(void *vp) // { // if ((Long_t) vp != TObject::GetDtorOnly()) // ::operator delete(vp); // delete space // else // TObject::SetDtorOnly(0); // } // // The second argument, s, indicates an approximate number of objects // that will be entered in the array. If more than s objects are entered, // the array will be automatically expanded. // // The third argument is not used anymore and only there for backward // compatibility reasons. fKeep = 0; SetClass(cl,s); } //______________________________________________________________________________ TClonesArray::TClonesArray(const TClonesArray& tc): TObjArray(tc) { // Copy ctor. fKeep = new TObjArray(tc.fSize); fClass = tc.fClass; BypassStreamer(kTRUE); for (Int_t i = 0; i < fSize; i++) { if (tc.fCont[i]) fCont[i] = tc.fCont[i]->Clone(); fKeep->fCont[i] = fCont[i]; } } //______________________________________________________________________________ TClonesArray& TClonesArray::operator=(const TClonesArray& tc) { // Assignment operator. if (this == &tc) return *this; if (fClass != tc.fClass) { Error("operator=", "cannot copy TClonesArray's when classes are different"); return *this; } if (tc.fSize > fSize) Expand(TMath::Max(tc.fSize, GrowBy(fSize))); Int_t i; for (i = 0; i < fSize; i++) if (fKeep->fCont[i]) { if (TObject::GetObjectStat() && gObjectTable) gObjectTable->RemoveQuietly(fKeep->fCont[i]); ::operator delete(fKeep->fCont[i]); fKeep->fCont[i] = 0; fCont[i] = 0; } BypassStreamer(kTRUE); for (i = 0; i < tc.fSize; i++) { if (tc.fCont[i]) fKeep->fCont[i] = tc.fCont[i]->Clone(); fCont[i] = fKeep->fCont[i]; } fLast = tc.fLast; Changed(); return *this; } //______________________________________________________________________________ TClonesArray::~TClonesArray() { // Delete a clones array. if (fKeep) { for (Int_t i = 0; i < fKeep->fSize; i++) { TObject* p = fKeep->fCont[i]; if (p && p->TestBit(kNotDeleted)) { // -- The TObject destructor has not been called. fClass->Destructor(p); fKeep->fCont[i] = 0; } else { // -- The TObject destructor was called, just free memory. // // remove any possible entries from the ObjectTable if (TObject::GetObjectStat() && gObjectTable) { gObjectTable->RemoveQuietly(p); } ::operator delete(p); fKeep->fCont[i] = 0; } } } SafeDelete(fKeep); // Protect against erroneously setting of owner bit SetOwner(kFALSE); } //______________________________________________________________________________ void TClonesArray::BypassStreamer(Bool_t bypass) { // When the kBypassStreamer bit is set, the automatically // generated Streamer can call directly TClass::WriteBuffer. // Bypassing the Streamer improves the performance when writing/reading // the objects in the TClonesArray. However there is a drawback: // When a TClonesArray is written with split=0 bypassing the Streamer, // the StreamerInfo of the class in the array being optimized, // one cannot use later the TClonesArray with split>0. For example, // there is a problem with the following scenario: // 1- A class Foo has a TClonesArray of Bar objects // 2- The Foo object is written with split=0 to Tree T1. // In this case the StreamerInfo for the class Bar is created // in optimized mode in such a way that data members of the same type // are written as an array improving the I/O performance. // 3- In a new program, T1 is read and a new Tree T2 is created // with the object Foo in split>1 // 4- When the T2 branch is created, the StreamerInfo for the class Bar // is created with no optimization (mandatory for the split mode). // The optimized Bar StreamerInfo is going to be used to read // the TClonesArray in T1. The result will be Bar objects with // data member values not in the right sequence. // The solution to this problem is to call BypassStreamer(kFALSE) // for the TClonesArray. In this case, the normal Bar::Streamer function // will be called. The Bar::Streamer function works OK independently // if the Bar StreamerInfo had been generated in optimized mode or not. if (bypass) SetBit(kBypassStreamer); else ResetBit(kBypassStreamer); } //______________________________________________________________________________ void TClonesArray::Compress() { // Remove empty slots from array. Int_t j = 0, je = 0; TObject **tmp = new TObject* [fSize]; for (Int_t i = 0; i < fSize; i++) { if (fCont[i]) { fCont[j] = fCont[i]; fKeep->fCont[j] = fKeep->fCont[i]; j++; } else { tmp[je] = fKeep->fCont[i]; je++; } } fLast = j - 1; Int_t jf = 0; for ( ; j < fSize; j++) { fCont[j] = 0; fKeep->fCont[j] = tmp[jf]; jf++; } delete [] tmp; R__ASSERT(je == jf); } //______________________________________________________________________________ TObject *TClonesArray::ConstructedAt(Int_t idx) { // Get an object at index 'idx' that is guaranteed to have been constructed. // It might be either a freshly allocated object or one that had already been // allocated (and assumingly used). In the later case, it is the callers // responsability to insure that the object is returned to a known state, // usually by calling the Clear method on the TClonesArray. // // Tests to see if the destructor has been called on the object. // If so, or if the object has never been constructed the class constructor is called using // New(). If not, return a pointer to the correct memory location. // This explicitly to deal with TObject classes that allocate memory // which will be reset (but not deallocated) in their Clear() // functions. TObject *obj = (*this)[idx]; if ( obj && obj->TestBit(TObject::kNotDeleted) ) { return obj; } return (fClass) ? static_cast<TObject*>(fClass->New(obj)) : 0; } //______________________________________________________________________________ TObject *TClonesArray::ConstructedAt(Int_t idx, Option_t *clear_options) { // Get an object at index 'idx' that is guaranteed to have been constructed. // It might be either a freshly allocated object or one that had already been // allocated (and assumingly used). In the later case, the function Clear // will be called and passed the value of 'clear_options' // // Tests to see if the destructor has been called on the object. // If so, or if the object has never been constructed the class constructor is called using // New(). If not, return a pointer to the correct memory location. // This explicitly to deal with TObject classes that allocate memory // which will be reset (but not deallocated) in their Clear() // functions. TObject *obj = (*this)[idx]; if ( obj && obj->TestBit(TObject::kNotDeleted) ) { obj->Clear(clear_options); return obj; } return (fClass) ? static_cast<TObject*>(fClass->New(obj)) : 0; } //______________________________________________________________________________ void TClonesArray::Clear(Option_t *option) { // Clear the clones array. Only use this routine when your objects don't // allocate memory since it will not call the object dtors. // However, if the class in the TClonesArray implements the function // Clear(Option_t *option) and if option = "C" the function Clear() // is called for all objects in the array. In the function Clear(), one // can delete objects or dynamic arrays allocated in the class. // This procedure is much faster than calling TClonesArray::Delete(). // When the option starts with "C+", eg "C+xyz" the objects in the array // are in turn cleared with the option "xyz" if (option && option[0] == 'C') { const char *cplus = strstr(option,"+"); if (cplus) { cplus = cplus + 1; } else { cplus = ""; } Int_t n = GetEntriesFast(); for (Int_t i = 0; i < n; i++) { TObject *obj = UncheckedAt(i); if (obj) { obj->Clear(cplus); obj->ResetBit( kHasUUID ); obj->ResetBit( kIsReferenced ); obj->SetUniqueID( 0 ); } } } // Protect against erroneously setting of owner bit SetOwner(kFALSE); TObjArray::Clear(); } //______________________________________________________________________________ void TClonesArray::Delete(Option_t *) { // Clear the clones array. Use this routine when your objects allocate // memory (e.g. objects inheriting from TNamed or containing TStrings // allocate memory). If not you better use Clear() since if is faster. if ( fClass->TestBit(TClass::kIsEmulation) ) { // In case of emulated class, we can not use the delete operator // directly, it would use the wrong destructor. for (Int_t i = 0; i < fSize; i++) { if (fCont[i] && fCont[i]->TestBit(kNotDeleted)) { fClass->Destructor(fCont[i],kTRUE); } } } else { Long_t dtoronly = TObject::GetDtorOnly(); for (Int_t i = 0; i < fSize; i++) { if (fCont[i] && fCont[i]->TestBit(kNotDeleted)) { // Tell custom operator delete() not to delete space when // object fCont[i] is deleted. Only destructors are called // for this object. TObject::SetDtorOnly(fCont[i]); delete fCont[i]; } } // Restore the state. TObject::SetDtorOnly((void*)dtoronly); } // Protect against erroneously setting of owner bit. SetOwner(kFALSE); TObjArray::Clear(); } //______________________________________________________________________________ void TClonesArray::Expand(Int_t newSize) { // Expand or shrink the array to newSize elements. if (newSize < 0) { Error ("Expand", "newSize must be positive (%d)", newSize); return; } if (newSize == fSize) return; if (newSize < fSize) { // release allocated space in fKeep and set to 0 so // Expand() will shrink correctly for (int i = newSize; i < fSize; i++) if (fKeep->fCont[i]) { if (TObject::GetObjectStat() && gObjectTable) gObjectTable->RemoveQuietly(fKeep->fCont[i]); ::operator delete(fKeep->fCont[i]); fKeep->fCont[i] = 0; } } TObjArray::Expand(newSize); fKeep->Expand(newSize); } //______________________________________________________________________________ void TClonesArray::ExpandCreate(Int_t n) { // Expand or shrink the array to n elements and create the clone // objects by calling their default ctor. If n is less than the current size // the array is shrunk and the allocated space is freed. // This routine is typically used to create a clonesarray into which // one can directly copy object data without going via the // "new (arr[i]) MyObj()" (i.e. the vtbl is already set correctly). if (n < 0) { Error("ExpandCreate", "n must be positive (%d)", n); return ; } if (n > fSize) Expand(TMath::Max(n, GrowBy(fSize))); Int_t i; for (i = 0; i < n; i++) { if (!fKeep->fCont[i]) { fKeep->fCont[i] = (TObject*)fClass->New(); } else if (!fKeep->fCont[i]->TestBit(kNotDeleted)) { // The object has been deleted (or never initialized) fClass->New(fKeep->fCont[i]); } fCont[i] = fKeep->fCont[i]; } for (i = n; i < fSize; i++) if (fKeep->fCont[i]) { if (TObject::GetObjectStat() && gObjectTable) gObjectTable->RemoveQuietly(fKeep->fCont[i]); ::operator delete(fKeep->fCont[i]); fKeep->fCont[i] = 0; fCont[i] = 0; } fLast = n - 1; Changed(); } //______________________________________________________________________________ void TClonesArray::ExpandCreateFast(Int_t n) { // Expand or shrink the array to n elements and create the clone // objects by calling their default ctor. If n is less than the current size // the array is shrinked but the allocated space is _not_ freed. // This routine is typically used to create a clonesarray into which // one can directly copy object data without going via the // "new (arr[i]) MyObj()" (i.e. the vtbl is already set correctly). // This is a simplified version of ExpandCreate used in the TTree mechanism. Int_t oldSize = fKeep->GetSize(); if (n > fSize) Expand(TMath::Max(n, GrowBy(fSize))); Int_t i; for (i = 0; i < n; i++) { if (i >= oldSize || !fKeep->fCont[i]) { fKeep->fCont[i] = (TObject*)fClass->New(); } else if (!fKeep->fCont[i]->TestBit(kNotDeleted)) { // The object has been deleted (or never initialized) fClass->New(fKeep->fCont[i]); } fCont[i] = fKeep->fCont[i]; } if (fLast >= n) { memset(fCont + n, 0, (fLast - n + 1) * sizeof(TObject*)); } fLast = n - 1; Changed(); } //______________________________________________________________________________ TObject *TClonesArray::RemoveAt(Int_t idx) { // Remove object at index idx. if (!BoundsOk("RemoveAt", idx)) return 0; int i = idx-fLowerBound; if (fCont[i] && fCont[i]->TestBit(kNotDeleted)) { // Tell custom operator delete() not to delete space when // object fCont[i] is deleted. Only destructors are called // for this object. Long_t dtoronly = TObject::GetDtorOnly(); TObject::SetDtorOnly(fCont[i]); delete fCont[i]; TObject::SetDtorOnly((void*)dtoronly); } if (fCont[i]) { fCont[i] = 0; // recalculate array size if (i == fLast) do { fLast--; } while (fLast >= 0 && fCont[fLast] == 0); Changed(); } return 0; } //______________________________________________________________________________ TObject *TClonesArray::Remove(TObject *obj) { // Remove object from array. if (!obj) return 0; Int_t i = IndexOf(obj) - fLowerBound; if (i == -1) return 0; if (fCont[i] && fCont[i]->TestBit(kNotDeleted)) { // Tell custom operator delete() not to delete space when // object fCont[i] is deleted. Only destructors are called // for this object. Long_t dtoronly = TObject::GetDtorOnly(); TObject::SetDtorOnly(fCont[i]); delete fCont[i]; TObject::SetDtorOnly((void*)dtoronly); } fCont[i] = 0; // recalculate array size if (i == fLast) do { fLast--; } while (fLast >= 0 && fCont[fLast] == 0); Changed(); return obj; } //______________________________________________________________________________ void TClonesArray::RemoveRange(Int_t idx1, Int_t idx2) { // Remove objects from index idx1 to idx2 included. if (!BoundsOk("RemoveRange", idx1)) return; if (!BoundsOk("RemoveRange", idx2)) return; Long_t dtoronly = TObject::GetDtorOnly(); idx1 -= fLowerBound; idx2 -= fLowerBound; Bool_t change = kFALSE; for (TObject **obj=fCont+idx1; obj<=fCont+idx2; obj++) { if (!*obj) continue; if ((*obj)->TestBit(kNotDeleted)) { // Tell custom operator delete() not to delete space when // object fCont[i] is deleted. Only destructors are called // for this object. TObject::SetDtorOnly(*obj); delete *obj; } *obj = 0; change = kTRUE; } TObject::SetDtorOnly((void*)dtoronly); // recalculate array size if (change) Changed(); if (idx1 < fLast || fLast > idx2) return; do { fLast--; } while (fLast >= 0 && fCont[fLast] == 0); } //______________________________________________________________________________ void TClonesArray::SetClass(const TClass *cl, Int_t s) { // Create an array of clone objects of class cl. The class must inherit from // TObject. If the class defines an own operator delete(), make sure that // it looks like this: // // void MyClass::operator delete(void *vp) // { // if ((Long_t) vp != TObject::GetDtorOnly()) // ::operator delete(vp); // delete space // else // TObject::SetDtorOnly(0); // } // // The second argument s indicates an approximate number of objects // that will be entered in the array. If more than s objects are entered, // the array will be automatically expanded. // // NB: This function should not be called in the TClonesArray is already // initialized with a class. if (fKeep) { Error("SetClass", "TClonesArray already initialized with another class"); return; } fClass = (TClass*)cl; if (!fClass) { MakeZombie(); Error("SetClass", "called with a null pointer"); return; } const char *classname = fClass->GetName(); if (!fClass->IsTObject()) { MakeZombie(); Error("SetClass", "%s does not inherit from TObject", classname); return; } if (fClass->GetBaseClassOffset(TObject::Class())!=0) { MakeZombie(); Error("SetClass", "%s must inherit from TObject as the left most base class.", classname); return; } Int_t nch = strlen(classname)+2; char *name = new char[nch]; snprintf(name,nch, "%ss", classname); SetName(name); delete [] name; fKeep = new TObjArray(s); BypassStreamer(kTRUE); } //______________________________________________________________________________ void TClonesArray::SetClass(const char *classname, Int_t s) { //see TClonesArray::SetClass(const TClass*) SetClass(TClass::GetClass(classname),s); } //______________________________________________________________________________ void TClonesArray::SetOwner(Bool_t /* enable */) { // A TClonesArray is always the owner of the object it contains. // However the collection its inherits from (TObjArray) does not. // Hence this member function needs to be a nop for TClonesArray. // Nothing to be done. } //______________________________________________________________________________ void TClonesArray::Sort(Int_t upto) { // If objects in array are sortable (i.e. IsSortable() returns true // for all objects) then sort array. Int_t nentries = GetAbsLast()+1; if (nentries <= 0 || fSorted) return; for (Int_t i = 0; i < fSize; i++) if (fCont[i]) { if (!fCont[i]->IsSortable()) { Error("Sort", "objects in array are not sortable"); return; } } QSort(fCont, fKeep->fCont, 0, TMath::Min(nentries, upto-fLowerBound)); fLast = -2; fSorted = kTRUE; } //_______________________________________________________________________ void TClonesArray::Streamer(TBuffer &b) { // Write all objects in array to the I/O buffer. ATTENTION: empty slots // are also stored (using one byte per slot). If you don't want this // use a TOrdCollection or TList. // Important Note: if you modify this function, remember to also modify // TConvertClonesArrayToProxy accordingly Int_t nobjects; char nch; TString s, classv; UInt_t R__s, R__c; if (b.IsReading()) { Version_t v = b.ReadVersion(&R__s, &R__c); if (v == 3) { const Int_t kOldBypassStreamer = BIT(14); if (TestBit(kOldBypassStreamer)) BypassStreamer(); } if (v > 2) TObject::Streamer(b); if (v > 1) fName.Streamer(b); s.Streamer(b); classv = s; Int_t clv = 0; Ssiz_t pos = s.Index(";"); if (pos != kNPOS) { classv = s(0, pos); s = s(pos+1, s.Length()-pos-1); clv = s.Atoi(); } TClass *cl = TClass::GetClass(classv); if (!cl) { printf("TClonesArray::Streamer expecting class %s\n", classv.Data()); b.CheckByteCount(R__s, R__c,TClonesArray::IsA()); return; } b >> nobjects; if (nobjects < 0) nobjects = -nobjects; // still there for backward compatibility b >> fLowerBound; if (fClass == 0 && fKeep == 0) { fClass = cl; fKeep = new TObjArray(fSize); Expand(nobjects); } if (cl != fClass) { fClass = cl; //this case may happen when switching from an emulated class to the real class //may not be an error. fClass may point to a deleted object //Error("Streamer", "expecting objects of type %s, finding objects" // " of type %s", fClass->GetName(), cl->GetName()); //return; } // make sure there are enough slots in the fKeep array if (fKeep->GetSize() < nobjects) Expand(nobjects); //reset fLast. nobjects may be 0 Int_t oldLast = fLast; fLast = nobjects-1; //TStreamerInfo *sinfo = fClass->GetStreamerInfo(clv); if (CanBypassStreamer() && !b.TestBit(TBuffer::kCannotHandleMemberWiseStreaming)) { for (Int_t i = 0; i < nobjects; i++) { if (!fKeep->fCont[i]) { fKeep->fCont[i] = (TObject*)fClass->New(); } else if (!fKeep->fCont[i]->TestBit(kNotDeleted)) { // The object has been deleted (or never initialized) fClass->New(fKeep->fCont[i]); } fCont[i] = fKeep->fCont[i]; } //sinfo->ReadBufferClones(b,this,nobjects,-1,0); b.ReadClones(this,nobjects,clv); } else { for (Int_t i = 0; i < nobjects; i++) { b >> nch; if (nch) { if (!fKeep->fCont[i]) fKeep->fCont[i] = (TObject*)fClass->New(); else if (!fKeep->fCont[i]->TestBit(kNotDeleted)) { // The object has been deleted (or never initialized) fClass->New(fKeep->fCont[i]); } fCont[i] = fKeep->fCont[i]; b.StreamObject(fKeep->fCont[i]); } } } for (Int_t i = TMath::Max(nobjects,0); i < oldLast+1; ++i) fCont[i] = 0; Changed(); b.CheckByteCount(R__s, R__c,TClonesArray::IsA()); } else { //Make sure TStreamerInfo is not optimized, otherwise it will not be //possible to support schema evolution in read mode. //In case the StreamerInfo has already been computed and optimized, //one must disable the option BypassStreamer b.ForceWriteInfoClones(this); // make sure the status of bypass streamer is part of the buffer // (bits in TObject), so that when reading the object the right // mode is used, independent of the method (e.g. written via // TMessage, received and stored to a file and then later read via // TBufferFile) Bool_t bypass = kFALSE; if (b.TestBit(TBuffer::kCannotHandleMemberWiseStreaming)) { bypass = CanBypassStreamer(); BypassStreamer(kFALSE); } R__c = b.WriteVersion(TClonesArray::IsA(), kTRUE); TObject::Streamer(b); fName.Streamer(b); s.Form("%s;%d", fClass->GetName(), fClass->GetClassVersion()); s.Streamer(b); nobjects = GetEntriesFast(); b << nobjects; b << fLowerBound; if (CanBypassStreamer()) { b.WriteClones(this,nobjects); } else { for (Int_t i = 0; i < nobjects; i++) { if (!fCont[i]) { nch = 0; b << nch; } else { nch = 1; b << nch; b.StreamObject(fCont[i]); } } } b.SetByteCount(R__c, kTRUE); if (bypass) BypassStreamer(); } } //______________________________________________________________________________ TObject *&TClonesArray::operator[](Int_t idx) { // Return pointer to reserved area in which a new object of clones // class can be constructed. This operator should not be used for // lefthand side assignments, like a[2] = xxx. Only like, // new (a[2]) myClass, or xxx = a[2]. Of course right hand side usage // is only legal after the object has been constructed via the // new operator or via the New() method. To remove elements from // the clones array use Remove() or RemoveAt(). if (idx < 0) { Error("operator[]", "out of bounds at %d in %lx", idx, (Long_t)this); return fCont[0]; } if (!fClass) { Error("operator[]", "invalid class specified in TClonesArray ctor"); return fCont[0]; } if (idx >= fSize) Expand(TMath::Max(idx+1, GrowBy(fSize))); if (!fKeep->fCont[idx]) { fKeep->fCont[idx] = (TObject*) TStorage::ObjectAlloc(fClass->Size()); // Reset the bit so that: // obj = myClonesArray[i]; // obj->TestBit(TObject::kNotDeleted) // will behave correctly. // TObject::kNotDeleted is one of the higher bit that is not settable via the public // interface. But luckily we are its friend. fKeep->fCont[idx]->fBits &= ~kNotDeleted; } fCont[idx] = fKeep->fCont[idx]; fLast = TMath::Max(idx, GetAbsLast()); Changed(); return fCont[idx]; } //______________________________________________________________________________ TObject *TClonesArray::operator[](Int_t idx) const { // Return the object at position idx. Returns 0 if idx is out of bounds. if (idx < 0 || idx >= fSize) { Error("operator[]", "out of bounds at %d in %lx", idx, (Long_t)this); return 0; } return fCont[idx]; } //______________________________________________________________________________ TObject *TClonesArray::New(Int_t idx) { // Create an object of type fClass with the default ctor at the specified // index. Returns 0 in case of error. if (idx < 0) { Error("New", "out of bounds at %d in %lx", idx, (Long_t)this); return 0; } if (!fClass) { Error("New", "invalid class specified in TClonesArray ctor"); return 0; } return (TObject *)fClass->New(operator[](idx)); } //______________________________________________________________________________ // // The following functions are utilities implemented by Jason Detwiler // (jadetwiler@lbl.gov) // //______________________________________________________________________________ void TClonesArray::AbsorbObjects(TClonesArray *tc) { // Directly move the object pointers from tc without cloning (copying). // This TClonesArray takes over ownership of all of tc's object // pointers. The tc array is left empty upon return. // tests if (tc == 0 || tc == this || tc->GetEntriesFast() == 0) return; if (fClass != tc->fClass) { Error("AbsorbObjects", "cannot absorb objects when classes are different"); return; } // cache the sorted status Bool_t wasSorted = IsSorted() && tc->IsSorted() && (Last() == 0 || Last()->Compare(tc->First()) == -1); // expand this Int_t oldSize = GetEntriesFast(); Int_t newSize = oldSize + tc->GetEntriesFast(); if(newSize > fSize) Expand(newSize); // move for (Int_t i = 0; i < tc->GetEntriesFast(); ++i) { fCont[oldSize+i] = tc->fCont[i]; (*fKeep)[oldSize+i] = (*(tc->fKeep))[i]; tc->fCont[i] = 0; (*(tc->fKeep))[i] = 0; } // cleanup fLast = newSize-1; tc->fLast = -1; if (!wasSorted) Changed(); } //______________________________________________________________________________ void TClonesArray::AbsorbObjects(TClonesArray *tc, Int_t idx1, Int_t idx2) { // Directly move the range of object pointers from tc without cloning // (copying). // This TClonesArray takes over ownership of all of tc's object pointers // from idx1 to idx2. The tc array is re-arranged by return. // tests if (tc == 0 || tc == this || tc->GetEntriesFast() == 0) return; if (fClass != tc->fClass) { Error("AbsorbObjects", "cannot absorb objects when classes are different"); return; } if (idx1 > idx2) { Error("AbsorbObjects", "range is not valid: idx1>idx2"); return; } // cache the sorted status Bool_t wasSorted = IsSorted() && tc->IsSorted() && (Last() == 0 || Last()->Compare(tc->First()) == -1); // expand this Int_t oldSize = GetEntriesFast(); Int_t newSize = oldSize + (idx2-idx1+1); if(newSize > fSize) Expand(newSize); // move for (Int_t i = idx1; i <= idx2; i++) { Int_t newindex = oldSize+i -idx1; fCont[newindex] = tc->fCont[i]; ::operator delete(fKeep->fCont[newindex]); (*fKeep)[newindex] = (*(tc->fKeep))[i]; tc->fCont[i] = 0; (*(tc->fKeep))[i] = 0; } // cleanup for (Int_t i = idx2+1; i < tc->GetEntriesFast(); i++) { tc->fCont[i-(idx2-idx1+1)] = tc->fCont[i]; (*(tc->fKeep))[i-(idx2-idx1+1)] = (*(tc->fKeep))[i]; tc->fCont[i] = 0; (*(tc->fKeep))[i] = 0; } tc->fLast = tc->GetEntriesFast() - 2 - (idx2 - idx1); fLast = newSize-1; if (!wasSorted) Changed(); } //______________________________________________________________________________ void TClonesArray::MultiSort(Int_t nTCs, TClonesArray** tcs, Int_t upto) { // Sort multiple TClonesArrays simultaneously with this array. // If objects in array are sortable (i.e. IsSortable() returns true // for all objects) then sort array. Int_t nentries = GetAbsLast()+1; if (nentries <= 1 || fSorted) return; Bool_t sortedCheck = kTRUE; for (Int_t i = 0; i < fSize; i++) { if (fCont[i]) { if (!fCont[i]->IsSortable()) { Error("MultiSort", "objects in array are not sortable"); return; } } if (sortedCheck && i > 1) { if (ObjCompare(fCont[i], fCont[i-1]) < 0) sortedCheck = kFALSE; } } if (sortedCheck) { fSorted = kTRUE; return; } for (int i = 0; i < nTCs; i++) { if (tcs[i] == this) { Error("MultiSort", "tcs[%d] = \"this\"", i); return; } if (tcs[i]->GetEntriesFast() != GetEntriesFast()) { Error("MultiSort", "tcs[%d] has length %d != length of this (%d)", i, tcs[i]->GetEntriesFast(), this->GetEntriesFast()); return; } } int nBs = nTCs*2+1; TObject*** b = new TObject**[nBs]; for (int i = 0; i < nTCs; i++) { b[2*i] = tcs[i]->fCont; b[2*i+1] = tcs[i]->fKeep->fCont; } b[nBs-1] = fKeep->fCont; QSort(fCont, nBs, b, 0, TMath::Min(nentries, upto-fLowerBound)); delete [] b; fLast = -2; fSorted = kTRUE; }
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id $ */ //------------------------------------------------------------------------- // The small angle absorber SAA (beam shield) // Author: A.Morsch // andreas.morsch@cern.ch //------------------------------------------------------------------------- #include <TVirtualMC.h> #include <TArrayI.h> #include <TGeoVolume.h> #include <TGeoTube.h> #include <TGeoManager.h> #include <TGeoMatrix.h> #include <TGeoCompositeShape.h> #include <TGeoBBox.h> #include <TGeoPgon.h> #include <TGeoCone.h> #include "AliSHILv3.h" #include "AliConst.h" #include "AliLog.h" ClassImp(AliSHILv3) //_____________________________________________________________________________ AliSHILv3::AliSHILv3() { // // Default constructor for muon shield // } //_____________________________________________________________________________ AliSHILv3::AliSHILv3(const char *name, const char *title) : AliSHIL(name,title) { // // Standard constructor for muon shield // } //_____________________________________________________________________________ void AliSHILv3::CreateGeometry() { // // The geometry of the small angle absorber "Beam Shield" // Float_t dz, dr, z, rmax; // // The top volume // TGeoVolume* top = gGeoManager->GetVolume("ALIC"); // Rotations TGeoRotation* rot000 = new TGeoRotation("rot000", 90., 0., 90., 90., 0., 0.); TGeoRotation* rot090 = new TGeoRotation("rot090", 90., 90., 90., 180., 0., 0.); TGeoRotation* rot180 = new TGeoRotation("rot180", 90., 180., 90., 270., 0., 0.); TGeoRotation* rot270 = new TGeoRotation("rot270", 90., 270., 90., 0., 0., 0.); Float_t alhc = 0.794; TGeoRotation* rotxzlhc = new TGeoRotation("rotxzlhc", 0., -alhc, 0.); TGeoRotation* rotlhc = new TGeoRotation("rotlhc", 0., alhc, 0.); // // Media // TGeoMedium* kMedNiW = gGeoManager->GetMedium("SHIL_Ni/W0"); TGeoMedium* kMedNiWsh = gGeoManager->GetMedium("SHIL_Ni/W3"); // TGeoMedium* kMedSteel = gGeoManager->GetMedium("SHIL_ST_C0"); TGeoMedium* kMedSteelSh = gGeoManager->GetMedium("SHIL_ST_C3"); // TGeoMedium* kMedAir = gGeoManager->GetMedium("SHIL_AIR_C0"); TGeoMedium* kMedAirMu = gGeoManager->GetMedium("SHIL_AIR_MUON"); // TGeoMedium* kMedPb = gGeoManager->GetMedium("SHIL_PB_C0"); TGeoMedium* kMedPbSh = gGeoManager->GetMedium("SHIL_PB_C2"); // TGeoMedium* kMedConcSh = gGeoManager->GetMedium("SHIL_CC_C2"); // const Float_t kDegRad = TMath::Pi() / 180.; const Float_t kAngle02 = TMath::Tan( 2.00 * kDegRad); const Float_t kAngle0071 = TMath::Tan( 0.71 * kDegRad); /////////////////////////////////// // FA Tungsten Tail // // Drawing ALIP2A__0049 // // Drawing ALIP2A__0111 // /////////////////////////////////// // // The tail as built is shorter than in drawing ALIP2A__0049. // The CDD data base has to be updated ! // // Inner radius at the entrance of the flange Float_t rInFaWTail1 = 13.98/2.; // Outer radius at the entrance of the flange Float_t rOuFaWTail1 = 52.00/2.; // Outer radius at the end of the section inside the FA Float_t rOuFaWTail2 = 35.27/2.; // Length of the Flange section inside the FA Float_t dzFaWTail1 = 6.00; // Length of the Flange section ouside the FA Float_t dzFaWTail2 = 12.70; // Inner radius at the end of the section inside the FA Float_t rInFaWTail2 = rInFaWTail1 + dzFaWTail1 * kAngle0071; // Inner radius at the end of the flange Float_t rInFaWTail3 = rInFaWTail2 + dzFaWTail2 * kAngle0071; // Outer radius at the end of the flange Float_t rOuFaWTail3 = rOuFaWTail2 + dzFaWTail2 * kAngle02; // Outer radius of the recess for station 1 Float_t rOuFaWTailR = 30.8/2.; // Length of the recess Float_t dzFaWTailR = 36.00; // Inner radiues at the end of the recess Float_t rInFaWTail4 = rInFaWTail3 + dzFaWTailR * kAngle0071; // Outer radius at the end of the recess Float_t rOuFaWTail4 = rOuFaWTail3 + dzFaWTailR * kAngle02; // Inner radius of the straight section Float_t rInFaWTailS = 22.30/2.; // Length of the bulge Float_t dzFaWTailB = 13.0; // Outer radius at the end of the bulge Float_t rOuFaWTailB = rOuFaWTail4 + dzFaWTailB * kAngle02; // Outer radius at the end of the tail Float_t rOuFaWTailE = 31.6/2.; // Total length of the tail Float_t dzFaWTail = 70.7; TGeoPcon* shFaWTail = new TGeoPcon(0., 360., 10); z = 0.; // Flange section inside FA shFaWTail->DefineSection(0, z, rInFaWTail1, rOuFaWTail1); z += dzFaWTail1; shFaWTail->DefineSection(1, z, rInFaWTail2, rOuFaWTail1); shFaWTail->DefineSection(2, z, rInFaWTail2, rOuFaWTail2); // Flange section outside FA z += dzFaWTail2; shFaWTail->DefineSection(3, z, rInFaWTail3, rOuFaWTail3); shFaWTail->DefineSection(4, z, rInFaWTail3, rOuFaWTailR); // Recess Station 1 z += dzFaWTailR; shFaWTail->DefineSection(5, z, rInFaWTail4, rOuFaWTailR); shFaWTail->DefineSection(6, z, rInFaWTailS, rOuFaWTail4); // Bulge z += dzFaWTailB; shFaWTail->DefineSection(7, z, rInFaWTailS, rOuFaWTailB); shFaWTail->DefineSection(8, z, rInFaWTailS, rOuFaWTailE); // End z = dzFaWTail; shFaWTail->DefineSection(9, z, rInFaWTailS, rOuFaWTailE); TGeoVolume* voFaWTail = new TGeoVolume("YFaWTail", shFaWTail, kMedNiW); // // Define an inner region with higher transport cuts TGeoPcon* shFaWTailI = new TGeoPcon(0., 360., 4); z = 0.; dr = 3.5; shFaWTailI->DefineSection(0, z, rInFaWTail1, rInFaWTail1 + dr); z += (dzFaWTail1 + dzFaWTail2 + dzFaWTailR); shFaWTailI->DefineSection(1, z, rInFaWTail4, rInFaWTail4 + dr); shFaWTailI->DefineSection(2, z, rInFaWTailS, rInFaWTailS + dr); z = dzFaWTail; shFaWTailI->DefineSection(3, z, rInFaWTailS, rInFaWTailS + dr); TGeoVolume* voFaWTailI = new TGeoVolume("YFaWTailI", shFaWTailI, kMedNiWsh); voFaWTail->AddNode(voFaWTailI, 1, gGeoIdentity); /////////////////////////////////// // // // Recess Station 1 // // Drawing ALIP2A__0260 // /////////////////////////////////// /////////////////////////////////// // FA W-Ring 2 // // Drawing ALIP2A__0220 // /////////////////////////////////// const Float_t kFaWring2Rinner = 15.40; const Float_t kFaWring2Router = 18.40; const Float_t kFaWring2HWidth = 3.75; const Float_t kFaWring2Cutoffx = 3.35; const Float_t kFaWring2Cutoffy = 3.35; TGeoTubeSeg* shFaWring2a = new TGeoTubeSeg(kFaWring2Rinner, kFaWring2Router, kFaWring2HWidth, 0., 90.); shFaWring2a->SetName("shFaWring2a"); TGeoBBox* shFaWring2b = new TGeoBBox(kFaWring2Router / 2., kFaWring2Router / 2., kFaWring2HWidth); shFaWring2b->SetName("shFaWring2b"); TGeoTranslation* trFaWring2b = new TGeoTranslation("trFaWring2b", kFaWring2Router / 2. + kFaWring2Cutoffx, kFaWring2Router / 2. + kFaWring2Cutoffy, 0.); trFaWring2b->RegisterYourself(); TGeoCompositeShape* shFaWring2 = new TGeoCompositeShape("shFaWring2", "(shFaWring2a)*(shFaWring2b:trFaWring2b)"); TGeoVolume* voFaWring2 = new TGeoVolume("YFA_WRING2", shFaWring2, kMedNiW); /////////////////////////////////// // FA W-Ring 3 // // Drawing ALIP2A__0219 // /////////////////////////////////// const Float_t kFaWring3Rinner = 15.40; const Float_t kFaWring3Router = 18.40; const Float_t kFaWring3HWidth = 3.75; const Float_t kFaWring3Cutoffx = 3.35; const Float_t kFaWring3Cutoffy = 3.35; TGeoTubeSeg* shFaWring3a = new TGeoTubeSeg(kFaWring3Rinner, kFaWring3Router, kFaWring3HWidth, 0., 90.); shFaWring3a->SetName("shFaWring3a"); TGeoBBox* shFaWring3b = new TGeoBBox(kFaWring3Router / 2., kFaWring3Router / 2., kFaWring3HWidth); shFaWring3b->SetName("shFaWring3b"); TGeoTranslation* trFaWring3b = new TGeoTranslation("trFaWring3b", kFaWring3Router / 2. + kFaWring3Cutoffx, kFaWring3Router / 2. + kFaWring3Cutoffy, 0.); trFaWring3b->RegisterYourself(); TGeoCompositeShape* shFaWring3 = new TGeoCompositeShape("shFaWring3", "(shFaWring3a)*(shFaWring3b:trFaWring3b)"); TGeoVolume* voFaWring3 = new TGeoVolume("YFA_WRING3", shFaWring3, kMedNiW); /////////////////////////////////// // FA W-Ring 5 // // Drawing ALIP2A__0221 // /////////////////////////////////// const Float_t kFaWring5Rinner = 15.40; const Float_t kFaWring5Router = 18.67; const Float_t kFaWring5HWidth = 1.08; TGeoVolume* voFaWring5 = new TGeoVolume("YFA_WRING5", new TGeoTube(kFaWring5Rinner, kFaWring5Router, kFaWring5HWidth), kMedNiW); // // Position the rings in the assembly // TGeoVolumeAssembly* asFaExtraShield = new TGeoVolumeAssembly("YCRE"); // Distance between rings const Float_t kFaDWrings = 1.92; // dz = 0.; dz += kFaWring2HWidth; asFaExtraShield->AddNode(voFaWring2, 1, new TGeoCombiTrans(0., 0., dz, rot090)); asFaExtraShield->AddNode(voFaWring2, 2, new TGeoCombiTrans(0., 0., dz, rot270)); dz += kFaWring2HWidth; dz += kFaDWrings; dz += kFaWring3HWidth; asFaExtraShield->AddNode(voFaWring3, 1, new TGeoCombiTrans(0., 0., dz, rot000)); asFaExtraShield->AddNode(voFaWring3, 2, new TGeoCombiTrans(0., 0., dz, rot180)); dz += kFaWring3HWidth; dz += kFaWring5HWidth; asFaExtraShield->AddNode(voFaWring5, 1, new TGeoTranslation(0., 0., dz)); dz += kFaWring5HWidth; dz += kFaWring3HWidth; asFaExtraShield->AddNode(voFaWring3, 3, new TGeoCombiTrans(0., 0., dz, rot090)); asFaExtraShield->AddNode(voFaWring3, 4, new TGeoCombiTrans(0., 0., dz, rot270)); dz += kFaWring3HWidth; dz += kFaDWrings; dz += kFaWring2HWidth; asFaExtraShield->AddNode(voFaWring2, 3, new TGeoCombiTrans(0., 0., dz, rot000)); asFaExtraShield->AddNode(voFaWring2, 4, new TGeoCombiTrans(0., 0., dz, rot180)); dz += kFaWring2HWidth; /////////////////////////////////////// // SAA1 // /////////////////////////////////////// /////////////////////////////////////// // FA/SAA1 W Joint // // Drawing ALIP2A__0060 // /////////////////////////////////////// // Length of flange FA side Float_t dzFaSaa1F1 = 2.8; // Inner radius of flange FA side Float_t rInFaSaa1F1 = 32.0/2.; // Outer radius of flange FA side Float_t rOuFaSaa1F1 = 39.5/2.; // Length of first straight section Float_t dzFaSaa1S1 = 18.5 - dzFaSaa1F1; // Inner radius of first straight section Float_t rInFaSaa1S1 = 22.3/2.; // Length of 45 deg transition region Float_t dzFaSaa1T1 = 2.2; // Inner radius of second straight section Float_t rInFaSaa1S2 = 17.9/2.; // Length of second straight section Float_t dzFaSaa1S2 = 10.1; // Length of flange SAA1 side // Float_t dzFaSaa1F2 = 4.0; // Inner radius of flange FA side Float_t rInFaSaa1F2 = 25.2/2.; // Length of joint Float_t dzFaSaa1 = 34.8; // Outer Radius at the end of the joint Float_t rOuFaSaa1E = 41.93/2.; TGeoPcon* shFaSaa1 = new TGeoPcon(0., 360., 8); z = 0; // Flange FA side shFaSaa1->DefineSection( 0, z, rInFaSaa1F1, rOuFaSaa1F1); z += dzFaSaa1F1; shFaSaa1->DefineSection( 1, z, rInFaSaa1F1, 40.0); shFaSaa1->DefineSection( 2, z, rInFaSaa1S1, 40.0); // First straight section z += dzFaSaa1S1; shFaSaa1->DefineSection( 3, z, rInFaSaa1S1, 40.0); // 45 deg transition region z += dzFaSaa1T1; shFaSaa1->DefineSection( 4, z, rInFaSaa1S2, 40.0); // Second straight section z += dzFaSaa1S2; shFaSaa1->DefineSection( 5, z, rInFaSaa1S2, 40.0); shFaSaa1->DefineSection( 6, z, rInFaSaa1F2, 40.0); // Flange SAA1 side z = dzFaSaa1; shFaSaa1->DefineSection( 7, z, rInFaSaa1F2, rOuFaSaa1E); // Outer 2 deg line for (Int_t i = 1; i < 7; i++) { Double_t z = shFaSaa1->GetZ(i); Double_t r1 = shFaSaa1->GetRmin(i); Double_t r2 = 39.5/2. + z * TMath::Tan(2. * kDegRad) - 0.01; shFaSaa1->DefineSection(i, z, r1, r2); } TGeoVolume* voFaSaa1 = new TGeoVolume("YFASAA1", shFaSaa1, kMedNiWsh); // // Outer region with lower transport cuts TGeoCone* shFaSaa1O = new TGeoCone(dzFaSaa1/2., rOuFaSaa1F1 - 3.5, rOuFaSaa1F1, rOuFaSaa1E - 3.5, rOuFaSaa1E); TGeoVolume* voFaSaa1O = new TGeoVolume("YFASAA1O", shFaSaa1O, kMedNiW); voFaSaa1->AddNode(voFaSaa1O, 1, new TGeoTranslation(0., 0., dzFaSaa1/2.)); /////////////////////////////////// // SAA1 Steel Envelope // // Drawing ALIP2A__0039 // /////////////////////////////////// Float_t rOut; // Outer radius // Thickness of the steel envelope Float_t dSt = 4.; // 4 Section // z-positions Float_t zSaa1StEnv[5] = {111.2, 113.7, 229.3, 195.0}; // Radii // 1 Float_t rOuSaa1StEnv1 = 40.4/2.; Float_t rInSaa1StEnv1 = rOuSaa1StEnv1 - dSt; // 2 Float_t rInSaa1StEnv2 = 41.7/2.; Float_t rOuSaa1StEnv2 = rInSaa1StEnv2 + dSt / TMath::Cos(2.0 * kDegRad); // 3 Float_t rOuSaa1StEnv3 = 57.6/2.; Float_t rInSaa1StEnv3 = rOuSaa1StEnv3 - dSt; // 4 Float_t rInSaa1StEnv4 = 63.4/2.; Float_t rOuSaa1StEnv4 = rInSaa1StEnv4 + dSt / TMath::Cos(1.6 * kDegRad); // end Float_t rInSaa1StEnv5 = 74.28/2.; Float_t rOuSaa1StEnv5 = rInSaa1StEnv5 + dSt / TMath::Cos(1.6 * kDegRad); // Relative starting position Float_t zSaa1StEnvS = 3.; TGeoPcon* shSaa1StEnv = new TGeoPcon(0., 360., 11); // 1st Section z = zSaa1StEnvS; shSaa1StEnv->DefineSection( 0, z, rInSaa1StEnv1, rOuSaa1StEnv1); z += (zSaa1StEnv[0] - dSt); shSaa1StEnv->DefineSection( 1, z, rInSaa1StEnv1, rOuSaa1StEnv1); // 1 - 2 shSaa1StEnv->DefineSection( 2, z, rInSaa1StEnv1, rOuSaa1StEnv2); z += dSt; shSaa1StEnv->DefineSection( 3, z, rInSaa1StEnv1, rOuSaa1StEnv2); // 2nd Section shSaa1StEnv->DefineSection( 4, z, rInSaa1StEnv2, rOuSaa1StEnv2); z += zSaa1StEnv[1]; shSaa1StEnv->DefineSection( 5, z, rInSaa1StEnv3, rOuSaa1StEnv3); // 3rd Section z += (zSaa1StEnv[2] - dSt); shSaa1StEnv->DefineSection( 6, z, rInSaa1StEnv3, rOuSaa1StEnv3); // 3 - 4 shSaa1StEnv->DefineSection( 7, z, rInSaa1StEnv3, rOuSaa1StEnv4); z += dSt; shSaa1StEnv->DefineSection( 8, z, rInSaa1StEnv3, rOuSaa1StEnv4); // 4th Section shSaa1StEnv->DefineSection( 9, z, rInSaa1StEnv4, rOuSaa1StEnv4); z += zSaa1StEnv[3]; shSaa1StEnv->DefineSection(10, z, rInSaa1StEnv5, rOuSaa1StEnv5); TGeoVolume* voSaa1StEnv = new TGeoVolume("YSAA1_SteelEnvelope", shSaa1StEnv, kMedSteel); /////////////////////////////////// // SAA1 W-Pipe // // Drawing ALIP2A__0059 // /////////////////////////////////// // // Flange FA side // Length of first section Float_t dzSaa1WPipeF1 = 0.9; // Outer radius Float_t rOuSaa1WPipeF1 = 24.5/2.; // Inner Radius Float_t rInSaa1WPipeF1 = 22.0/2.; // Length of second section Float_t dzSaa1WPipeF11 = 2.1; // Inner Radius Float_t rInSaa1WPipeF11 = 18.5/2.; // // Central tube // Length Float_t dzSaa1WPipeC = 111.2; // Inner Radius at the end Float_t rInSaa1WPipeC = 22.0/2.; // Outer Radius Float_t rOuSaa1WPipeC = 31.9/2.; // // Flange SAA2 Side // Length Float_t dzSaa1WPipeF2 = 6.0; // Outer radius Float_t rOuSaa1WPipeF2 = 41.56/2.; // TGeoPcon* shSaa1WPipe = new TGeoPcon(0., 360., 8); z = 0.; // Flange FA side first section shSaa1WPipe->DefineSection( 0, z, rInSaa1WPipeF1 , rOuSaa1WPipeF1); z += dzSaa1WPipeF1; shSaa1WPipe->DefineSection( 1, z, rInSaa1WPipeF1 , rOuSaa1WPipeF1); // Flange FA side second section shSaa1WPipe->DefineSection( 2, z, rInSaa1WPipeF11, rOuSaa1WPipeF1); z += dzSaa1WPipeF11; shSaa1WPipe->DefineSection( 3, z, rInSaa1WPipeF11, rOuSaa1WPipeF1); // Central Section shSaa1WPipe->DefineSection( 4, z, rInSaa1WPipeF11, rOuSaa1WPipeC); z += dzSaa1WPipeC; shSaa1WPipe->DefineSection( 5, z, rInSaa1WPipeC, rOuSaa1WPipeC); // Flange SAA2 side shSaa1WPipe->DefineSection( 6, z, rInSaa1WPipeC, rOuSaa1WPipeF2); z += dzSaa1WPipeF2; shSaa1WPipe->DefineSection( 7, z, rInSaa1WPipeC, rOuSaa1WPipeF2); TGeoVolume* voSaa1WPipe = new TGeoVolume("YSAA1_WPipe", shSaa1WPipe, kMedNiW); // // Inner region with higher transport cuts TGeoTube* shSaa1WPipeI = new TGeoTube(rInSaa1WPipeC, rOuSaa1WPipeC, dzSaa1WPipeC/2.); TGeoVolume* voSaa1WPipeI = new TGeoVolume("YSAA1_WPipeI", shSaa1WPipeI, kMedNiWsh); voSaa1WPipe->AddNode(voSaa1WPipeI, 1, new TGeoTranslation(0., 0., dzSaa1WPipeF1 + dzSaa1WPipeF11 + dzSaa1WPipeC/2)); /////////////////////////////////// // SAA1 Pb Components // // Drawing ALIP2A__0078 // /////////////////////////////////// // // Inner angle Float_t tanAlpha = TMath::Tan(1.69 / 2. * kDegRad); Float_t tanBeta = TMath::Tan(3.20 / 2. * kDegRad); // // 1st Section 2deg opening cone // Length Float_t dzSaa1PbComp1 = 100.23; // Inner radius at entrance Float_t rInSaa1PbComp1 = 22.0/2.; // It's 21 cm diameter in the drawing. Is this a typo ??!! // Outer radius at entrance Float_t rOuSaa1PbComp1 = 42.0/2.; // // 2nd Section: Straight Section // Length Float_t dzSaa1PbComp2 = 236.77; // Inner radius Float_t rInSaa1PbComp2 = rInSaa1PbComp1 + dzSaa1PbComp1 * tanAlpha; // Outer radius Float_t rOuSaa1PbComp2 = 49.0/2.; // // 3rd Section: 1.6deg opening cone until bellow // Length Float_t dzSaa1PbComp3 = 175.6; // Inner radius Float_t rInSaa1PbComp3 = rInSaa1PbComp2 + dzSaa1PbComp2 * tanAlpha; // Outer radius Float_t rOuSaa1PbComp3 = 62.8/2.; // // 4th Section: Bellow region Float_t dzSaa1PbComp4 = 26.4; // Inner radius Float_t rInSaa1PbComp4 = 37.1/2.; Float_t rInSaa1PbCompB = 43.0/2.; // Outer radius Float_t rOuSaa1PbComp4 = rOuSaa1PbComp3 + dzSaa1PbComp3 * tanBeta; // // 5th Section: Flange SAA2 side // 1st detail Float_t dzSaa1PbCompF1 = 4.; Float_t rOuSaa1PbCompF1 = 74.1/2.; // 2nd detail Float_t dzSaa1PbCompF2 = 3.; Float_t rOuSaa1PbCompF2 = 66.0/2.; Float_t rOuSaa1PbCompF3 = 58.0/2.; TGeoPcon* shSaa1PbComp = new TGeoPcon(0., 360., 11); z = 120.2; // 2 deg opening cone shSaa1PbComp->DefineSection( 0, z, rInSaa1PbComp1, rOuSaa1PbComp1); z += dzSaa1PbComp1; shSaa1PbComp->DefineSection( 1, z, rInSaa1PbComp2, rOuSaa1PbComp2); // Straight section z += dzSaa1PbComp2; shSaa1PbComp->DefineSection( 2, z, rInSaa1PbComp3, rOuSaa1PbComp2); // 1.6 deg opening cone shSaa1PbComp->DefineSection( 3, z, rInSaa1PbComp3, rOuSaa1PbComp3); z += dzSaa1PbComp3; shSaa1PbComp->DefineSection( 4, z, rInSaa1PbComp4, rOuSaa1PbComp4); // Bellow region until outer flange shSaa1PbComp->DefineSection( 5, z, rInSaa1PbCompB, rOuSaa1PbComp4); z += (dzSaa1PbComp4 - dzSaa1PbCompF1 - dzSaa1PbCompF2); shSaa1PbComp->DefineSection( 6, z, rInSaa1PbCompB, rOuSaa1PbCompF1); shSaa1PbComp->DefineSection( 7, z, rInSaa1PbCompB, rOuSaa1PbCompF2); // Flange first step z += dzSaa1PbCompF1; shSaa1PbComp->DefineSection( 8, z, rInSaa1PbCompB, rOuSaa1PbCompF2); shSaa1PbComp->DefineSection( 9, z, rInSaa1PbCompB, rOuSaa1PbCompF3); // Flange second step z += dzSaa1PbCompF2; shSaa1PbComp->DefineSection( 10, z, rInSaa1PbCompB, rOuSaa1PbCompF3); TGeoVolume* voSaa1PbComp = new TGeoVolume("YSAA1_PbComp", shSaa1PbComp, kMedPb); // // Inner region with higher transport cuts TGeoPcon* shSaa1PbCompI = MakeShapeFromTemplate(shSaa1PbComp, 0., -3.); TGeoVolume* voSaa1PbCompI = new TGeoVolume("YSAA1_PbCompI", shSaa1PbCompI, kMedPbSh); voSaa1PbComp->AddNode(voSaa1PbCompI, 1, gGeoIdentity); /////////////////////////////////// // SAA1 W-Cone // // Drawing ALIP2A__0058 // /////////////////////////////////// // Length of the Cone Float_t dzSaa1WCone = 52.9; // Inner and outer radii Float_t rInSaa1WCone1 = 20.4; Float_t rOuSaa1WCone1 = rInSaa1WCone1 + 0.97; Float_t rOuSaa1WCone2 = rInSaa1WCone1 + 2.80; // relative z-position Float_t zSaa1WCone = 9.3; TGeoPcon* shSaa1WCone = new TGeoPcon(0., 360., 2); z = zSaa1WCone; shSaa1WCone->DefineSection( 0, z, rInSaa1WCone1, rOuSaa1WCone1); z += dzSaa1WCone; shSaa1WCone->DefineSection( 1, z, rInSaa1WCone1, rOuSaa1WCone2); TGeoVolume* voSaa1WCone = new TGeoVolume("YSAA1_WCone", shSaa1WCone, kMedNiW); /////////////////////////////////// // SAA1 Steel-Ring // // Drawing ALIP2A__0040 // /////////////////////////////////// // // Length of the ring Float_t dzSaa1StRing = 4.; // Inner and outer radius Float_t rInSaa1String = 33.0; Float_t rOuSaa1String = 41.1; // Relative z-position Float_t zSaa1StRing = 652.2; TGeoPcon* shSaa1StRing = new TGeoPcon(0., 360., 2); z = zSaa1StRing; shSaa1StRing->DefineSection( 0, z, rInSaa1String, rOuSaa1String); z += dzSaa1StRing; shSaa1StRing->DefineSection( 1, z, rInSaa1String, rOuSaa1String); TGeoVolume* voSaa1StRing = new TGeoVolume("YSAA1_StRing", shSaa1StRing, kMedSteel); /////////////////////////////////// // SAA1 Inner Tube // // Drawing ALIP2A__0082 // /////////////////////////////////// // // Length of saa2: 659.2 cm // Length of inner tube: 631.9 cm // Lenth of bellow cavern: 27.3 cm // Radius at entrance 18.5/2, d = 0.3 // Radius at exit 37.1/2, d = 0.3 // Float_t dzSaa1InnerTube = 631.9/2.; // Half length of the tube Float_t rInSaa1InnerTube = 18.2/2.; // Radius at entrance Float_t rOuSaa1InnerTube = 36.8/2.; // Radius at exit Float_t dSaa1InnerTube = 0.2 ; // Thickness TGeoVolume* voSaa1InnerTube = new TGeoVolume("YSAA1_InnerTube", new TGeoCone(dzSaa1InnerTube, rInSaa1InnerTube - dSaa1InnerTube, rInSaa1InnerTube, rOuSaa1InnerTube - dSaa1InnerTube, rOuSaa1InnerTube), kMedSteelSh); /////////////////////////////////// // SAA1 Outer Shape // // Drawing ALIP2A__0107 // /////////////////////////////////// // Total length Float_t dzSaa1 = 659.2; // TGeoPcon* shSaa1M = new TGeoPcon(0., 360., 20); Float_t kSec = 0.01; // security distance to avoid trivial extrusions Float_t rmin = rInSaa1InnerTube - dSaa1InnerTube - kSec; rmax = rOuSaa1InnerTube - dSaa1InnerTube - kSec; z = 0.; shSaa1M->DefineSection( 0, z, rmin, rOuSaa1WPipeF1); z += dzSaa1WPipeF1; shSaa1M->DefineSection( 1, z, rmin, rOuSaa1WPipeF1); shSaa1M->DefineSection( 2, z, 0., rOuSaa1WPipeF1); z += dzSaa1WPipeF11; shSaa1M->DefineSection( 3, z, 0., rOuSaa1WPipeF1); shSaa1M->DefineSection( 4, z, 0., rOuSaa1StEnv1); z = zSaa1WCone; shSaa1M->DefineSection( 5, z, 0., rOuSaa1StEnv1); shSaa1M->DefineSection( 6, z, 0., rOuSaa1WCone1); z += dzSaa1WCone; shSaa1M->DefineSection( 7, z, 0., rOuSaa1WCone2); shSaa1M->DefineSection( 8, z, 0., rOuSaa1StEnv1); z = zSaa1StEnv[0] - dSt + zSaa1StEnvS; shSaa1M->DefineSection( 9, z, 0., rOuSaa1StEnv1); shSaa1M->DefineSection(10, z, 0., rOuSaa1StEnv2); z += (zSaa1StEnv[1] + dSt); shSaa1M->DefineSection(11, z, 0., rOuSaa1StEnv3); z += (zSaa1StEnv[2] - dSt); shSaa1M->DefineSection(12, z, 0., rOuSaa1StEnv3); shSaa1M->DefineSection(13, z, 0., rOuSaa1StEnv4); z += (zSaa1StEnv[3] - dSt + dzSaa1PbCompF1 + dzSaa1PbCompF2 - dzSaa1PbComp4); Float_t rmaxSaa1 = shSaa1M->GetRmax(13) + (z - shSaa1M->GetZ(13)) * TMath::Tan(1.6 * kDegRad); shSaa1M->DefineSection(14, z, 0., rmaxSaa1); shSaa1M->DefineSection(15, z, rmax, rmaxSaa1); z = zSaa1StRing; shSaa1M->DefineSection(16, z, rmax, rOuSaa1String); z += dzSaa1PbCompF1; shSaa1M->DefineSection(17, z, rmax, rOuSaa1String); shSaa1M->DefineSection(18, z, rmax, rOuSaa1PbCompF3); z += dzSaa1PbCompF2; shSaa1M->DefineSection(19, z, rmax, rOuSaa1PbCompF3); // // Inner 1.69deg line for (Int_t i = 2; i < 15; i++) { Double_t z = shSaa1M->GetZ(i); Double_t r2 = shSaa1M->GetRmax(i); Double_t r1 = rmin + (z - 0.9) * TMath::Tan(1.69 / 2. * kDegRad) - kSec; shSaa1M->DefineSection(i, z, r1, r2); } TGeoVolume* voSaa1M = new TGeoVolume("YSAA1M", shSaa1M, kMedAir); voSaa1M->SetVisibility(0); /////////////////////////////////// // // // Recess Station 2 // // Drawing ALIP2A__0260 // /////////////////////////////////// /////////////////////////////////// // SAA1 W-Ring 1 // // Drawing ALIP2A__0217 // /////////////////////////////////// Float_t saa1Wring1Width = 5.85; TGeoPcon* shSaa1Wring1 = new TGeoPcon(0., 360., 2); shSaa1Wring1->DefineSection(0, 0.00 , 20.30, 23.175); shSaa1Wring1->DefineSection(1, saa1Wring1Width, 20.30, 23.400); TGeoVolume* voSaa1Wring1 = new TGeoVolume("YSAA1_WRING1", shSaa1Wring1, kMedNiW); /////////////////////////////////// // SAA1 W-Ring 2 // // Drawing ALIP2A__0055 // /////////////////////////////////// Float_t saa1Wring2Rinner = 20.30; Float_t saa1Wring2Router = 23.40; Float_t saa1Wring2HWidth = 3.75; Float_t saa1Wring2Cutoffx = 4.45; Float_t saa1Wring2Cutoffy = 4.45; TGeoTubeSeg* shSaa1Wring2a = new TGeoTubeSeg(saa1Wring2Rinner, saa1Wring2Router, saa1Wring2HWidth, 0., 90.); shSaa1Wring2a->SetName("shSaa1Wring2a"); TGeoBBox* shSaa1Wring2b = new TGeoBBox(saa1Wring2Router / 2., saa1Wring2Router / 2., saa1Wring2HWidth); shSaa1Wring2b->SetName("shSaa1Wring2b"); TGeoTranslation* trSaa1Wring2b = new TGeoTranslation("trSaa1Wring2b", saa1Wring2Router / 2. + saa1Wring2Cutoffx, saa1Wring2Router / 2. + saa1Wring2Cutoffy, 0.); trSaa1Wring2b->RegisterYourself(); TGeoCompositeShape* shSaa1Wring2 = new TGeoCompositeShape("shSaa1Wring2", "(shSaa1Wring2a)*(shSaa1Wring2b:trSaa1Wring2b)"); TGeoVolume* voSaa1Wring2 = new TGeoVolume("YSAA1_WRING2", shSaa1Wring2, kMedNiW); /////////////////////////////////// // SAA1 W-Ring 3 // // Drawing ALIP2A__0216 // /////////////////////////////////// Float_t saa1Wring3Rinner = 20.30; Float_t saa1Wring3Router = 23.40; Float_t saa1Wring3HWidth = 3.75; Float_t saa1Wring3Cutoffx = 4.50; Float_t saa1Wring3Cutoffy = 4.40; TGeoTubeSeg* shSaa1Wring3a = new TGeoTubeSeg(saa1Wring3Rinner, saa1Wring3Router, saa1Wring3HWidth, 0., 90.); shSaa1Wring3a->SetName("shSaa1Wring3a"); TGeoBBox* shSaa1Wring3b = new TGeoBBox(saa1Wring3Router / 2., saa1Wring3Router / 2., saa1Wring3HWidth); shSaa1Wring3b->SetName("shSaa1Wring3b"); TGeoTranslation* trSaa1Wring3b = new TGeoTranslation("trSaa1Wring3b", saa1Wring3Router / 2. + saa1Wring3Cutoffx, saa1Wring3Router / 2. + saa1Wring3Cutoffy, 0.); trSaa1Wring3b->RegisterYourself(); TGeoCompositeShape* shSaa1Wring3 = new TGeoCompositeShape("shSaa1Wring3", "(shSaa1Wring3a)*(shSaa1Wring3b:trSaa1Wring3b)"); TGeoVolume* voSaa1Wring3 = new TGeoVolume("YSAA1_WRING3", shSaa1Wring3, kMedNiW); /////////////////////////////////// // SAA1 W-Ring 4 // // Drawing ALIP2A__0215 // /////////////////////////////////// Float_t saa1Wring4Width = 5.85; TGeoPcon* shSaa1Wring4 = new TGeoPcon(0., 360., 5); shSaa1Wring4->DefineSection(0, 0.00, 20.30, 23.40); shSaa1Wring4->DefineSection(1, 1.00, 20.30, 23.40); shSaa1Wring4->DefineSection(2, 1.00, 20.30, 24.50); shSaa1Wring4->DefineSection(3, 4.85, 20.30, 24.80); shSaa1Wring4->DefineSection(4, 5.85, 24.10, 24.80); TGeoVolume* voSaa1Wring4 = new TGeoVolume("YSAA1_WRING4", shSaa1Wring4, kMedNiW); /////////////////////////////////// // SAA1 W-Ring 5 // // Drawing ALIP2A__0218 // /////////////////////////////////// Float_t saa1Wring5Rinner = 20.30; Float_t saa1Wring5Router = 23.40; Float_t saa1Wring5HWidth = 0.85; TGeoVolume* voSaa1Wring5 = new TGeoVolume("YSAA1_WRING5", new TGeoTube(saa1Wring5Rinner, saa1Wring5Router, saa1Wring5HWidth), kMedNiW); // // Position the rings in the assembly // TGeoVolumeAssembly* asSaa1ExtraShield = new TGeoVolumeAssembly("YSAA1ExtraShield"); // Distance between rings Float_t saa1DWrings = 2.3; // dz = - (saa1Wring1Width + 6. * saa1Wring2HWidth + 2. * saa1Wring3HWidth + saa1Wring4Width + 2. * saa1Wring5HWidth + 2. * saa1DWrings) / 2.; asSaa1ExtraShield->AddNode(voSaa1Wring1, 1, new TGeoTranslation(0., 0., dz)); dz += saa1Wring1Width; dz += saa1Wring2HWidth; asSaa1ExtraShield->AddNode(voSaa1Wring2, 1, new TGeoCombiTrans(0., 0., dz, rot000)); asSaa1ExtraShield->AddNode(voSaa1Wring2, 2, new TGeoCombiTrans(0., 0., dz, rot180)); dz += saa1Wring2HWidth; dz += saa1DWrings; dz += saa1Wring2HWidth; asSaa1ExtraShield->AddNode(voSaa1Wring2, 3, new TGeoCombiTrans(0., 0., dz, rot090)); asSaa1ExtraShield->AddNode(voSaa1Wring2, 4, new TGeoCombiTrans(0., 0., dz, rot270)); dz += saa1Wring2HWidth; dz += saa1Wring5HWidth; asSaa1ExtraShield->AddNode(voSaa1Wring5, 1, new TGeoTranslation(0., 0., dz)); dz += saa1Wring5HWidth; dz += saa1Wring2HWidth; asSaa1ExtraShield->AddNode(voSaa1Wring2, 5, new TGeoCombiTrans(0., 0., dz, rot000)); asSaa1ExtraShield->AddNode(voSaa1Wring2, 6, new TGeoCombiTrans(0., 0., dz, rot180)); dz += saa1Wring2HWidth; dz += saa1DWrings; dz += saa1Wring3HWidth; asSaa1ExtraShield->AddNode(voSaa1Wring3, 1, new TGeoCombiTrans(0., 0., dz, rot090)); asSaa1ExtraShield->AddNode(voSaa1Wring3, 2, new TGeoCombiTrans(0., 0., dz, rot270)); dz += saa1Wring3HWidth; asSaa1ExtraShield->AddNode(voSaa1Wring4, 1, new TGeoTranslation(0., 0., dz)); dz += saa1Wring4Width; const Float_t saa1ExtraShieldL = 48; // // Assemble SAA1 voSaa1M->AddNode(voSaa1StEnv, 1, gGeoIdentity); voSaa1M->AddNode(voSaa1WPipe, 1, gGeoIdentity); voSaa1M->AddNode(voSaa1PbComp, 1, gGeoIdentity); voSaa1M->AddNode(voSaa1WCone, 1, gGeoIdentity); voSaa1M->AddNode(voSaa1StRing, 1, gGeoIdentity); voSaa1M->AddNode(voSaa1InnerTube, 1, new TGeoTranslation(0., 0., dzSaa1InnerTube + 0.9)); TGeoVolumeAssembly* voSaa1 = new TGeoVolumeAssembly("YSAA1"); voSaa1->AddNode(voSaa1M, 1, gGeoIdentity); /////////////////////////////////////// // SAA1/SAA2 Pb Joint // // Drawing ALIP2A__0081 // /////////////////////////////////////// // // Outer radius Float_t rOuSaa1Saa2 = 70.0/2.; // Flange SAA1 side Float_t dzSaa1Saa2F1 = 3.; Float_t rInSaa1Saa2F1 = 58.5/2.; // 1st Central Section Float_t dzSaa1Saa2C1 = 19.3; Float_t rInSaa1Saa2C1 = 42.8/2.; // Transition Region Float_t dzSaa1Saa2T = 3.3; // 1st Central Section Float_t dzSaa1Saa2C2 = 6.2; Float_t rInSaa1Saa2C2 = 36.2/2.; // Flange SAA2 side Float_t dzSaa1Saa2F2 = 3.1; Float_t rInSaa1Saa2F2 = 54.1/2.; // Total length Float_t dzSaa1Saa2 = 34.9; TGeoPcon* shSaa1Saa2Pb = new TGeoPcon(0., 360., 8); z = 0.; // Flange SAA1 side shSaa1Saa2Pb->DefineSection( 0, z, rInSaa1Saa2F1, rOuSaa1Saa2); z += dzSaa1Saa2F1; shSaa1Saa2Pb->DefineSection( 1, z, rInSaa1Saa2F1, rOuSaa1Saa2); shSaa1Saa2Pb->DefineSection( 2, z, rInSaa1Saa2C1, rOuSaa1Saa2); // Central region 1 z += dzSaa1Saa2C1; shSaa1Saa2Pb->DefineSection( 3, z, rInSaa1Saa2C1, rOuSaa1Saa2); // 45 deg transition z += dzSaa1Saa2T; shSaa1Saa2Pb->DefineSection( 4, z, rInSaa1Saa2C2, rOuSaa1Saa2); z += dzSaa1Saa2C2; shSaa1Saa2Pb->DefineSection( 5, z, rInSaa1Saa2C2, rOuSaa1Saa2); shSaa1Saa2Pb->DefineSection( 6, z, rInSaa1Saa2F2, rOuSaa1Saa2); z += dzSaa1Saa2F2; shSaa1Saa2Pb->DefineSection( 7, z, rInSaa1Saa2F2, rOuSaa1Saa2); TGeoVolume* voSaa1Saa2Pb = new TGeoVolume("YSAA1SAA2Pb", shSaa1Saa2Pb, kMedPb); // // Mother volume and outer steel envelope Float_t rOuSaa1Saa2Steel = 36.9; TGeoPcon* shSaa1Saa2 = MakeShapeFromTemplate(shSaa1Saa2Pb, 0., rOuSaa1Saa2Steel-rOuSaa1Saa2); TGeoVolume* voSaa1Saa2 = new TGeoVolume("YSAA1SAA2", shSaa1Saa2, kMedSteel); voSaa1Saa2->AddNode(voSaa1Saa2Pb, 1, gGeoIdentity); // // Inner region with higher transport cuts // TGeoPcon* shSaa1Saa2I = MakeShapeFromTemplate(shSaa1Saa2Pb, 0., -3.); TGeoVolume* voSaa1Saa2I = new TGeoVolume("YSAA1_SAA2I", shSaa1Saa2I, kMedPbSh); voSaa1Saa2Pb->AddNode(voSaa1Saa2I, 1, gGeoIdentity); /////////////////////////////////////// // SAA2 // /////////////////////////////////////// /////////////////////////////////// // SAA2 Steel Envelope // // Drawing ALIP2A__0041 // /////////////////////////////////// dSt = 4.; // Thickness of steel envelope // Length of the first section Float_t dzSaa2StEnv1 = 163.15; Float_t rInSaa2StEnv1 = 65.8/2.; // Length of the second section Float_t dzSaa2StEnv2 = 340.35 - 4.; Float_t rInSaa2StEnv2 = 87.2/2.; // Rel. starting position Float_t zSaa2StEnv = 3.; TGeoPcon* shSaa2StEnv = new TGeoPcon(0., 360., 6); // First Section z = zSaa2StEnv; shSaa2StEnv->DefineSection( 0, z, rInSaa2StEnv1, rInSaa2StEnv1 + dSt); z += dzSaa2StEnv1; shSaa2StEnv->DefineSection( 1, z, rInSaa2StEnv1, rInSaa2StEnv1 + dSt); // Transition region shSaa2StEnv->DefineSection( 2, z, rInSaa2StEnv1, rInSaa2StEnv2 + dSt); z += dSt; shSaa2StEnv->DefineSection( 3, z, rInSaa2StEnv1, rInSaa2StEnv2 + dSt); // Second section shSaa2StEnv->DefineSection( 4, z, rInSaa2StEnv2, rInSaa2StEnv2 + dSt); z += dzSaa2StEnv2; shSaa2StEnv->DefineSection( 5, z, rInSaa2StEnv2, rInSaa2StEnv2 + dSt); TGeoVolume* voSaa2StEnv = new TGeoVolume("YSAA2_SteelEnvelope", shSaa2StEnv, kMedSteel); /////////////////////////////////// // SAA2 Pb Ring // // Drawing ALIP2A__0080 // // Drawing ALIP2A__0111 // /////////////////////////////////// // // Rel. position in z Float_t zSaa2PbRing = 35.25; // Length Float_t dzSaa2PbRing = 65.90; // Inner radius Float_t rInSaa2PbRing = 37.00; // Outer radius at front Float_t rOuSaa2PbRingF = 42.74; // Outer Rradius at rear Float_t rOuSaa2PbRingR = 44.58; TGeoPcon* shSaa2PbRing = new TGeoPcon(0., 360., 2); z = zSaa2PbRing; shSaa2PbRing->DefineSection(0, z, rInSaa2PbRing, rOuSaa2PbRingF); z += dzSaa2PbRing; shSaa2PbRing->DefineSection(1, z, rInSaa2PbRing, rOuSaa2PbRingR); TGeoVolume* voSaa2PbRing = new TGeoVolume("YSAA2_PbRing", shSaa2PbRing, kMedPb); /////////////////////////////////// // SAA2 Pb Components // // Drawing ALIP2A__0079 // /////////////////////////////////// tanAlpha = TMath::Tan(1.89 / 2. * kDegRad); TGeoPcon* shSaa2PbComp = new TGeoPcon(0., 360., 16); // Total length Float_t dzSaa2PbComp = 512.; // Length of 1st bellow recess Float_t dzSaa2PbCompB1 = 24.; // Length of 2nd bellow recess Float_t dzSaa2PbCompB2 = 27.; // Flange on the SAA1 side Detail A // 1st Step Float_t dzSaa2PbCompA1 = 1.5; Float_t rInSaa2PbCompA1 = 43.0/2.; Float_t rOuSaa2PbCompA1 = 53.0/2.; // 2nd Step Float_t dzSaa2PbCompA2 = 1.5; Float_t rInSaa2PbCompA2 = 36.8/2.; Float_t rOuSaa2PbCompA2 = rOuSaa2PbCompA1; // Straight section Float_t dzSaa2PbCompA3 = 21.0; Float_t rInSaa2PbCompA3 = rInSaa2PbCompA2; Float_t rOuSaa2PbCompA3 = 65.2/2.; // // 1st Section (outer straight, inner 1.89/2. deg opening cone) // Length Float_t dzSaa2PbComp1 = 146.15; // Inner radius at the end Float_t rInSaa2PbComp1 = rInSaa2PbCompA3 + dzSaa2PbComp1 * tanAlpha; // Outer radius Float_t rOuSaa2PbComp1 = rOuSaa2PbCompA3; // // 2nd Section (outer straight, inner 1.89/2. deg opening cone) // Length Float_t dzSaa2PbComp2 = (dzSaa2PbComp - dzSaa2PbComp1 - dzSaa2PbCompB1 - dzSaa2PbCompB2); // Inner radius at the end Float_t rInSaa2PbComp2 = rInSaa2PbComp1 + dzSaa2PbComp2 * tanAlpha; // Outer radius Float_t rOuSaa2PbComp2 = 86.6/2.; // // Flange on the SAA3 side (Detail E) // // Straight Section // Length dzSaa2PbCompB2 - 8.8 = 27 - 8.8 = 18.2 Float_t dzSaa2PbCompE1 = 18.2; Float_t rInSaa2PbCompE1 = 52.0/2.; Float_t rOuSaa2PbCompE1 = 86.6/2.; // 45 deg transition Float_t dzSaa2PbCompE2 = 2.7; // 1st Step Float_t dzSaa2PbCompE3 = 0.6; Float_t rInSaa2PbCompE3 = 52.0/2.+ dzSaa2PbCompE2; Float_t rOuSaa2PbCompE3 = 83.0/2.; // 2nd Step Float_t dzSaa2PbCompE4 = 4.0; Float_t rOuSaa2PbCompE4 = 61.6/2.; // end Float_t dzSaa2PbCompE5 = 1.5; // // Flange on SAA1 side (Detail A) z = 0.; // 1st Step shSaa2PbComp->DefineSection( 0, z, rInSaa2PbCompA1, rOuSaa2PbCompA1); z += dzSaa2PbCompA1; shSaa2PbComp->DefineSection( 1, z, rInSaa2PbCompA1, rOuSaa2PbCompA1); shSaa2PbComp->DefineSection( 2, z, rInSaa2PbCompA2, rOuSaa2PbCompA2); // 2nd Step z += dzSaa2PbCompA2; shSaa2PbComp->DefineSection( 3, z, rInSaa2PbCompA2, rOuSaa2PbCompA2); shSaa2PbComp->DefineSection( 4, z, rInSaa2PbCompA3, rOuSaa2PbCompA3); // straight section z += dzSaa2PbCompA3; shSaa2PbComp->DefineSection( 5, z, rInSaa2PbCompA3, rOuSaa2PbCompA3); // // Section 1 z += dzSaa2PbComp1; shSaa2PbComp->DefineSection( 6, z, rInSaa2PbComp1, rOuSaa2PbComp1); shSaa2PbComp->DefineSection( 7, z, rInSaa2PbComp1, rOuSaa2PbComp2); // // Section 2 z += dzSaa2PbComp2; shSaa2PbComp->DefineSection( 8, z, rInSaa2PbComp2, rOuSaa2PbComp2); // // Flange SAA3 side (Detail E) z += dzSaa2PbCompE1; shSaa2PbComp->DefineSection( 9, z, rInSaa2PbCompE1, rOuSaa2PbCompE1); // 45 deg transition z += dzSaa2PbCompE2; shSaa2PbComp->DefineSection( 10, z, rInSaa2PbCompE3, rOuSaa2PbCompE1); // 1st step z += dzSaa2PbCompE3; shSaa2PbComp->DefineSection( 11, z, rInSaa2PbCompE3, rOuSaa2PbCompE1); shSaa2PbComp->DefineSection( 12, z, rInSaa2PbCompE3, rOuSaa2PbCompE3); // 2nd step z += dzSaa2PbCompE4; shSaa2PbComp->DefineSection( 13, z, rInSaa2PbCompE3, rOuSaa2PbCompE3); shSaa2PbComp->DefineSection( 14, z, rInSaa2PbCompE3, rOuSaa2PbCompE4); // end z += dzSaa2PbCompE5; shSaa2PbComp->DefineSection( 15, z, rInSaa2PbCompE3, rOuSaa2PbCompE4); TGeoVolume* voSaa2PbComp = new TGeoVolume("YSAA2_PbComp", shSaa2PbComp, kMedPbSh); /////////////////////////////////// // SAA2 Inner Tube // // Drawing ALIP2A__0083 // /////////////////////////////////// // // // // Length of saa2: 512.0 cm // Length of inner tube: 501.7 cm // Lenth of bellow recess: 10.3 cm ( 1.5 + 8.8) // Radius at entrance 36.8/2, d = 0.1 // Radius at exit 52.0/2, d = 0.1 // const Float_t kSaa2InnerTubeL = 501.7; // Length of the tube const Float_t kSaa2InnerTubeRmin = 36.6/2.; // Radius at entrance const Float_t kSaa2InnerTubeRmax = 51.8/2.; // Radius at exit const Float_t kSaa2InnerTubeD = 0.2 ; // Thickness TGeoPcon* shSaa2InnerTube = new TGeoPcon(0., 360., 4); z = 0.; shSaa2InnerTube->DefineSection( 0, z, kSaa2InnerTubeRmin - kSaa2InnerTubeD, kSaa2InnerTubeRmin); z += dzSaa2PbCompA2 + dzSaa2PbCompA3; shSaa2InnerTube->DefineSection( 1, z, kSaa2InnerTubeRmin - kSaa2InnerTubeD, kSaa2InnerTubeRmin); z = kSaa2InnerTubeL - dzSaa2PbCompE1; shSaa2InnerTube->DefineSection( 2, z, kSaa2InnerTubeRmax - kSaa2InnerTubeD, kSaa2InnerTubeRmax); z = kSaa2InnerTubeL; shSaa2InnerTube->DefineSection( 3, z, kSaa2InnerTubeRmax - kSaa2InnerTubeD, kSaa2InnerTubeRmax); TGeoVolume* voSaa2InnerTube = new TGeoVolume("YSAA2_InnerTube", shSaa2InnerTube, kMedSteelSh); /////////////////////////////////// // SAA2 Steel Ring // // Drawing ALIP2A__0042 // /////////////////////////////////// // HalfWidth Float_t dzSaa2SteelRing = 2.; TGeoTube* shSaa2SteelRing = new TGeoTube(41.6, 47.6, dzSaa2SteelRing); TGeoVolume* voSaa2SteelRing = new TGeoVolume("YSAA2_SteelRing", shSaa2SteelRing, kMedSteel); /////////////////////////////////// // SAA2 Outer Shape // // Drawing ALIP2A__0108 // /////////////////////////////////// TGeoPcon* shSaa2 = new TGeoPcon(0., 360., 16); kSec = 0.02; // security distance to avoid trivial extrusions rmin = kSaa2InnerTubeRmin - kSaa2InnerTubeD - kSec; rmax = kSaa2InnerTubeRmax - kSaa2InnerTubeD - kSec; // Flange SAA1 side z = 0.; shSaa2->DefineSection( 0, z, rmin , rOuSaa2PbCompA1); z += dzSaa2PbCompA1 + dzSaa2PbCompA2; shSaa2->DefineSection( 1, z, rmin , rOuSaa2PbCompA1); shSaa2->DefineSection( 2, z, rmin , rInSaa2StEnv1 + dSt); z += dzSaa2PbCompA3; shSaa2->DefineSection( 3, z, rmin , rInSaa2StEnv1 + dSt); z = zSaa2PbRing; shSaa2->DefineSection( 4, z, 0. , rInSaa2StEnv1 + dSt); shSaa2->DefineSection( 5, z, 0. , rOuSaa2PbRingF); z += dzSaa2PbRing; shSaa2->DefineSection( 6, z, 0. , rOuSaa2PbRingR); shSaa2->DefineSection( 7, z, 0. , rInSaa2StEnv1 + dSt); z = dzSaa2PbCompA1 + dzSaa2PbCompA2 + dzSaa2StEnv1; shSaa2->DefineSection( 8, z, 0. , rInSaa2StEnv1 + dSt); shSaa2->DefineSection( 9, z, 0. , rInSaa2StEnv2 + dSt); z = dzSaa2PbComp - dzSaa2PbCompB2; shSaa2->DefineSection(10, z, rmax , rInSaa2StEnv2 + dSt); z += dzSaa2PbCompE1; shSaa2->DefineSection(11, z, rmax , rInSaa2StEnv2 + dSt); z += dzSaa2PbCompE2; shSaa2->DefineSection(12, z, rInSaa2PbCompE3, rInSaa2StEnv2 + dSt); z += (dzSaa2PbCompE3 + dzSaa2PbCompE4); shSaa2->DefineSection(13, z, rInSaa2PbCompE3, rInSaa2StEnv2 + dSt); shSaa2->DefineSection(14, z, rInSaa2PbCompE3, rOuSaa2PbCompE4); z += dzSaa2PbCompE5; shSaa2->DefineSection(15, z, rInSaa2PbCompE3, rOuSaa2PbCompE4); TGeoVolume* voSaa2 = new TGeoVolume("YSAA2", shSaa2, kMedAir); voSaa2->SetVisibility(0); // Inner 1.89/2 deg line Double_t zref = dzSaa2PbCompA1 + dzSaa2PbCompA2 + dzSaa2PbCompA3; for (Int_t i = 4; i < 10; i++) { Double_t z = shSaa2->GetZ(i); Double_t r2 = shSaa2->GetRmax(i); Double_t r1 = rmin + (z - zref) * TMath::Tan(1.89 / 2. * kDegRad) - kSec; shSaa2->DefineSection(i, z, r1, r2); } // // Assemble SAA2 voSaa2->AddNode(voSaa2StEnv, 1, gGeoIdentity); voSaa2->AddNode(voSaa2PbRing, 1, gGeoIdentity); voSaa2->AddNode(voSaa2PbComp, 1, gGeoIdentity); voSaa2->AddNode(voSaa2InnerTube, 1, new TGeoTranslation(0., 0., dzSaa2PbCompA1)); z = (dzSaa2PbComp - dzSaa2PbCompE4 - dzSaa2PbCompE5) + dzSaa2SteelRing; voSaa2->AddNode(voSaa2SteelRing, 1, new TGeoTranslation(0., 0., z)); /////////////////////////////////////// // SAA3 // /////////////////////////////////////// // // // This is a study performed by S. Maridor // The SAA3 has not yet been designed !!!!!!!! // /////////////////////////////////// // SAA3 Outer Shape // // Drawing ALIP2A__0xxx // /////////////////////////////////// TGeoVolumeAssembly* voSaa3 = new TGeoVolumeAssembly("YSAA3"); /////////////////////////////////// // SAA3 Steel Components // // Drawing ALIP2A__0xxx // /////////////////////////////////// // Block TGeoBBox* shSaa3CCBlockO = new TGeoBBox(80./2., 80./2., 100./2.); shSaa3CCBlockO->SetName("Saa3CCBlockO"); TGeoPcon* shSaa3InnerRegion = new TGeoPcon(0., 360., 6); shSaa3InnerRegion->DefineSection( 0, -60.0, 0., 56.6/2.); shSaa3InnerRegion->DefineSection( 1, -45.0, 0., 56.6/2.); shSaa3InnerRegion->DefineSection( 2, -42.0, 0., 50.6/2.); shSaa3InnerRegion->DefineSection( 3, -30.0, 0., 50.6/2.); shSaa3InnerRegion->DefineSection( 4, 30.5, 0., 16.8/2.); shSaa3InnerRegion->DefineSection( 5, 60.0, 0., 16.8/2.); shSaa3InnerRegion->SetName("Saa3InnerRegion"); TGeoCompositeShape* shSaa3CCBlock = new TGeoCompositeShape("Saa3CCBlock", "Saa3CCBlockO-Saa3InnerRegion"); TGeoVolume* voSaa3CCBlock = new TGeoVolume("YSAA3CCBlock", shSaa3CCBlock, kMedConcSh); voSaa3->AddNode(voSaa3CCBlock, 1, gGeoIdentity); // Plate 1: 240 cm x 80 cm x 100 cm (x 2) TGeoVolume* voSaa3SteelPlate1 = new TGeoVolume("YSAA3SteelPlate1", new TGeoBBox(240./2., 80./2., 100./2.), kMedSteelSh); TGeoVolume* voSaa3SteelPlate11 = new TGeoVolume("YSAA3SteelPlate11", new TGeoBBox(240./2., 80./2., 10./2.), kMedSteel); voSaa3SteelPlate1->AddNode(voSaa3SteelPlate11, 1, new TGeoTranslation(0., 0., -45.)); voSaa3->AddNode(voSaa3SteelPlate1, 1, new TGeoTranslation(0., +80., 0.)); voSaa3->AddNode(voSaa3SteelPlate1, 2, new TGeoTranslation(0., -80., 0.)); // Plate 2: 80 cm x 80 cm x 100 cm (x 2) TGeoVolume* voSaa3SteelPlate2 = new TGeoVolume("YSAA3SteelPlate2", new TGeoBBox( 80./2., 80./2., 100./2.), kMedSteelSh); TGeoVolume* voSaa3SteelPlate21 = new TGeoVolume("YSAA3SteelPlate21", new TGeoBBox( 80./2., 80./2., 10./2.), kMedSteel); voSaa3SteelPlate2->AddNode(voSaa3SteelPlate21, 1, new TGeoTranslation(0., 0., -45.)); voSaa3->AddNode(voSaa3SteelPlate2, 1, new TGeoTranslation(+80, 0., 0.)); voSaa3->AddNode(voSaa3SteelPlate2, 2, new TGeoTranslation(-80, 0., 0.)); /////////////////////////////////// // Muon Filter // // Drawing ALIP2A__0105 // /////////////////////////////////// // Half Length Float_t dzMuonFilter = 60.; TGeoBBox* shMuonFilterO = new TGeoBBox(550./2., 620./2., dzMuonFilter); shMuonFilterO->SetName("FilterO"); TGeoCombiTrans* trFilter = new TGeoCombiTrans("trFilter", 0., -dzMuonFilter * TMath::Tan(alhc * kDegrad), 0., rotlhc); trFilter->RegisterYourself(); TGeoTube* shMuonFilterI = new TGeoTube(0., 48.8, dzMuonFilter + 20.); shMuonFilterI->SetName("FilterI"); TGeoCompositeShape* shMuonFilter = new TGeoCompositeShape("MuonFilter", "FilterO-FilterI:trFilter"); // // !!!!! Needs to be inclined TGeoVolume* voMuonFilter = new TGeoVolume("YMuonFilter", shMuonFilter, kMedSteel); // Inner part with higher transport cuts Float_t dzMuonFilterH = 50.; TGeoBBox* shMuonFilterOH = new TGeoBBox(550./2., 620./2., dzMuonFilterH); shMuonFilterOH->SetName("FilterOH"); TGeoTube* shMuonFilterIH = new TGeoTube(0., 50., dzMuonFilterH + 5.); shMuonFilterIH->SetName("FilterIH"); TGeoCompositeShape* shMuonFilterH = new TGeoCompositeShape("MuonFilterH", "FilterOH-FilterIH:trFilter"); TGeoVolume* voMuonFilterH = new TGeoVolume("YMuonFilterH", shMuonFilterH, kMedSteelSh); voMuonFilter->AddNode(voMuonFilterH, 1, gGeoIdentity); // TGeoVolumeAssembly* voSaa = new TGeoVolumeAssembly("YSAA"); // // // // // // Starting position of the FA Flange/Tail Float_t ziFaWTail = 499.0; // End of the FA Flange/Tail Float_t zoFaWTail = ziFaWTail + dzFaWTail; // Starting position of the FA/SAA1 Joint (2.8 cm overlap with tail) Float_t ozFaSaa1 = 2.8; Float_t ziFaSaa1 = zoFaWTail - ozFaSaa1; // End of the FA/SAA1 Joint Float_t zoFaSaa1 = ziFaSaa1 + dzFaSaa1; // Starting position of SAA1 (2.0 cm overlap with joint) Float_t ozSaa1 = 2.; Float_t ziSaa1 = zoFaSaa1 - ozSaa1; // End of SAA1 Float_t zoSaa1 = ziSaa1 + dzSaa1; // Starting position of SAA1/SAA2 Joint (1.95 cm overlap with SAA1) Float_t ziSaa1Saa2 = zoSaa1 - 1.95; // End of SAA1/SAA2 Joint Float_t zoSaa1Saa2 = ziSaa1Saa2 + dzSaa1Saa2; // Starting position of SAA2 (3.1 cm overlap with the joint) Float_t ziSaa2 = zoSaa1Saa2 - 3.1; // End of SAA2 Float_t zoSaa2 = ziSaa2 + dzSaa2PbComp; // Position of SAA3 Float_t zcSaa3 = zoSaa2 + 50.; // Position of the Muon Filter Float_t zcFilter = 1465.9 + dzMuonFilter; voSaa->AddNode(voFaWTail, 1, new TGeoTranslation(0., 0., ziFaWTail)); voSaa->AddNode(voFaSaa1, 1, new TGeoTranslation(0., 0., ziFaSaa1)); voSaa->AddNode(voSaa1 , 1, new TGeoTranslation(0., 0., ziSaa1)); voSaa->AddNode(voSaa1Saa2, 1, new TGeoTranslation(0., 0., ziSaa1Saa2)); voSaa->AddNode(voSaa2 , 1, new TGeoTranslation(0., 0., ziSaa2)); voSaa->AddNode(voSaa3, 1, new TGeoTranslation(0., 0., zcSaa3)); TGeoRotation* rotxz = new TGeoRotation("rotxz", 90., 0., 90., 90., 180., 0.); top->AddNode(voSaa, 1, new TGeoCombiTrans(0., 0., 0., rotxz)); // // Mother volume for muon stations 1+2 and shielding material placed between the quadrants // // Position of the dipole Float_t ziDipole = 741.; TGeoPcon* shYOUT1 = new TGeoPcon(0., 360., 25); Float_t eps = 1.e-2; // FA Tail Section for (Int_t iz = 0; iz < 9; iz++) { z = shFaWTail->GetZ(iz+1); if (iz == 8) z -= ozFaSaa1; shYOUT1->DefineSection(iz, z + ziFaWTail, shFaWTail->GetRmax(iz+1) + eps, 150.); } // FA-SAA1 Joint z = shYOUT1->GetZ(8); for (Int_t iz = 9; iz < 17; iz++) shYOUT1->DefineSection(iz, z + shFaSaa1->GetZ(iz-9), shFaSaa1->GetRmax(iz-9) + eps, 150.); z = shYOUT1->GetZ(16) - ozSaa1; // SAA1 - Dipole for (Int_t iz = 17; iz < 24; iz++) shYOUT1->DefineSection(iz, z + shSaa1M->GetZ(iz-13), shSaa1M->GetRmax(iz-13) + eps, 150.); // Distance between dipole and start of SAA1 2deg opening cone dz = ziDipole - (zSaa1StEnv[0] - dSt + zSaa1StEnvS + ziSaa1); rOut = rOuSaa1StEnv2 + dz * TMath::Tan(2. * kDegRad); shYOUT1->DefineSection(24, ziDipole, rOut + eps, 150.); InvertPcon(shYOUT1); TGeoVolume* voYOUT1 = new TGeoVolume("YOUT1", shYOUT1, kMedAirMu); voYOUT1->SetVisibility(0); voYOUT1->AddNode(asSaa1ExtraShield, 1, new TGeoCombiTrans(0., 0., - (100.7 + 62.2 + saa1ExtraShieldL / 2. + ziFaWTail), rotxz)); voYOUT1->AddNode(asFaExtraShield, 1, new TGeoCombiTrans(0., 0., - (16.41 + kFaWring2HWidth + ziFaWTail), rotxz)); top->AddNode(voYOUT1, 1, gGeoIdentity); // // Mother volume for muon stations 4+5 and trigger stations. // Float_t zoDipole = 1249.; TGeoPcon* shYOUT2 = new TGeoPcon(0., 360., 14); z = zoDipole; shYOUT2->DefineSection(0, z, rOuSaa1String, 252.); // Start of SAA1-SAA2 z = ziSaa1Saa2; shYOUT2->DefineSection(1, z, rOuSaa1String, 252.); shYOUT2->DefineSection(2, z, rOuSaa1Saa2Steel, 252.); // End of SAA1-SAA2 z = ziSaa2; shYOUT2->DefineSection(3, z, rOuSaa1Saa2Steel, 252.); // SAA2 shYOUT2->DefineSection( 4, z, rInSaa2StEnv1 + dSt, 252.); z = ziSaa2 + zSaa2PbRing; shYOUT2->DefineSection( 5, z, rInSaa2StEnv1 + dSt, 252.); // Pb Cone shYOUT2->DefineSection( 6, z, rOuSaa2PbRingF, 252.); rmin = rOuSaa2PbRingF + (1380. - z) * TMath::Tan(1.6 * kDegRad); shYOUT2->DefineSection( 7, 1380., rmin, 252.); shYOUT2->DefineSection( 8, 1380., rmin, 304.); z = ziSaa2 + zSaa2PbRing + dzSaa2PbRing; shYOUT2->DefineSection( 9, z, rOuSaa2PbRingR, 304.); // Straight Sections shYOUT2->DefineSection(10, z, rInSaa2StEnv1 + dSt, 460.); z = ziSaa2 + dzSaa2StEnv1; shYOUT2->DefineSection(11, z, rInSaa2StEnv1 + dSt, 460.); shYOUT2->DefineSection(12, z, rInSaa2StEnv2 + dSt, 460.); z += dzSaa2StEnv2; shYOUT2->DefineSection(13, z, rInSaa2StEnv2 + dSt, 460.); InvertPcon(shYOUT2); TGeoVolume* voYOUT2 = new TGeoVolume("YOUT2", shYOUT2, kMedAirMu); voYOUT2->SetVisibility(0); voYOUT2->AddNode(voMuonFilter, 1, new TGeoCombiTrans(0., dzMuonFilter * TMath::Tan(alhc * kDegrad), -zcFilter, rotxzlhc)); top->AddNode(voYOUT2, 1, gGeoIdentity); } void AliSHILv3::Init() { // // Initialise the muon shield after it has been built // Int_t i; // if(AliLog::GetGlobalDebugLevel()>0) { printf("\n%s: ",ClassName()); for(i=0;i<35;i++) printf("*"); printf(" SHILv3_INIT "); for(i=0;i<35;i++) printf("*"); printf("\n%s: ",ClassName()); // // Here the SHIL initialisation code (if any!) for(i=0;i<80;i++) printf("*"); printf("\n"); } } void AliSHILv3::InvertPcon(TGeoPcon* pcon) { // // z -> -z // Int_t nz = pcon->GetNz(); Double_t* z = new Double_t[nz]; Double_t* rmin = new Double_t[nz]; Double_t* rmax = new Double_t[nz]; Double_t* z0 = pcon->GetZ(); Double_t* rmin0 = pcon->GetRmin(); Double_t* rmax0 = pcon->GetRmax(); for (Int_t i = 0; i < nz; i++) { z[i] = z0[i]; rmin[i] = rmin0[i]; rmax[i] = rmax0[i]; } for (Int_t i = 0; i < nz; i++) { Int_t j = nz - i - 1; pcon->DefineSection(i, - z[j], rmin[j], rmax[j]); } delete[] z; delete[] rmin; delete[] rmax; } TGeoPcon* AliSHILv3::MakeShapeFromTemplate(TGeoPcon* pcon, Float_t drMin, Float_t drMax) { // // Returns new shape based on a template changing // the inner radii by drMin and the outer radii by drMax. // Int_t nz = pcon->GetNz(); TGeoPcon* cpcon = new TGeoPcon(0., 360., nz); for (Int_t i = 0; i < nz; i++) cpcon->DefineSection(i, pcon->GetZ(i), pcon->GetRmin(i) + drMin, pcon->GetRmax(i) + drMax); return cpcon; } SAA3 as built update. /************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //------------------------------------------------------------------------- // The small angle absorber SAA (beam shield) // Author: A.Morsch // andreas.morsch@cern.ch //------------------------------------------------------------------------- #include <TVirtualMC.h> #include <TArrayI.h> #include <TGeoVolume.h> #include <TGeoTube.h> #include <TGeoManager.h> #include <TGeoMatrix.h> #include <TGeoCompositeShape.h> #include <TGeoBBox.h> #include <TGeoPgon.h> #include <TGeoCone.h> #include "AliSHILv3.h" #include "AliConst.h" #include "AliLog.h" ClassImp(AliSHILv3) //_____________________________________________________________________________ AliSHILv3::AliSHILv3() { // // Default constructor for muon shield // } //_____________________________________________________________________________ AliSHILv3::AliSHILv3(const char *name, const char *title) : AliSHIL(name,title) { // // Standard constructor for muon shield // } //_____________________________________________________________________________ void AliSHILv3::CreateGeometry() { // // The geometry of the small angle absorber "Beam Shield" // Float_t dz, dr, z, rmax; // // The top volume // TGeoVolume* top = gGeoManager->GetVolume("ALIC"); // Rotations TGeoRotation* rot000 = new TGeoRotation("rot000", 90., 0., 90., 90., 0., 0.); TGeoRotation* rot090 = new TGeoRotation("rot090", 90., 90., 90., 180., 0., 0.); TGeoRotation* rot180 = new TGeoRotation("rot180", 90., 180., 90., 270., 0., 0.); TGeoRotation* rot270 = new TGeoRotation("rot270", 90., 270., 90., 0., 0., 0.); Float_t alhc = 0.794; TGeoRotation* rotxzlhc = new TGeoRotation("rotxzlhc", 0., -alhc, 0.); TGeoRotation* rotlhc = new TGeoRotation("rotlhc", 0., alhc, 0.); // // Media // TGeoMedium* kMedNiW = gGeoManager->GetMedium("SHIL_Ni/W0"); TGeoMedium* kMedNiWsh = gGeoManager->GetMedium("SHIL_Ni/W3"); // TGeoMedium* kMedSteel = gGeoManager->GetMedium("SHIL_ST_C0"); TGeoMedium* kMedSteelSh = gGeoManager->GetMedium("SHIL_ST_C3"); // TGeoMedium* kMedAir = gGeoManager->GetMedium("SHIL_AIR_C0"); TGeoMedium* kMedAirMu = gGeoManager->GetMedium("SHIL_AIR_MUON"); // TGeoMedium* kMedPb = gGeoManager->GetMedium("SHIL_PB_C0"); TGeoMedium* kMedPbSh = gGeoManager->GetMedium("SHIL_PB_C2"); // TGeoMedium* kMedConcSh = gGeoManager->GetMedium("SHIL_CC_C2"); // const Float_t kDegRad = TMath::Pi() / 180.; const Float_t kAngle02 = TMath::Tan( 2.00 * kDegRad); const Float_t kAngle0071 = TMath::Tan( 0.71 * kDegRad); /////////////////////////////////// // FA Tungsten Tail // // Drawing ALIP2A__0049 // // Drawing ALIP2A__0111 // /////////////////////////////////// // // The tail as built is shorter than in drawing ALIP2A__0049. // The CDD data base has to be updated ! // // Inner radius at the entrance of the flange Float_t rInFaWTail1 = 13.98/2.; // Outer radius at the entrance of the flange Float_t rOuFaWTail1 = 52.00/2.; // Outer radius at the end of the section inside the FA Float_t rOuFaWTail2 = 35.27/2.; // Length of the Flange section inside the FA Float_t dzFaWTail1 = 6.00; // Length of the Flange section ouside the FA Float_t dzFaWTail2 = 12.70; // Inner radius at the end of the section inside the FA Float_t rInFaWTail2 = rInFaWTail1 + dzFaWTail1 * kAngle0071; // Inner radius at the end of the flange Float_t rInFaWTail3 = rInFaWTail2 + dzFaWTail2 * kAngle0071; // Outer radius at the end of the flange Float_t rOuFaWTail3 = rOuFaWTail2 + dzFaWTail2 * kAngle02; // Outer radius of the recess for station 1 Float_t rOuFaWTailR = 30.8/2.; // Length of the recess Float_t dzFaWTailR = 36.00; // Inner radiues at the end of the recess Float_t rInFaWTail4 = rInFaWTail3 + dzFaWTailR * kAngle0071; // Outer radius at the end of the recess Float_t rOuFaWTail4 = rOuFaWTail3 + dzFaWTailR * kAngle02; // Inner radius of the straight section Float_t rInFaWTailS = 22.30/2.; // Length of the bulge Float_t dzFaWTailB = 13.0; // Outer radius at the end of the bulge Float_t rOuFaWTailB = rOuFaWTail4 + dzFaWTailB * kAngle02; // Outer radius at the end of the tail Float_t rOuFaWTailE = 31.6/2.; // Total length of the tail Float_t dzFaWTail = 70.7; TGeoPcon* shFaWTail = new TGeoPcon(0., 360., 10); z = 0.; // Flange section inside FA shFaWTail->DefineSection(0, z, rInFaWTail1, rOuFaWTail1); z += dzFaWTail1; shFaWTail->DefineSection(1, z, rInFaWTail2, rOuFaWTail1); shFaWTail->DefineSection(2, z, rInFaWTail2, rOuFaWTail2); // Flange section outside FA z += dzFaWTail2; shFaWTail->DefineSection(3, z, rInFaWTail3, rOuFaWTail3); shFaWTail->DefineSection(4, z, rInFaWTail3, rOuFaWTailR); // Recess Station 1 z += dzFaWTailR; shFaWTail->DefineSection(5, z, rInFaWTail4, rOuFaWTailR); shFaWTail->DefineSection(6, z, rInFaWTailS, rOuFaWTail4); // Bulge z += dzFaWTailB; shFaWTail->DefineSection(7, z, rInFaWTailS, rOuFaWTailB); shFaWTail->DefineSection(8, z, rInFaWTailS, rOuFaWTailE); // End z = dzFaWTail; shFaWTail->DefineSection(9, z, rInFaWTailS, rOuFaWTailE); TGeoVolume* voFaWTail = new TGeoVolume("YFaWTail", shFaWTail, kMedNiW); // // Define an inner region with higher transport cuts TGeoPcon* shFaWTailI = new TGeoPcon(0., 360., 4); z = 0.; dr = 3.5; shFaWTailI->DefineSection(0, z, rInFaWTail1, rInFaWTail1 + dr); z += (dzFaWTail1 + dzFaWTail2 + dzFaWTailR); shFaWTailI->DefineSection(1, z, rInFaWTail4, rInFaWTail4 + dr); shFaWTailI->DefineSection(2, z, rInFaWTailS, rInFaWTailS + dr); z = dzFaWTail; shFaWTailI->DefineSection(3, z, rInFaWTailS, rInFaWTailS + dr); TGeoVolume* voFaWTailI = new TGeoVolume("YFaWTailI", shFaWTailI, kMedNiWsh); voFaWTail->AddNode(voFaWTailI, 1, gGeoIdentity); /////////////////////////////////// // // // Recess Station 1 // // Drawing ALIP2A__0260 // /////////////////////////////////// /////////////////////////////////// // FA W-Ring 2 // // Drawing ALIP2A__0220 // /////////////////////////////////// const Float_t kFaWring2Rinner = 15.40; const Float_t kFaWring2Router = 18.40; const Float_t kFaWring2HWidth = 3.75; const Float_t kFaWring2Cutoffx = 3.35; const Float_t kFaWring2Cutoffy = 3.35; TGeoTubeSeg* shFaWring2a = new TGeoTubeSeg(kFaWring2Rinner, kFaWring2Router, kFaWring2HWidth, 0., 90.); shFaWring2a->SetName("shFaWring2a"); TGeoBBox* shFaWring2b = new TGeoBBox(kFaWring2Router / 2., kFaWring2Router / 2., kFaWring2HWidth); shFaWring2b->SetName("shFaWring2b"); TGeoTranslation* trFaWring2b = new TGeoTranslation("trFaWring2b", kFaWring2Router / 2. + kFaWring2Cutoffx, kFaWring2Router / 2. + kFaWring2Cutoffy, 0.); trFaWring2b->RegisterYourself(); TGeoCompositeShape* shFaWring2 = new TGeoCompositeShape("shFaWring2", "(shFaWring2a)*(shFaWring2b:trFaWring2b)"); TGeoVolume* voFaWring2 = new TGeoVolume("YFA_WRING2", shFaWring2, kMedNiW); /////////////////////////////////// // FA W-Ring 3 // // Drawing ALIP2A__0219 // /////////////////////////////////// const Float_t kFaWring3Rinner = 15.40; const Float_t kFaWring3Router = 18.40; const Float_t kFaWring3HWidth = 3.75; const Float_t kFaWring3Cutoffx = 3.35; const Float_t kFaWring3Cutoffy = 3.35; TGeoTubeSeg* shFaWring3a = new TGeoTubeSeg(kFaWring3Rinner, kFaWring3Router, kFaWring3HWidth, 0., 90.); shFaWring3a->SetName("shFaWring3a"); TGeoBBox* shFaWring3b = new TGeoBBox(kFaWring3Router / 2., kFaWring3Router / 2., kFaWring3HWidth); shFaWring3b->SetName("shFaWring3b"); TGeoTranslation* trFaWring3b = new TGeoTranslation("trFaWring3b", kFaWring3Router / 2. + kFaWring3Cutoffx, kFaWring3Router / 2. + kFaWring3Cutoffy, 0.); trFaWring3b->RegisterYourself(); TGeoCompositeShape* shFaWring3 = new TGeoCompositeShape("shFaWring3", "(shFaWring3a)*(shFaWring3b:trFaWring3b)"); TGeoVolume* voFaWring3 = new TGeoVolume("YFA_WRING3", shFaWring3, kMedNiW); /////////////////////////////////// // FA W-Ring 5 // // Drawing ALIP2A__0221 // /////////////////////////////////// const Float_t kFaWring5Rinner = 15.40; const Float_t kFaWring5Router = 18.67; const Float_t kFaWring5HWidth = 1.08; TGeoVolume* voFaWring5 = new TGeoVolume("YFA_WRING5", new TGeoTube(kFaWring5Rinner, kFaWring5Router, kFaWring5HWidth), kMedNiW); // // Position the rings in the assembly // TGeoVolumeAssembly* asFaExtraShield = new TGeoVolumeAssembly("YCRE"); // Distance between rings const Float_t kFaDWrings = 1.92; // dz = 0.; dz += kFaWring2HWidth; asFaExtraShield->AddNode(voFaWring2, 1, new TGeoCombiTrans(0., 0., dz, rot090)); asFaExtraShield->AddNode(voFaWring2, 2, new TGeoCombiTrans(0., 0., dz, rot270)); dz += kFaWring2HWidth; dz += kFaDWrings; dz += kFaWring3HWidth; asFaExtraShield->AddNode(voFaWring3, 1, new TGeoCombiTrans(0., 0., dz, rot000)); asFaExtraShield->AddNode(voFaWring3, 2, new TGeoCombiTrans(0., 0., dz, rot180)); dz += kFaWring3HWidth; dz += kFaWring5HWidth; asFaExtraShield->AddNode(voFaWring5, 1, new TGeoTranslation(0., 0., dz)); dz += kFaWring5HWidth; dz += kFaWring3HWidth; asFaExtraShield->AddNode(voFaWring3, 3, new TGeoCombiTrans(0., 0., dz, rot090)); asFaExtraShield->AddNode(voFaWring3, 4, new TGeoCombiTrans(0., 0., dz, rot270)); dz += kFaWring3HWidth; dz += kFaDWrings; dz += kFaWring2HWidth; asFaExtraShield->AddNode(voFaWring2, 3, new TGeoCombiTrans(0., 0., dz, rot000)); asFaExtraShield->AddNode(voFaWring2, 4, new TGeoCombiTrans(0., 0., dz, rot180)); dz += kFaWring2HWidth; /////////////////////////////////////// // SAA1 // /////////////////////////////////////// /////////////////////////////////////// // FA/SAA1 W Joint // // Drawing ALIP2A__0060 // /////////////////////////////////////// // Length of flange FA side Float_t dzFaSaa1F1 = 2.8; // Inner radius of flange FA side Float_t rInFaSaa1F1 = 32.0/2.; // Outer radius of flange FA side Float_t rOuFaSaa1F1 = 39.5/2.; // Length of first straight section Float_t dzFaSaa1S1 = 18.5 - dzFaSaa1F1; // Inner radius of first straight section Float_t rInFaSaa1S1 = 22.3/2.; // Length of 45 deg transition region Float_t dzFaSaa1T1 = 2.2; // Inner radius of second straight section Float_t rInFaSaa1S2 = 17.9/2.; // Length of second straight section Float_t dzFaSaa1S2 = 10.1; // Length of flange SAA1 side // Float_t dzFaSaa1F2 = 4.0; // Inner radius of flange FA side Float_t rInFaSaa1F2 = 25.2/2.; // Length of joint Float_t dzFaSaa1 = 34.8; // Outer Radius at the end of the joint Float_t rOuFaSaa1E = 41.93/2.; TGeoPcon* shFaSaa1 = new TGeoPcon(0., 360., 8); z = 0; // Flange FA side shFaSaa1->DefineSection( 0, z, rInFaSaa1F1, rOuFaSaa1F1); z += dzFaSaa1F1; shFaSaa1->DefineSection( 1, z, rInFaSaa1F1, 40.0); shFaSaa1->DefineSection( 2, z, rInFaSaa1S1, 40.0); // First straight section z += dzFaSaa1S1; shFaSaa1->DefineSection( 3, z, rInFaSaa1S1, 40.0); // 45 deg transition region z += dzFaSaa1T1; shFaSaa1->DefineSection( 4, z, rInFaSaa1S2, 40.0); // Second straight section z += dzFaSaa1S2; shFaSaa1->DefineSection( 5, z, rInFaSaa1S2, 40.0); shFaSaa1->DefineSection( 6, z, rInFaSaa1F2, 40.0); // Flange SAA1 side z = dzFaSaa1; shFaSaa1->DefineSection( 7, z, rInFaSaa1F2, rOuFaSaa1E); // Outer 2 deg line for (Int_t i = 1; i < 7; i++) { Double_t z = shFaSaa1->GetZ(i); Double_t r1 = shFaSaa1->GetRmin(i); Double_t r2 = 39.5/2. + z * TMath::Tan(2. * kDegRad) - 0.01; shFaSaa1->DefineSection(i, z, r1, r2); } TGeoVolume* voFaSaa1 = new TGeoVolume("YFASAA1", shFaSaa1, kMedNiWsh); // // Outer region with lower transport cuts TGeoCone* shFaSaa1O = new TGeoCone(dzFaSaa1/2., rOuFaSaa1F1 - 3.5, rOuFaSaa1F1, rOuFaSaa1E - 3.5, rOuFaSaa1E); TGeoVolume* voFaSaa1O = new TGeoVolume("YFASAA1O", shFaSaa1O, kMedNiW); voFaSaa1->AddNode(voFaSaa1O, 1, new TGeoTranslation(0., 0., dzFaSaa1/2.)); /////////////////////////////////// // SAA1 Steel Envelope // // Drawing ALIP2A__0039 // /////////////////////////////////// Float_t rOut; // Outer radius // Thickness of the steel envelope Float_t dSt = 4.; // 4 Section // z-positions Float_t zSaa1StEnv[5] = {111.2, 113.7, 229.3, 195.0}; // Radii // 1 Float_t rOuSaa1StEnv1 = 40.4/2.; Float_t rInSaa1StEnv1 = rOuSaa1StEnv1 - dSt; // 2 Float_t rInSaa1StEnv2 = 41.7/2.; Float_t rOuSaa1StEnv2 = rInSaa1StEnv2 + dSt / TMath::Cos(2.0 * kDegRad); // 3 Float_t rOuSaa1StEnv3 = 57.6/2.; Float_t rInSaa1StEnv3 = rOuSaa1StEnv3 - dSt; // 4 Float_t rInSaa1StEnv4 = 63.4/2.; Float_t rOuSaa1StEnv4 = rInSaa1StEnv4 + dSt / TMath::Cos(1.6 * kDegRad); // end Float_t rInSaa1StEnv5 = 74.28/2.; Float_t rOuSaa1StEnv5 = rInSaa1StEnv5 + dSt / TMath::Cos(1.6 * kDegRad); // Relative starting position Float_t zSaa1StEnvS = 3.; TGeoPcon* shSaa1StEnv = new TGeoPcon(0., 360., 11); // 1st Section z = zSaa1StEnvS; shSaa1StEnv->DefineSection( 0, z, rInSaa1StEnv1, rOuSaa1StEnv1); z += (zSaa1StEnv[0] - dSt); shSaa1StEnv->DefineSection( 1, z, rInSaa1StEnv1, rOuSaa1StEnv1); // 1 - 2 shSaa1StEnv->DefineSection( 2, z, rInSaa1StEnv1, rOuSaa1StEnv2); z += dSt; shSaa1StEnv->DefineSection( 3, z, rInSaa1StEnv1, rOuSaa1StEnv2); // 2nd Section shSaa1StEnv->DefineSection( 4, z, rInSaa1StEnv2, rOuSaa1StEnv2); z += zSaa1StEnv[1]; shSaa1StEnv->DefineSection( 5, z, rInSaa1StEnv3, rOuSaa1StEnv3); // 3rd Section z += (zSaa1StEnv[2] - dSt); shSaa1StEnv->DefineSection( 6, z, rInSaa1StEnv3, rOuSaa1StEnv3); // 3 - 4 shSaa1StEnv->DefineSection( 7, z, rInSaa1StEnv3, rOuSaa1StEnv4); z += dSt; shSaa1StEnv->DefineSection( 8, z, rInSaa1StEnv3, rOuSaa1StEnv4); // 4th Section shSaa1StEnv->DefineSection( 9, z, rInSaa1StEnv4, rOuSaa1StEnv4); z += zSaa1StEnv[3]; shSaa1StEnv->DefineSection(10, z, rInSaa1StEnv5, rOuSaa1StEnv5); TGeoVolume* voSaa1StEnv = new TGeoVolume("YSAA1_SteelEnvelope", shSaa1StEnv, kMedSteel); /////////////////////////////////// // SAA1 W-Pipe // // Drawing ALIP2A__0059 // /////////////////////////////////// // // Flange FA side // Length of first section Float_t dzSaa1WPipeF1 = 0.9; // Outer radius Float_t rOuSaa1WPipeF1 = 24.5/2.; // Inner Radius Float_t rInSaa1WPipeF1 = 22.0/2.; // Length of second section Float_t dzSaa1WPipeF11 = 2.1; // Inner Radius Float_t rInSaa1WPipeF11 = 18.5/2.; // // Central tube // Length Float_t dzSaa1WPipeC = 111.2; // Inner Radius at the end Float_t rInSaa1WPipeC = 22.0/2.; // Outer Radius Float_t rOuSaa1WPipeC = 31.9/2.; // // Flange SAA2 Side // Length Float_t dzSaa1WPipeF2 = 6.0; // Outer radius Float_t rOuSaa1WPipeF2 = 41.56/2.; // TGeoPcon* shSaa1WPipe = new TGeoPcon(0., 360., 8); z = 0.; // Flange FA side first section shSaa1WPipe->DefineSection( 0, z, rInSaa1WPipeF1 , rOuSaa1WPipeF1); z += dzSaa1WPipeF1; shSaa1WPipe->DefineSection( 1, z, rInSaa1WPipeF1 , rOuSaa1WPipeF1); // Flange FA side second section shSaa1WPipe->DefineSection( 2, z, rInSaa1WPipeF11, rOuSaa1WPipeF1); z += dzSaa1WPipeF11; shSaa1WPipe->DefineSection( 3, z, rInSaa1WPipeF11, rOuSaa1WPipeF1); // Central Section shSaa1WPipe->DefineSection( 4, z, rInSaa1WPipeF11, rOuSaa1WPipeC); z += dzSaa1WPipeC; shSaa1WPipe->DefineSection( 5, z, rInSaa1WPipeC, rOuSaa1WPipeC); // Flange SAA2 side shSaa1WPipe->DefineSection( 6, z, rInSaa1WPipeC, rOuSaa1WPipeF2); z += dzSaa1WPipeF2; shSaa1WPipe->DefineSection( 7, z, rInSaa1WPipeC, rOuSaa1WPipeF2); TGeoVolume* voSaa1WPipe = new TGeoVolume("YSAA1_WPipe", shSaa1WPipe, kMedNiW); // // Inner region with higher transport cuts TGeoTube* shSaa1WPipeI = new TGeoTube(rInSaa1WPipeC, rOuSaa1WPipeC, dzSaa1WPipeC/2.); TGeoVolume* voSaa1WPipeI = new TGeoVolume("YSAA1_WPipeI", shSaa1WPipeI, kMedNiWsh); voSaa1WPipe->AddNode(voSaa1WPipeI, 1, new TGeoTranslation(0., 0., dzSaa1WPipeF1 + dzSaa1WPipeF11 + dzSaa1WPipeC/2)); /////////////////////////////////// // SAA1 Pb Components // // Drawing ALIP2A__0078 // /////////////////////////////////// // // Inner angle Float_t tanAlpha = TMath::Tan(1.69 / 2. * kDegRad); Float_t tanBeta = TMath::Tan(3.20 / 2. * kDegRad); // // 1st Section 2deg opening cone // Length Float_t dzSaa1PbComp1 = 100.23; // Inner radius at entrance Float_t rInSaa1PbComp1 = 22.0/2.; // It's 21 cm diameter in the drawing. Is this a typo ??!! // Outer radius at entrance Float_t rOuSaa1PbComp1 = 42.0/2.; // // 2nd Section: Straight Section // Length Float_t dzSaa1PbComp2 = 236.77; // Inner radius Float_t rInSaa1PbComp2 = rInSaa1PbComp1 + dzSaa1PbComp1 * tanAlpha; // Outer radius Float_t rOuSaa1PbComp2 = 49.0/2.; // // 3rd Section: 1.6deg opening cone until bellow // Length Float_t dzSaa1PbComp3 = 175.6; // Inner radius Float_t rInSaa1PbComp3 = rInSaa1PbComp2 + dzSaa1PbComp2 * tanAlpha; // Outer radius Float_t rOuSaa1PbComp3 = 62.8/2.; // // 4th Section: Bellow region Float_t dzSaa1PbComp4 = 26.4; // Inner radius Float_t rInSaa1PbComp4 = 37.1/2.; Float_t rInSaa1PbCompB = 43.0/2.; // Outer radius Float_t rOuSaa1PbComp4 = rOuSaa1PbComp3 + dzSaa1PbComp3 * tanBeta; // // 5th Section: Flange SAA2 side // 1st detail Float_t dzSaa1PbCompF1 = 4.; Float_t rOuSaa1PbCompF1 = 74.1/2.; // 2nd detail Float_t dzSaa1PbCompF2 = 3.; Float_t rOuSaa1PbCompF2 = 66.0/2.; Float_t rOuSaa1PbCompF3 = 58.0/2.; TGeoPcon* shSaa1PbComp = new TGeoPcon(0., 360., 11); z = 120.2; // 2 deg opening cone shSaa1PbComp->DefineSection( 0, z, rInSaa1PbComp1, rOuSaa1PbComp1); z += dzSaa1PbComp1; shSaa1PbComp->DefineSection( 1, z, rInSaa1PbComp2, rOuSaa1PbComp2); // Straight section z += dzSaa1PbComp2; shSaa1PbComp->DefineSection( 2, z, rInSaa1PbComp3, rOuSaa1PbComp2); // 1.6 deg opening cone shSaa1PbComp->DefineSection( 3, z, rInSaa1PbComp3, rOuSaa1PbComp3); z += dzSaa1PbComp3; shSaa1PbComp->DefineSection( 4, z, rInSaa1PbComp4, rOuSaa1PbComp4); // Bellow region until outer flange shSaa1PbComp->DefineSection( 5, z, rInSaa1PbCompB, rOuSaa1PbComp4); z += (dzSaa1PbComp4 - dzSaa1PbCompF1 - dzSaa1PbCompF2); shSaa1PbComp->DefineSection( 6, z, rInSaa1PbCompB, rOuSaa1PbCompF1); shSaa1PbComp->DefineSection( 7, z, rInSaa1PbCompB, rOuSaa1PbCompF2); // Flange first step z += dzSaa1PbCompF1; shSaa1PbComp->DefineSection( 8, z, rInSaa1PbCompB, rOuSaa1PbCompF2); shSaa1PbComp->DefineSection( 9, z, rInSaa1PbCompB, rOuSaa1PbCompF3); // Flange second step z += dzSaa1PbCompF2; shSaa1PbComp->DefineSection( 10, z, rInSaa1PbCompB, rOuSaa1PbCompF3); TGeoVolume* voSaa1PbComp = new TGeoVolume("YSAA1_PbComp", shSaa1PbComp, kMedPb); // // Inner region with higher transport cuts TGeoPcon* shSaa1PbCompI = MakeShapeFromTemplate(shSaa1PbComp, 0., -3.); TGeoVolume* voSaa1PbCompI = new TGeoVolume("YSAA1_PbCompI", shSaa1PbCompI, kMedPbSh); voSaa1PbComp->AddNode(voSaa1PbCompI, 1, gGeoIdentity); /////////////////////////////////// // SAA1 W-Cone // // Drawing ALIP2A__0058 // /////////////////////////////////// // Length of the Cone Float_t dzSaa1WCone = 52.9; // Inner and outer radii Float_t rInSaa1WCone1 = 20.4; Float_t rOuSaa1WCone1 = rInSaa1WCone1 + 0.97; Float_t rOuSaa1WCone2 = rInSaa1WCone1 + 2.80; // relative z-position Float_t zSaa1WCone = 9.3; TGeoPcon* shSaa1WCone = new TGeoPcon(0., 360., 2); z = zSaa1WCone; shSaa1WCone->DefineSection( 0, z, rInSaa1WCone1, rOuSaa1WCone1); z += dzSaa1WCone; shSaa1WCone->DefineSection( 1, z, rInSaa1WCone1, rOuSaa1WCone2); TGeoVolume* voSaa1WCone = new TGeoVolume("YSAA1_WCone", shSaa1WCone, kMedNiW); /////////////////////////////////// // SAA1 Steel-Ring // // Drawing ALIP2A__0040 // /////////////////////////////////// // // Length of the ring Float_t dzSaa1StRing = 4.; // Inner and outer radius Float_t rInSaa1String = 33.0; Float_t rOuSaa1String = 41.1; // Relative z-position Float_t zSaa1StRing = 652.2; TGeoPcon* shSaa1StRing = new TGeoPcon(0., 360., 2); z = zSaa1StRing; shSaa1StRing->DefineSection( 0, z, rInSaa1String, rOuSaa1String); z += dzSaa1StRing; shSaa1StRing->DefineSection( 1, z, rInSaa1String, rOuSaa1String); TGeoVolume* voSaa1StRing = new TGeoVolume("YSAA1_StRing", shSaa1StRing, kMedSteel); /////////////////////////////////// // SAA1 Inner Tube // // Drawing ALIP2A__0082 // /////////////////////////////////// // // Length of saa2: 659.2 cm // Length of inner tube: 631.9 cm // Lenth of bellow cavern: 27.3 cm // Radius at entrance 18.5/2, d = 0.3 // Radius at exit 37.1/2, d = 0.3 // Float_t dzSaa1InnerTube = 631.9/2.; // Half length of the tube Float_t rInSaa1InnerTube = 18.2/2.; // Radius at entrance Float_t rOuSaa1InnerTube = 36.8/2.; // Radius at exit Float_t dSaa1InnerTube = 0.2 ; // Thickness TGeoVolume* voSaa1InnerTube = new TGeoVolume("YSAA1_InnerTube", new TGeoCone(dzSaa1InnerTube, rInSaa1InnerTube - dSaa1InnerTube, rInSaa1InnerTube, rOuSaa1InnerTube - dSaa1InnerTube, rOuSaa1InnerTube), kMedSteelSh); /////////////////////////////////// // SAA1 Outer Shape // // Drawing ALIP2A__0107 // /////////////////////////////////// // Total length Float_t dzSaa1 = 659.2; // TGeoPcon* shSaa1M = new TGeoPcon(0., 360., 20); Float_t kSec = 0.01; // security distance to avoid trivial extrusions Float_t rmin = rInSaa1InnerTube - dSaa1InnerTube - kSec; rmax = rOuSaa1InnerTube - dSaa1InnerTube - kSec; z = 0.; shSaa1M->DefineSection( 0, z, rmin, rOuSaa1WPipeF1); z += dzSaa1WPipeF1; shSaa1M->DefineSection( 1, z, rmin, rOuSaa1WPipeF1); shSaa1M->DefineSection( 2, z, 0., rOuSaa1WPipeF1); z += dzSaa1WPipeF11; shSaa1M->DefineSection( 3, z, 0., rOuSaa1WPipeF1); shSaa1M->DefineSection( 4, z, 0., rOuSaa1StEnv1); z = zSaa1WCone; shSaa1M->DefineSection( 5, z, 0., rOuSaa1StEnv1); shSaa1M->DefineSection( 6, z, 0., rOuSaa1WCone1); z += dzSaa1WCone; shSaa1M->DefineSection( 7, z, 0., rOuSaa1WCone2); shSaa1M->DefineSection( 8, z, 0., rOuSaa1StEnv1); z = zSaa1StEnv[0] - dSt + zSaa1StEnvS; shSaa1M->DefineSection( 9, z, 0., rOuSaa1StEnv1); shSaa1M->DefineSection(10, z, 0., rOuSaa1StEnv2); z += (zSaa1StEnv[1] + dSt); shSaa1M->DefineSection(11, z, 0., rOuSaa1StEnv3); z += (zSaa1StEnv[2] - dSt); shSaa1M->DefineSection(12, z, 0., rOuSaa1StEnv3); shSaa1M->DefineSection(13, z, 0., rOuSaa1StEnv4); z += (zSaa1StEnv[3] - dSt + dzSaa1PbCompF1 + dzSaa1PbCompF2 - dzSaa1PbComp4); Float_t rmaxSaa1 = shSaa1M->GetRmax(13) + (z - shSaa1M->GetZ(13)) * TMath::Tan(1.6 * kDegRad); shSaa1M->DefineSection(14, z, 0., rmaxSaa1); shSaa1M->DefineSection(15, z, rmax, rmaxSaa1); z = zSaa1StRing; shSaa1M->DefineSection(16, z, rmax, rOuSaa1String); z += dzSaa1PbCompF1; shSaa1M->DefineSection(17, z, rmax, rOuSaa1String); shSaa1M->DefineSection(18, z, rmax, rOuSaa1PbCompF3); z += dzSaa1PbCompF2; shSaa1M->DefineSection(19, z, rmax, rOuSaa1PbCompF3); // // Inner 1.69deg line for (Int_t i = 2; i < 15; i++) { Double_t z = shSaa1M->GetZ(i); Double_t r2 = shSaa1M->GetRmax(i); Double_t r1 = rmin + (z - 0.9) * TMath::Tan(1.69 / 2. * kDegRad) - kSec; shSaa1M->DefineSection(i, z, r1, r2); } TGeoVolume* voSaa1M = new TGeoVolume("YSAA1M", shSaa1M, kMedAir); voSaa1M->SetVisibility(0); /////////////////////////////////// // // // Recess Station 2 // // Drawing ALIP2A__0260 // /////////////////////////////////// /////////////////////////////////// // SAA1 W-Ring 1 // // Drawing ALIP2A__0217 // /////////////////////////////////// Float_t saa1Wring1Width = 5.85; TGeoPcon* shSaa1Wring1 = new TGeoPcon(0., 360., 2); shSaa1Wring1->DefineSection(0, 0.00 , 20.30, 23.175); shSaa1Wring1->DefineSection(1, saa1Wring1Width, 20.30, 23.400); TGeoVolume* voSaa1Wring1 = new TGeoVolume("YSAA1_WRING1", shSaa1Wring1, kMedNiW); /////////////////////////////////// // SAA1 W-Ring 2 // // Drawing ALIP2A__0055 // /////////////////////////////////// Float_t saa1Wring2Rinner = 20.30; Float_t saa1Wring2Router = 23.40; Float_t saa1Wring2HWidth = 3.75; Float_t saa1Wring2Cutoffx = 4.45; Float_t saa1Wring2Cutoffy = 4.45; TGeoTubeSeg* shSaa1Wring2a = new TGeoTubeSeg(saa1Wring2Rinner, saa1Wring2Router, saa1Wring2HWidth, 0., 90.); shSaa1Wring2a->SetName("shSaa1Wring2a"); TGeoBBox* shSaa1Wring2b = new TGeoBBox(saa1Wring2Router / 2., saa1Wring2Router / 2., saa1Wring2HWidth); shSaa1Wring2b->SetName("shSaa1Wring2b"); TGeoTranslation* trSaa1Wring2b = new TGeoTranslation("trSaa1Wring2b", saa1Wring2Router / 2. + saa1Wring2Cutoffx, saa1Wring2Router / 2. + saa1Wring2Cutoffy, 0.); trSaa1Wring2b->RegisterYourself(); TGeoCompositeShape* shSaa1Wring2 = new TGeoCompositeShape("shSaa1Wring2", "(shSaa1Wring2a)*(shSaa1Wring2b:trSaa1Wring2b)"); TGeoVolume* voSaa1Wring2 = new TGeoVolume("YSAA1_WRING2", shSaa1Wring2, kMedNiW); /////////////////////////////////// // SAA1 W-Ring 3 // // Drawing ALIP2A__0216 // /////////////////////////////////// Float_t saa1Wring3Rinner = 20.30; Float_t saa1Wring3Router = 23.40; Float_t saa1Wring3HWidth = 3.75; Float_t saa1Wring3Cutoffx = 4.50; Float_t saa1Wring3Cutoffy = 4.40; TGeoTubeSeg* shSaa1Wring3a = new TGeoTubeSeg(saa1Wring3Rinner, saa1Wring3Router, saa1Wring3HWidth, 0., 90.); shSaa1Wring3a->SetName("shSaa1Wring3a"); TGeoBBox* shSaa1Wring3b = new TGeoBBox(saa1Wring3Router / 2., saa1Wring3Router / 2., saa1Wring3HWidth); shSaa1Wring3b->SetName("shSaa1Wring3b"); TGeoTranslation* trSaa1Wring3b = new TGeoTranslation("trSaa1Wring3b", saa1Wring3Router / 2. + saa1Wring3Cutoffx, saa1Wring3Router / 2. + saa1Wring3Cutoffy, 0.); trSaa1Wring3b->RegisterYourself(); TGeoCompositeShape* shSaa1Wring3 = new TGeoCompositeShape("shSaa1Wring3", "(shSaa1Wring3a)*(shSaa1Wring3b:trSaa1Wring3b)"); TGeoVolume* voSaa1Wring3 = new TGeoVolume("YSAA1_WRING3", shSaa1Wring3, kMedNiW); /////////////////////////////////// // SAA1 W-Ring 4 // // Drawing ALIP2A__0215 // /////////////////////////////////// Float_t saa1Wring4Width = 5.85; TGeoPcon* shSaa1Wring4 = new TGeoPcon(0., 360., 5); shSaa1Wring4->DefineSection(0, 0.00, 20.30, 23.40); shSaa1Wring4->DefineSection(1, 1.00, 20.30, 23.40); shSaa1Wring4->DefineSection(2, 1.00, 20.30, 24.50); shSaa1Wring4->DefineSection(3, 4.85, 20.30, 24.80); shSaa1Wring4->DefineSection(4, 5.85, 24.10, 24.80); TGeoVolume* voSaa1Wring4 = new TGeoVolume("YSAA1_WRING4", shSaa1Wring4, kMedNiW); /////////////////////////////////// // SAA1 W-Ring 5 // // Drawing ALIP2A__0218 // /////////////////////////////////// Float_t saa1Wring5Rinner = 20.30; Float_t saa1Wring5Router = 23.40; Float_t saa1Wring5HWidth = 0.85; TGeoVolume* voSaa1Wring5 = new TGeoVolume("YSAA1_WRING5", new TGeoTube(saa1Wring5Rinner, saa1Wring5Router, saa1Wring5HWidth), kMedNiW); // // Position the rings in the assembly // TGeoVolumeAssembly* asSaa1ExtraShield = new TGeoVolumeAssembly("YSAA1ExtraShield"); // Distance between rings Float_t saa1DWrings = 2.3; // dz = - (saa1Wring1Width + 6. * saa1Wring2HWidth + 2. * saa1Wring3HWidth + saa1Wring4Width + 2. * saa1Wring5HWidth + 2. * saa1DWrings) / 2.; asSaa1ExtraShield->AddNode(voSaa1Wring1, 1, new TGeoTranslation(0., 0., dz)); dz += saa1Wring1Width; dz += saa1Wring2HWidth; asSaa1ExtraShield->AddNode(voSaa1Wring2, 1, new TGeoCombiTrans(0., 0., dz, rot000)); asSaa1ExtraShield->AddNode(voSaa1Wring2, 2, new TGeoCombiTrans(0., 0., dz, rot180)); dz += saa1Wring2HWidth; dz += saa1DWrings; dz += saa1Wring2HWidth; asSaa1ExtraShield->AddNode(voSaa1Wring2, 3, new TGeoCombiTrans(0., 0., dz, rot090)); asSaa1ExtraShield->AddNode(voSaa1Wring2, 4, new TGeoCombiTrans(0., 0., dz, rot270)); dz += saa1Wring2HWidth; dz += saa1Wring5HWidth; asSaa1ExtraShield->AddNode(voSaa1Wring5, 1, new TGeoTranslation(0., 0., dz)); dz += saa1Wring5HWidth; dz += saa1Wring2HWidth; asSaa1ExtraShield->AddNode(voSaa1Wring2, 5, new TGeoCombiTrans(0., 0., dz, rot000)); asSaa1ExtraShield->AddNode(voSaa1Wring2, 6, new TGeoCombiTrans(0., 0., dz, rot180)); dz += saa1Wring2HWidth; dz += saa1DWrings; dz += saa1Wring3HWidth; asSaa1ExtraShield->AddNode(voSaa1Wring3, 1, new TGeoCombiTrans(0., 0., dz, rot090)); asSaa1ExtraShield->AddNode(voSaa1Wring3, 2, new TGeoCombiTrans(0., 0., dz, rot270)); dz += saa1Wring3HWidth; asSaa1ExtraShield->AddNode(voSaa1Wring4, 1, new TGeoTranslation(0., 0., dz)); dz += saa1Wring4Width; const Float_t saa1ExtraShieldL = 48; // // Assemble SAA1 voSaa1M->AddNode(voSaa1StEnv, 1, gGeoIdentity); voSaa1M->AddNode(voSaa1WPipe, 1, gGeoIdentity); voSaa1M->AddNode(voSaa1PbComp, 1, gGeoIdentity); voSaa1M->AddNode(voSaa1WCone, 1, gGeoIdentity); voSaa1M->AddNode(voSaa1StRing, 1, gGeoIdentity); voSaa1M->AddNode(voSaa1InnerTube, 1, new TGeoTranslation(0., 0., dzSaa1InnerTube + 0.9)); TGeoVolumeAssembly* voSaa1 = new TGeoVolumeAssembly("YSAA1"); voSaa1->AddNode(voSaa1M, 1, gGeoIdentity); /////////////////////////////////////// // SAA1/SAA2 Pb Joint // // Drawing ALIP2A__0081 // /////////////////////////////////////// // // Outer radius Float_t rOuSaa1Saa2 = 70.0/2.; // Flange SAA1 side Float_t dzSaa1Saa2F1 = 3.; Float_t rInSaa1Saa2F1 = 58.5/2.; // 1st Central Section Float_t dzSaa1Saa2C1 = 19.3; Float_t rInSaa1Saa2C1 = 42.8/2.; // Transition Region Float_t dzSaa1Saa2T = 3.3; // 1st Central Section Float_t dzSaa1Saa2C2 = 6.2; Float_t rInSaa1Saa2C2 = 36.2/2.; // Flange SAA2 side Float_t dzSaa1Saa2F2 = 3.1; Float_t rInSaa1Saa2F2 = 54.1/2.; // Total length Float_t dzSaa1Saa2 = 34.9; TGeoPcon* shSaa1Saa2Pb = new TGeoPcon(0., 360., 8); z = 0.; // Flange SAA1 side shSaa1Saa2Pb->DefineSection( 0, z, rInSaa1Saa2F1, rOuSaa1Saa2); z += dzSaa1Saa2F1; shSaa1Saa2Pb->DefineSection( 1, z, rInSaa1Saa2F1, rOuSaa1Saa2); shSaa1Saa2Pb->DefineSection( 2, z, rInSaa1Saa2C1, rOuSaa1Saa2); // Central region 1 z += dzSaa1Saa2C1; shSaa1Saa2Pb->DefineSection( 3, z, rInSaa1Saa2C1, rOuSaa1Saa2); // 45 deg transition z += dzSaa1Saa2T; shSaa1Saa2Pb->DefineSection( 4, z, rInSaa1Saa2C2, rOuSaa1Saa2); z += dzSaa1Saa2C2; shSaa1Saa2Pb->DefineSection( 5, z, rInSaa1Saa2C2, rOuSaa1Saa2); shSaa1Saa2Pb->DefineSection( 6, z, rInSaa1Saa2F2, rOuSaa1Saa2); z += dzSaa1Saa2F2; shSaa1Saa2Pb->DefineSection( 7, z, rInSaa1Saa2F2, rOuSaa1Saa2); TGeoVolume* voSaa1Saa2Pb = new TGeoVolume("YSAA1SAA2Pb", shSaa1Saa2Pb, kMedPb); // // Mother volume and outer steel envelope Float_t rOuSaa1Saa2Steel = 36.9; TGeoPcon* shSaa1Saa2 = MakeShapeFromTemplate(shSaa1Saa2Pb, 0., rOuSaa1Saa2Steel-rOuSaa1Saa2); TGeoVolume* voSaa1Saa2 = new TGeoVolume("YSAA1SAA2", shSaa1Saa2, kMedSteel); voSaa1Saa2->AddNode(voSaa1Saa2Pb, 1, gGeoIdentity); // // Inner region with higher transport cuts // TGeoPcon* shSaa1Saa2I = MakeShapeFromTemplate(shSaa1Saa2Pb, 0., -3.); TGeoVolume* voSaa1Saa2I = new TGeoVolume("YSAA1_SAA2I", shSaa1Saa2I, kMedPbSh); voSaa1Saa2Pb->AddNode(voSaa1Saa2I, 1, gGeoIdentity); /////////////////////////////////////// // SAA2 // /////////////////////////////////////// /////////////////////////////////// // SAA2 Steel Envelope // // Drawing ALIP2A__0041 // /////////////////////////////////// dSt = 4.; // Thickness of steel envelope // Length of the first section Float_t dzSaa2StEnv1 = 163.15; Float_t rInSaa2StEnv1 = 65.8/2.; // Length of the second section Float_t dzSaa2StEnv2 = 340.35 - 4.; Float_t rInSaa2StEnv2 = 87.2/2.; // Rel. starting position Float_t zSaa2StEnv = 3.; TGeoPcon* shSaa2StEnv = new TGeoPcon(0., 360., 6); // First Section z = zSaa2StEnv; shSaa2StEnv->DefineSection( 0, z, rInSaa2StEnv1, rInSaa2StEnv1 + dSt); z += dzSaa2StEnv1; shSaa2StEnv->DefineSection( 1, z, rInSaa2StEnv1, rInSaa2StEnv1 + dSt); // Transition region shSaa2StEnv->DefineSection( 2, z, rInSaa2StEnv1, rInSaa2StEnv2 + dSt); z += dSt; shSaa2StEnv->DefineSection( 3, z, rInSaa2StEnv1, rInSaa2StEnv2 + dSt); // Second section shSaa2StEnv->DefineSection( 4, z, rInSaa2StEnv2, rInSaa2StEnv2 + dSt); z += dzSaa2StEnv2; shSaa2StEnv->DefineSection( 5, z, rInSaa2StEnv2, rInSaa2StEnv2 + dSt); TGeoVolume* voSaa2StEnv = new TGeoVolume("YSAA2_SteelEnvelope", shSaa2StEnv, kMedSteel); /////////////////////////////////// // SAA2 Pb Ring // // Drawing ALIP2A__0080 // // Drawing ALIP2A__0111 // /////////////////////////////////// // // Rel. position in z Float_t zSaa2PbRing = 35.25; // Length Float_t dzSaa2PbRing = 65.90; // Inner radius Float_t rInSaa2PbRing = 37.00; // Outer radius at front Float_t rOuSaa2PbRingF = 42.74; // Outer Rradius at rear Float_t rOuSaa2PbRingR = 44.58; TGeoPcon* shSaa2PbRing = new TGeoPcon(0., 360., 2); z = zSaa2PbRing; shSaa2PbRing->DefineSection(0, z, rInSaa2PbRing, rOuSaa2PbRingF); z += dzSaa2PbRing; shSaa2PbRing->DefineSection(1, z, rInSaa2PbRing, rOuSaa2PbRingR); TGeoVolume* voSaa2PbRing = new TGeoVolume("YSAA2_PbRing", shSaa2PbRing, kMedPb); /////////////////////////////////// // SAA2 Pb Components // // Drawing ALIP2A__0079 // /////////////////////////////////// tanAlpha = TMath::Tan(1.89 / 2. * kDegRad); TGeoPcon* shSaa2PbComp = new TGeoPcon(0., 360., 16); // Total length Float_t dzSaa2PbComp = 512.; // Length of 1st bellow recess Float_t dzSaa2PbCompB1 = 24.; // Length of 2nd bellow recess Float_t dzSaa2PbCompB2 = 27.; // Flange on the SAA1 side Detail A // 1st Step Float_t dzSaa2PbCompA1 = 1.5; Float_t rInSaa2PbCompA1 = 43.0/2.; Float_t rOuSaa2PbCompA1 = 53.0/2.; // 2nd Step Float_t dzSaa2PbCompA2 = 1.5; Float_t rInSaa2PbCompA2 = 36.8/2.; Float_t rOuSaa2PbCompA2 = rOuSaa2PbCompA1; // Straight section Float_t dzSaa2PbCompA3 = 21.0; Float_t rInSaa2PbCompA3 = rInSaa2PbCompA2; Float_t rOuSaa2PbCompA3 = 65.2/2.; // // 1st Section (outer straight, inner 1.89/2. deg opening cone) // Length Float_t dzSaa2PbComp1 = 146.15; // Inner radius at the end Float_t rInSaa2PbComp1 = rInSaa2PbCompA3 + dzSaa2PbComp1 * tanAlpha; // Outer radius Float_t rOuSaa2PbComp1 = rOuSaa2PbCompA3; // // 2nd Section (outer straight, inner 1.89/2. deg opening cone) // Length Float_t dzSaa2PbComp2 = (dzSaa2PbComp - dzSaa2PbComp1 - dzSaa2PbCompB1 - dzSaa2PbCompB2); // Inner radius at the end Float_t rInSaa2PbComp2 = rInSaa2PbComp1 + dzSaa2PbComp2 * tanAlpha; // Outer radius Float_t rOuSaa2PbComp2 = 86.6/2.; // // Flange on the SAA3 side (Detail E) // // Straight Section // Length dzSaa2PbCompB2 - 8.8 = 27 - 8.8 = 18.2 Float_t dzSaa2PbCompE1 = 18.2; Float_t rInSaa2PbCompE1 = 52.0/2.; Float_t rOuSaa2PbCompE1 = 86.6/2.; // 45 deg transition Float_t dzSaa2PbCompE2 = 2.7; // 1st Step Float_t dzSaa2PbCompE3 = 0.6; Float_t rInSaa2PbCompE3 = 52.0/2.+ dzSaa2PbCompE2; Float_t rOuSaa2PbCompE3 = 83.0/2.; // 2nd Step Float_t dzSaa2PbCompE4 = 4.0; Float_t rOuSaa2PbCompE4 = 61.6/2.; // end Float_t dzSaa2PbCompE5 = 1.5; // // Flange on SAA1 side (Detail A) z = 0.; // 1st Step shSaa2PbComp->DefineSection( 0, z, rInSaa2PbCompA1, rOuSaa2PbCompA1); z += dzSaa2PbCompA1; shSaa2PbComp->DefineSection( 1, z, rInSaa2PbCompA1, rOuSaa2PbCompA1); shSaa2PbComp->DefineSection( 2, z, rInSaa2PbCompA2, rOuSaa2PbCompA2); // 2nd Step z += dzSaa2PbCompA2; shSaa2PbComp->DefineSection( 3, z, rInSaa2PbCompA2, rOuSaa2PbCompA2); shSaa2PbComp->DefineSection( 4, z, rInSaa2PbCompA3, rOuSaa2PbCompA3); // straight section z += dzSaa2PbCompA3; shSaa2PbComp->DefineSection( 5, z, rInSaa2PbCompA3, rOuSaa2PbCompA3); // // Section 1 z += dzSaa2PbComp1; shSaa2PbComp->DefineSection( 6, z, rInSaa2PbComp1, rOuSaa2PbComp1); shSaa2PbComp->DefineSection( 7, z, rInSaa2PbComp1, rOuSaa2PbComp2); // // Section 2 z += dzSaa2PbComp2; shSaa2PbComp->DefineSection( 8, z, rInSaa2PbComp2, rOuSaa2PbComp2); // // Flange SAA3 side (Detail E) z += dzSaa2PbCompE1; shSaa2PbComp->DefineSection( 9, z, rInSaa2PbCompE1, rOuSaa2PbCompE1); // 45 deg transition z += dzSaa2PbCompE2; shSaa2PbComp->DefineSection( 10, z, rInSaa2PbCompE3, rOuSaa2PbCompE1); // 1st step z += dzSaa2PbCompE3; shSaa2PbComp->DefineSection( 11, z, rInSaa2PbCompE3, rOuSaa2PbCompE1); shSaa2PbComp->DefineSection( 12, z, rInSaa2PbCompE3, rOuSaa2PbCompE3); // 2nd step z += dzSaa2PbCompE4; shSaa2PbComp->DefineSection( 13, z, rInSaa2PbCompE3, rOuSaa2PbCompE3); shSaa2PbComp->DefineSection( 14, z, rInSaa2PbCompE3, rOuSaa2PbCompE4); // end z += dzSaa2PbCompE5; shSaa2PbComp->DefineSection( 15, z, rInSaa2PbCompE3, rOuSaa2PbCompE4); TGeoVolume* voSaa2PbComp = new TGeoVolume("YSAA2_PbComp", shSaa2PbComp, kMedPbSh); /////////////////////////////////// // SAA2 Inner Tube // // Drawing ALIP2A__0083 // /////////////////////////////////// // // // // Length of saa2: 512.0 cm // Length of inner tube: 501.7 cm // Lenth of bellow recess: 10.3 cm ( 1.5 + 8.8) // Radius at entrance 36.8/2, d = 0.1 // Radius at exit 52.0/2, d = 0.1 // const Float_t kSaa2InnerTubeL = 501.7; // Length of the tube const Float_t kSaa2InnerTubeRmin = 36.6/2.; // Radius at entrance const Float_t kSaa2InnerTubeRmax = 51.8/2.; // Radius at exit const Float_t kSaa2InnerTubeD = 0.2 ; // Thickness TGeoPcon* shSaa2InnerTube = new TGeoPcon(0., 360., 4); z = 0.; shSaa2InnerTube->DefineSection( 0, z, kSaa2InnerTubeRmin - kSaa2InnerTubeD, kSaa2InnerTubeRmin); z += dzSaa2PbCompA2 + dzSaa2PbCompA3; shSaa2InnerTube->DefineSection( 1, z, kSaa2InnerTubeRmin - kSaa2InnerTubeD, kSaa2InnerTubeRmin); z = kSaa2InnerTubeL - dzSaa2PbCompE1; shSaa2InnerTube->DefineSection( 2, z, kSaa2InnerTubeRmax - kSaa2InnerTubeD, kSaa2InnerTubeRmax); z = kSaa2InnerTubeL; shSaa2InnerTube->DefineSection( 3, z, kSaa2InnerTubeRmax - kSaa2InnerTubeD, kSaa2InnerTubeRmax); TGeoVolume* voSaa2InnerTube = new TGeoVolume("YSAA2_InnerTube", shSaa2InnerTube, kMedSteelSh); /////////////////////////////////// // SAA2 Steel Ring // // Drawing ALIP2A__0042 // /////////////////////////////////// // HalfWidth Float_t dzSaa2SteelRing = 2.; TGeoTube* shSaa2SteelRing = new TGeoTube(41.6, 47.6, dzSaa2SteelRing); TGeoVolume* voSaa2SteelRing = new TGeoVolume("YSAA2_SteelRing", shSaa2SteelRing, kMedSteel); /////////////////////////////////// // SAA2 Outer Shape // // Drawing ALIP2A__0108 // /////////////////////////////////// TGeoPcon* shSaa2 = new TGeoPcon(0., 360., 16); kSec = 0.02; // security distance to avoid trivial extrusions rmin = kSaa2InnerTubeRmin - kSaa2InnerTubeD - kSec; rmax = kSaa2InnerTubeRmax - kSaa2InnerTubeD - kSec; // Flange SAA1 side z = 0.; shSaa2->DefineSection( 0, z, rmin , rOuSaa2PbCompA1); z += dzSaa2PbCompA1 + dzSaa2PbCompA2; shSaa2->DefineSection( 1, z, rmin , rOuSaa2PbCompA1); shSaa2->DefineSection( 2, z, rmin , rInSaa2StEnv1 + dSt); z += dzSaa2PbCompA3; shSaa2->DefineSection( 3, z, rmin , rInSaa2StEnv1 + dSt); z = zSaa2PbRing; shSaa2->DefineSection( 4, z, 0. , rInSaa2StEnv1 + dSt); shSaa2->DefineSection( 5, z, 0. , rOuSaa2PbRingF); z += dzSaa2PbRing; shSaa2->DefineSection( 6, z, 0. , rOuSaa2PbRingR); shSaa2->DefineSection( 7, z, 0. , rInSaa2StEnv1 + dSt); z = dzSaa2PbCompA1 + dzSaa2PbCompA2 + dzSaa2StEnv1; shSaa2->DefineSection( 8, z, 0. , rInSaa2StEnv1 + dSt); shSaa2->DefineSection( 9, z, 0. , rInSaa2StEnv2 + dSt); z = dzSaa2PbComp - dzSaa2PbCompB2; shSaa2->DefineSection(10, z, rmax , rInSaa2StEnv2 + dSt); z += dzSaa2PbCompE1; shSaa2->DefineSection(11, z, rmax , rInSaa2StEnv2 + dSt); z += dzSaa2PbCompE2; shSaa2->DefineSection(12, z, rInSaa2PbCompE3, rInSaa2StEnv2 + dSt); z += (dzSaa2PbCompE3 + dzSaa2PbCompE4); shSaa2->DefineSection(13, z, rInSaa2PbCompE3, rInSaa2StEnv2 + dSt); shSaa2->DefineSection(14, z, rInSaa2PbCompE3, rOuSaa2PbCompE4); z += dzSaa2PbCompE5; shSaa2->DefineSection(15, z, rInSaa2PbCompE3, rOuSaa2PbCompE4); TGeoVolume* voSaa2 = new TGeoVolume("YSAA2", shSaa2, kMedAir); voSaa2->SetVisibility(0); // Inner 1.89/2 deg line Double_t zref = dzSaa2PbCompA1 + dzSaa2PbCompA2 + dzSaa2PbCompA3; for (Int_t i = 4; i < 10; i++) { Double_t z = shSaa2->GetZ(i); Double_t r2 = shSaa2->GetRmax(i); Double_t r1 = rmin + (z - zref) * TMath::Tan(1.89 / 2. * kDegRad) - kSec; shSaa2->DefineSection(i, z, r1, r2); } // // Assemble SAA2 voSaa2->AddNode(voSaa2StEnv, 1, gGeoIdentity); voSaa2->AddNode(voSaa2PbRing, 1, gGeoIdentity); voSaa2->AddNode(voSaa2PbComp, 1, gGeoIdentity); voSaa2->AddNode(voSaa2InnerTube, 1, new TGeoTranslation(0., 0., dzSaa2PbCompA1)); z = (dzSaa2PbComp - dzSaa2PbCompE4 - dzSaa2PbCompE5) + dzSaa2SteelRing; voSaa2->AddNode(voSaa2SteelRing, 1, new TGeoTranslation(0., 0., z)); /////////////////////////////////////// // SAA3 // /////////////////////////////////////// // // // This is a study performed by S. Maridor // The SAA3 has not yet been designed !!!!!!!! // /////////////////////////////////// // SAA3 Outer Shape // // Drawing ALIP2A__0288 // /////////////////////////////////// TGeoVolumeAssembly* voSaa3 = new TGeoVolumeAssembly("YSAA3"); /////////////////////////////////// // SAA3 Concrete cone // // Drawing ALIP2A__0284 // /////////////////////////////////// // Block TGeoBBox* shSaa3CCBlockO = new TGeoBBox(80./2., 80./2., 100./2.); shSaa3CCBlockO->SetName("Saa3CCBlockO"); TGeoPcon* shSaa3InnerRegion = new TGeoPcon(0., 360., 4); shSaa3InnerRegion->DefineSection( 0, -60.0, 0., 27.1); shSaa3InnerRegion->DefineSection( 1, -23.0, 0., 27.1); shSaa3InnerRegion->DefineSection( 2, 29.1, 0., 12.3); shSaa3InnerRegion->DefineSection( 3, 60.0, 0., 12.3); shSaa3InnerRegion->SetName("Saa3InnerRegion"); TGeoCompositeShape* shSaa3CCBlock = new TGeoCompositeShape("Saa3CCBlock", "Saa3CCBlockO-Saa3InnerRegion"); TGeoVolume* voSaa3CCBlock = new TGeoVolume("YSAA3CCBlock", shSaa3CCBlock, kMedConcSh); voSaa3->AddNode(voSaa3CCBlock, 1, gGeoIdentity); // Plate 1: 240 cm x 80 cm x 100 cm (x 2) TGeoVolume* voSaa3SteelPlate1 = new TGeoVolume("YSAA3SteelPlate1", new TGeoBBox(240./2., 80./2., 100./2.), kMedSteelSh); TGeoVolume* voSaa3SteelPlate11 = new TGeoVolume("YSAA3SteelPlate11", new TGeoBBox(240./2., 80./2., 10./2.), kMedSteel); voSaa3SteelPlate1->AddNode(voSaa3SteelPlate11, 1, new TGeoTranslation(0., 0., -45.)); voSaa3->AddNode(voSaa3SteelPlate1, 1, new TGeoTranslation(0., +80., 0.)); voSaa3->AddNode(voSaa3SteelPlate1, 2, new TGeoTranslation(0., -80., 0.)); // Plate 2: 80 cm x 80 cm x 100 cm (x 2) TGeoVolume* voSaa3SteelPlate2 = new TGeoVolume("YSAA3SteelPlate2", new TGeoBBox( 80./2., 80./2., 100./2.), kMedSteelSh); TGeoVolume* voSaa3SteelPlate21 = new TGeoVolume("YSAA3SteelPlate21", new TGeoBBox( 80./2., 80./2., 10./2.), kMedSteel); voSaa3SteelPlate2->AddNode(voSaa3SteelPlate21, 1, new TGeoTranslation(0., 0., -45.)); voSaa3->AddNode(voSaa3SteelPlate2, 1, new TGeoTranslation(+80, 0., 0.)); voSaa3->AddNode(voSaa3SteelPlate2, 2, new TGeoTranslation(-80, 0., 0.)); /////////////////////////////////// // Muon Filter // // Drawing ALIP2A__0105 // /////////////////////////////////// // Half Length Float_t dzMuonFilter = 60.; TGeoBBox* shMuonFilterO = new TGeoBBox(550./2., 620./2., dzMuonFilter); shMuonFilterO->SetName("FilterO"); TGeoCombiTrans* trFilter = new TGeoCombiTrans("trFilter", 0., -dzMuonFilter * TMath::Tan(alhc * kDegrad), 0., rotlhc); trFilter->RegisterYourself(); TGeoTube* shMuonFilterI = new TGeoTube(0., 48.8, dzMuonFilter + 20.); shMuonFilterI->SetName("FilterI"); TGeoCompositeShape* shMuonFilter = new TGeoCompositeShape("MuonFilter", "FilterO-FilterI:trFilter"); // // !!!!! Needs to be inclined TGeoVolume* voMuonFilter = new TGeoVolume("YMuonFilter", shMuonFilter, kMedSteel); // Inner part with higher transport cuts Float_t dzMuonFilterH = 50.; TGeoBBox* shMuonFilterOH = new TGeoBBox(550./2., 620./2., dzMuonFilterH); shMuonFilterOH->SetName("FilterOH"); TGeoTube* shMuonFilterIH = new TGeoTube(0., 50., dzMuonFilterH + 5.); shMuonFilterIH->SetName("FilterIH"); TGeoCompositeShape* shMuonFilterH = new TGeoCompositeShape("MuonFilterH", "FilterOH-FilterIH:trFilter"); TGeoVolume* voMuonFilterH = new TGeoVolume("YMuonFilterH", shMuonFilterH, kMedSteelSh); voMuonFilter->AddNode(voMuonFilterH, 1, gGeoIdentity); // TGeoVolumeAssembly* voSaa = new TGeoVolumeAssembly("YSAA"); // // // // // // Starting position of the FA Flange/Tail Float_t ziFaWTail = 499.0; // End of the FA Flange/Tail Float_t zoFaWTail = ziFaWTail + dzFaWTail; // Starting position of the FA/SAA1 Joint (2.8 cm overlap with tail) Float_t ozFaSaa1 = 2.8; Float_t ziFaSaa1 = zoFaWTail - ozFaSaa1; // End of the FA/SAA1 Joint Float_t zoFaSaa1 = ziFaSaa1 + dzFaSaa1; // Starting position of SAA1 (2.0 cm overlap with joint) Float_t ozSaa1 = 2.; Float_t ziSaa1 = zoFaSaa1 - ozSaa1; // End of SAA1 Float_t zoSaa1 = ziSaa1 + dzSaa1; // Starting position of SAA1/SAA2 Joint (1.95 cm overlap with SAA1) Float_t ziSaa1Saa2 = zoSaa1 - 1.95; // End of SAA1/SAA2 Joint Float_t zoSaa1Saa2 = ziSaa1Saa2 + dzSaa1Saa2; // Starting position of SAA2 (3.1 cm overlap with the joint) Float_t ziSaa2 = zoSaa1Saa2 - 3.1; // End of SAA2 Float_t zoSaa2 = ziSaa2 + dzSaa2PbComp; // Position of SAA3 Float_t zcSaa3 = zoSaa2 + 50.; // Position of the Muon Filter Float_t zcFilter = 1465.9 + dzMuonFilter; voSaa->AddNode(voFaWTail, 1, new TGeoTranslation(0., 0., ziFaWTail)); voSaa->AddNode(voFaSaa1, 1, new TGeoTranslation(0., 0., ziFaSaa1)); voSaa->AddNode(voSaa1 , 1, new TGeoTranslation(0., 0., ziSaa1)); voSaa->AddNode(voSaa1Saa2, 1, new TGeoTranslation(0., 0., ziSaa1Saa2)); voSaa->AddNode(voSaa2 , 1, new TGeoTranslation(0., 0., ziSaa2)); voSaa->AddNode(voSaa3, 1, new TGeoTranslation(0., 0., zcSaa3)); TGeoRotation* rotxz = new TGeoRotation("rotxz", 90., 0., 90., 90., 180., 0.); top->AddNode(voSaa, 1, new TGeoCombiTrans(0., 0., 0., rotxz)); // // Mother volume for muon stations 1+2 and shielding material placed between the quadrants // // Position of the dipole Float_t ziDipole = 741.; TGeoPcon* shYOUT1 = new TGeoPcon(0., 360., 25); Float_t eps = 1.e-2; // FA Tail Section for (Int_t iz = 0; iz < 9; iz++) { z = shFaWTail->GetZ(iz+1); if (iz == 8) z -= ozFaSaa1; shYOUT1->DefineSection(iz, z + ziFaWTail, shFaWTail->GetRmax(iz+1) + eps, 150.); } // FA-SAA1 Joint z = shYOUT1->GetZ(8); for (Int_t iz = 9; iz < 17; iz++) shYOUT1->DefineSection(iz, z + shFaSaa1->GetZ(iz-9), shFaSaa1->GetRmax(iz-9) + eps, 150.); z = shYOUT1->GetZ(16) - ozSaa1; // SAA1 - Dipole for (Int_t iz = 17; iz < 24; iz++) shYOUT1->DefineSection(iz, z + shSaa1M->GetZ(iz-13), shSaa1M->GetRmax(iz-13) + eps, 150.); // Distance between dipole and start of SAA1 2deg opening cone dz = ziDipole - (zSaa1StEnv[0] - dSt + zSaa1StEnvS + ziSaa1); rOut = rOuSaa1StEnv2 + dz * TMath::Tan(2. * kDegRad); shYOUT1->DefineSection(24, ziDipole, rOut + eps, 150.); InvertPcon(shYOUT1); TGeoVolume* voYOUT1 = new TGeoVolume("YOUT1", shYOUT1, kMedAirMu); voYOUT1->SetVisibility(0); voYOUT1->AddNode(asSaa1ExtraShield, 1, new TGeoCombiTrans(0., 0., - (100.7 + 62.2 + saa1ExtraShieldL / 2. + ziFaWTail), rotxz)); voYOUT1->AddNode(asFaExtraShield, 1, new TGeoCombiTrans(0., 0., - (16.41 + kFaWring2HWidth + ziFaWTail), rotxz)); top->AddNode(voYOUT1, 1, gGeoIdentity); // // Mother volume for muon stations 4+5 and trigger stations. // Float_t zoDipole = 1249.; TGeoPcon* shYOUT2 = new TGeoPcon(0., 360., 14); z = zoDipole; shYOUT2->DefineSection(0, z, rOuSaa1String, 252.); // Start of SAA1-SAA2 z = ziSaa1Saa2; shYOUT2->DefineSection(1, z, rOuSaa1String, 252.); shYOUT2->DefineSection(2, z, rOuSaa1Saa2Steel, 252.); // End of SAA1-SAA2 z = ziSaa2; shYOUT2->DefineSection(3, z, rOuSaa1Saa2Steel, 252.); // SAA2 shYOUT2->DefineSection( 4, z, rInSaa2StEnv1 + dSt, 252.); z = ziSaa2 + zSaa2PbRing; shYOUT2->DefineSection( 5, z, rInSaa2StEnv1 + dSt, 252.); // Pb Cone shYOUT2->DefineSection( 6, z, rOuSaa2PbRingF, 252.); rmin = rOuSaa2PbRingF + (1380. - z) * TMath::Tan(1.6 * kDegRad); shYOUT2->DefineSection( 7, 1380., rmin, 252.); shYOUT2->DefineSection( 8, 1380., rmin, 304.); z = ziSaa2 + zSaa2PbRing + dzSaa2PbRing; shYOUT2->DefineSection( 9, z, rOuSaa2PbRingR, 304.); // Straight Sections shYOUT2->DefineSection(10, z, rInSaa2StEnv1 + dSt, 460.); z = ziSaa2 + dzSaa2StEnv1; shYOUT2->DefineSection(11, z, rInSaa2StEnv1 + dSt, 460.); shYOUT2->DefineSection(12, z, rInSaa2StEnv2 + dSt, 460.); z += dzSaa2StEnv2; shYOUT2->DefineSection(13, z, rInSaa2StEnv2 + dSt, 460.); InvertPcon(shYOUT2); TGeoVolume* voYOUT2 = new TGeoVolume("YOUT2", shYOUT2, kMedAirMu); voYOUT2->SetVisibility(0); voYOUT2->AddNode(voMuonFilter, 1, new TGeoCombiTrans(0., dzMuonFilter * TMath::Tan(alhc * kDegrad), -zcFilter, rotxzlhc)); top->AddNode(voYOUT2, 1, gGeoIdentity); } void AliSHILv3::Init() { // // Initialise the muon shield after it has been built // Int_t i; // if(AliLog::GetGlobalDebugLevel()>0) { printf("\n%s: ",ClassName()); for(i=0;i<35;i++) printf("*"); printf(" SHILv3_INIT "); for(i=0;i<35;i++) printf("*"); printf("\n%s: ",ClassName()); // // Here the SHIL initialisation code (if any!) for(i=0;i<80;i++) printf("*"); printf("\n"); } } void AliSHILv3::InvertPcon(TGeoPcon* pcon) { // // z -> -z // Int_t nz = pcon->GetNz(); Double_t* z = new Double_t[nz]; Double_t* rmin = new Double_t[nz]; Double_t* rmax = new Double_t[nz]; Double_t* z0 = pcon->GetZ(); Double_t* rmin0 = pcon->GetRmin(); Double_t* rmax0 = pcon->GetRmax(); for (Int_t i = 0; i < nz; i++) { z[i] = z0[i]; rmin[i] = rmin0[i]; rmax[i] = rmax0[i]; } for (Int_t i = 0; i < nz; i++) { Int_t j = nz - i - 1; pcon->DefineSection(i, - z[j], rmin[j], rmax[j]); } delete[] z; delete[] rmin; delete[] rmax; } TGeoPcon* AliSHILv3::MakeShapeFromTemplate(TGeoPcon* pcon, Float_t drMin, Float_t drMax) { // // Returns new shape based on a template changing // the inner radii by drMin and the outer radii by drMax. // Int_t nz = pcon->GetNz(); TGeoPcon* cpcon = new TGeoPcon(0., 360., nz); for (Int_t i = 0; i < nz; i++) cpcon->DefineSection(i, pcon->GetZ(i), pcon->GetRmin(i) + drMin, pcon->GetRmax(i) + drMax); return cpcon; }
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ // --- // Macro for MUON alignment using physics tracks. The macro uses AliMUONAlignment // class to calculate the alignment parameters. // An array for the alignment parameters is created and can be filled with // initial values that will be used as starting values by the alignment // algorithm. // Ny default the macro run over galice.root in the working directory. If a file list // of galice.root is provided as third argument the macro will run over all files. // The macro loop over the files, events and tracks. For each track // AliMUONAlignment::ProcessTrack(AliMUONTrack * track) and then // AliMUONAlignment::LocalFit(Int_t iTrack, Double_t *lTrackParam, Int_t // lSingleFit) are called. After all tracks have been procesed and fitted // AliMUONAlignment::GlobalFit(Double_t *parameters,Double_t *errors,Double_t *pulls) // is called. The array parameters contains the obatained misalignement parameters. // A realigned geometry is generated in a local CDB. // // Authors: B. Becker and J. Castillo // --- #if !defined(__CINT__) || defined(__MAKECINT__) #include "AliMUONAlignment.h" #include "AliMUONTrack.h" #include "AliMUONTrackExtrap.h" #include "AliMUONTrackParam.h" #include "AliMUONGeometryTransformer.h" #include "AliMUONDataInterface.h" #include "AliMagFMaps.h" #include "AliTracker.h" #include "AliCDBManager.h" #include "AliCDBMetaData.h" #include "AliCDBId.h" #include <TString.h> #include <TGeoManager.h> #include <TError.h> #include <TH1.h> #include <TGraphErrors.h> #include <TFile.h> #include <TClonesArray.h> #include <Riostream.h> #include <fstream> #endif void MUONAlignment(Int_t nEvents = 100000, char* geoFilename = "geometry.root", TString fileName = "galice.root", TString fileList = "") { // Import TGeo geometry (needed by AliMUONTrackExtrap::ExtrapToVertex) if (!gGeoManager) { TGeoManager::Import(geoFilename); if (!gGeoManager) { Error("MUONmass_ESD", "getting geometry from file %s failed", geoFilename); return; } } // set mag field // waiting for mag field in CDB printf("Loading field map...\n"); AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 1, 1., 10., AliMagFMaps::k5kG); AliTracker::SetFieldMap(field, kFALSE); // set the magnetic field for track extrapolations AliMUONTrackExtrap::SetField(AliTracker::GetFieldMap()); Double_t parameters[3*156]; Double_t errors[3*156]; Double_t pulls[3*156]; for(Int_t k=0;k<3*156;k++) { parameters[k]=0.; errors[k]=0.; pulls[k]=0.; } Double_t trackParams[8] = {0.,0.,0.,0.,0.,0.,0.,0.}; // Set initial values here, good guess may help convergence // St 1 // Int_t iPar = 0; // parameters[iPar++] = 0.010300 ; parameters[iPar++] = 0.010600 ; parameters[iPar++] = 0.000396 ; bool bLoop = kFALSE; ifstream sFileList; if (fileList.Contains(".list")) { cout << "Reading file list: " << fileList.Data() << endl; bLoop = kTRUE; TString fullListName("."); fullListName +="/"; fullListName +=fileList; sFileList.open(fileList.Data()); } TH1F *fInvBenMom = new TH1F("fInvBenMom","fInvBenMom",200,-0.1,0.1); TH1F *fBenMom = new TH1F("fBenMom","fBenMom",200,-40,40); AliMUONAlignment* alig = new AliMUONAlignment(); alig->InitGlobalParameters(parameters); AliMUONGeometryTransformer *transform = new AliMUONGeometryTransformer(true); transform->ReadGeometryData("volpath.dat", gGeoManager); alig->SetGeometryTransformer(transform); // Set tracking station to use Bool_t bStOnOff[5] = {kTRUE,kTRUE,kTRUE,kTRUE,kTRUE}; // Fix parameters or add constraints here for (Int_t iSt=0; iSt<5; iSt++) if (!bStOnOff[iSt]) alig->FixStation(iSt+1); // Left and right sides of the detector are independent, one can choose to align // only one side Bool_t bSpecLROnOff[2] = {kTRUE,kTRUE}; alig->FixHalfSpectrometer(bStOnOff,bSpecLROnOff); // Set predifined global constrains: X, Y, P, XvsZ, YvsZ, PvsZ, XvsY, YvsY, PvsY Bool_t bVarXYT[9] = {kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE}; Bool_t bDetTLBR[4] = {kFALSE,kTRUE,kFALSE,kTRUE}; alig->AddConstraints(bStOnOff,bVarXYT,bDetTLBR,bSpecLROnOff); char cFileName[100]; AliMUONDataInterface amdi; Int_t lMaxFile = 1000; Int_t iFile = 0; Int_t iEvent = 0; bool bKeepLoop = kTRUE; Int_t iTrackTot=0; Int_t iTrackOk=0; while(bKeepLoop && iFile<lMaxFile){ iFile++; if (bLoop) { sFileList.getline(cFileName,100); if (sFileList.eof()) bKeepLoop = kFALSE; } else { sprintf(cFileName,fileName.Data()); bKeepLoop = kFALSE; } if (!strstr(cFileName,"galice.root")) continue; cout << "Using file: " << cFileName << endl; amdi.SetFile(cFileName); Int_t nevents = amdi.NumberOfEvents(); cout << "... with " << nevents << endl; for(Int_t event = 0; event < nevents; event++) { amdi.GetEvent(event); if (iEvent >= nEvents){ bKeepLoop = kFALSE; break; } iEvent++; Int_t ntracks = amdi.NumberOfRecTracks(); if (!event%100) cout << " there are " << ntracks << " tracks in event " << event << endl; Int_t iTrack=0; AliMUONTrack* track = amdi.RecTrack(iTrack); while(track) { AliMUONTrackParam trackParam(*((AliMUONTrackParam*)(track->GetTrackParamAtHit()->First()))); AliMUONTrackExtrap::ExtrapToVertex(&trackParam,0.,0.,0.); Double_t invBenMom = trackParam.GetInverseBendingMomentum(); fInvBenMom->Fill(invBenMom); fBenMom->Fill(1./invBenMom); if (TMath::Abs(invBenMom)<=1.04) { alig->ProcessTrack(track); alig->LocalFit(iTrackOk++,trackParams,0); } iTrack++; iTrackTot++; track = amdi.RecTrack(iTrack); } } cout << "Processed " << iTrackTot << " Tracks so far." << endl; } alig->GlobalFit(parameters,errors,pulls); cout << "Done with GlobalFit " << endl; // Store results Double_t DEid[156] = {0}; Double_t MSDEx[156] = {0}; Double_t MSDEy[156] = {0}; Double_t MSDExt[156] = {0}; Double_t MSDEyt[156] = {0}; Double_t DEidErr[156] = {0}; Double_t MSDExErr[156] = {0}; Double_t MSDEyErr[156] = {0}; Double_t MSDExtErr[156] = {0}; Double_t MSDEytErr[156] = {0}; Int_t lNDetElem = 4*2+4*2+18*2+26*2+26*2; Int_t lNDetElemCh[10] = {4,4,4,4,18,18,26,26,26,26}; // Int_t lSNDetElemCh[10] = {4,8,12,16,34,52,78,104,130,156}; Int_t idOffset = 0; // 400 Int_t lSDetElemCh = 0; for(Int_t iDE=0; iDE<lNDetElem; iDE++){ DEidErr[iDE] = 0.; DEid[iDE] = idOffset+100; DEid[iDE] += iDE; lSDetElemCh = 0; for(Int_t iCh=0; iCh<9; iCh++){ lSDetElemCh += lNDetElemCh[iCh]; if (iDE>=lSDetElemCh) { DEid[iDE] += 100; DEid[iDE] -= lNDetElemCh[iCh]; } } MSDEx[iDE]=parameters[3*iDE+0]; MSDEy[iDE]=parameters[3*iDE+1]; MSDExt[iDE]=parameters[3*iDE+2]; MSDEyt[iDE]=parameters[3*iDE+2]; MSDExErr[iDE]=(Double_t)alig->GetParError(3*iDE+0); MSDEyErr[iDE]=(Double_t)alig->GetParError(3*iDE+1); MSDExtErr[iDE]=(Double_t)alig->GetParError(3*iDE+2); MSDEytErr[iDE]=(Double_t)alig->GetParError(3*iDE+2); } cout << "Let's create graphs ... " << endl; TGraphErrors *gMSDEx = new TGraphErrors(lNDetElem,DEid,MSDEx,DEidErr,MSDExErr); TGraphErrors *gMSDEy = new TGraphErrors(lNDetElem,DEid,MSDEy,DEidErr,MSDEyErr); TGraphErrors *gMSDExt = new TGraphErrors(lNDetElem,DEid,MSDExt,DEidErr,MSDExtErr); TGraphErrors *gMSDEyt = new TGraphErrors(lNDetElem,DEid,MSDEyt,DEidErr,MSDEytErr); cout << "... graphs created, open file ... " << endl; TFile *hFile = new TFile("measShifts.root","RECREATE"); cout << "... file opened ... " << endl; gMSDEx->Write("gMSDEx"); gMSDEy->Write("gMSDEy"); gMSDExt->Write("gMSDExt"); gMSDEyt->Write("gMSDEyt"); fInvBenMom->Write(); fBenMom->Write(); hFile->Close(); cout << "... and closed!" << endl; // Re Align AliMUONGeometryTransformer *newTransform = alig->ReAlign(transform,parameters,true); newTransform->WriteTransformations("transform2ReAlign.dat"); // Generate realigned data in local cdb const TClonesArray* array = newTransform->GetMisAlignmentData(); // CDB manager AliCDBManager* cdbManager = AliCDBManager::Instance(); cdbManager->SetDefaultStorage("local://ReAlignCDB"); AliCDBMetaData* cdbData = new AliCDBMetaData(); cdbData->SetResponsible("Dimuon Offline project"); cdbData->SetComment("MUON alignment objects with residual misalignment"); AliCDBId id("MUON/Align/Data", 0, 0); cdbManager->Put(const_cast<TClonesArray*>(array), id, cdbData); } UPdated for changes in geometry classes /************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ // --- // Macro for MUON alignment using physics tracks. The macro uses AliMUONAlignment // class to calculate the alignment parameters. // An array for the alignment parameters is created and can be filled with // initial values that will be used as starting values by the alignment // algorithm. // Ny default the macro run over galice.root in the working directory. If a file list // of galice.root is provided as third argument the macro will run over all files. // The macro loop over the files, events and tracks. For each track // AliMUONAlignment::ProcessTrack(AliMUONTrack * track) and then // AliMUONAlignment::LocalFit(Int_t iTrack, Double_t *lTrackParam, Int_t // lSingleFit) are called. After all tracks have been procesed and fitted // AliMUONAlignment::GlobalFit(Double_t *parameters,Double_t *errors,Double_t *pulls) // is called. The array parameters contains the obatained misalignement parameters. // A realigned geometry is generated in a local CDB. // // Authors: B. Becker and J. Castillo // --- #if !defined(__CINT__) || defined(__MAKECINT__) #include "AliMUONAlignment.h" #include "AliMUONTrack.h" #include "AliMUONTrackExtrap.h" #include "AliMUONTrackParam.h" #include "AliMUONGeometryTransformer.h" #include "AliMUONDataInterface.h" #include "AliMagFMaps.h" #include "AliTracker.h" #include "AliCDBManager.h" #include "AliCDBMetaData.h" #include "AliCDBId.h" #include "AliGeomManager.h" #include <TString.h> #include <TError.h> #include <TH1.h> #include <TGraphErrors.h> #include <TFile.h> #include <TClonesArray.h> #include <Riostream.h> #include <fstream> #endif void MUONAlignment(Int_t nEvents = 100000, char* geoFilename = "geometry.root", TString fileName = "galice.root", TString fileList = "") { // Import TGeo geometry (needed by AliMUONTrackExtrap::ExtrapToVertex) if ( ! AliGeomManager::GetGeometry() ) { AliGeomManager::LoadGeometry(geoFilename); if (! AliGeomManager::GetGeometry() ) { Error("MUONAlignment", "getting geometry from file %s failed", geoFilename); return; } } // set mag field // waiting for mag field in CDB printf("Loading field map...\n"); AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 1, 1., 10., AliMagFMaps::k5kG); AliTracker::SetFieldMap(field, kFALSE); // set the magnetic field for track extrapolations AliMUONTrackExtrap::SetField(AliTracker::GetFieldMap()); Double_t parameters[3*156]; Double_t errors[3*156]; Double_t pulls[3*156]; for(Int_t k=0;k<3*156;k++) { parameters[k]=0.; errors[k]=0.; pulls[k]=0.; } Double_t trackParams[8] = {0.,0.,0.,0.,0.,0.,0.,0.}; // Set initial values here, good guess may help convergence // St 1 // Int_t iPar = 0; // parameters[iPar++] = 0.010300 ; parameters[iPar++] = 0.010600 ; parameters[iPar++] = 0.000396 ; bool bLoop = kFALSE; ifstream sFileList; if (fileList.Contains(".list")) { cout << "Reading file list: " << fileList.Data() << endl; bLoop = kTRUE; TString fullListName("."); fullListName +="/"; fullListName +=fileList; sFileList.open(fileList.Data()); } TH1F *fInvBenMom = new TH1F("fInvBenMom","fInvBenMom",200,-0.1,0.1); TH1F *fBenMom = new TH1F("fBenMom","fBenMom",200,-40,40); AliMUONAlignment* alig = new AliMUONAlignment(); alig->InitGlobalParameters(parameters); AliMUONGeometryTransformer *transform = new AliMUONGeometryTransformer(); transform->LoadGeometryData(); alig->SetGeometryTransformer(transform); // Set tracking station to use Bool_t bStOnOff[5] = {kTRUE,kTRUE,kTRUE,kTRUE,kTRUE}; // Fix parameters or add constraints here for (Int_t iSt=0; iSt<5; iSt++) if (!bStOnOff[iSt]) alig->FixStation(iSt+1); // Left and right sides of the detector are independent, one can choose to align // only one side Bool_t bSpecLROnOff[2] = {kTRUE,kTRUE}; alig->FixHalfSpectrometer(bStOnOff,bSpecLROnOff); // Set predifined global constrains: X, Y, P, XvsZ, YvsZ, PvsZ, XvsY, YvsY, PvsY Bool_t bVarXYT[9] = {kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE}; Bool_t bDetTLBR[4] = {kFALSE,kTRUE,kFALSE,kTRUE}; alig->AddConstraints(bStOnOff,bVarXYT,bDetTLBR,bSpecLROnOff); char cFileName[100]; AliMUONDataInterface amdi; Int_t lMaxFile = 1000; Int_t iFile = 0; Int_t iEvent = 0; bool bKeepLoop = kTRUE; Int_t iTrackTot=0; Int_t iTrackOk=0; while(bKeepLoop && iFile<lMaxFile){ iFile++; if (bLoop) { sFileList.getline(cFileName,100); if (sFileList.eof()) bKeepLoop = kFALSE; } else { sprintf(cFileName,fileName.Data()); bKeepLoop = kFALSE; } if (!strstr(cFileName,"galice.root")) continue; cout << "Using file: " << cFileName << endl; amdi.SetFile(cFileName); Int_t nevents = amdi.NumberOfEvents(); cout << "... with " << nevents << endl; for(Int_t event = 0; event < nevents; event++) { amdi.GetEvent(event); if (iEvent >= nEvents){ bKeepLoop = kFALSE; break; } iEvent++; Int_t ntracks = amdi.NumberOfRecTracks(); if (!event%100) cout << " there are " << ntracks << " tracks in event " << event << endl; Int_t iTrack=0; AliMUONTrack* track = amdi.RecTrack(iTrack); while(track) { AliMUONTrackParam trackParam(*((AliMUONTrackParam*)(track->GetTrackParamAtHit()->First()))); AliMUONTrackExtrap::ExtrapToVertex(&trackParam,0.,0.,0.); Double_t invBenMom = trackParam.GetInverseBendingMomentum(); fInvBenMom->Fill(invBenMom); fBenMom->Fill(1./invBenMom); if (TMath::Abs(invBenMom)<=1.04) { alig->ProcessTrack(track); alig->LocalFit(iTrackOk++,trackParams,0); } iTrack++; iTrackTot++; track = amdi.RecTrack(iTrack); } } cout << "Processed " << iTrackTot << " Tracks so far." << endl; } alig->GlobalFit(parameters,errors,pulls); cout << "Done with GlobalFit " << endl; // Store results Double_t DEid[156] = {0}; Double_t MSDEx[156] = {0}; Double_t MSDEy[156] = {0}; Double_t MSDExt[156] = {0}; Double_t MSDEyt[156] = {0}; Double_t DEidErr[156] = {0}; Double_t MSDExErr[156] = {0}; Double_t MSDEyErr[156] = {0}; Double_t MSDExtErr[156] = {0}; Double_t MSDEytErr[156] = {0}; Int_t lNDetElem = 4*2+4*2+18*2+26*2+26*2; Int_t lNDetElemCh[10] = {4,4,4,4,18,18,26,26,26,26}; // Int_t lSNDetElemCh[10] = {4,8,12,16,34,52,78,104,130,156}; Int_t idOffset = 0; // 400 Int_t lSDetElemCh = 0; for(Int_t iDE=0; iDE<lNDetElem; iDE++){ DEidErr[iDE] = 0.; DEid[iDE] = idOffset+100; DEid[iDE] += iDE; lSDetElemCh = 0; for(Int_t iCh=0; iCh<9; iCh++){ lSDetElemCh += lNDetElemCh[iCh]; if (iDE>=lSDetElemCh) { DEid[iDE] += 100; DEid[iDE] -= lNDetElemCh[iCh]; } } MSDEx[iDE]=parameters[3*iDE+0]; MSDEy[iDE]=parameters[3*iDE+1]; MSDExt[iDE]=parameters[3*iDE+2]; MSDEyt[iDE]=parameters[3*iDE+2]; MSDExErr[iDE]=(Double_t)alig->GetParError(3*iDE+0); MSDEyErr[iDE]=(Double_t)alig->GetParError(3*iDE+1); MSDExtErr[iDE]=(Double_t)alig->GetParError(3*iDE+2); MSDEytErr[iDE]=(Double_t)alig->GetParError(3*iDE+2); } cout << "Let's create graphs ... " << endl; TGraphErrors *gMSDEx = new TGraphErrors(lNDetElem,DEid,MSDEx,DEidErr,MSDExErr); TGraphErrors *gMSDEy = new TGraphErrors(lNDetElem,DEid,MSDEy,DEidErr,MSDEyErr); TGraphErrors *gMSDExt = new TGraphErrors(lNDetElem,DEid,MSDExt,DEidErr,MSDExtErr); TGraphErrors *gMSDEyt = new TGraphErrors(lNDetElem,DEid,MSDEyt,DEidErr,MSDEytErr); cout << "... graphs created, open file ... " << endl; TFile *hFile = new TFile("measShifts.root","RECREATE"); cout << "... file opened ... " << endl; gMSDEx->Write("gMSDEx"); gMSDEy->Write("gMSDEy"); gMSDExt->Write("gMSDExt"); gMSDEyt->Write("gMSDEyt"); fInvBenMom->Write(); fBenMom->Write(); hFile->Close(); cout << "... and closed!" << endl; // Re Align AliMUONGeometryTransformer *newTransform = alig->ReAlign(transform,parameters,true); newTransform->WriteTransformations("transform2ReAlign.dat"); // Generate realigned data in local cdb const TClonesArray* array = newTransform->GetMisAlignmentData(); // CDB manager AliCDBManager* cdbManager = AliCDBManager::Instance(); cdbManager->SetDefaultStorage("local://ReAlignCDB"); AliCDBMetaData* cdbData = new AliCDBMetaData(); cdbData->SetResponsible("Dimuon Offline project"); cdbData->SetComment("MUON alignment objects with residual misalignment"); AliCDBId id("MUON/Align/Data", 0, 0); cdbManager->Put(const_cast<TClonesArray*>(array), id, cdbData); }
#include "win32/AcceleratorTableGenerator.h" using namespace Framework::Win32; CAcceleratorTableGenerator::CAcceleratorTableGenerator() { } CAcceleratorTableGenerator::~CAcceleratorTableGenerator() { } void CAcceleratorTableGenerator::Insert(unsigned int cmd, unsigned int key, unsigned int virt) { ACCEL accel; memset(&accel, 0, sizeof(ACCEL)); accel.cmd = cmd; accel.key = key; accel.fVirt = virt; m_table.push_back(accel); } HACCEL CAcceleratorTableGenerator::Create() { return CreateAcceleratorTable(&m_table[0], static_cast<int>(m_table.size())); } Don't crash if we generate an accelerator table with no entries. git-svn-id: 36de21aa7b1472b3fce746da1590bf50bb7584d6@231 6a6d099a-6a11-0410-877e-d5a07a98cbd2 #include "win32/AcceleratorTableGenerator.h" using namespace Framework::Win32; CAcceleratorTableGenerator::CAcceleratorTableGenerator() { } CAcceleratorTableGenerator::~CAcceleratorTableGenerator() { } void CAcceleratorTableGenerator::Insert(unsigned int cmd, unsigned int key, unsigned int virt) { ACCEL accel; memset(&accel, 0, sizeof(ACCEL)); accel.cmd = cmd; accel.key = key; accel.fVirt = virt; m_table.push_back(accel); } HACCEL CAcceleratorTableGenerator::Create() { if(m_table.size() == 0) return NULL; return CreateAcceleratorTable(&m_table[0], static_cast<int>(m_table.size())); }
// 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 "ui/aura/desktop/desktop_activation_client.h" #include "base/auto_reset.h" #include "base/compiler_specific.h" #include "ui/aura/client/activation_delegate.h" #include "ui/aura/client/activation_change_observer.h" #include "ui/aura/focus_manager.h" #include "ui/aura/root_window.h" #include "ui/aura/window.h" namespace { // Checks to make sure this window is a direct child of the Root Window. We do // this to mirror ash's more interesting behaviour: it checks to make sure the // window it's going to activate is a child of one a few container windows. bool IsChildOfRootWindow(aura::Window* window) { return window && window->parent() == window->GetRootWindow(); } } // namespace namespace aura { DesktopActivationClient::DesktopActivationClient(FocusManager* focus_manager) : focus_manager_(focus_manager), current_active_(NULL), updating_activation_(false), ALLOW_THIS_IN_INITIALIZER_LIST(observer_manager_(this)) { focus_manager->AddObserver(this); } DesktopActivationClient::~DesktopActivationClient() { focus_manager_->RemoveObserver(this); } void DesktopActivationClient::AddObserver( client::ActivationChangeObserver* observer) { observers_.AddObserver(observer); } void DesktopActivationClient::RemoveObserver( client::ActivationChangeObserver* observer) { observers_.RemoveObserver(observer); } void DesktopActivationClient::ActivateWindow(Window* window) { // Prevent recursion when called from focus. if (updating_activation_) return; AutoReset<bool> in_activate_window(&updating_activation_, true); // Nothing may actually have changed. if (current_active_ == window) return; // The stacking client may impose rules on what window configurations can be // activated or deactivated. if (window && !CanActivateWindow(window)) return; // Switch internal focus before we change the activation. Will probably cause // recursion. if (window && !window->Contains(window->GetFocusManager()->GetFocusedWindow())) { window->GetFocusManager()->SetFocusedWindow(window, NULL); } aura::Window* old_active = current_active_; current_active_ = window; if (window && !observer_manager_.IsObserving(window)) observer_manager_.Add(window); FOR_EACH_OBSERVER(client::ActivationChangeObserver, observers_, OnWindowActivated(window, old_active)); // Invoke OnLostActive after we've changed the active window. That way if the // delegate queries for active state it doesn't think the window is still // active. if (old_active && client::GetActivationDelegate(old_active)) client::GetActivationDelegate(old_active)->OnLostActive(); // Send an activation event to the new window if (window && client::GetActivationDelegate(window)) client::GetActivationDelegate(window)->OnActivated(); } void DesktopActivationClient::DeactivateWindow(Window* window) { if (window == current_active_) current_active_ = NULL; } Window* DesktopActivationClient::GetActiveWindow() { return current_active_; } bool DesktopActivationClient::OnWillFocusWindow(Window* window, const ui::Event* event) { return CanActivateWindow(GetActivatableWindow(window)); } void DesktopActivationClient::OnWindowDestroying(aura::Window* window) { if (current_active_ == window) { current_active_ = NULL; FOR_EACH_OBSERVER(aura::client::ActivationChangeObserver, observers_, OnWindowActivated(NULL, window)); // ash::ActivationController will also activate the next window here; we // don't do this because that's the desktop environment's job. } observer_manager_.Remove(window); } void DesktopActivationClient::OnWindowFocused(aura::Window* window) { ActivateWindow(GetActivatableWindow(window)); } bool DesktopActivationClient::CanActivateWindow(aura::Window* window) const { return window && window->IsVisible() && (!aura::client::GetActivationDelegate(window) || aura::client::GetActivationDelegate(window)->ShouldActivate(NULL)); } aura::Window* DesktopActivationClient::GetActivatableWindow( aura::Window* window) { aura::Window* parent = window->parent(); aura::Window* child = window; while (parent) { if (CanActivateWindow(child)) { if (child->transient_parent()) child = GetActivatableWindow(child->transient_parent()); return child; } // If |child| isn't activatable, but has transient parent, trace // that path instead. if (child->transient_parent()) return GetActivatableWindow(child->transient_parent()); parent = parent->parent(); child = child->parent(); } return NULL; } } // namespace aura linux_aura: Temporarily restore IsChildOfRootWindow() checks on Linux. This was causing the main frame to Blur(). Use #ifdefs for OS_WIN. BUG=158118 Review URL: https://chromiumcodereview.appspot.com/11314015 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@164731 0039d316-1c4b-4281-b951-d872f2087c98 // 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 "ui/aura/desktop/desktop_activation_client.h" #include "base/auto_reset.h" #include "base/compiler_specific.h" #include "ui/aura/client/activation_delegate.h" #include "ui/aura/client/activation_change_observer.h" #include "ui/aura/focus_manager.h" #include "ui/aura/root_window.h" #include "ui/aura/window.h" namespace aura { DesktopActivationClient::DesktopActivationClient(FocusManager* focus_manager) : focus_manager_(focus_manager), current_active_(NULL), updating_activation_(false), ALLOW_THIS_IN_INITIALIZER_LIST(observer_manager_(this)) { focus_manager->AddObserver(this); } DesktopActivationClient::~DesktopActivationClient() { focus_manager_->RemoveObserver(this); } void DesktopActivationClient::AddObserver( client::ActivationChangeObserver* observer) { observers_.AddObserver(observer); } void DesktopActivationClient::RemoveObserver( client::ActivationChangeObserver* observer) { observers_.RemoveObserver(observer); } void DesktopActivationClient::ActivateWindow(Window* window) { // Prevent recursion when called from focus. if (updating_activation_) return; AutoReset<bool> in_activate_window(&updating_activation_, true); // Nothing may actually have changed. if (current_active_ == window) return; // The stacking client may impose rules on what window configurations can be // activated or deactivated. if (window && !CanActivateWindow(window)) return; // Switch internal focus before we change the activation. Will probably cause // recursion. if (window && !window->Contains(window->GetFocusManager()->GetFocusedWindow())) { window->GetFocusManager()->SetFocusedWindow(window, NULL); } aura::Window* old_active = current_active_; current_active_ = window; if (window && !observer_manager_.IsObserving(window)) observer_manager_.Add(window); FOR_EACH_OBSERVER(client::ActivationChangeObserver, observers_, OnWindowActivated(window, old_active)); // Invoke OnLostActive after we've changed the active window. That way if the // delegate queries for active state it doesn't think the window is still // active. if (old_active && client::GetActivationDelegate(old_active)) client::GetActivationDelegate(old_active)->OnLostActive(); // Send an activation event to the new window if (window && client::GetActivationDelegate(window)) client::GetActivationDelegate(window)->OnActivated(); } void DesktopActivationClient::DeactivateWindow(Window* window) { if (window == current_active_) current_active_ = NULL; } Window* DesktopActivationClient::GetActiveWindow() { return current_active_; } bool DesktopActivationClient::OnWillFocusWindow(Window* window, const ui::Event* event) { return CanActivateWindow(GetActivatableWindow(window)); } void DesktopActivationClient::OnWindowDestroying(aura::Window* window) { if (current_active_ == window) { current_active_ = NULL; FOR_EACH_OBSERVER(aura::client::ActivationChangeObserver, observers_, OnWindowActivated(NULL, window)); // ash::ActivationController will also activate the next window here; we // don't do this because that's the desktop environment's job. } observer_manager_.Remove(window); } void DesktopActivationClient::OnWindowFocused(aura::Window* window) { ActivateWindow(GetActivatableWindow(window)); } bool DesktopActivationClient::CanActivateWindow(aura::Window* window) const { bool can_activate = window && window->IsVisible() && (!aura::client::GetActivationDelegate(window) || aura::client::GetActivationDelegate(window)->ShouldActivate(NULL)); #if defined(OS_LINUX) if (can_activate) { // TODO(erg,ananta): Windows behaves differently than Linux; clicking will // always send an activation message on windows while on Linux we'll need // to emulate that behavior if views is expecting it. can_activate = window->parent() == window->GetRootWindow(); } #endif return can_activate; } aura::Window* DesktopActivationClient::GetActivatableWindow( aura::Window* window) { aura::Window* parent = window->parent(); aura::Window* child = window; while (parent) { if (CanActivateWindow(child)) { if (child->transient_parent()) child = GetActivatableWindow(child->transient_parent()); return child; } // If |child| isn't activatable, but has transient parent, trace // that path instead. if (child->transient_parent()) return GetActivatableWindow(child->transient_parent()); parent = parent->parent(); child = child->parent(); } return NULL; } } // namespace aura
/* * Copyright (C) 2017 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "leveled_manifest.hh" namespace sstables { class leveled_compaction_strategy : public compaction_strategy_impl { static constexpr int32_t DEFAULT_MAX_SSTABLE_SIZE_IN_MB = 160; const sstring SSTABLE_SIZE_OPTION = "sstable_size_in_mb"; int32_t _max_sstable_size_in_mb = DEFAULT_MAX_SSTABLE_SIZE_IN_MB; stdx::optional<std::vector<stdx::optional<dht::decorated_key>>> _last_compacted_keys; std::vector<int> _compaction_counter; public: leveled_compaction_strategy(const std::map<sstring, sstring>& options) : compaction_strategy_impl(options) { using namespace cql3::statements; auto tmp_value = compaction_strategy_impl::get_value(options, SSTABLE_SIZE_OPTION); _max_sstable_size_in_mb = property_definitions::to_int(SSTABLE_SIZE_OPTION, tmp_value, DEFAULT_MAX_SSTABLE_SIZE_IN_MB); if (_max_sstable_size_in_mb >= 1000) { leveled_manifest::logger.warn("Max sstable size of {}MB is configured; having a unit of compaction this large is probably a bad idea", _max_sstable_size_in_mb); } else if (_max_sstable_size_in_mb < 50) { leveled_manifest::logger.warn("Max sstable size of {}MB is configured. Testing done for CASSANDRA-5727 indicates that performance" \ "improves up to 160MB", _max_sstable_size_in_mb); } _compaction_counter.resize(leveled_manifest::MAX_LEVELS); } virtual compaction_descriptor get_sstables_for_compaction(column_family& cfs, std::vector<sstables::shared_sstable> candidates) override; virtual std::vector<resharding_descriptor> get_resharding_jobs(column_family& cf, std::vector<shared_sstable> candidates) override; virtual void notify_completion(const std::vector<lw_shared_ptr<sstable>>& removed, const std::vector<lw_shared_ptr<sstable>>& added) override; // for each level > 0, get newest sstable and use its last key as last // compacted key for the previous level. void generate_last_compacted_keys(leveled_manifest& manifest); virtual int64_t estimated_pending_compactions(column_family& cf) const override; virtual bool parallel_compaction() const override { return false; } virtual compaction_strategy_type type() const { return compaction_strategy_type::leveled; } virtual std::unique_ptr<sstable_set_impl> make_sstable_set(schema_ptr schema) const override; }; compaction_descriptor leveled_compaction_strategy::get_sstables_for_compaction(column_family& cfs, std::vector<sstables::shared_sstable> candidates) { // NOTE: leveled_manifest creation may be slightly expensive, so later on, // we may want to store it in the strategy itself. However, the sstable // lists managed by the manifest may become outdated. For example, one // sstable in it may be marked for deletion after compacted. // Currently, we create a new manifest whenever it's time for compaction. leveled_manifest manifest = leveled_manifest::create(cfs, candidates, _max_sstable_size_in_mb); if (!_last_compacted_keys) { generate_last_compacted_keys(manifest); } auto candidate = manifest.get_compaction_candidates(*_last_compacted_keys, _compaction_counter); if (!candidate.sstables.empty()) { leveled_manifest::logger.debug("leveled: Compacting {} out of {} sstables", candidate.sstables.size(), cfs.get_sstables()->size()); return std::move(candidate); } // if there is no sstable to compact in standard way, try compacting based on droppable tombstone ratio // unlike stcs, lcs can look for sstable with highest droppable tombstone ratio, so as not to choose // a sstable which droppable data shadow data in older sstable, by starting from highest levels which // theoretically contain oldest non-overlapping data. auto gc_before = gc_clock::now() - cfs.schema()->gc_grace_seconds(); for (auto level = manifest.get_level_count(); level >= 0; level--) { auto& sstables = manifest.get_level(level); // filter out sstables which droppable tombstone ratio isn't greater than the defined threshold. auto e = boost::range::remove_if(sstables, [this, &gc_before] (const sstables::shared_sstable& sst) -> bool { return !worth_dropping_tombstones(sst, gc_before); }); sstables.erase(e, sstables.end()); if (sstables.empty()) { continue; } auto& sst = *std::max_element(sstables.begin(), sstables.end(), [&] (auto& i, auto& j) { return i->estimate_droppable_tombstone_ratio(gc_before) < j->estimate_droppable_tombstone_ratio(gc_before); }); return sstables::compaction_descriptor({ sst }, sst->get_sstable_level()); } } std::vector<resharding_descriptor> leveled_compaction_strategy::get_resharding_jobs(column_family& cf, std::vector<shared_sstable> candidates) { leveled_manifest manifest = leveled_manifest::create(cf, candidates, _max_sstable_size_in_mb); std::vector<resharding_descriptor> descriptors; shard_id target_shard = 0; auto get_shard = [&target_shard] { return target_shard++ % smp::count; }; // Basically, we'll iterate through all levels, and for each, we'll sort the // sstables by first key because there's a need to reshard together adjacent // sstables. // The shard at which the job will run is chosen in a round-robin fashion. for (auto level = 0U; level <= manifest.get_level_count(); level++) { uint64_t max_sstable_size = !level ? std::numeric_limits<uint64_t>::max() : (_max_sstable_size_in_mb*1024*1024); auto& sstables = manifest.get_level(level); boost::sort(sstables, [] (auto& i, auto& j) { return i->compare_by_first_key(*j) < 0; }); resharding_descriptor current_descriptor = resharding_descriptor{{}, max_sstable_size, get_shard(), level}; for (auto it = sstables.begin(); it != sstables.end(); it++) { current_descriptor.sstables.push_back(*it); auto next = std::next(it); if (current_descriptor.sstables.size() == smp::count || next == sstables.end()) { descriptors.push_back(std::move(current_descriptor)); current_descriptor = resharding_descriptor{{}, max_sstable_size, get_shard(), level}; } } } return descriptors; } void leveled_compaction_strategy::notify_completion(const std::vector<lw_shared_ptr<sstable>>& removed, const std::vector<lw_shared_ptr<sstable>>& added) { if (removed.empty() || added.empty()) { return; } auto min_level = std::numeric_limits<uint32_t>::max(); for (auto& sstable : removed) { min_level = std::min(min_level, sstable->get_sstable_level()); } const sstables::sstable *last = nullptr; for (auto& candidate : added) { if (!last || last->compare_by_first_key(*candidate) < 0) { last = &*candidate; } } _last_compacted_keys.value().at(min_level) = last->get_last_decorated_key(); } void leveled_compaction_strategy::generate_last_compacted_keys(leveled_manifest& manifest) { std::vector<stdx::optional<dht::decorated_key>> last_compacted_keys(leveled_manifest::MAX_LEVELS); for (auto i = 0; i < leveled_manifest::MAX_LEVELS - 1; i++) { if (manifest.get_level(i + 1).empty()) { continue; } const sstables::sstable* sstable_with_last_compacted_key = nullptr; stdx::optional<db_clock::time_point> max_creation_time; for (auto& sst : manifest.get_level(i + 1)) { auto wtime = sst->data_file_write_time(); if (!max_creation_time || wtime >= *max_creation_time) { sstable_with_last_compacted_key = &*sst; max_creation_time = wtime; } } last_compacted_keys[i] = sstable_with_last_compacted_key->get_last_decorated_key(); } _last_compacted_keys = std::move(last_compacted_keys); } int64_t leveled_compaction_strategy::estimated_pending_compactions(column_family& cf) const { std::vector<sstables::shared_sstable> sstables; sstables.reserve(cf.sstables_count()); for (auto& entry : *cf.get_sstables()) { sstables.push_back(entry); } leveled_manifest manifest = leveled_manifest::create(cf, sstables, _max_sstable_size_in_mb); return manifest.get_estimated_tasks(); } } compaction: fix return in leveled compaction droppable tombstones loop If the loop ever terminates, we need to return something. Message-Id: <e4d4480359968bb01faf7e1a1009e85ad0c51d58@scylladb.com> /* * Copyright (C) 2017 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "leveled_manifest.hh" namespace sstables { class leveled_compaction_strategy : public compaction_strategy_impl { static constexpr int32_t DEFAULT_MAX_SSTABLE_SIZE_IN_MB = 160; const sstring SSTABLE_SIZE_OPTION = "sstable_size_in_mb"; int32_t _max_sstable_size_in_mb = DEFAULT_MAX_SSTABLE_SIZE_IN_MB; stdx::optional<std::vector<stdx::optional<dht::decorated_key>>> _last_compacted_keys; std::vector<int> _compaction_counter; public: leveled_compaction_strategy(const std::map<sstring, sstring>& options) : compaction_strategy_impl(options) { using namespace cql3::statements; auto tmp_value = compaction_strategy_impl::get_value(options, SSTABLE_SIZE_OPTION); _max_sstable_size_in_mb = property_definitions::to_int(SSTABLE_SIZE_OPTION, tmp_value, DEFAULT_MAX_SSTABLE_SIZE_IN_MB); if (_max_sstable_size_in_mb >= 1000) { leveled_manifest::logger.warn("Max sstable size of {}MB is configured; having a unit of compaction this large is probably a bad idea", _max_sstable_size_in_mb); } else if (_max_sstable_size_in_mb < 50) { leveled_manifest::logger.warn("Max sstable size of {}MB is configured. Testing done for CASSANDRA-5727 indicates that performance" \ "improves up to 160MB", _max_sstable_size_in_mb); } _compaction_counter.resize(leveled_manifest::MAX_LEVELS); } virtual compaction_descriptor get_sstables_for_compaction(column_family& cfs, std::vector<sstables::shared_sstable> candidates) override; virtual std::vector<resharding_descriptor> get_resharding_jobs(column_family& cf, std::vector<shared_sstable> candidates) override; virtual void notify_completion(const std::vector<lw_shared_ptr<sstable>>& removed, const std::vector<lw_shared_ptr<sstable>>& added) override; // for each level > 0, get newest sstable and use its last key as last // compacted key for the previous level. void generate_last_compacted_keys(leveled_manifest& manifest); virtual int64_t estimated_pending_compactions(column_family& cf) const override; virtual bool parallel_compaction() const override { return false; } virtual compaction_strategy_type type() const { return compaction_strategy_type::leveled; } virtual std::unique_ptr<sstable_set_impl> make_sstable_set(schema_ptr schema) const override; }; compaction_descriptor leveled_compaction_strategy::get_sstables_for_compaction(column_family& cfs, std::vector<sstables::shared_sstable> candidates) { // NOTE: leveled_manifest creation may be slightly expensive, so later on, // we may want to store it in the strategy itself. However, the sstable // lists managed by the manifest may become outdated. For example, one // sstable in it may be marked for deletion after compacted. // Currently, we create a new manifest whenever it's time for compaction. leveled_manifest manifest = leveled_manifest::create(cfs, candidates, _max_sstable_size_in_mb); if (!_last_compacted_keys) { generate_last_compacted_keys(manifest); } auto candidate = manifest.get_compaction_candidates(*_last_compacted_keys, _compaction_counter); if (!candidate.sstables.empty()) { leveled_manifest::logger.debug("leveled: Compacting {} out of {} sstables", candidate.sstables.size(), cfs.get_sstables()->size()); return std::move(candidate); } // if there is no sstable to compact in standard way, try compacting based on droppable tombstone ratio // unlike stcs, lcs can look for sstable with highest droppable tombstone ratio, so as not to choose // a sstable which droppable data shadow data in older sstable, by starting from highest levels which // theoretically contain oldest non-overlapping data. auto gc_before = gc_clock::now() - cfs.schema()->gc_grace_seconds(); for (auto level = manifest.get_level_count(); level >= 0; level--) { auto& sstables = manifest.get_level(level); // filter out sstables which droppable tombstone ratio isn't greater than the defined threshold. auto e = boost::range::remove_if(sstables, [this, &gc_before] (const sstables::shared_sstable& sst) -> bool { return !worth_dropping_tombstones(sst, gc_before); }); sstables.erase(e, sstables.end()); if (sstables.empty()) { continue; } auto& sst = *std::max_element(sstables.begin(), sstables.end(), [&] (auto& i, auto& j) { return i->estimate_droppable_tombstone_ratio(gc_before) < j->estimate_droppable_tombstone_ratio(gc_before); }); return sstables::compaction_descriptor({ sst }, sst->get_sstable_level()); } return {}; } std::vector<resharding_descriptor> leveled_compaction_strategy::get_resharding_jobs(column_family& cf, std::vector<shared_sstable> candidates) { leveled_manifest manifest = leveled_manifest::create(cf, candidates, _max_sstable_size_in_mb); std::vector<resharding_descriptor> descriptors; shard_id target_shard = 0; auto get_shard = [&target_shard] { return target_shard++ % smp::count; }; // Basically, we'll iterate through all levels, and for each, we'll sort the // sstables by first key because there's a need to reshard together adjacent // sstables. // The shard at which the job will run is chosen in a round-robin fashion. for (auto level = 0U; level <= manifest.get_level_count(); level++) { uint64_t max_sstable_size = !level ? std::numeric_limits<uint64_t>::max() : (_max_sstable_size_in_mb*1024*1024); auto& sstables = manifest.get_level(level); boost::sort(sstables, [] (auto& i, auto& j) { return i->compare_by_first_key(*j) < 0; }); resharding_descriptor current_descriptor = resharding_descriptor{{}, max_sstable_size, get_shard(), level}; for (auto it = sstables.begin(); it != sstables.end(); it++) { current_descriptor.sstables.push_back(*it); auto next = std::next(it); if (current_descriptor.sstables.size() == smp::count || next == sstables.end()) { descriptors.push_back(std::move(current_descriptor)); current_descriptor = resharding_descriptor{{}, max_sstable_size, get_shard(), level}; } } } return descriptors; } void leveled_compaction_strategy::notify_completion(const std::vector<lw_shared_ptr<sstable>>& removed, const std::vector<lw_shared_ptr<sstable>>& added) { if (removed.empty() || added.empty()) { return; } auto min_level = std::numeric_limits<uint32_t>::max(); for (auto& sstable : removed) { min_level = std::min(min_level, sstable->get_sstable_level()); } const sstables::sstable *last = nullptr; for (auto& candidate : added) { if (!last || last->compare_by_first_key(*candidate) < 0) { last = &*candidate; } } _last_compacted_keys.value().at(min_level) = last->get_last_decorated_key(); } void leveled_compaction_strategy::generate_last_compacted_keys(leveled_manifest& manifest) { std::vector<stdx::optional<dht::decorated_key>> last_compacted_keys(leveled_manifest::MAX_LEVELS); for (auto i = 0; i < leveled_manifest::MAX_LEVELS - 1; i++) { if (manifest.get_level(i + 1).empty()) { continue; } const sstables::sstable* sstable_with_last_compacted_key = nullptr; stdx::optional<db_clock::time_point> max_creation_time; for (auto& sst : manifest.get_level(i + 1)) { auto wtime = sst->data_file_write_time(); if (!max_creation_time || wtime >= *max_creation_time) { sstable_with_last_compacted_key = &*sst; max_creation_time = wtime; } } last_compacted_keys[i] = sstable_with_last_compacted_key->get_last_decorated_key(); } _last_compacted_keys = std::move(last_compacted_keys); } int64_t leveled_compaction_strategy::estimated_pending_compactions(column_family& cf) const { std::vector<sstables::shared_sstable> sstables; sstables.reserve(cf.sstables_count()); for (auto& entry : *cf.get_sstables()) { sstables.push_back(entry); } leveled_manifest manifest = leveled_manifest::create(cf, sstables, _max_sstable_size_in_mb); return manifest.get_estimated_tasks(); } }
#include "ServiceDiscovery.h" #include "ServerPeer.h" #include <iostream> #include <stdio.h> /* printf, NULL */ #include <stdlib.h> /* srand, rand */ #include <time.h> /* time */ #include "DatabaseLinker.h" using namespace std; ServiceDiscovery::ServiceDiscovery(char* _listen_hostname, int _listen_port):Server(_listen_hostname, _listen_port){ startListen(); } bool ServiceDiscovery::auth(string username, string token){ cout << "SERVICEDISCOVERY::AUTH!"; if(token_user[token]==username) return true; return false; } //check if in token_user? true: false; string ServiceDiscovery::signUp(string username, string password, string addr){ cout << "SERVICEDISCOVERY::SIGNUP!"; srand(time(NULL)); string token; users[username] = password; do{ token = to_string(rand()%10000); }while(token_user.count(token)>0); token_user[token] = username; online_users[username]=addr; // pending_requests needs username or token? return token; } string ServiceDiscovery::signIn(string username, string password, string addr){ cout << "SERVICEDISCOVERY::SIGNIN!"; srand(time(NULL)); string token; if(users[username]==password){ do{ token = to_string(rand()%10000); }while(token_user.count(token)>0); token_user[token] = username; online_users[username]=addr; // pending_requests needs username or token? return token; } token = ""; return token; } //check if in (users)?generate random token..add to token_user..check if he has pending requests..receive ack...return token: return error. map<string, string> ServiceDiscovery::getListOfOnlineUsers(string username, string token){ cout << "SERVICEDISCOVERY::getListofOnlineUsers!"; if(auth(username,token)){ return online_users; } std::map<string, string> mss; return mss; } void ServiceDiscovery::stillUp(string username, string token, string addr){ cout << "SERVICEDISCOVERY::stillUp!"; if(auth(username,token)){ token_time[token]++; } online_users[username]=addr; } //auth()? update time_cnt in token_time: ignore void ServiceDiscovery::down(string username, string token){ cout << "SERVICEDISCOVERY::DOWN!"; if(auth(username,token)){ token_time.erase(token); online_users.erase(username); } } //TODO: Handle Pending Requests void ServiceDiscovery::pendingRequest(string username, string token, string to_user, string imageID){ if(auth(username,token)){ } } Message* ServiceDiscovery::doOperation(Message* _message){ cout << "SERVICEDISCOVERY::doOperation!"; _message->print(); Message* reply_message = new Message(Reply); vector<Parameter> args; vector<Parameter> reply_args; int operation = _message->getOperation(); MessageDecoder::decode(_message, args); switch(operation){ case 1:{ string token = signUp(args[0].getString(), args[1].getString(), args[2].getString()); Parameter arg1; arg1.setString(token); reply_args.push_back(arg1); } break; case 2:{ string token = signIn(args[0].getString(), args[1].getString(), args[2].getString()); Parameter arg1; arg1.setString(token); reply_args.push_back(arg1); } break; case 3:{ stillUp(args[0].getString(), args[1].getString(), args[2].getString()); } break; case 4:{ down(args[0].getString(), args[1].getString()); } break; case 5:{ //pendingrequest } break; case 6:{ //GetListofOnlineUsers map<string, string> _mss = getListOfOnlineUsers(args[0].getString(), args[1].getString()); Parameter arg1; arg1.setMapSS(_mss); cout << arg1.getMapSS()["3wais"] << endl; reply_args.push_back(arg1); } break; case 10:{ //Auth bool _auth = auth(args[0].getString(), args[1].getString()); Parameter arg1; arg1.setBoolean(_auth); reply_args.push_back(arg1); } break; } MessageDecoder::encode(*reply_message, reply_args, operation, Reply); reply_message->print(); cout << "SERVICE DISCOVERY OUT!" << endl; return reply_message; } ServiceDiscovery:: ~ServiceDiscovery(){ }//destructor fixes #include "ServiceDiscovery.h" #include "ServerPeer.h" #include <iostream> #include <stdio.h> /* printf, NULL */ #include <stdlib.h> /* srand, rand */ #include <time.h> /* time */ #include "DatabaseLinker.h" using namespace std; ServiceDiscovery::ServiceDiscovery(char* _listen_hostname, int _listen_port):Server(_listen_hostname, _listen_port){ startListen(); } bool ServiceDiscovery::auth(string username, string token){ cout << "SERVICEDISCOVERY::AUTH!"; if(token_user[token]==username) return true; return false; } //check if in token_user? true: false; string ServiceDiscovery::signUp(string username, string password, string addr){ cout << "SERVICEDISCOVERY::SIGNUP!"; srand(time(NULL)); string token; users[username] = password; do{ token = to_string(rand()%10000); }while(token_user.count(token)>0); token_user[token] = username; online_users[username]=addr; // pending_requests needs username or token? return token; } string ServiceDiscovery::signIn(string username, string password, string addr){ cout << "SERVICEDISCOVERY::SIGNIN!"; srand(time(NULL)); string token; if(users[username]==password){ do{ token = to_string(rand()%10000); }while(token_user.count(token)>0); token_user[token] = username; online_users[username]=addr; // pending_requests needs username or token? return token; } token = ""; return token; } //check if in (users)?generate random token..add to token_user..check if he has pending requests..receive ack...return token: return error. map<string, string> ServiceDiscovery::getListOfOnlineUsers(string username, string token){ cout << "SERVICEDISCOVERY::getListofOnlineUsers!"; if(auth(username,token)){ return online_users; } std::map<string, string> mss; return mss; } void ServiceDiscovery::stillUp(string username, string token, string addr){ cout << "SERVICEDISCOVERY::stillUp!"; if(auth(username,token)){ token_time[token]++; } online_users[username]=addr; } //auth()? update time_cnt in token_time: ignore void ServiceDiscovery::down(string username, string token){ cout << "SERVICEDISCOVERY::DOWN!"; if(auth(username,token)){ token_time.erase(token); online_users.erase(username); } } //TODO: Handle Pending Requests void ServiceDiscovery::pendingRequest(string username, string token, string to_user, string imageID){ if(auth(username,token)){ } } Message* ServiceDiscovery::doOperation(Message* _message){ cout << "SERVICEDISCOVERY::doOperation!"; _message->print(); Message* reply_message = new Message(Reply); vector<Parameter> args; vector<Parameter> reply_args; int operation = _message->getOperation(); MessageDecoder::decode(_message, args); switch(operation){ case 1:{ string token = signUp(args[0].getString(), args[1].getString(), args[2].getString()); Parameter arg1; arg1.setString(token); reply_args.push_back(arg1); } break; case 2:{ string token = signIn(args[0].getString(), args[1].getString(), args[2].getString()); Parameter arg1; arg1.setString(token); reply_args.push_back(arg1); } break; case 3:{ stillUp(args[0].getString(), args[1].getString(), args[2].getString()); } break; case 4:{ down(args[0].getString(), args[1].getString()); } break; case 5:{ //pendingrequest } break; case 6:{ //GetListofOnlineUsers map<string, string> _mss = getListOfOnlineUsers(args[0].getString(), args[1].getString()); Parameter arg1; arg1.setMapSS(_mss); reply_args.push_back(arg1); } break; case 10:{ //Auth bool _auth = auth(args[0].getString(), args[1].getString()); Parameter arg1; arg1.setBoolean(_auth); reply_args.push_back(arg1); } break; } MessageDecoder::encode(*reply_message, reply_args, operation, Reply); reply_message->print(); cout << "SERVICE DISCOVERY OUT!" << endl; return reply_message; } ServiceDiscovery:: ~ServiceDiscovery(){ }//destructor
/*************************************************************************/ /* packed_data_container.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "packed_data_container.h" #include "core/core_string_names.h" #include "core/io/marshalls.h" Variant PackedDataContainer::getvar(const Variant &p_key, bool *r_valid) const { bool err = false; Variant ret = _key_at_ofs(0, p_key, err); if (r_valid) *r_valid = !err; return ret; } int PackedDataContainer::size() const { return _size(0); }; Variant PackedDataContainer::_iter_init_ofs(const Array &p_iter, uint32_t p_offset) { Array ref = p_iter; uint32_t size = _size(p_offset); if (size == 0 || ref.size() != 1) return false; else { ref[0] = 0; return true; } } Variant PackedDataContainer::_iter_next_ofs(const Array &p_iter, uint32_t p_offset) { Array ref = p_iter; int size = _size(p_offset); if (ref.size() != 1) return false; int pos = ref[0]; if (pos < 0 || pos >= size) return false; pos += 1; ref[0] = pos; return pos != size; } Variant PackedDataContainer::_iter_get_ofs(const Variant &p_iter, uint32_t p_offset) { int size = _size(p_offset); int pos = p_iter; if (pos < 0 || pos >= size) return Variant(); PoolVector<uint8_t>::Read rd = data.read(); const uint8_t *r = &rd[p_offset]; uint32_t type = decode_uint32(r); bool err = false; if (type == TYPE_ARRAY) { uint32_t vpos = decode_uint32(rd.ptr() + p_offset + 8 + pos * 4); return _get_at_ofs(vpos, rd.ptr(), err); } else if (type == TYPE_DICT) { uint32_t vpos = decode_uint32(rd.ptr() + p_offset + 8 + pos * 12 + 4); return _get_at_ofs(vpos, rd.ptr(), err); } else { ERR_FAIL_V(Variant()); } } Variant PackedDataContainer::_get_at_ofs(uint32_t p_ofs, const uint8_t *p_buf, bool &err) const { uint32_t type = decode_uint32(p_buf + p_ofs); if (type == TYPE_ARRAY || type == TYPE_DICT) { Ref<PackedDataContainerRef> pdcr = memnew(PackedDataContainerRef); Ref<PackedDataContainer> pdc = Ref<PackedDataContainer>((PackedDataContainer *)this); pdcr->from = pdc; pdcr->offset = p_ofs; return pdcr; } else { Variant v; Error rerr = decode_variant(v, p_buf + p_ofs, datalen - p_ofs, NULL, false); if (rerr != OK) { err = true; ERR_FAIL_COND_V_MSG(err != OK, Variant(), "Error when trying to decode Variant."); } return v; } } uint32_t PackedDataContainer::_type_at_ofs(uint32_t p_ofs) const { PoolVector<uint8_t>::Read rd = data.read(); const uint8_t *r = &rd[p_ofs]; uint32_t type = decode_uint32(r); return type; }; int PackedDataContainer::_size(uint32_t p_ofs) const { PoolVector<uint8_t>::Read rd = data.read(); ERR_FAIL_COND_V(!rd.ptr(), 0); const uint8_t *r = &rd[p_ofs]; uint32_t type = decode_uint32(r); if (type == TYPE_ARRAY) { uint32_t len = decode_uint32(r + 4); return len; } else if (type == TYPE_DICT) { uint32_t len = decode_uint32(r + 4); return len; }; return -1; }; Variant PackedDataContainer::_key_at_ofs(uint32_t p_ofs, const Variant &p_key, bool &err) const { PoolVector<uint8_t>::Read rd = data.read(); const uint8_t *r = &rd[p_ofs]; uint32_t type = decode_uint32(r); if (type == TYPE_ARRAY) { if (p_key.is_num()) { int idx = p_key; int len = decode_uint32(r + 4); if (idx < 0 || idx >= len) { err = true; return Variant(); } uint32_t ofs = decode_uint32(r + 8 + 4 * idx); return _get_at_ofs(ofs, rd.ptr(), err); } else { err = true; return Variant(); } } else if (type == TYPE_DICT) { uint32_t hash = p_key.hash(); uint32_t len = decode_uint32(r + 4); bool found = false; for (uint32_t i = 0; i < len; i++) { uint32_t khash = decode_uint32(r + 8 + i * 12 + 0); if (khash == hash) { Variant key = _get_at_ofs(decode_uint32(r + 8 + i * 12 + 4), rd.ptr(), err); if (err) return Variant(); if (key == p_key) { //key matches, return value return _get_at_ofs(decode_uint32(r + 8 + i * 12 + 8), rd.ptr(), err); } found = true; } else { if (found) break; } } err = true; return Variant(); } else { err = true; return Variant(); } } uint32_t PackedDataContainer::_pack(const Variant &p_data, Vector<uint8_t> &tmpdata, Map<String, uint32_t> &string_cache) { switch (p_data.get_type()) { case Variant::STRING: { String s = p_data; if (string_cache.has(s)) { return string_cache[s]; } string_cache[s] = tmpdata.size(); FALLTHROUGH; }; case Variant::NIL: case Variant::BOOL: case Variant::INT: case Variant::REAL: case Variant::VECTOR2: case Variant::RECT2: case Variant::VECTOR3: case Variant::TRANSFORM2D: case Variant::PLANE: case Variant::QUAT: case Variant::AABB: case Variant::BASIS: case Variant::TRANSFORM: case Variant::POOL_BYTE_ARRAY: case Variant::POOL_INT_ARRAY: case Variant::POOL_REAL_ARRAY: case Variant::POOL_STRING_ARRAY: case Variant::POOL_VECTOR2_ARRAY: case Variant::POOL_VECTOR3_ARRAY: case Variant::POOL_COLOR_ARRAY: case Variant::NODE_PATH: { uint32_t pos = tmpdata.size(); int len; encode_variant(p_data, NULL, len, false); tmpdata.resize(tmpdata.size() + len); encode_variant(p_data, &tmpdata.write[pos], len, false); return pos; } break; // misc types case Variant::_RID: case Variant::OBJECT: { return _pack(Variant(), tmpdata, string_cache); } break; case Variant::DICTIONARY: { Dictionary d = p_data; //size is known, use sort uint32_t pos = tmpdata.size(); int len = d.size(); tmpdata.resize(tmpdata.size() + len * 12 + 8); encode_uint32(TYPE_DICT, &tmpdata.write[pos + 0]); encode_uint32(len, &tmpdata.write[pos + 4]); List<Variant> keys; d.get_key_list(&keys); List<DictKey> sortk; for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { DictKey dk; dk.hash = E->get().hash(); dk.key = E->get(); sortk.push_back(dk); } sortk.sort(); int idx = 0; for (List<DictKey>::Element *E = sortk.front(); E; E = E->next()) { encode_uint32(E->get().hash, &tmpdata.write[pos + 8 + idx * 12 + 0]); uint32_t ofs = _pack(E->get().key, tmpdata, string_cache); encode_uint32(ofs, &tmpdata.write[pos + 8 + idx * 12 + 4]); ofs = _pack(d[E->get().key], tmpdata, string_cache); encode_uint32(ofs, &tmpdata.write[pos + 8 + idx * 12 + 8]); idx++; } return pos; } break; case Variant::ARRAY: { Array a = p_data; //size is known, use sort uint32_t pos = tmpdata.size(); int len = a.size(); tmpdata.resize(tmpdata.size() + len * 4 + 8); encode_uint32(TYPE_ARRAY, &tmpdata.write[pos + 0]); encode_uint32(len, &tmpdata.write[pos + 4]); for (int i = 0; i < len; i++) { uint32_t ofs = _pack(a[i], tmpdata, string_cache); encode_uint32(ofs, &tmpdata.write[pos + 8 + i * 4]); } return pos; } break; default: { } } return OK; } Error PackedDataContainer::pack(const Variant &p_data) { Vector<uint8_t> tmpdata; Map<String, uint32_t> string_cache; _pack(p_data, tmpdata, string_cache); datalen = tmpdata.size(); data.resize(tmpdata.size()); PoolVector<uint8_t>::Write w = data.write(); memcpy(w.ptr(), tmpdata.ptr(), tmpdata.size()); return OK; } void PackedDataContainer::_set_data(const PoolVector<uint8_t> &p_data) { data = p_data; datalen = data.size(); } PoolVector<uint8_t> PackedDataContainer::_get_data() const { return data; } Variant PackedDataContainer::_iter_init(const Array &p_iter) { return _iter_init_ofs(p_iter, 0); } Variant PackedDataContainer::_iter_next(const Array &p_iter) { return _iter_next_ofs(p_iter, 0); } Variant PackedDataContainer::_iter_get(const Variant &p_iter) { return _iter_get_ofs(p_iter, 0); } void PackedDataContainer::_bind_methods() { ClassDB::bind_method(D_METHOD("_set_data"), &PackedDataContainer::_set_data); ClassDB::bind_method(D_METHOD("_get_data"), &PackedDataContainer::_get_data); ClassDB::bind_method(D_METHOD("_iter_init"), &PackedDataContainer::_iter_init); ClassDB::bind_method(D_METHOD("_iter_get"), &PackedDataContainer::_iter_get); ClassDB::bind_method(D_METHOD("_iter_next"), &PackedDataContainer::_iter_next); ClassDB::bind_method(D_METHOD("pack", "value"), &PackedDataContainer::pack); ClassDB::bind_method(D_METHOD("size"), &PackedDataContainer::size); ADD_PROPERTY(PropertyInfo(Variant::POOL_BYTE_ARRAY, "__data__"), "_set_data", "_get_data"); } PackedDataContainer::PackedDataContainer() { datalen = 0; } ////////////////// Variant PackedDataContainerRef::_iter_init(const Array &p_iter) { return from->_iter_init_ofs(p_iter, offset); } Variant PackedDataContainerRef::_iter_next(const Array &p_iter) { return from->_iter_next_ofs(p_iter, offset); } Variant PackedDataContainerRef::_iter_get(const Variant &p_iter) { return from->_iter_get_ofs(p_iter, offset); } bool PackedDataContainerRef::_is_dictionary() const { return from->_type_at_ofs(offset) == PackedDataContainer::TYPE_DICT; }; void PackedDataContainerRef::_bind_methods() { ClassDB::bind_method(D_METHOD("size"), &PackedDataContainerRef::size); ClassDB::bind_method(D_METHOD("_iter_init"), &PackedDataContainerRef::_iter_init); ClassDB::bind_method(D_METHOD("_iter_get"), &PackedDataContainerRef::_iter_get); ClassDB::bind_method(D_METHOD("_iter_next"), &PackedDataContainerRef::_iter_next); ClassDB::bind_method(D_METHOD("_is_dictionary"), &PackedDataContainerRef::_is_dictionary); } Variant PackedDataContainerRef::getvar(const Variant &p_key, bool *r_valid) const { bool err = false; Variant ret = from->_key_at_ofs(offset, p_key, err); if (r_valid) *r_valid = !err; return ret; } int PackedDataContainerRef::size() const { return from->_size(offset); }; PackedDataContainerRef::PackedDataContainerRef() { } Add PackedDataContainer data pointer check for non nullable /*************************************************************************/ /* packed_data_container.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "packed_data_container.h" #include "core/core_string_names.h" #include "core/io/marshalls.h" Variant PackedDataContainer::getvar(const Variant &p_key, bool *r_valid) const { bool err = false; Variant ret = _key_at_ofs(0, p_key, err); if (r_valid) *r_valid = !err; return ret; } int PackedDataContainer::size() const { return _size(0); }; Variant PackedDataContainer::_iter_init_ofs(const Array &p_iter, uint32_t p_offset) { Array ref = p_iter; uint32_t size = _size(p_offset); if (size == 0 || ref.size() != 1) return false; else { ref[0] = 0; return true; } } Variant PackedDataContainer::_iter_next_ofs(const Array &p_iter, uint32_t p_offset) { Array ref = p_iter; int size = _size(p_offset); if (ref.size() != 1) return false; int pos = ref[0]; if (pos < 0 || pos >= size) return false; pos += 1; ref[0] = pos; return pos != size; } Variant PackedDataContainer::_iter_get_ofs(const Variant &p_iter, uint32_t p_offset) { int size = _size(p_offset); int pos = p_iter; if (pos < 0 || pos >= size) return Variant(); PoolVector<uint8_t>::Read rd = data.read(); const uint8_t *r = &rd[p_offset]; uint32_t type = decode_uint32(r); bool err = false; if (type == TYPE_ARRAY) { uint32_t vpos = decode_uint32(rd.ptr() + p_offset + 8 + pos * 4); return _get_at_ofs(vpos, rd.ptr(), err); } else if (type == TYPE_DICT) { uint32_t vpos = decode_uint32(rd.ptr() + p_offset + 8 + pos * 12 + 4); return _get_at_ofs(vpos, rd.ptr(), err); } else { ERR_FAIL_V(Variant()); } } Variant PackedDataContainer::_get_at_ofs(uint32_t p_ofs, const uint8_t *p_buf, bool &err) const { uint32_t type = decode_uint32(p_buf + p_ofs); if (type == TYPE_ARRAY || type == TYPE_DICT) { Ref<PackedDataContainerRef> pdcr = memnew(PackedDataContainerRef); Ref<PackedDataContainer> pdc = Ref<PackedDataContainer>((PackedDataContainer *)this); pdcr->from = pdc; pdcr->offset = p_ofs; return pdcr; } else { Variant v; Error rerr = decode_variant(v, p_buf + p_ofs, datalen - p_ofs, NULL, false); if (rerr != OK) { err = true; ERR_FAIL_COND_V_MSG(err != OK, Variant(), "Error when trying to decode Variant."); } return v; } } uint32_t PackedDataContainer::_type_at_ofs(uint32_t p_ofs) const { PoolVector<uint8_t>::Read rd = data.read(); ERR_FAIL_COND_V(!rd.ptr(), 0); const uint8_t *r = &rd[p_ofs]; uint32_t type = decode_uint32(r); return type; }; int PackedDataContainer::_size(uint32_t p_ofs) const { PoolVector<uint8_t>::Read rd = data.read(); ERR_FAIL_COND_V(!rd.ptr(), 0); const uint8_t *r = &rd[p_ofs]; uint32_t type = decode_uint32(r); if (type == TYPE_ARRAY) { uint32_t len = decode_uint32(r + 4); return len; } else if (type == TYPE_DICT) { uint32_t len = decode_uint32(r + 4); return len; }; return -1; }; Variant PackedDataContainer::_key_at_ofs(uint32_t p_ofs, const Variant &p_key, bool &err) const { PoolVector<uint8_t>::Read rd = data.read(); if (!rd.ptr()) { err = true; ERR_FAIL_COND_V(!rd.ptr(), Variant()); } const uint8_t *r = &rd[p_ofs]; uint32_t type = decode_uint32(r); if (type == TYPE_ARRAY) { if (p_key.is_num()) { int idx = p_key; int len = decode_uint32(r + 4); if (idx < 0 || idx >= len) { err = true; return Variant(); } uint32_t ofs = decode_uint32(r + 8 + 4 * idx); return _get_at_ofs(ofs, rd.ptr(), err); } else { err = true; return Variant(); } } else if (type == TYPE_DICT) { uint32_t hash = p_key.hash(); uint32_t len = decode_uint32(r + 4); bool found = false; for (uint32_t i = 0; i < len; i++) { uint32_t khash = decode_uint32(r + 8 + i * 12 + 0); if (khash == hash) { Variant key = _get_at_ofs(decode_uint32(r + 8 + i * 12 + 4), rd.ptr(), err); if (err) return Variant(); if (key == p_key) { //key matches, return value return _get_at_ofs(decode_uint32(r + 8 + i * 12 + 8), rd.ptr(), err); } found = true; } else { if (found) break; } } err = true; return Variant(); } else { err = true; return Variant(); } } uint32_t PackedDataContainer::_pack(const Variant &p_data, Vector<uint8_t> &tmpdata, Map<String, uint32_t> &string_cache) { switch (p_data.get_type()) { case Variant::STRING: { String s = p_data; if (string_cache.has(s)) { return string_cache[s]; } string_cache[s] = tmpdata.size(); FALLTHROUGH; }; case Variant::NIL: case Variant::BOOL: case Variant::INT: case Variant::REAL: case Variant::VECTOR2: case Variant::RECT2: case Variant::VECTOR3: case Variant::TRANSFORM2D: case Variant::PLANE: case Variant::QUAT: case Variant::AABB: case Variant::BASIS: case Variant::TRANSFORM: case Variant::POOL_BYTE_ARRAY: case Variant::POOL_INT_ARRAY: case Variant::POOL_REAL_ARRAY: case Variant::POOL_STRING_ARRAY: case Variant::POOL_VECTOR2_ARRAY: case Variant::POOL_VECTOR3_ARRAY: case Variant::POOL_COLOR_ARRAY: case Variant::NODE_PATH: { uint32_t pos = tmpdata.size(); int len; encode_variant(p_data, NULL, len, false); tmpdata.resize(tmpdata.size() + len); encode_variant(p_data, &tmpdata.write[pos], len, false); return pos; } break; // misc types case Variant::_RID: case Variant::OBJECT: { return _pack(Variant(), tmpdata, string_cache); } break; case Variant::DICTIONARY: { Dictionary d = p_data; //size is known, use sort uint32_t pos = tmpdata.size(); int len = d.size(); tmpdata.resize(tmpdata.size() + len * 12 + 8); encode_uint32(TYPE_DICT, &tmpdata.write[pos + 0]); encode_uint32(len, &tmpdata.write[pos + 4]); List<Variant> keys; d.get_key_list(&keys); List<DictKey> sortk; for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { DictKey dk; dk.hash = E->get().hash(); dk.key = E->get(); sortk.push_back(dk); } sortk.sort(); int idx = 0; for (List<DictKey>::Element *E = sortk.front(); E; E = E->next()) { encode_uint32(E->get().hash, &tmpdata.write[pos + 8 + idx * 12 + 0]); uint32_t ofs = _pack(E->get().key, tmpdata, string_cache); encode_uint32(ofs, &tmpdata.write[pos + 8 + idx * 12 + 4]); ofs = _pack(d[E->get().key], tmpdata, string_cache); encode_uint32(ofs, &tmpdata.write[pos + 8 + idx * 12 + 8]); idx++; } return pos; } break; case Variant::ARRAY: { Array a = p_data; //size is known, use sort uint32_t pos = tmpdata.size(); int len = a.size(); tmpdata.resize(tmpdata.size() + len * 4 + 8); encode_uint32(TYPE_ARRAY, &tmpdata.write[pos + 0]); encode_uint32(len, &tmpdata.write[pos + 4]); for (int i = 0; i < len; i++) { uint32_t ofs = _pack(a[i], tmpdata, string_cache); encode_uint32(ofs, &tmpdata.write[pos + 8 + i * 4]); } return pos; } break; default: { } } return OK; } Error PackedDataContainer::pack(const Variant &p_data) { Vector<uint8_t> tmpdata; Map<String, uint32_t> string_cache; _pack(p_data, tmpdata, string_cache); datalen = tmpdata.size(); data.resize(tmpdata.size()); PoolVector<uint8_t>::Write w = data.write(); memcpy(w.ptr(), tmpdata.ptr(), tmpdata.size()); return OK; } void PackedDataContainer::_set_data(const PoolVector<uint8_t> &p_data) { data = p_data; datalen = data.size(); } PoolVector<uint8_t> PackedDataContainer::_get_data() const { return data; } Variant PackedDataContainer::_iter_init(const Array &p_iter) { return _iter_init_ofs(p_iter, 0); } Variant PackedDataContainer::_iter_next(const Array &p_iter) { return _iter_next_ofs(p_iter, 0); } Variant PackedDataContainer::_iter_get(const Variant &p_iter) { return _iter_get_ofs(p_iter, 0); } void PackedDataContainer::_bind_methods() { ClassDB::bind_method(D_METHOD("_set_data"), &PackedDataContainer::_set_data); ClassDB::bind_method(D_METHOD("_get_data"), &PackedDataContainer::_get_data); ClassDB::bind_method(D_METHOD("_iter_init"), &PackedDataContainer::_iter_init); ClassDB::bind_method(D_METHOD("_iter_get"), &PackedDataContainer::_iter_get); ClassDB::bind_method(D_METHOD("_iter_next"), &PackedDataContainer::_iter_next); ClassDB::bind_method(D_METHOD("pack", "value"), &PackedDataContainer::pack); ClassDB::bind_method(D_METHOD("size"), &PackedDataContainer::size); ADD_PROPERTY(PropertyInfo(Variant::POOL_BYTE_ARRAY, "__data__"), "_set_data", "_get_data"); } PackedDataContainer::PackedDataContainer() { datalen = 0; } ////////////////// Variant PackedDataContainerRef::_iter_init(const Array &p_iter) { return from->_iter_init_ofs(p_iter, offset); } Variant PackedDataContainerRef::_iter_next(const Array &p_iter) { return from->_iter_next_ofs(p_iter, offset); } Variant PackedDataContainerRef::_iter_get(const Variant &p_iter) { return from->_iter_get_ofs(p_iter, offset); } bool PackedDataContainerRef::_is_dictionary() const { return from->_type_at_ofs(offset) == PackedDataContainer::TYPE_DICT; }; void PackedDataContainerRef::_bind_methods() { ClassDB::bind_method(D_METHOD("size"), &PackedDataContainerRef::size); ClassDB::bind_method(D_METHOD("_iter_init"), &PackedDataContainerRef::_iter_init); ClassDB::bind_method(D_METHOD("_iter_get"), &PackedDataContainerRef::_iter_get); ClassDB::bind_method(D_METHOD("_iter_next"), &PackedDataContainerRef::_iter_next); ClassDB::bind_method(D_METHOD("_is_dictionary"), &PackedDataContainerRef::_is_dictionary); } Variant PackedDataContainerRef::getvar(const Variant &p_key, bool *r_valid) const { bool err = false; Variant ret = from->_key_at_ofs(offset, p_key, err); if (r_valid) *r_valid = !err; return ret; } int PackedDataContainerRef::size() const { return from->_size(offset); }; PackedDataContainerRef::PackedDataContainerRef() { }
/********************************************************************** // @@@ START COPYRIGHT @@@ // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. // // @@@ END COPYRIGHT @@@ **********************************************************************/ #include "hiveHook.h" #include <stdio.h> #include <stdlib.h> #include <iostream> #include <iomanip> #undef _MSC_VER #include "str.h" #include "NAStringDef.h" #include "HBaseClient_JNI.h" #include "Globals.h" struct hive_sd_desc* populateSD(HiveMetaData *md, Int32 mainSdID, Int32 tblID, NAText* tblStr, size_t& pos); struct hive_column_desc* populateColumns(HiveMetaData *md, Int32 cdID, NAText* tblStr, size_t& pos); struct hive_pkey_desc* populatePartitionKey(HiveMetaData *md, Int32 tblID, NAText* tblStr, size_t& pos); struct hive_skey_desc* populateSortCols(HiveMetaData *md, Int32 sdID, NAText* tblStr, size_t& pos); struct hive_bkey_desc* populateBucketingCols(HiveMetaData *md, Int32 sdID, NAText* tblStr, size_t& pos); NABoolean populateSerDeParams(HiveMetaData *md, Int32 serdeID, char& fieldSep, char& recordSep, NAText* tblStr, size_t& pos); NABoolean findAToken (HiveMetaData *md, NAText* tblStr, size_t& pos, const char* tok, const char* errStr, NABoolean raiseError = TRUE); NABoolean extractValueStr (HiveMetaData *md, NAText* tblStr, size_t& pos, const char* beginTok, const char * endTok, NAText& valueStr, const char* errStr, NABoolean raiseError = TRUE); HiveMetaData::HiveMetaData() : tbl_(NULL), currDesc_(NULL), errCode_(0) , errDetail_(NULL), errMethodName_(NULL), errCodeStr_(NULL), client_(NULL) { } HiveMetaData::~HiveMetaData() { CollHeap *h = CmpCommon::contextHeap(); disconnect(); hive_tbl_desc* ptr ; while (tbl_) { ptr = tbl_->next_; NADELETEBASIC(tbl_, h); tbl_ = ptr; } } NABoolean HiveMetaData::init(NABoolean readEntireSchema, const char * hiveSchemaName, const char * tabSearchPredStr) { CollHeap *h = CmpCommon::contextHeap(); /* Create a connection */ if (!connect()) return FALSE; // errCode_ should be set if (!readEntireSchema) return TRUE; int i = 0 ; LIST(NAText *) tblNames(h); HVC_RetCode retCode = client_->getAllTables(hiveSchemaName, tblNames); if ((retCode != HVC_OK) && (retCode != HVC_DONE)) { return recordError((Int32)retCode, "HiveClient_JNI::getAllTables()"); } while (i < tblNames.entries()) { getTableDesc(hiveSchemaName, tblNames[i]->c_str()); delete tblNames[i]; } currDesc_ = 0; //disconnect(); return TRUE; } static NABoolean splitURL(const char *url, NAString &host, Int32 &port, NAString &options) { NABoolean result = TRUE; // split the url into host and file name, proto://host:port/file, // split point is at the third slash in the URL const char *c = url; const char *hostMark = NULL; const char *portMark = NULL; const char *dirMark = NULL; int numSlashes = 0; int numColons = 0; while (*c && dirMark == NULL) { if (*c == '/') numSlashes++; else if (*c == ':') numColons++; c++; if (hostMark == NULL && numSlashes == 2) hostMark = c; else if (portMark == NULL && hostMark && numColons == 2) portMark = c; else if (numSlashes == 3 || // regular URL (numSlashes == 1 && c == url+1)) // just a file name dirMark = c-1; // include the leading slash } if (dirMark == NULL) { dirMark = c; // point to end of string options = ""; } else options = NAString(dirMark); if (hostMark) host = NAString(hostMark, (portMark ? portMark-hostMark-1 : dirMark-hostMark)); if (portMark) port = atoi(portMark); else port = 0; return result; } NABoolean HiveMetaData::connect() { if (!client_) { HiveClient_JNI* hiveClient = HiveClient_JNI::getInstance(); if (hiveClient->isInitialized() == FALSE) { HVC_RetCode retCode = hiveClient->init(); if (retCode != HVC_OK) return recordError((Int32)retCode, "HiveClient_JNI::init()"); } if (hiveClient->isConnected() == FALSE) { Text metastoreURI(""); HVC_RetCode retCode = hiveClient->initConnection(metastoreURI.c_str()); if (retCode != HVC_OK) return recordError((Int32)retCode, "HiveClient_JNI::initConnection()"); } client_ = hiveClient; } // client_ exists return TRUE; } NABoolean HiveMetaData::disconnect() { client_ = NULL; // client connection is owned by CliGlobals. return TRUE; } void HiveMetaData::position() { currDesc_ = tbl_; } struct hive_tbl_desc * HiveMetaData::getNext() { return currDesc_; } void HiveMetaData::advance() { if (currDesc_) currDesc_ = currDesc_->next_; } NABoolean HiveMetaData::atEnd() { return (currDesc_ ? FALSE : TRUE); } NABoolean HiveMetaData::recordError(Int32 errCode, const char *errMethodName) { if (errCode != HVC_OK) { errCode_ = errCode; if (client_) errCodeStr_ = client_->getErrorText((HVC_RetCode)errCode_); errMethodName_ = errMethodName; errDetail_ = GetCliGlobals()->getJniErrorStrPtr(); return FALSE; } return TRUE; } void HiveMetaData::recordParseError(Int32 errCode, const char* errCodeStr, const char *errMethodName, const char* errDetail) { errCode_ = errCode; errCodeStr_ = errCodeStr; errMethodName_ = errMethodName; errDetail_ = errDetail; } void HiveMetaData::resetErrorInfo() { errCode_ = 0; errDetail_ = NULL; errMethodName_ = NULL; errCodeStr_ = NULL; } struct hive_sd_desc* populateSD(HiveMetaData *md, Int32 mainSdID, Int32 tblID, NAText* tblStr, size_t& pos) { struct hive_sd_desc* result = NULL; struct hive_sd_desc* mainSD = NULL; struct hive_sd_desc* last = NULL; char fieldTerminator, recordTerminator; size_t foundB; if (!findAToken(md, tblStr, pos, "sd:StorageDescriptor(", "getTableDesc::sd:StorageDescriptor(###")) return NULL; struct hive_column_desc* newColumns = populateColumns(md, 0, tblStr, pos); if (!newColumns) return NULL; NAText locationStr; if(!extractValueStr(md, tblStr, pos, "location:", ",", locationStr, "populateSD::location:###")) return NULL; NAText inputStr; if(!extractValueStr(md, tblStr, pos, "inputFormat:", ",", inputStr, "populateSD:inputFormat:###")) return NULL; NAText outputStr; if(!extractValueStr(md, tblStr, pos, "outputFormat:", ",", outputStr, "populateSD:outputFormat:###")) return NULL; NAText numBucketsStr; if(!extractValueStr(md, tblStr, pos, "numBuckets:", ",", numBucketsStr, "populateSD:numBuckets:###")) return NULL; Int32 numBuckets = atoi(numBucketsStr.c_str()); NABoolean success = populateSerDeParams(md, 0, fieldTerminator, recordTerminator, tblStr, pos); if (!success) return NULL; struct hive_bkey_desc* newBucketingCols = populateBucketingCols(md, 0, tblStr, pos); struct hive_skey_desc* newSortCols = populateSortCols(md, 0, tblStr, pos); struct hive_sd_desc* newSD = new (CmpCommon::contextHeap()) struct hive_sd_desc(0, //SdID locationStr.c_str(), 0, // creation time numBuckets, inputStr.c_str(), outputStr.c_str(), hive_sd_desc::TABLE_SD, // TODO : no support for hive_sd_desc::PARTN_SD newColumns, newSortCols, newBucketingCols, fieldTerminator, recordTerminator ); result = newSD; // TODO : loop over SDs if (findAToken(md, tblStr, pos, "sd:StorageDescriptor(", "getTableDesc::sd:StorageDescriptor(###"),FALSE) return NULL; return result; } NABoolean hive_sd_desc::isOrcFile() const { return strstr(inputFormat_, "Orc") && strstr(outputFormat_, "Orc"); } NABoolean hive_sd_desc::isSequenceFile() const { return strstr(inputFormat_, "Sequence") && strstr(outputFormat_, "Sequence"); } NABoolean hive_sd_desc::isTextFile() const { return strstr(inputFormat_, "Text") && strstr(outputFormat_, "Text"); } struct hive_column_desc* populateColumns(HiveMetaData *md, Int32 cdID, NAText* tblStr, size_t& pos) { struct hive_column_desc* result = NULL; struct hive_column_desc* last = result; std::size_t foundB ; if (!findAToken(md, tblStr, pos, "cols:", "populateColumns::cols:###")) return NULL; std::size_t foundE = pos; if (!findAToken(md, tblStr, foundE, ")],", "populateColumns::cols:],###")) return NULL; Int32 colIdx = 0; while (pos < foundE) { NAText nameStr; if(!extractValueStr(md, tblStr, pos, "FieldSchema(name:", ",", nameStr, "populateColumns::FieldSchema(name:###")) return NULL; NAText typeStr; if(!extractValueStr(md, tblStr, pos, "type:", ",", typeStr, "populateColumns::type:###")) return NULL; pos++; if (!findAToken(md, tblStr, pos, ",", "populateColumns::comment:,###")) return NULL; struct hive_column_desc* newCol = new (CmpCommon::contextHeap()) struct hive_column_desc(0, nameStr.c_str(), typeStr.c_str(), colIdx); if ( result == NULL ) { last = result = newCol; } else { last->next_ = newCol; last = newCol; } colIdx++; } // end of while return result; } struct hive_pkey_desc* populatePartitionKey(HiveMetaData *md, Int32 tblID, NAText* tblStr, size_t& pos) { hive_pkey_desc* result = NULL; hive_pkey_desc* last = NULL; std::size_t foundB ; if (!findAToken(md, tblStr, pos, "partitionKeys:", "populatePartitionKeys::partitionKeys:###")) return NULL; std::size_t foundE = pos ; if (!findAToken(md, tblStr, foundE, "],", "populatePartitionKeys::partitionKeys:],###")) return NULL; Int32 colIdx = 0; while (pos < foundE) { foundB = tblStr->find("FieldSchema(name:", pos); if ((foundB == std::string::npos)||(foundB > foundE)) { return NULL; // no part Key } foundB = foundB + strlen("FieldSchema(name:"); pos = foundB ; if (!findAToken(md, tblStr, pos, ",", "populatePartitionKeys::comment:,###")) return NULL; NAText nameStr = tblStr->substr(foundB, pos-foundB); NAText typeStr; if(!extractValueStr(md, tblStr, pos, "type:", ",", typeStr, "populatePartitionKeys::type:###")) return NULL; pos++; if (!findAToken(md, tblStr, pos, ",", "populateColumns::comment:,###")) return NULL; hive_pkey_desc* newPkey = new (CmpCommon::contextHeap()) struct hive_pkey_desc(nameStr.c_str(), typeStr.c_str(), colIdx); if ( result == NULL ) { last = result = newPkey; } else { last->next_ = newPkey; last = newPkey; } colIdx++; } // end of while return result; } struct hive_skey_desc* populateSortCols(HiveMetaData *md, Int32 sdID, NAText* tblStr, size_t& pos) { hive_skey_desc* result = NULL; hive_skey_desc* last = NULL; std::size_t foundB ; if (!findAToken(md, tblStr, pos, "sortCols:", "populateSortCols::sortCols:###")) return NULL; std::size_t foundE = pos ; if (!findAToken(md, tblStr, foundE, "],", "populateSortCols::sortCols:],###")) return NULL; Int32 colIdx = 0; while (pos < foundE) { foundB = tblStr->find("Order(col:", pos); if ((foundB == std::string::npos)||(foundB > foundE)) { return NULL; } foundB = foundB + strlen("Order(col:"); pos = foundB ; if (!findAToken(md, tblStr, pos, ",", "populateSortCols::name:,###")) return NULL; NAText nameStr = tblStr->substr(foundB, pos-foundB); NAText orderStr; if(!extractValueStr(md, tblStr, pos, "order:", ",", orderStr, "populateSortCols::order:###")) return NULL; pos++; if (!findAToken(md, tblStr, pos, ",", "populateSortColumns::comment:,###")) return NULL; hive_skey_desc* newSkey = new (CmpCommon::contextHeap()) struct hive_skey_desc(nameStr.c_str(), colIdx, atoi(orderStr.c_str())); if ( result == NULL ) { last = result = newSkey; } else { last->next_ = newSkey; last = newSkey; } colIdx++; } // end of while return result; } static int getAsciiDecimalValue(const char * valPtr) { if (str_len(valPtr) <= 0) return 0; if (str_len(valPtr) == 1) return valPtr[0]; return atoi(valPtr); } NABoolean populateSerDeParams(HiveMetaData *md, Int32 serdeID, char& fieldTerminator, char& recordTerminator, NAText* tblStr, size_t& pos) { fieldTerminator = '\001'; // this the Hive default ^A or ascii code 1 recordTerminator = '\n'; // this is the Hive default std::size_t foundB ; if (!findAToken(md, tblStr, pos, "serdeInfo:", "populateSerDeParams::serdeInfo:###")) return NULL; std::size_t foundE = pos ; if (!findAToken(md, tblStr, foundE, "}),", "populateSerDeParams::serDeInfo:)},###")) return NULL; const char * fieldStr = "field.delim" ; const char * lineStr = "line.delim" ; foundB = tblStr->find(fieldStr,pos); if ((foundB != std::string::npos) && (foundB < foundE)) fieldTerminator = tblStr->at(foundB+strlen(fieldStr)+1); foundB = tblStr->find("line.delim=",pos); if ((foundB != std::string::npos) && (foundB < foundE)) recordTerminator = tblStr->at(foundB+strlen(lineStr)+1); pos = foundE; return TRUE; } struct hive_bkey_desc* populateBucketingCols(HiveMetaData *md, Int32 sdID, NAText* tblStr, size_t& pos) { hive_bkey_desc* result = NULL; hive_bkey_desc* last = NULL; std::size_t foundB ; if (!findAToken(md, tblStr, pos, "bucketCols:", "populateBucketingCols::bucketCols:###")) return NULL; std::size_t foundE = pos ; if (!findAToken(md, tblStr, foundE, "],", "populateBucketingCols::bucketCols:],###")) return NULL; pos = pos + strlen("bucketCols:["); if (pos == foundE) return NULL ; // empty bucket cols list. This line is code is for // clarity alone, the while condition alone is sufficient. Int32 colIdx = 0; while (pos < foundE) { foundB = tblStr->find(",", pos); if ((foundB == std::string::npos)||(foundB > foundE)) { foundB = foundE; // we have only one bucketing col or // this is the last bucket col } NAText nameStr = tblStr->substr(pos, foundB-pos); pos = foundB; hive_bkey_desc* newBkey = new (CmpCommon::contextHeap()) struct hive_bkey_desc(nameStr.c_str(), colIdx); if ( result == NULL ) { last = result = newBkey; } else { last->next_ = newBkey; last = newBkey; } colIdx++; } // end of while return result; } NABoolean findAToken (HiveMetaData *md, NAText* tblStr, size_t& pos, const char* tok, const char* errStr, NABoolean raiseError) { size_t foundB = tblStr->find(tok, pos); if (foundB == std::string::npos) { if (raiseError) { NAText *errText = new (CmpCommon::statementHeap()) string(errStr); char xPos[7]; str_itoa(pos, xPos); errText->append(" at position "); errText->append(xPos); errText->append(tblStr->c_str()); md->recordParseError(1500, "PARSE_ERROR", errText->c_str(), tblStr->c_str()); } return FALSE; } pos = foundB; return TRUE; } NABoolean extractValueStr (HiveMetaData *md, NAText* tblStr, size_t& pos, const char* beginTok, const char* endTok, NAText& valueStr, const char* errStr, NABoolean raiseError) { if (!findAToken(md, tblStr, pos, beginTok, errStr, raiseError)) return FALSE; size_t foundB = pos + strlen(beginTok); if (!findAToken(md, tblStr, pos, endTok, errStr, TRUE)) return FALSE; valueStr.append(tblStr->substr(foundB, pos-foundB )); return TRUE; } struct hive_tbl_desc* HiveMetaData::getFakedTableDesc(const char* tblName) { CollHeap *h = CmpCommon::contextHeap(); hive_column_desc* c1 = new (h) hive_column_desc(1, "C1", "int", 0); hive_column_desc* c2 = new (h) hive_column_desc(2, "C2", "string", 1); hive_column_desc* c3 = new (h) hive_column_desc(3, "C3", "float", 2); c1->next_ = c2; c2->next_ = c3; // sort key c1 hive_skey_desc* sk1 = new (h) hive_skey_desc("C1", 1, 1); // bucket key c2 hive_bkey_desc* bk1 = new (h) hive_bkey_desc("C2", 1); hive_sd_desc* sd1 = new (h)hive_sd_desc(1, "loc", 0, 1, "ift", "oft", hive_sd_desc::TABLE_SD, c1, sk1, bk1, '\010', '\n'); hive_tbl_desc* tbl1 = new (h) hive_tbl_desc(1, "myHive", "default", 0, sd1, 0); return tbl1; } struct hive_tbl_desc* HiveMetaData::getTableDesc(const char* schemaName, const char* tblName) { struct hive_tbl_desc *ptr = tbl_; while (ptr) { if ( !(strcmp(ptr->tblName_, tblName) ||strcmp(ptr->schName_, schemaName))) { if (validate(ptr->tblID_, ptr->redeftime(), schemaName, tblName)) return ptr; else { // table changed, delete it and re-read below if (tbl_ == ptr) tbl_ = ptr->next_; else { struct hive_tbl_desc *ptr2 = tbl_; while (ptr2) { if (ptr2->next_ == ptr) ptr2->next_ = ptr->next_; ptr2 = ptr2->next_; } } NADELETEBASIC(ptr, CmpCommon::contextHeap()); ptr = NULL; break; } } ptr = ptr->next_; } // table not found in cache, try to read it from metadata hive_tbl_desc * result = NULL; Int64 creationTS; NABoolean needToConnect ; needToConnect = (client_ == NULL); /* Create a connection */ if (needToConnect) if (!connect()) return NULL; NAText* tblStr = new (CmpCommon::statementHeap()) string(); if (!tblStr) return NULL; HVC_RetCode retCode = client_->getHiveTableStr(schemaName, tblName, *tblStr); if ((retCode != HVC_OK) && (retCode != HVC_DONE)) { recordError((Int32)retCode, "HiveClient_JNI::getTableStr()"); return NULL; } if (retCode == HVC_DONE) // table not found. return NULL; NAText tblNameStr; size_t pos = 0; if(!extractValueStr(this, tblStr, pos, "tableName:", ",", tblNameStr, "getTableDesc::tableName:###")) return NULL; NAText schNameStr; pos = 0; if(!extractValueStr(this, tblStr, pos, "dbName:", ",", schNameStr, "getTableDesc::dbName:###")) return NULL; NAText createTimeStr; pos = 0; if(!extractValueStr(this, tblStr, pos, "createTime:", ",", createTimeStr, "getTableDesc::createTime:###")) return NULL; creationTS = atol(createTimeStr.c_str()); // TODO: need to handle multiple SDs struct hive_sd_desc* sd = populateSD(this, 0,0, tblStr, pos); if (!sd) return NULL; struct hive_pkey_desc* pkey = populatePartitionKey(this, 0, tblStr, pos); result = new (CmpCommon::contextHeap()) struct hive_tbl_desc(0, // no tblID with JNI tblNameStr.c_str(), schNameStr.c_str(), creationTS, sd, pkey); // add the new table to the cache result->next_ = tbl_; tbl_ = result; //delete tblStr ; return result; } NABoolean HiveMetaData::validate(Int32 tableId, Int64 redefTS, const char* schName, const char* tblName) { NABoolean result = FALSE; // validate creation timestamp if (!connect()) return FALSE; Int64 currentRedefTime = 0; HVC_RetCode retCode = client_->getRedefTime(schName, tblName, currentRedefTime); if ((retCode != HVC_OK) && (retCode != HVC_DONE)) { return recordError((Int32)retCode, "HiveClient_JNI::getRedefTime()"); } if ((retCode == HVC_DONE) || (currentRedefTime != redefTS)) return result; else return TRUE; return result; } struct hive_column_desc* hive_tbl_desc::getColumns() { struct hive_sd_desc* sd = sd_; // assume all SDs have the same column structure! if ( sd ) return sd->column_; return NULL; } struct hive_bkey_desc* hive_tbl_desc::getBucketingKeys() { struct hive_sd_desc* sd = sd_; // assume all SDs have the same bucketing key structure! if ( sd ) return sd->bkey_; return NULL; } struct hive_skey_desc* hive_tbl_desc::getSortKeys() { struct hive_sd_desc* sd = sd_; // assume all SDs have the same sort key structure! if ( sd ) { return sd->skey_; } return NULL; } Int32 hive_tbl_desc::getNumOfPartCols() const { Int32 result = 0; hive_pkey_desc *pk = pkey_; while (pk) { result++; pk = pk->next_; } return result; } Int64 hive_tbl_desc::redeftime() { Int64 result = creationTS_; struct hive_sd_desc* sd = sd_; while (sd) { if (sd->creationTS_ > result) result = sd->creationTS_; sd = sd->next_; } return result; } hive_tbl_desc::~hive_tbl_desc() { CollHeap *h = CmpCommon::contextHeap(); if (tblName_) NADELETEBASIC(tblName_, h); if (schName_) NADELETEBASIC(schName_, h); hive_sd_desc* ptr ; while (sd_) { ptr = sd_->next_; NADELETEBASIC(sd_, h); sd_ = ptr; } hive_pkey_desc* ptr1 ; while (pkey_) { ptr1 = pkey_->next_; NADELETEBASIC(pkey_, h); pkey_ = ptr1; } } hive_sd_desc::~hive_sd_desc() { CollHeap *h = CmpCommon::contextHeap(); if (location_) NADELETEBASIC(location_, h); if (inputFormat_) NADELETEBASIC(inputFormat_, h); if (outputFormat_) NADELETEBASIC(outputFormat_, h); hive_column_desc* ptr ; while (column_) { ptr = column_->next_; NADELETEBASIC(column_, h); column_ = ptr; } hive_skey_desc* ptr1 ; while (skey_) { ptr1 = skey_->next_; NADELETEBASIC(skey_, h); skey_ = ptr1; } hive_bkey_desc* ptr2 ; while (bkey_) { ptr2 = bkey_->next_; NADELETEBASIC(bkey_, h); bkey_ = ptr2; } } hive_pkey_desc::~hive_pkey_desc() { CollHeap *h = CmpCommon::contextHeap(); if (name_) NADELETEBASIC(name_, h); if (type_) NADELETEBASIC(type_, h); } hive_skey_desc::~hive_skey_desc() { CollHeap *h = CmpCommon::contextHeap(); if (name_) NADELETEBASIC(name_, h); } hive_bkey_desc::~hive_bkey_desc() { CollHeap *h = CmpCommon::contextHeap(); if (name_) NADELETEBASIC(name_, h); } hive_column_desc::~hive_column_desc() { CollHeap *h = CmpCommon::contextHeap(); if (name_) NADELETEBASIC(name_, h); if (type_) NADELETEBASIC(type_, h); } [TRAFODION-1742] Rework, misplaced parenthesis A misplaced paranthesis caused the previous change to not work as expected. /********************************************************************** // @@@ START COPYRIGHT @@@ // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. // // @@@ END COPYRIGHT @@@ **********************************************************************/ #include "hiveHook.h" #include <stdio.h> #include <stdlib.h> #include <iostream> #include <iomanip> #undef _MSC_VER #include "str.h" #include "NAStringDef.h" #include "HBaseClient_JNI.h" #include "Globals.h" struct hive_sd_desc* populateSD(HiveMetaData *md, Int32 mainSdID, Int32 tblID, NAText* tblStr, size_t& pos); struct hive_column_desc* populateColumns(HiveMetaData *md, Int32 cdID, NAText* tblStr, size_t& pos); struct hive_pkey_desc* populatePartitionKey(HiveMetaData *md, Int32 tblID, NAText* tblStr, size_t& pos); struct hive_skey_desc* populateSortCols(HiveMetaData *md, Int32 sdID, NAText* tblStr, size_t& pos); struct hive_bkey_desc* populateBucketingCols(HiveMetaData *md, Int32 sdID, NAText* tblStr, size_t& pos); NABoolean populateSerDeParams(HiveMetaData *md, Int32 serdeID, char& fieldSep, char& recordSep, NAText* tblStr, size_t& pos); NABoolean findAToken (HiveMetaData *md, NAText* tblStr, size_t& pos, const char* tok, const char* errStr, NABoolean raiseError = TRUE); NABoolean extractValueStr (HiveMetaData *md, NAText* tblStr, size_t& pos, const char* beginTok, const char * endTok, NAText& valueStr, const char* errStr, NABoolean raiseError = TRUE); HiveMetaData::HiveMetaData() : tbl_(NULL), currDesc_(NULL), errCode_(0) , errDetail_(NULL), errMethodName_(NULL), errCodeStr_(NULL), client_(NULL) { } HiveMetaData::~HiveMetaData() { CollHeap *h = CmpCommon::contextHeap(); disconnect(); hive_tbl_desc* ptr ; while (tbl_) { ptr = tbl_->next_; NADELETEBASIC(tbl_, h); tbl_ = ptr; } } NABoolean HiveMetaData::init(NABoolean readEntireSchema, const char * hiveSchemaName, const char * tabSearchPredStr) { CollHeap *h = CmpCommon::contextHeap(); /* Create a connection */ if (!connect()) return FALSE; // errCode_ should be set if (!readEntireSchema) return TRUE; int i = 0 ; LIST(NAText *) tblNames(h); HVC_RetCode retCode = client_->getAllTables(hiveSchemaName, tblNames); if ((retCode != HVC_OK) && (retCode != HVC_DONE)) { return recordError((Int32)retCode, "HiveClient_JNI::getAllTables()"); } while (i < tblNames.entries()) { getTableDesc(hiveSchemaName, tblNames[i]->c_str()); delete tblNames[i]; } currDesc_ = 0; //disconnect(); return TRUE; } static NABoolean splitURL(const char *url, NAString &host, Int32 &port, NAString &options) { NABoolean result = TRUE; // split the url into host and file name, proto://host:port/file, // split point is at the third slash in the URL const char *c = url; const char *hostMark = NULL; const char *portMark = NULL; const char *dirMark = NULL; int numSlashes = 0; int numColons = 0; while (*c && dirMark == NULL) { if (*c == '/') numSlashes++; else if (*c == ':') numColons++; c++; if (hostMark == NULL && numSlashes == 2) hostMark = c; else if (portMark == NULL && hostMark && numColons == 2) portMark = c; else if (numSlashes == 3 || // regular URL (numSlashes == 1 && c == url+1)) // just a file name dirMark = c-1; // include the leading slash } if (dirMark == NULL) { dirMark = c; // point to end of string options = ""; } else options = NAString(dirMark); if (hostMark) host = NAString(hostMark, (portMark ? portMark-hostMark-1 : dirMark-hostMark)); if (portMark) port = atoi(portMark); else port = 0; return result; } NABoolean HiveMetaData::connect() { if (!client_) { HiveClient_JNI* hiveClient = HiveClient_JNI::getInstance(); if (hiveClient->isInitialized() == FALSE) { HVC_RetCode retCode = hiveClient->init(); if (retCode != HVC_OK) return recordError((Int32)retCode, "HiveClient_JNI::init()"); } if (hiveClient->isConnected() == FALSE) { Text metastoreURI(""); HVC_RetCode retCode = hiveClient->initConnection(metastoreURI.c_str()); if (retCode != HVC_OK) return recordError((Int32)retCode, "HiveClient_JNI::initConnection()"); } client_ = hiveClient; } // client_ exists return TRUE; } NABoolean HiveMetaData::disconnect() { client_ = NULL; // client connection is owned by CliGlobals. return TRUE; } void HiveMetaData::position() { currDesc_ = tbl_; } struct hive_tbl_desc * HiveMetaData::getNext() { return currDesc_; } void HiveMetaData::advance() { if (currDesc_) currDesc_ = currDesc_->next_; } NABoolean HiveMetaData::atEnd() { return (currDesc_ ? FALSE : TRUE); } NABoolean HiveMetaData::recordError(Int32 errCode, const char *errMethodName) { if (errCode != HVC_OK) { errCode_ = errCode; if (client_) errCodeStr_ = client_->getErrorText((HVC_RetCode)errCode_); errMethodName_ = errMethodName; errDetail_ = GetCliGlobals()->getJniErrorStrPtr(); return FALSE; } return TRUE; } void HiveMetaData::recordParseError(Int32 errCode, const char* errCodeStr, const char *errMethodName, const char* errDetail) { errCode_ = errCode; errCodeStr_ = errCodeStr; errMethodName_ = errMethodName; errDetail_ = errDetail; } void HiveMetaData::resetErrorInfo() { errCode_ = 0; errDetail_ = NULL; errMethodName_ = NULL; errCodeStr_ = NULL; } struct hive_sd_desc* populateSD(HiveMetaData *md, Int32 mainSdID, Int32 tblID, NAText* tblStr, size_t& pos) { struct hive_sd_desc* result = NULL; struct hive_sd_desc* mainSD = NULL; struct hive_sd_desc* last = NULL; char fieldTerminator, recordTerminator; size_t foundB; if (!findAToken(md, tblStr, pos, "sd:StorageDescriptor(", "getTableDesc::sd:StorageDescriptor(###")) return NULL; struct hive_column_desc* newColumns = populateColumns(md, 0, tblStr, pos); if (!newColumns) return NULL; NAText locationStr; if(!extractValueStr(md, tblStr, pos, "location:", ",", locationStr, "populateSD::location:###")) return NULL; NAText inputStr; if(!extractValueStr(md, tblStr, pos, "inputFormat:", ",", inputStr, "populateSD:inputFormat:###")) return NULL; NAText outputStr; if(!extractValueStr(md, tblStr, pos, "outputFormat:", ",", outputStr, "populateSD:outputFormat:###")) return NULL; NAText numBucketsStr; if(!extractValueStr(md, tblStr, pos, "numBuckets:", ",", numBucketsStr, "populateSD:numBuckets:###")) return NULL; Int32 numBuckets = atoi(numBucketsStr.c_str()); NABoolean success = populateSerDeParams(md, 0, fieldTerminator, recordTerminator, tblStr, pos); if (!success) return NULL; struct hive_bkey_desc* newBucketingCols = populateBucketingCols(md, 0, tblStr, pos); struct hive_skey_desc* newSortCols = populateSortCols(md, 0, tblStr, pos); struct hive_sd_desc* newSD = new (CmpCommon::contextHeap()) struct hive_sd_desc(0, //SdID locationStr.c_str(), 0, // creation time numBuckets, inputStr.c_str(), outputStr.c_str(), hive_sd_desc::TABLE_SD, // TODO : no support for hive_sd_desc::PARTN_SD newColumns, newSortCols, newBucketingCols, fieldTerminator, recordTerminator ); result = newSD; // TODO : loop over SDs if (findAToken(md, tblStr, pos, "sd:StorageDescriptor(", "getTableDesc::sd:StorageDescriptor(###)",FALSE)) return NULL; return result; } NABoolean hive_sd_desc::isOrcFile() const { return strstr(inputFormat_, "Orc") && strstr(outputFormat_, "Orc"); } NABoolean hive_sd_desc::isSequenceFile() const { return strstr(inputFormat_, "Sequence") && strstr(outputFormat_, "Sequence"); } NABoolean hive_sd_desc::isTextFile() const { return strstr(inputFormat_, "Text") && strstr(outputFormat_, "Text"); } struct hive_column_desc* populateColumns(HiveMetaData *md, Int32 cdID, NAText* tblStr, size_t& pos) { struct hive_column_desc* result = NULL; struct hive_column_desc* last = result; std::size_t foundB ; if (!findAToken(md, tblStr, pos, "cols:", "populateColumns::cols:###")) return NULL; std::size_t foundE = pos; if (!findAToken(md, tblStr, foundE, ")],", "populateColumns::cols:],###")) return NULL; Int32 colIdx = 0; while (pos < foundE) { NAText nameStr; if(!extractValueStr(md, tblStr, pos, "FieldSchema(name:", ",", nameStr, "populateColumns::FieldSchema(name:###")) return NULL; NAText typeStr; if(!extractValueStr(md, tblStr, pos, "type:", ",", typeStr, "populateColumns::type:###")) return NULL; pos++; if (!findAToken(md, tblStr, pos, ",", "populateColumns::comment:,###")) return NULL; struct hive_column_desc* newCol = new (CmpCommon::contextHeap()) struct hive_column_desc(0, nameStr.c_str(), typeStr.c_str(), colIdx); if ( result == NULL ) { last = result = newCol; } else { last->next_ = newCol; last = newCol; } colIdx++; } // end of while return result; } struct hive_pkey_desc* populatePartitionKey(HiveMetaData *md, Int32 tblID, NAText* tblStr, size_t& pos) { hive_pkey_desc* result = NULL; hive_pkey_desc* last = NULL; std::size_t foundB ; if (!findAToken(md, tblStr, pos, "partitionKeys:", "populatePartitionKeys::partitionKeys:###")) return NULL; std::size_t foundE = pos ; if (!findAToken(md, tblStr, foundE, "],", "populatePartitionKeys::partitionKeys:],###")) return NULL; Int32 colIdx = 0; while (pos < foundE) { foundB = tblStr->find("FieldSchema(name:", pos); if ((foundB == std::string::npos)||(foundB > foundE)) { return NULL; // no part Key } foundB = foundB + strlen("FieldSchema(name:"); pos = foundB ; if (!findAToken(md, tblStr, pos, ",", "populatePartitionKeys::comment:,###")) return NULL; NAText nameStr = tblStr->substr(foundB, pos-foundB); NAText typeStr; if(!extractValueStr(md, tblStr, pos, "type:", ",", typeStr, "populatePartitionKeys::type:###")) return NULL; pos++; if (!findAToken(md, tblStr, pos, ",", "populateColumns::comment:,###")) return NULL; hive_pkey_desc* newPkey = new (CmpCommon::contextHeap()) struct hive_pkey_desc(nameStr.c_str(), typeStr.c_str(), colIdx); if ( result == NULL ) { last = result = newPkey; } else { last->next_ = newPkey; last = newPkey; } colIdx++; } // end of while return result; } struct hive_skey_desc* populateSortCols(HiveMetaData *md, Int32 sdID, NAText* tblStr, size_t& pos) { hive_skey_desc* result = NULL; hive_skey_desc* last = NULL; std::size_t foundB ; if (!findAToken(md, tblStr, pos, "sortCols:", "populateSortCols::sortCols:###")) return NULL; std::size_t foundE = pos ; if (!findAToken(md, tblStr, foundE, "],", "populateSortCols::sortCols:],###")) return NULL; Int32 colIdx = 0; while (pos < foundE) { foundB = tblStr->find("Order(col:", pos); if ((foundB == std::string::npos)||(foundB > foundE)) { return NULL; } foundB = foundB + strlen("Order(col:"); pos = foundB ; if (!findAToken(md, tblStr, pos, ",", "populateSortCols::name:,###")) return NULL; NAText nameStr = tblStr->substr(foundB, pos-foundB); NAText orderStr; if(!extractValueStr(md, tblStr, pos, "order:", ",", orderStr, "populateSortCols::order:###")) return NULL; pos++; if (!findAToken(md, tblStr, pos, ",", "populateSortColumns::comment:,###")) return NULL; hive_skey_desc* newSkey = new (CmpCommon::contextHeap()) struct hive_skey_desc(nameStr.c_str(), colIdx, atoi(orderStr.c_str())); if ( result == NULL ) { last = result = newSkey; } else { last->next_ = newSkey; last = newSkey; } colIdx++; } // end of while return result; } static int getAsciiDecimalValue(const char * valPtr) { if (str_len(valPtr) <= 0) return 0; if (str_len(valPtr) == 1) return valPtr[0]; return atoi(valPtr); } NABoolean populateSerDeParams(HiveMetaData *md, Int32 serdeID, char& fieldTerminator, char& recordTerminator, NAText* tblStr, size_t& pos) { fieldTerminator = '\001'; // this the Hive default ^A or ascii code 1 recordTerminator = '\n'; // this is the Hive default std::size_t foundB ; if (!findAToken(md, tblStr, pos, "serdeInfo:", "populateSerDeParams::serdeInfo:###")) return NULL; std::size_t foundE = pos ; if (!findAToken(md, tblStr, foundE, "}),", "populateSerDeParams::serDeInfo:)},###")) return NULL; const char * fieldStr = "field.delim" ; const char * lineStr = "line.delim" ; foundB = tblStr->find(fieldStr,pos); if ((foundB != std::string::npos) && (foundB < foundE)) fieldTerminator = tblStr->at(foundB+strlen(fieldStr)+1); foundB = tblStr->find("line.delim=",pos); if ((foundB != std::string::npos) && (foundB < foundE)) recordTerminator = tblStr->at(foundB+strlen(lineStr)+1); pos = foundE; return TRUE; } struct hive_bkey_desc* populateBucketingCols(HiveMetaData *md, Int32 sdID, NAText* tblStr, size_t& pos) { hive_bkey_desc* result = NULL; hive_bkey_desc* last = NULL; std::size_t foundB ; if (!findAToken(md, tblStr, pos, "bucketCols:", "populateBucketingCols::bucketCols:###")) return NULL; std::size_t foundE = pos ; if (!findAToken(md, tblStr, foundE, "],", "populateBucketingCols::bucketCols:],###")) return NULL; pos = pos + strlen("bucketCols:["); if (pos == foundE) return NULL ; // empty bucket cols list. This line is code is for // clarity alone, the while condition alone is sufficient. Int32 colIdx = 0; while (pos < foundE) { foundB = tblStr->find(",", pos); if ((foundB == std::string::npos)||(foundB > foundE)) { foundB = foundE; // we have only one bucketing col or // this is the last bucket col } NAText nameStr = tblStr->substr(pos, foundB-pos); pos = foundB; hive_bkey_desc* newBkey = new (CmpCommon::contextHeap()) struct hive_bkey_desc(nameStr.c_str(), colIdx); if ( result == NULL ) { last = result = newBkey; } else { last->next_ = newBkey; last = newBkey; } colIdx++; } // end of while return result; } NABoolean findAToken (HiveMetaData *md, NAText* tblStr, size_t& pos, const char* tok, const char* errStr, NABoolean raiseError) { size_t foundB = tblStr->find(tok, pos); if (foundB == std::string::npos) { if (raiseError) { NAText *errText = new (CmpCommon::statementHeap()) string(errStr); char xPos[7]; str_itoa(pos, xPos); errText->append(" at position "); errText->append(xPos); errText->append(tblStr->c_str()); md->recordParseError(1500, "PARSE_ERROR", errText->c_str(), tblStr->c_str()); } return FALSE; } pos = foundB; return TRUE; } NABoolean extractValueStr (HiveMetaData *md, NAText* tblStr, size_t& pos, const char* beginTok, const char* endTok, NAText& valueStr, const char* errStr, NABoolean raiseError) { if (!findAToken(md, tblStr, pos, beginTok, errStr, raiseError)) return FALSE; size_t foundB = pos + strlen(beginTok); if (!findAToken(md, tblStr, pos, endTok, errStr, TRUE)) return FALSE; valueStr.append(tblStr->substr(foundB, pos-foundB )); return TRUE; } struct hive_tbl_desc* HiveMetaData::getFakedTableDesc(const char* tblName) { CollHeap *h = CmpCommon::contextHeap(); hive_column_desc* c1 = new (h) hive_column_desc(1, "C1", "int", 0); hive_column_desc* c2 = new (h) hive_column_desc(2, "C2", "string", 1); hive_column_desc* c3 = new (h) hive_column_desc(3, "C3", "float", 2); c1->next_ = c2; c2->next_ = c3; // sort key c1 hive_skey_desc* sk1 = new (h) hive_skey_desc("C1", 1, 1); // bucket key c2 hive_bkey_desc* bk1 = new (h) hive_bkey_desc("C2", 1); hive_sd_desc* sd1 = new (h)hive_sd_desc(1, "loc", 0, 1, "ift", "oft", hive_sd_desc::TABLE_SD, c1, sk1, bk1, '\010', '\n'); hive_tbl_desc* tbl1 = new (h) hive_tbl_desc(1, "myHive", "default", 0, sd1, 0); return tbl1; } struct hive_tbl_desc* HiveMetaData::getTableDesc(const char* schemaName, const char* tblName) { struct hive_tbl_desc *ptr = tbl_; while (ptr) { if ( !(strcmp(ptr->tblName_, tblName) ||strcmp(ptr->schName_, schemaName))) { if (validate(ptr->tblID_, ptr->redeftime(), schemaName, tblName)) return ptr; else { // table changed, delete it and re-read below if (tbl_ == ptr) tbl_ = ptr->next_; else { struct hive_tbl_desc *ptr2 = tbl_; while (ptr2) { if (ptr2->next_ == ptr) ptr2->next_ = ptr->next_; ptr2 = ptr2->next_; } } NADELETEBASIC(ptr, CmpCommon::contextHeap()); ptr = NULL; break; } } ptr = ptr->next_; } // table not found in cache, try to read it from metadata hive_tbl_desc * result = NULL; Int64 creationTS; NABoolean needToConnect ; needToConnect = (client_ == NULL); /* Create a connection */ if (needToConnect) if (!connect()) return NULL; NAText* tblStr = new (CmpCommon::statementHeap()) string(); if (!tblStr) return NULL; HVC_RetCode retCode = client_->getHiveTableStr(schemaName, tblName, *tblStr); if ((retCode != HVC_OK) && (retCode != HVC_DONE)) { recordError((Int32)retCode, "HiveClient_JNI::getTableStr()"); return NULL; } if (retCode == HVC_DONE) // table not found. return NULL; NAText tblNameStr; size_t pos = 0; if(!extractValueStr(this, tblStr, pos, "tableName:", ",", tblNameStr, "getTableDesc::tableName:###")) return NULL; NAText schNameStr; pos = 0; if(!extractValueStr(this, tblStr, pos, "dbName:", ",", schNameStr, "getTableDesc::dbName:###")) return NULL; NAText createTimeStr; pos = 0; if(!extractValueStr(this, tblStr, pos, "createTime:", ",", createTimeStr, "getTableDesc::createTime:###")) return NULL; creationTS = atol(createTimeStr.c_str()); // TODO: need to handle multiple SDs struct hive_sd_desc* sd = populateSD(this, 0,0, tblStr, pos); if (!sd) return NULL; struct hive_pkey_desc* pkey = populatePartitionKey(this, 0, tblStr, pos); result = new (CmpCommon::contextHeap()) struct hive_tbl_desc(0, // no tblID with JNI tblNameStr.c_str(), schNameStr.c_str(), creationTS, sd, pkey); // add the new table to the cache result->next_ = tbl_; tbl_ = result; //delete tblStr ; return result; } NABoolean HiveMetaData::validate(Int32 tableId, Int64 redefTS, const char* schName, const char* tblName) { NABoolean result = FALSE; // validate creation timestamp if (!connect()) return FALSE; Int64 currentRedefTime = 0; HVC_RetCode retCode = client_->getRedefTime(schName, tblName, currentRedefTime); if ((retCode != HVC_OK) && (retCode != HVC_DONE)) { return recordError((Int32)retCode, "HiveClient_JNI::getRedefTime()"); } if ((retCode == HVC_DONE) || (currentRedefTime != redefTS)) return result; else return TRUE; return result; } struct hive_column_desc* hive_tbl_desc::getColumns() { struct hive_sd_desc* sd = sd_; // assume all SDs have the same column structure! if ( sd ) return sd->column_; return NULL; } struct hive_bkey_desc* hive_tbl_desc::getBucketingKeys() { struct hive_sd_desc* sd = sd_; // assume all SDs have the same bucketing key structure! if ( sd ) return sd->bkey_; return NULL; } struct hive_skey_desc* hive_tbl_desc::getSortKeys() { struct hive_sd_desc* sd = sd_; // assume all SDs have the same sort key structure! if ( sd ) { return sd->skey_; } return NULL; } Int32 hive_tbl_desc::getNumOfPartCols() const { Int32 result = 0; hive_pkey_desc *pk = pkey_; while (pk) { result++; pk = pk->next_; } return result; } Int64 hive_tbl_desc::redeftime() { Int64 result = creationTS_; struct hive_sd_desc* sd = sd_; while (sd) { if (sd->creationTS_ > result) result = sd->creationTS_; sd = sd->next_; } return result; } hive_tbl_desc::~hive_tbl_desc() { CollHeap *h = CmpCommon::contextHeap(); if (tblName_) NADELETEBASIC(tblName_, h); if (schName_) NADELETEBASIC(schName_, h); hive_sd_desc* ptr ; while (sd_) { ptr = sd_->next_; NADELETEBASIC(sd_, h); sd_ = ptr; } hive_pkey_desc* ptr1 ; while (pkey_) { ptr1 = pkey_->next_; NADELETEBASIC(pkey_, h); pkey_ = ptr1; } } hive_sd_desc::~hive_sd_desc() { CollHeap *h = CmpCommon::contextHeap(); if (location_) NADELETEBASIC(location_, h); if (inputFormat_) NADELETEBASIC(inputFormat_, h); if (outputFormat_) NADELETEBASIC(outputFormat_, h); hive_column_desc* ptr ; while (column_) { ptr = column_->next_; NADELETEBASIC(column_, h); column_ = ptr; } hive_skey_desc* ptr1 ; while (skey_) { ptr1 = skey_->next_; NADELETEBASIC(skey_, h); skey_ = ptr1; } hive_bkey_desc* ptr2 ; while (bkey_) { ptr2 = bkey_->next_; NADELETEBASIC(bkey_, h); bkey_ = ptr2; } } hive_pkey_desc::~hive_pkey_desc() { CollHeap *h = CmpCommon::contextHeap(); if (name_) NADELETEBASIC(name_, h); if (type_) NADELETEBASIC(type_, h); } hive_skey_desc::~hive_skey_desc() { CollHeap *h = CmpCommon::contextHeap(); if (name_) NADELETEBASIC(name_, h); } hive_bkey_desc::~hive_bkey_desc() { CollHeap *h = CmpCommon::contextHeap(); if (name_) NADELETEBASIC(name_, h); } hive_column_desc::~hive_column_desc() { CollHeap *h = CmpCommon::contextHeap(); if (name_) NADELETEBASIC(name_, h); if (type_) NADELETEBASIC(type_, h); }
#include "ExecutableLauncherUnix.h" #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <cstdlib> using namespace clt::filesystem::operations; void ExecutableLauncherUnix::execute(const entities::Path & path) { pid_t cpid; cpid = fork(); switch (cpid) { case -1: perror("fork"); break; case 0: execl(path.getValue().c_str(), ""); /* this is the child */ _exit(EXIT_FAILURE); break; default: waitpid(cpid, NULL, 0); } } Add first parameter when launching executable for unix #include "ExecutableLauncherUnix.h" #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <cstdlib> using namespace clt::filesystem::operations; void ExecutableLauncherUnix::execute(const entities::Path & path) { pid_t cpid; cpid = fork(); switch (cpid) { case -1: perror("fork"); break; case 0: execl(path.getValue().c_str(), path.getValue().c_str(), NULL, NULL); /* this is the child */ _exit(EXIT_FAILURE); break; default: waitpid(cpid, NULL, 0); } }
// @(#)root/thread:$Id$ // Author: Fons Rademakers 02/07/97 (Revised: G Ganis, Nov 2015) /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TSemaphore // // // // This class implements a counting semaphore. Use a semaphore // // to synchronize threads. // // // ////////////////////////////////////////////////////////////////////////// #include "TSemaphore.h" //////////////////////////////////////////////////////////////////////////////// /// Create counting semaphore. TSemaphore::TSemaphore(Int_t initial) : fValue(initial), fWakeups(0) { } //////////////////////////////////////////////////////////////////////////////// /// If the semaphore value is > 0 then decrement it and carry on, else block, /// waiting on the condition until it is signaled. /// Returns always 0, for backward compatibility with the first implementation. Int_t TSemaphore::Wait() { std::unique_lock<std::mutex> lk(fMutex); fValue--; if (fValue < 0) { do { fCond.wait(lk); } while (fWakeups < 1); // We have been waken-up: decrease the related counter fWakeups--; } return 0; } //////////////////////////////////////////////////////////////////////////////// /// If the semaphore value is > 0 then decrement it and carry on, else block. /// If millisec > 0 then a relative timeout of millisec milliseconds is applied. /// For backward compatibility with the first implementation, millisec == 0 means /// no timeout. /// Returns 1 if timed-out, 0 otherwise. Int_t TSemaphore::Wait(Int_t millisec) { // For backward compatibility with the first implementation if (millisec <= 0) return Wait(); Int_t rc= 0; std::unique_lock<std::mutex> lk(fMutex); fValue--; if (fValue < 0) { std::cv_status cvs; do { cvs = fCond.wait_for(lk,std::chrono::milliseconds(millisec)); } while (fWakeups < 1 && cvs != std::cv_status::timeout); if (cvs == std::cv_status::timeout) { // Give back the token ... fValue++; rc = 1; } else { // We have been waken-up: decrease the related counter fWakeups--; } } return rc; } //////////////////////////////////////////////////////////////////////////////// /// If the semaphore value is > 0 then decrement it and return 0. If it's /// already 0 then return 1. This call never blocks. Int_t TSemaphore::TryWait() { std::unique_lock<std::mutex> lk(fMutex); if (fValue > 0) { fValue--; } else { return 1; } return 0; } //////////////////////////////////////////////////////////////////////////////// /// Increment the value of the semaphore. If any threads are blocked in Wait(), /// wakeup one of them. /// Returns always 0, for backward compatibility with the first implementation. Int_t TSemaphore::Post() { std::unique_lock<std::mutex> lk(fMutex); fValue++; if (fValue <= 0) { // There were threads waiting: wake up one fWakeups++; fCond.notify_one(); } return 0; } Initialize variable, fixes builds on 10.9 SDK or gcc6. Patch by Roman Zulak! // @(#)root/thread:$Id$ // Author: Fons Rademakers 02/07/97 (Revised: G Ganis, Nov 2015) /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TSemaphore // // // // This class implements a counting semaphore. Use a semaphore // // to synchronize threads. // // // ////////////////////////////////////////////////////////////////////////// #include "TSemaphore.h" //////////////////////////////////////////////////////////////////////////////// /// Create counting semaphore. TSemaphore::TSemaphore(Int_t initial) : fValue(initial), fWakeups(0) { } //////////////////////////////////////////////////////////////////////////////// /// If the semaphore value is > 0 then decrement it and carry on, else block, /// waiting on the condition until it is signaled. /// Returns always 0, for backward compatibility with the first implementation. Int_t TSemaphore::Wait() { std::unique_lock<std::mutex> lk(fMutex); fValue--; if (fValue < 0) { do { fCond.wait(lk); } while (fWakeups < 1); // We have been waken-up: decrease the related counter fWakeups--; } return 0; } //////////////////////////////////////////////////////////////////////////////// /// If the semaphore value is > 0 then decrement it and carry on, else block. /// If millisec > 0 then a relative timeout of millisec milliseconds is applied. /// For backward compatibility with the first implementation, millisec == 0 means /// no timeout. /// Returns 1 if timed-out, 0 otherwise. Int_t TSemaphore::Wait(Int_t millisec) { // For backward compatibility with the first implementation if (millisec <= 0) return Wait(); Int_t rc= 0; std::unique_lock<std::mutex> lk(fMutex); fValue--; if (fValue < 0) { std::cv_status cvs = std::cv_status::timeout; do { cvs = fCond.wait_for(lk,std::chrono::milliseconds(millisec)); } while (fWakeups < 1 && cvs != std::cv_status::timeout); if (cvs == std::cv_status::timeout) { // Give back the token ... fValue++; rc = 1; } else { // We have been waken-up: decrease the related counter fWakeups--; } } return rc; } //////////////////////////////////////////////////////////////////////////////// /// If the semaphore value is > 0 then decrement it and return 0. If it's /// already 0 then return 1. This call never blocks. Int_t TSemaphore::TryWait() { std::unique_lock<std::mutex> lk(fMutex); if (fValue > 0) { fValue--; } else { return 1; } return 0; } //////////////////////////////////////////////////////////////////////////////// /// Increment the value of the semaphore. If any threads are blocked in Wait(), /// wakeup one of them. /// Returns always 0, for backward compatibility with the first implementation. Int_t TSemaphore::Post() { std::unique_lock<std::mutex> lk(fMutex); fValue++; if (fValue <= 0) { // There were threads waiting: wake up one fWakeups++; fCond.notify_one(); } return 0; }
// // reference.c // WhateverGreen // Explanation of how RadeonFramebuffer connectors are created // // Copyright © 2017 vit9696. All rights reserved. // // Reverse-engineered from AMDSupport.kext // Copyright © 2017 Apple Inc. All rights reserved. // /** * Connectors from AMDSupport since 10.12 */ struct ModernConnector { uint32_t type; uint32_t flags; uint16_t features; uint16_t priority; uint32_t reserved1; uint8_t transmitter; uint8_t encoder; uint8_t hotplug; uint8_t sense; uint32_t reserved2; }; enum ConnectorType { ConnectorLVDS = 0x2, ConnectorDigitalDVI = 0x4, ConnectorSVID = 0x8, ConnectorVGA = 0x10, ConnectorDP = 0x400, ConnectorHDMI = 0x800, ConnectorAnalogDVI = 0x2000 }; /** * Internal atom connector struct since 10.13 */ struct AtomConnectorInfo { uint16_t *atomObject; uint16_t usConnObjectId; uint16_t usGraphicObjIds; uint8_t *hpdRecord; uint8_t *i2cRecord; }; // Definitions taken from asic_reg/ObjectID.h enum { /* External Third Party Encoders */ ENCODER_OBJECT_ID_SI170B = 0x08, ENCODER_OBJECT_ID_CH7303 = 0x09, ENCODER_OBJECT_ID_CH7301 = 0x0A, ENCODER_OBJECT_ID_INTERNAL_DVO1 = 0x0B, /* This belongs to Radeon Class Display Hardware */ ENCODER_OBJECT_ID_EXTERNAL_SDVOA = 0x0C, ENCODER_OBJECT_ID_EXTERNAL_SDVOB = 0x0D, ENCODER_OBJECT_ID_TITFP513 = 0x0E, ENCODER_OBJECT_ID_INTERNAL_LVTM1 = 0x0F, /* not used for Radeon */ ENCODER_OBJECT_ID_VT1623 = 0x10, ENCODER_OBJECT_ID_HDMI_SI1930 = 0x11, ENCODER_OBJECT_ID_HDMI_INTERNAL = 0x12, /* Kaleidoscope (KLDSCP) Class Display Hardware (internal) */ ENCODER_OBJECT_ID_INTERNAL_KLDSCP_TMDS1 = 0x13, ENCODER_OBJECT_ID_INTERNAL_KLDSCP_DVO1 = 0x14, ENCODER_OBJECT_ID_INTERNAL_KLDSCP_DAC1 = 0x15, ENCODER_OBJECT_ID_INTERNAL_KLDSCP_DAC2 = 0x16, /* Shared with CV/TV and CRT */ ENCODER_OBJECT_ID_SI178 = 0X17, /* External TMDS (dual link, no HDCP.) */ ENCODER_OBJECT_ID_MVPU_FPGA = 0x18, /* MVPU FPGA chip */ ENCODER_OBJECT_ID_INTERNAL_DDI = 0x19, ENCODER_OBJECT_ID_VT1625 = 0x1A, ENCODER_OBJECT_ID_HDMI_SI1932 = 0x1B, ENCODER_OBJECT_ID_DP_AN9801 = 0x1C, ENCODER_OBJECT_ID_DP_DP501 = 0x1D, ENCODER_OBJECT_ID_INTERNAL_UNIPHY = 0x1E, ENCODER_OBJECT_ID_INTERNAL_KLDSCP_LVTMA = 0x1F, ENCODER_OBJECT_ID_INTERNAL_UNIPHY1 = 0x20, ENCODER_OBJECT_ID_INTERNAL_UNIPHY2 = 0x21, ENCODER_OBJECT_ID_ALMOND = 0x22, ENCODER_OBJECT_ID_NUTMEG = 0x22, ENCODER_OBJECT_ID_TRAVIS = 0x23, ENCODER_OBJECT_ID_INTERNAL_VCE = 0x24, ENCODER_OBJECT_ID_INTERNAL_UNIPHY3 = 0x25, ENCODER_OBJECT_ID_INTERNAL_AMCLK = 0x27 }; enum { CONNECTOR_OBJECT_ID_NONE = 0x00, CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_I = 0x01, CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_I = 0x02, CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_D = 0x03, CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_D = 0x04, CONNECTOR_OBJECT_ID_VGA = 0x05, CONNECTOR_OBJECT_ID_COMPOSITE = 0x06, CONNECTOR_OBJECT_ID_SVIDEO = 0x07, CONNECTOR_OBJECT_ID_YPbPr = 0x08, CONNECTOR_OBJECT_ID_D_CONNECTOR = 0x09, CONNECTOR_OBJECT_ID_9PIN_DIN = 0x0A, /* Supports both CV & TV */ CONNECTOR_OBJECT_ID_SCART = 0x0B, CONNECTOR_OBJECT_ID_HDMI_TYPE_A = 0x0C, CONNECTOR_OBJECT_ID_HDMI_TYPE_B = 0x0D, CONNECTOR_OBJECT_ID_LVDS = 0x0E, CONNECTOR_OBJECT_ID_7PIN_DIN = 0x0F, CONNECTOR_OBJECT_ID_PCIE_CONNECTOR = 0x10, CONNECTOR_OBJECT_ID_CROSSFIRE = 0x11, CONNECTOR_OBJECT_ID_HARDCODE_DVI = 0x12, CONNECTOR_OBJECT_ID_DISPLAYPORT = 0x13, CONNECTOR_OBJECT_ID_eDP = 0x14, CONNECTOR_OBJECT_ID_MXM = 0x15, CONNECTOR_OBJECT_ID_LVDS_eDP = 0x16 }; // Initially applecon data is nulled. IOReturn AtiBiosParser2::translateAtomConnectorInfo(AtiBiosParser2 *parser, AtomConnectorInfo *atomcon, ModernConnector *applecon) { if (((atomcon->usConnObjectId & OBJECT_TYPE_MASK) >> OBJECT_TYPE_SHIFT) != GRAPH_OBJECT_TYPE_CONNECTOR) return kIOReturnNotFound; uint8_t *i2cRecord = atomcon->i2cRecord; if (i2cRecord) { applecon->sense = (i2cRecord[2] & 0xF) + 1; } else { applecon->sense = 0; kprintf("ATOM: %s: ASSERT(NULL != i2cRecord)\n", "uint8_t AtiBiosParser2::getAuxDdcLine(atom_i2c_record *)"); } uint8_t *hpdRecord = (uint8_t *)atomcon->hpdRecord; if (hpdRecord) { applecon->hotplug = hpdRecord[2]; } else { applecon->hotplug = 0; kprintf("ATOM: %s: ASSERT(NULL != hpdRecord)\n", "uint8_t AtiBiosParser2::getHotPlugPin(atom_hpd_int_record *)"); } AtiBiosParser2::getOutputInformation(parser, atomcon, applecon); AtiBiosParser2::getConnectorFeatures(parser, atomcon, applecon); if (applecon->flags) { if ((applecon->flags & 0x704) && applecon->hotplug) applecon->features |= 0x100; return kIOReturnSuccess; } else { kprintf("ATOM: %s: ASSERT(0 != drvInfo.connections)\n", "IOReturn AtiBiosParser2::translateAtomConnectorInfo(AtiObjectInfoTableInterface_V2::AtomConnectorInfo &, ConnectorInfo &)"); } return kIOReturnNotFound; } IOReturn AtiBiosParser2::getOutputInformation(AtiBiosParser2 *parser, AtomConnectorInfo *atomcon, ModernConnector *applecon) { if (!atomcon->usGraphicObjIds) { kprintf("ATOM: %s: ASSERT(0 != objId.u16All)\n", "IOReturn AtiBiosParser2::getOutputInformation(AtiObjectInfoTableInterface_V2::AtomConnectorInfo &, ConnectorInfo &)"); return kIOReturnBadArgument; } uint8_t encoder = (uint8_t)atomcon->usGraphicObjIds; bool one = ((atomcon->usGraphicObjIds & ENUM_ID_MASK) >> ENUM_ID_SHIFT) == 1; switch (encoder) { case ENCODER_OBJECT_ID_NUTMEG: applecon->flags |= 0x10; return kIOReturnSuccess; case ENCODER_OBJECT_ID_INTERNAL_UNIPHY: if (one) { applecon->transmitter |= 0x10; } else { applecon->transmitter |= 0x20; applecon->encoder |= 0x1; } return kIOReturnSuccess; case ENCODER_OBJECT_ID_INTERNAL_UNIPHY1: if (one) { applecon->transmitter |= 0x11; applecon->encoder |= 0x2; } else { applecon->transmitter |= 0x21; applecon->encoder |= 0x3; } return kIOReturnSuccess; case ENCODER_OBJECT_ID_INTERNAL_UNIPHY2: if (one) { applecon->transmitter |= 0x12; applecon->encoder |= 0x4; } else { applecon->transmitter |= 0x22; applecon->encoder |= 0x5; } return kIOReturnSuccess; case ENCODER_OBJECT_ID_INTERNAL_UNIPHY3: if (one) { applecon->transmitter |= 0x13; applecon->encoder |= 0x6; } else { applecon->transmitter |= 0x23; applecon->encoder |= 0x7; } return kIOReturnSuccess; } return kIOReturnInvalid; } IOReturn AtiBiosParser2::getConnectorFeatures(AtiBiosParser2 *parser, AtomConnectorInfo *atomcon, ModernConnector *applecon) { if (!atomcon->usConnObjectId) { kprintf("ATOM: %s: ASSERT(0 != objId.u16All)\n", "IOReturn AtiBiosParser2::getConnectorFeatures(AtiObjectInfoTableInterface_V2::AtomConnectorInfo &, ConnectorInfo &)"); result = kIOReturnBadArgument; } uint8_t connector = (uint8_t)atomcon->usGraphicObjIds; switch (connector) { case CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_I: case CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_D: applecon->type = ConnectorDigitalDVI; applecon->flags |= 4; // unlock 2k res, causes crashes on R9 290X // undone by -raddvi applecon->transmitter &= 0xCF; return kIOReturnSuccess; case CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_I: case CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_D: applecon->type = ConnectorDigitalDVI; applecon->flags |= 4; return kIOReturnSuccess; case CONNECTOR_OBJECT_ID_HDMI_TYPE_A: case CONNECTOR_OBJECT_ID_HDMI_TYPE_B: applecon->type = ConnectorHDMI; applecon->flags |= 0x204; return kIOReturnSuccess; case CONNECTOR_OBJECT_ID_VGA: applecon->type = ConnectorVGA; applecon->flags |= 0x10; return kIOReturnSuccess; case CONNECTOR_OBJECT_ID_LVDS: applecon->type = ConnectorLVDS; applecon->flags |= 0x40; applecon->features |= 0x9; // unlock 2k res applecon->transmitter &= 0xCF; return kIOReturnSuccess; case CONNECTOR_OBJECT_ID_DISPLAYPORT: applecon->type = ConnectorDP; applecon->flags |= 0x304; return kIOReturnSuccess; case CONNECTOR_OBJECT_ID_eDP: applecon->type = ConnectorLVDS; applecon->flags |= 0x100; applecon->features |= 0x109; return kIOReturnSuccess; } return kIOReturnInvalid; } Fixed a small typo in reference code // // reference.c // WhateverGreen // Explanation of how RadeonFramebuffer connectors are created // // Copyright © 2017 vit9696. All rights reserved. // // Reverse-engineered from AMDSupport.kext // Copyright © 2017 Apple Inc. All rights reserved. // /** * Connectors from AMDSupport since 10.12 */ struct ModernConnector { uint32_t type; uint32_t flags; uint16_t features; uint16_t priority; uint32_t reserved1; uint8_t transmitter; uint8_t encoder; uint8_t hotplug; uint8_t sense; uint32_t reserved2; }; enum ConnectorType { ConnectorLVDS = 0x2, ConnectorDigitalDVI = 0x4, ConnectorSVID = 0x8, ConnectorVGA = 0x10, ConnectorDP = 0x400, ConnectorHDMI = 0x800, ConnectorAnalogDVI = 0x2000 }; /** * Internal atom connector struct since 10.13 */ struct AtomConnectorInfo { uint16_t *atomObject; uint16_t usConnObjectId; uint16_t usGraphicObjIds; uint8_t *hpdRecord; uint8_t *i2cRecord; }; // Definitions taken from asic_reg/ObjectID.h enum { /* External Third Party Encoders */ ENCODER_OBJECT_ID_SI170B = 0x08, ENCODER_OBJECT_ID_CH7303 = 0x09, ENCODER_OBJECT_ID_CH7301 = 0x0A, ENCODER_OBJECT_ID_INTERNAL_DVO1 = 0x0B, /* This belongs to Radeon Class Display Hardware */ ENCODER_OBJECT_ID_EXTERNAL_SDVOA = 0x0C, ENCODER_OBJECT_ID_EXTERNAL_SDVOB = 0x0D, ENCODER_OBJECT_ID_TITFP513 = 0x0E, ENCODER_OBJECT_ID_INTERNAL_LVTM1 = 0x0F, /* not used for Radeon */ ENCODER_OBJECT_ID_VT1623 = 0x10, ENCODER_OBJECT_ID_HDMI_SI1930 = 0x11, ENCODER_OBJECT_ID_HDMI_INTERNAL = 0x12, /* Kaleidoscope (KLDSCP) Class Display Hardware (internal) */ ENCODER_OBJECT_ID_INTERNAL_KLDSCP_TMDS1 = 0x13, ENCODER_OBJECT_ID_INTERNAL_KLDSCP_DVO1 = 0x14, ENCODER_OBJECT_ID_INTERNAL_KLDSCP_DAC1 = 0x15, ENCODER_OBJECT_ID_INTERNAL_KLDSCP_DAC2 = 0x16, /* Shared with CV/TV and CRT */ ENCODER_OBJECT_ID_SI178 = 0X17, /* External TMDS (dual link, no HDCP.) */ ENCODER_OBJECT_ID_MVPU_FPGA = 0x18, /* MVPU FPGA chip */ ENCODER_OBJECT_ID_INTERNAL_DDI = 0x19, ENCODER_OBJECT_ID_VT1625 = 0x1A, ENCODER_OBJECT_ID_HDMI_SI1932 = 0x1B, ENCODER_OBJECT_ID_DP_AN9801 = 0x1C, ENCODER_OBJECT_ID_DP_DP501 = 0x1D, ENCODER_OBJECT_ID_INTERNAL_UNIPHY = 0x1E, ENCODER_OBJECT_ID_INTERNAL_KLDSCP_LVTMA = 0x1F, ENCODER_OBJECT_ID_INTERNAL_UNIPHY1 = 0x20, ENCODER_OBJECT_ID_INTERNAL_UNIPHY2 = 0x21, ENCODER_OBJECT_ID_ALMOND = 0x22, ENCODER_OBJECT_ID_NUTMEG = 0x22, ENCODER_OBJECT_ID_TRAVIS = 0x23, ENCODER_OBJECT_ID_INTERNAL_VCE = 0x24, ENCODER_OBJECT_ID_INTERNAL_UNIPHY3 = 0x25, ENCODER_OBJECT_ID_INTERNAL_AMCLK = 0x27 }; enum { CONNECTOR_OBJECT_ID_NONE = 0x00, CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_I = 0x01, CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_I = 0x02, CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_D = 0x03, CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_D = 0x04, CONNECTOR_OBJECT_ID_VGA = 0x05, CONNECTOR_OBJECT_ID_COMPOSITE = 0x06, CONNECTOR_OBJECT_ID_SVIDEO = 0x07, CONNECTOR_OBJECT_ID_YPbPr = 0x08, CONNECTOR_OBJECT_ID_D_CONNECTOR = 0x09, CONNECTOR_OBJECT_ID_9PIN_DIN = 0x0A, /* Supports both CV & TV */ CONNECTOR_OBJECT_ID_SCART = 0x0B, CONNECTOR_OBJECT_ID_HDMI_TYPE_A = 0x0C, CONNECTOR_OBJECT_ID_HDMI_TYPE_B = 0x0D, CONNECTOR_OBJECT_ID_LVDS = 0x0E, CONNECTOR_OBJECT_ID_7PIN_DIN = 0x0F, CONNECTOR_OBJECT_ID_PCIE_CONNECTOR = 0x10, CONNECTOR_OBJECT_ID_CROSSFIRE = 0x11, CONNECTOR_OBJECT_ID_HARDCODE_DVI = 0x12, CONNECTOR_OBJECT_ID_DISPLAYPORT = 0x13, CONNECTOR_OBJECT_ID_eDP = 0x14, CONNECTOR_OBJECT_ID_MXM = 0x15, CONNECTOR_OBJECT_ID_LVDS_eDP = 0x16 }; // Initially applecon data is nulled. IOReturn AtiBiosParser2::translateAtomConnectorInfo(AtiBiosParser2 *parser, AtomConnectorInfo *atomcon, ModernConnector *applecon) { if (((atomcon->usConnObjectId & OBJECT_TYPE_MASK) >> OBJECT_TYPE_SHIFT) != GRAPH_OBJECT_TYPE_CONNECTOR) return kIOReturnNotFound; uint8_t *i2cRecord = atomcon->i2cRecord; if (i2cRecord) { applecon->sense = (i2cRecord[2] & 0xF) + 1; } else { applecon->sense = 0; kprintf("ATOM: %s: ASSERT(NULL != i2cRecord)\n", "uint8_t AtiBiosParser2::getAuxDdcLine(atom_i2c_record *)"); } uint8_t *hpdRecord = (uint8_t *)atomcon->hpdRecord; if (hpdRecord) { applecon->hotplug = hpdRecord[2]; } else { applecon->hotplug = 0; kprintf("ATOM: %s: ASSERT(NULL != hpdRecord)\n", "uint8_t AtiBiosParser2::getHotPlugPin(atom_hpd_int_record *)"); } AtiBiosParser2::getOutputInformation(parser, atomcon, applecon); AtiBiosParser2::getConnectorFeatures(parser, atomcon, applecon); if (applecon->flags) { if ((applecon->flags & 0x704) && applecon->hotplug) applecon->features |= 0x100; return kIOReturnSuccess; } else { kprintf("ATOM: %s: ASSERT(0 != drvInfo.connections)\n", "IOReturn AtiBiosParser2::translateAtomConnectorInfo(AtiObjectInfoTableInterface_V2::AtomConnectorInfo &, ConnectorInfo &)"); } return kIOReturnNotFound; } IOReturn AtiBiosParser2::getOutputInformation(AtiBiosParser2 *parser, AtomConnectorInfo *atomcon, ModernConnector *applecon) { if (!atomcon->usGraphicObjIds) { kprintf("ATOM: %s: ASSERT(0 != objId.u16All)\n", "IOReturn AtiBiosParser2::getOutputInformation(AtiObjectInfoTableInterface_V2::AtomConnectorInfo &, ConnectorInfo &)"); return kIOReturnBadArgument; } uint8_t encoder = (uint8_t)atomcon->usGraphicObjIds; bool one = ((atomcon->usGraphicObjIds & ENUM_ID_MASK) >> ENUM_ID_SHIFT) == 1; switch (encoder) { case ENCODER_OBJECT_ID_NUTMEG: applecon->flags |= 0x10; return kIOReturnSuccess; case ENCODER_OBJECT_ID_INTERNAL_UNIPHY: if (one) { applecon->transmitter |= 0x10; } else { applecon->transmitter |= 0x20; applecon->encoder |= 0x1; } return kIOReturnSuccess; case ENCODER_OBJECT_ID_INTERNAL_UNIPHY1: if (one) { applecon->transmitter |= 0x11; applecon->encoder |= 0x2; } else { applecon->transmitter |= 0x21; applecon->encoder |= 0x3; } return kIOReturnSuccess; case ENCODER_OBJECT_ID_INTERNAL_UNIPHY2: if (one) { applecon->transmitter |= 0x12; applecon->encoder |= 0x4; } else { applecon->transmitter |= 0x22; applecon->encoder |= 0x5; } return kIOReturnSuccess; case ENCODER_OBJECT_ID_INTERNAL_UNIPHY3: if (one) { applecon->transmitter |= 0x13; applecon->encoder |= 0x6; } else { applecon->transmitter |= 0x23; applecon->encoder |= 0x7; } return kIOReturnSuccess; } return kIOReturnInvalid; } IOReturn AtiBiosParser2::getConnectorFeatures(AtiBiosParser2 *parser, AtomConnectorInfo *atomcon, ModernConnector *applecon) { if (!atomcon->usConnObjectId) { kprintf("ATOM: %s: ASSERT(0 != objId.u16All)\n", "IOReturn AtiBiosParser2::getConnectorFeatures(AtiObjectInfoTableInterface_V2::AtomConnectorInfo &, ConnectorInfo &)"); return kIOReturnBadArgument; } uint8_t connector = (uint8_t)atomcon->usGraphicObjIds; switch (connector) { case CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_I: case CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_D: applecon->type = ConnectorDigitalDVI; applecon->flags |= 4; // unlock 2k res, causes crashes on R9 290X // undone by -raddvi applecon->transmitter &= 0xCF; return kIOReturnSuccess; case CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_I: case CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_D: applecon->type = ConnectorDigitalDVI; applecon->flags |= 4; return kIOReturnSuccess; case CONNECTOR_OBJECT_ID_HDMI_TYPE_A: case CONNECTOR_OBJECT_ID_HDMI_TYPE_B: applecon->type = ConnectorHDMI; applecon->flags |= 0x204; return kIOReturnSuccess; case CONNECTOR_OBJECT_ID_VGA: applecon->type = ConnectorVGA; applecon->flags |= 0x10; return kIOReturnSuccess; case CONNECTOR_OBJECT_ID_LVDS: applecon->type = ConnectorLVDS; applecon->flags |= 0x40; applecon->features |= 0x9; // unlock 2k res applecon->transmitter &= 0xCF; return kIOReturnSuccess; case CONNECTOR_OBJECT_ID_DISPLAYPORT: applecon->type = ConnectorDP; applecon->flags |= 0x304; return kIOReturnSuccess; case CONNECTOR_OBJECT_ID_eDP: applecon->type = ConnectorLVDS; applecon->flags |= 0x100; applecon->features |= 0x109; return kIOReturnSuccess; } return kIOReturnInvalid; }
// Generated by the gRPC protobuf plugin. // If you make any local change, they will be lost. // source: helloworld.proto #include "helloworld.grpc_cb.pb.h" #include <google/protobuf/descriptor.h> #include <google/protobuf/stubs/once.h> #include <grpc_cb/impl/client/client_async_call_cqtag.h> // for ClientAsyncCallCqTag #include <grpc_cb/impl/client/client_call_cqtag.h> // for ClientCallCqTag #include <grpc_cb/impl/cqueue_for_pluck.h> // for CQueueForPluck #include <grpc_cb/impl/proto_utils.h> // for Proto::Deserialize() #include <grpc_cb/impl/server/server_reader_cqtag.h> // for ServerReaderCqTag #include <grpc_cb/impl/server/server_reader_writer_cqtag.h> // for ServerReaderWriterCqTag // package helloworld namespace helloworld { namespace { const ::google::protobuf::ServiceDescriptor* service_descriptor_Greeter = nullptr; void AssignDesc_helloworld_2eproto() { // Get the file's descriptor from the pool. const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "helloworld.proto"); GOOGLE_CHECK(file != NULL); service_descriptor_Greeter = file->service(0); } // AssignDesc_helloworld_2eproto() GOOGLE_PROTOBUF_DECLARE_ONCE(grpc_cb_AssignDescriptors_once_); inline void AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit( &grpc_cb_AssignDescriptors_once_, &AssignDesc_helloworld_2eproto); } } // namespace namespace Greeter { // service Greeter static const std::string method_names[] = { "/helloworld.Greeter/SayHello", }; const ::google::protobuf::ServiceDescriptor& GetServiceDescriptor() { AssignDescriptorsOnce(); assert(service_descriptor_Greeter); return *service_descriptor_Greeter; } Stub::Stub(const ::grpc_cb::ChannelSptr& channel, const ::grpc_cb::CompletionQueueForNextSptr& cq4n_sptr) : ::grpc_cb::ServiceStub(channel, cq4n_sptr) {} ::grpc_cb::Status Stub::BlockingSayHello( const ::helloworld::HelloRequest& request, ::helloworld::HelloReply* response) { std::string req_str(request.SerializeAsString()); const std::string& method = method_names[0]; std::string resp_str; ::grpc_cb::Status status = BlockingRequest(method, req_str, resp_str); if (!status.ok() || !response) return status; if (response->ParseFromString(resp_str)) return status; return status.InternalError("Failed to parse response."); } void Stub::AsyncSayHello( const ::helloworld::HelloRequest& request, const SayHelloCallback& cb, const ::grpc_cb::ErrorCallback& ecb) { ::grpc_cb::CallSptr call_sptr(MakeSharedCall(method_names[0])); using CqTag = ::grpc_cb::ClientAsyncCallCqTag<::helloworld::HelloReply>; CqTag* tag = new CqTag(call_sptr); tag->SetOnResponse(cb); tag->SetOnError(ecb); if (tag->Start(request)) return; delete tag; if (ecb) ecb(::grpc_cb::Status::InternalError("Failed to async request.")); } Service::Service() {} Service::~Service() {} const std::string& Service::GetMethodName(size_t method_index) const { assert(method_index < GetMethodCount()); return method_names[method_index]; } void Service::CallMethod( size_t method_index, grpc_byte_buffer* request_buffer, const ::grpc_cb::CallSptr& call_sptr) { assert(method_index < GetMethodCount()); switch (method_index) { case 0: if (!request_buffer) return; SayHello(*request_buffer, SayHello_Replier(call_sptr)); return; } // switch assert(false); (void)request_buffer; (void)call_sptr; } void Service::SayHello( grpc_byte_buffer& request_buffer, const SayHello_Replier& replier) { using Request = ::helloworld::HelloRequest; Request request; ::grpc_cb::Status status = ::grpc_cb::Proto::Deserialize( &request_buffer, &request, 0 /* TODO: max_message_size*/); if (status.ok()) { SayHello(request, replier); return; } SayHello_Replier( replier).ReplyError(status); } void Service::SayHello( const ::helloworld::HelloRequest& request, SayHello_Replier replier) { (void)request; replier.ReplyError(::grpc_cb::Status::UNIMPLEMENTED); } } // namespace Greeter } // namespace helloworld Change to use ServiceStub::AsyncRequest(). // Generated by the gRPC protobuf plugin. // If you make any local change, they will be lost. // source: helloworld.proto #include "helloworld.grpc_cb.pb.h" #include <google/protobuf/descriptor.h> #include <google/protobuf/stubs/once.h> #include <grpc_cb/impl/client/client_async_call_cqtag.h> // for ClientAsyncCallCqTag #include <grpc_cb/impl/client/client_call_cqtag.h> // for ClientCallCqTag #include <grpc_cb/impl/cqueue_for_pluck.h> // for CQueueForPluck #include <grpc_cb/impl/proto_utils.h> // for Proto::Deserialize() #include <grpc_cb/impl/server/server_reader_cqtag.h> // for ServerReaderCqTag #include <grpc_cb/impl/server/server_reader_writer_cqtag.h> // for ServerReaderWriterCqTag // package helloworld namespace helloworld { namespace { const ::google::protobuf::ServiceDescriptor* service_descriptor_Greeter = nullptr; void AssignDesc_helloworld_2eproto() { // Get the file's descriptor from the pool. const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "helloworld.proto"); GOOGLE_CHECK(file != NULL); service_descriptor_Greeter = file->service(0); } // AssignDesc_helloworld_2eproto() GOOGLE_PROTOBUF_DECLARE_ONCE(grpc_cb_AssignDescriptors_once_); inline void AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit( &grpc_cb_AssignDescriptors_once_, &AssignDesc_helloworld_2eproto); } } // namespace namespace Greeter { // service Greeter static const std::string method_names[] = { "/helloworld.Greeter/SayHello", }; const ::google::protobuf::ServiceDescriptor& GetServiceDescriptor() { AssignDescriptorsOnce(); assert(service_descriptor_Greeter); return *service_descriptor_Greeter; } Stub::Stub(const ::grpc_cb::ChannelSptr& channel, const ::grpc_cb::CompletionQueueForNextSptr& cq4n_sptr) : ::grpc_cb::ServiceStub(channel, cq4n_sptr) {} ::grpc_cb::Status Stub::BlockingSayHello( const ::helloworld::HelloRequest& request, ::helloworld::HelloReply* response) { std::string resp_str; ::grpc_cb::Status status = BlockingRequest(method_names[0], request.SerializeAsString(), resp_str); if (!status.ok() || !response) return status; if (response->ParseFromString(resp_str)) return status; return status.InternalError("Failed to parse response."); } void Stub::AsyncSayHello( const ::helloworld::HelloRequest& request, const SayHelloCallback& cb, const ::grpc_cb::ErrorCallback& ecb) { AsyncRequest(method_names[0], request.SerializeAsString(), ((!cb) ? OnResponse() : [cb, ecb](const std::string& resp_str) { ::helloworld::HelloReply response; if (response.ParseFromString(resp_str)) { cb(response); return; } if (ecb) ecb(::grpc_cb::Status::InternalError("Failed to parse response.")); }), ecb); //::grpc_cb::CallSptr call_sptr(MakeSharedCall(method_names[0])); //using CqTag = ::grpc_cb::ClientAsyncCallCqTag<::helloworld::HelloReply>; //CqTag* tag = new CqTag(call_sptr); //tag->SetOnResponse(cb); //tag->SetOnError(ecb); //if (tag->Start(request.SerializeAsString())) // return; //delete tag; //if (ecb) // ecb(::grpc_cb::Status::InternalError("Failed to async request.")); } Service::Service() {} Service::~Service() {} const std::string& Service::GetMethodName(size_t method_index) const { assert(method_index < GetMethodCount()); return method_names[method_index]; } void Service::CallMethod( size_t method_index, grpc_byte_buffer* request_buffer, const ::grpc_cb::CallSptr& call_sptr) { assert(method_index < GetMethodCount()); switch (method_index) { case 0: if (!request_buffer) return; SayHello(*request_buffer, SayHello_Replier(call_sptr)); return; } // switch assert(false); (void)request_buffer; (void)call_sptr; } void Service::SayHello( grpc_byte_buffer& request_buffer, const SayHello_Replier& replier) { using Request = ::helloworld::HelloRequest; Request request; ::grpc_cb::Status status = ::grpc_cb::Proto::Deserialize( &request_buffer, &request, 0 /* TODO: max_message_size*/); if (status.ok()) { SayHello(request, replier); return; } SayHello_Replier( replier).ReplyError(status); } void Service::SayHello( const ::helloworld::HelloRequest& request, SayHello_Replier replier) { (void)request; replier.ReplyError(::grpc_cb::Status::UNIMPLEMENTED); } } // namespace Greeter } // namespace helloworld
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "configuration.h" // appleseed.renderer headers. #include "renderer/kernel/lighting/backwardlightsampler.h" #include "renderer/kernel/lighting/pt/ptlightingengine.h" #include "renderer/kernel/lighting/sppm/sppmlightingengine.h" #include "renderer/kernel/rendering/final/adaptivepixelrenderer.h" #include "renderer/kernel/rendering/final/uniformpixelrenderer.h" #include "renderer/kernel/rendering/generic/genericframerenderer.h" #include "renderer/kernel/rendering/progressive/progressiveframerenderer.h" #include "renderer/kernel/texturing/texturestore.h" #include "renderer/utility/paramarray.h" // appleseed.foundation headers. #include "foundation/utility/containers/dictionary.h" // Standard headers. #include <cassert> #include <cstring> using namespace foundation; using namespace std; namespace renderer { // // Configuration class implementation. // namespace { const UniqueID g_class_uid = new_guid(); } UniqueID Configuration::get_class_uid() { return g_class_uid; } Configuration::Configuration(const char* name) : Entity(g_class_uid) , m_base(nullptr) { set_name(name); } void Configuration::release() { delete this; } void Configuration::set_base(const Configuration* base) { m_base = base; } const Configuration* Configuration::get_base() const { return m_base; } ParamArray Configuration::get_inherited_parameters() const { if (m_base) { ParamArray params = m_base->m_params; params.merge(m_params); return params; } else { return m_params; } } Dictionary Configuration::get_metadata() { Dictionary metadata; metadata.insert( "spectrum_mode", Dictionary() .insert("type", "enum") .insert("values", "rgb|spectral") .insert("default", "rgb") .insert("label", "Color Pipeline") .insert("help", "Color pipeline used throughout the renderer") .insert( "options", Dictionary() .insert( "rgb", Dictionary() .insert("label", "RGB") .insert("help", "RGB pipeline")) .insert( "spectral", Dictionary() .insert("label", "Spectral") .insert("help", "Spectral pipeline using 31 equidistant components in the 400-700 nm range")))); metadata.insert( "sampling_mode", Dictionary() .insert("type", "enum") .insert("values", "rng|qmc") .insert("default", "qmc") .insert("label", "Sampler") .insert("help", "Sampling algorithm used in Monte Carlo integration") .insert( "options", Dictionary() .insert( "rng", Dictionary() .insert("label", "RNG") .insert("help", "Random sampler")) .insert( "qmc", Dictionary() .insert("label", "QMC") .insert("help", "Quasi Monte Carlo sampler")))); metadata.insert( "lighting_engine", Dictionary() .insert("type", "enum") .insert("values", "pt|sppm") .insert("default", "pt") .insert("label", "Lighting Engine") .insert("help", "Lighting engine used when rendering") .insert( "options", Dictionary() .insert( "pt", Dictionary() .insert("label", "Unidirectional Path Tracer") .insert("help", "Unidirectional path tracing")) .insert( "sppm", Dictionary() .insert("label", "Progressive Photon Mapping") .insert("help", "Stochastic progressive photon mapping")))); metadata.insert( "rendering_threads", Dictionary() .insert("type", "int") .insert("label", "Render Threads") .insert("help", "Number of threads to use for rendering")); metadata.dictionaries().insert( "light_sampler", BackwardLightSampler::get_params_metadata()); metadata.dictionaries().insert( "texture_store", TextureStore::get_params_metadata()); metadata.dictionaries().insert( "uniform_pixel_renderer", UniformPixelRendererFactory::get_params_metadata()); metadata.dictionaries().insert( "adaptive_pixel_renderer", AdaptivePixelRendererFactory::get_params_metadata()); metadata.dictionaries().insert( "generic_frame_renderer", GenericFrameRendererFactory::get_params_metadata()); metadata.dictionaries().insert( "progressive_frame_renderer", ProgressiveFrameRendererFactory::get_params_metadata()); metadata.dictionaries().insert("pt", PTLightingEngineFactory::get_params_metadata()); metadata.dictionaries().insert("sppm", SPPMLightingEngineFactory::get_params_metadata()); return metadata; } // // ConfigurationFactory class implementation. // auto_release_ptr<Configuration> ConfigurationFactory::create(const char* name) { assert(name); return auto_release_ptr<Configuration>(new Configuration(name)); } auto_release_ptr<Configuration> ConfigurationFactory::create( const char* name, const ParamArray& params) { assert(name); auto_release_ptr<Configuration> configuration(new Configuration(name)); configuration->get_parameters().merge(params); return configuration; } // // BaseConfigurationFactory class implementation. // auto_release_ptr<Configuration> BaseConfigurationFactory::create_base_final() { auto_release_ptr<Configuration> configuration(new Configuration("base_final")); ParamArray& parameters = configuration->get_parameters(); parameters.insert("spectrum_mode", "rgb"); parameters.insert("sampling_mode", "qmc"); parameters.insert("frame_renderer", "generic"); parameters.insert("tile_renderer", "generic"); parameters.insert("pixel_renderer", "uniform"); parameters.dictionaries().insert( "uniform_pixel_renderer", ParamArray() .insert("samples", "64")); parameters.insert("sample_renderer", "generic"); parameters.insert("lighting_engine", "pt"); return configuration; } auto_release_ptr<Configuration> BaseConfigurationFactory::create_base_interactive() { auto_release_ptr<Configuration> configuration(new Configuration("base_interactive")); ParamArray& parameters = configuration->get_parameters(); parameters.insert("spectrum_mode", "rgb"); parameters.insert("sampling_mode", "qmc"); parameters.insert("frame_renderer", "progressive"); parameters.insert("sample_generator", "generic"); parameters.insert("sample_renderer", "generic"); parameters.insert("lighting_engine", "pt"); return configuration; } bool BaseConfigurationFactory::is_base_final_configuration(const char* name) { assert(name); return strcmp(name, "base_final") == 0; } bool BaseConfigurationFactory::is_base_interactive_configuration(const char* name) { assert(name); return strcmp(name, "base_interactive") == 0; } bool BaseConfigurationFactory::is_base_configuration(const char* name) { return is_base_final_configuration(name) || is_base_interactive_configuration(name); } } // namespace renderer Tweak input metadata // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "configuration.h" // appleseed.renderer headers. #include "renderer/kernel/lighting/backwardlightsampler.h" #include "renderer/kernel/lighting/pt/ptlightingengine.h" #include "renderer/kernel/lighting/sppm/sppmlightingengine.h" #include "renderer/kernel/rendering/final/adaptivepixelrenderer.h" #include "renderer/kernel/rendering/final/uniformpixelrenderer.h" #include "renderer/kernel/rendering/generic/genericframerenderer.h" #include "renderer/kernel/rendering/progressive/progressiveframerenderer.h" #include "renderer/kernel/texturing/texturestore.h" #include "renderer/utility/paramarray.h" // appleseed.foundation headers. #include "foundation/utility/containers/dictionary.h" // Standard headers. #include <cassert> #include <cstring> using namespace foundation; using namespace std; namespace renderer { // // Configuration class implementation. // namespace { const UniqueID g_class_uid = new_guid(); } UniqueID Configuration::get_class_uid() { return g_class_uid; } Configuration::Configuration(const char* name) : Entity(g_class_uid) , m_base(nullptr) { set_name(name); } void Configuration::release() { delete this; } void Configuration::set_base(const Configuration* base) { m_base = base; } const Configuration* Configuration::get_base() const { return m_base; } ParamArray Configuration::get_inherited_parameters() const { if (m_base) { ParamArray params = m_base->m_params; params.merge(m_params); return params; } else { return m_params; } } Dictionary Configuration::get_metadata() { Dictionary metadata; metadata.insert( "spectrum_mode", Dictionary() .insert("type", "enum") .insert("values", "rgb|spectral") .insert("default", "rgb") .insert("label", "Color Pipeline") .insert("help", "Color pipeline used throughout the renderer") .insert( "options", Dictionary() .insert( "rgb", Dictionary() .insert("label", "RGB") .insert("help", "RGB pipeline")) .insert( "spectral", Dictionary() .insert("label", "Spectral") .insert("help", "Spectral pipeline using 31 equidistant components in the 400-700 nm range")))); metadata.insert( "sampling_mode", Dictionary() .insert("type", "enum") .insert("values", "rng|qmc") .insert("default", "qmc") .insert("label", "Sampler") .insert("help", "Sampling algorithm used in Monte Carlo integration") .insert( "options", Dictionary() .insert( "rng", Dictionary() .insert("label", "RNG") .insert("help", "Random sampler")) .insert( "qmc", Dictionary() .insert("label", "QMC") .insert("help", "Quasi Monte Carlo sampler")))); metadata.insert( "lighting_engine", Dictionary() .insert("type", "enum") .insert("values", "pt|sppm") .insert("default", "pt") .insert("label", "Lighting Engine") .insert("help", "Light transport engine") .insert( "options", Dictionary() .insert( "pt", Dictionary() .insert("label", "Unidirectional Path Tracer") .insert("help", "Unidirectional path tracing")) .insert( "sppm", Dictionary() .insert("label", "Stochastic Progressive Photon Mapping") .insert("help", "Stochastic Progressive Photon Mapping")))); metadata.insert( "rendering_threads", Dictionary() .insert("type", "int") .insert("label", "Render Threads") .insert("help", "Number of threads to use for rendering")); metadata.dictionaries().insert( "light_sampler", BackwardLightSampler::get_params_metadata()); metadata.dictionaries().insert( "texture_store", TextureStore::get_params_metadata()); metadata.dictionaries().insert( "uniform_pixel_renderer", UniformPixelRendererFactory::get_params_metadata()); metadata.dictionaries().insert( "adaptive_pixel_renderer", AdaptivePixelRendererFactory::get_params_metadata()); metadata.dictionaries().insert( "generic_frame_renderer", GenericFrameRendererFactory::get_params_metadata()); metadata.dictionaries().insert( "progressive_frame_renderer", ProgressiveFrameRendererFactory::get_params_metadata()); metadata.dictionaries().insert("pt", PTLightingEngineFactory::get_params_metadata()); metadata.dictionaries().insert("sppm", SPPMLightingEngineFactory::get_params_metadata()); return metadata; } // // ConfigurationFactory class implementation. // auto_release_ptr<Configuration> ConfigurationFactory::create(const char* name) { assert(name); return auto_release_ptr<Configuration>(new Configuration(name)); } auto_release_ptr<Configuration> ConfigurationFactory::create( const char* name, const ParamArray& params) { assert(name); auto_release_ptr<Configuration> configuration(new Configuration(name)); configuration->get_parameters().merge(params); return configuration; } // // BaseConfigurationFactory class implementation. // auto_release_ptr<Configuration> BaseConfigurationFactory::create_base_final() { auto_release_ptr<Configuration> configuration(new Configuration("base_final")); ParamArray& parameters = configuration->get_parameters(); parameters.insert("spectrum_mode", "rgb"); parameters.insert("sampling_mode", "qmc"); parameters.insert("frame_renderer", "generic"); parameters.insert("tile_renderer", "generic"); parameters.insert("pixel_renderer", "uniform"); parameters.dictionaries().insert( "uniform_pixel_renderer", ParamArray() .insert("samples", "64")); parameters.insert("sample_renderer", "generic"); parameters.insert("lighting_engine", "pt"); return configuration; } auto_release_ptr<Configuration> BaseConfigurationFactory::create_base_interactive() { auto_release_ptr<Configuration> configuration(new Configuration("base_interactive")); ParamArray& parameters = configuration->get_parameters(); parameters.insert("spectrum_mode", "rgb"); parameters.insert("sampling_mode", "qmc"); parameters.insert("frame_renderer", "progressive"); parameters.insert("sample_generator", "generic"); parameters.insert("sample_renderer", "generic"); parameters.insert("lighting_engine", "pt"); return configuration; } bool BaseConfigurationFactory::is_base_final_configuration(const char* name) { assert(name); return strcmp(name, "base_final") == 0; } bool BaseConfigurationFactory::is_base_interactive_configuration(const char* name) { assert(name); return strcmp(name, "base_interactive") == 0; } bool BaseConfigurationFactory::is_base_configuration(const char* name) { return is_base_final_configuration(name) || is_base_interactive_configuration(name); } } // namespace renderer
/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * Description: * What is this file about? * * Revision history: * xxxx-xx-xx, author, first version * xxxx-xx-xx, author, fix bug about xxx */ #include "replication_failure_detector.h" #include "replica_stub.h" # ifdef __TITLE__ # undef __TITLE__ # endif # define __TITLE__ "replica.FD" namespace dsn { namespace replication { replication_failure_detector::replication_failure_detector( replica_stub* stub, std::vector< ::dsn::rpc_address>& meta_servers) { _meta_servers.assign_group(dsn_group_build("meta.servers")); _stub = stub; for (auto& s : meta_servers) { dsn_group_add(_meta_servers.group_handle(), s.c_addr()); } dsn_group_set_leader(_meta_servers.group_handle(), meta_servers[random32(0, (uint32_t)meta_servers.size() - 1)].c_addr()); } replication_failure_detector::~replication_failure_detector(void) { dsn_group_destroy(_meta_servers.group_handle()); } void replication_failure_detector::end_ping(::dsn::error_code err, const fd::beacon_ack& ack, void* context) { dinfo("end ping result, error[%s], ack.this_node[%s], ack.primary_node[%s], ack.is_master[%s], ack.allowed[%s]", err.to_string(), ack.this_node.to_string(), ack.primary_node.to_string(), ack.is_master ? "true" : "false", ack.allowed ? "true" : "false"); if (!failure_detector::end_ping_internal(err, ack)) { // not applicable return; } { zauto_lock l(_meta_lock); if (dsn_group_is_leader(_meta_servers.group_handle(), ack.this_node.c_addr())) { if (err != ERR_OK) { // ping failed, switch master rpc_address node = dsn_group_next(_meta_servers.group_handle(), ack.this_node.c_addr()); if (ack.this_node != node) { dsn_group_set_leader(_meta_servers.group_handle(), node.c_addr()); switch_master(ack.this_node, node); } } else if (ack.is_master == false) { // switch master if (!ack.primary_node.is_invalid() && !dsn_group_is_leader(_meta_servers.group_handle(), ack.primary_node.c_addr())) { dsn_group_set_leader(_meta_servers.group_handle(), ack.primary_node.c_addr()); switch_master(ack.this_node, ack.primary_node); } } else { } } else // ack.this_node is not leader { if (err != ERR_OK) { // do nothing } else if (ack.is_master == false) { // switch master if (!ack.primary_node.is_invalid() && !dsn_group_is_leader(_meta_servers.group_handle(), ack.primary_node.c_addr())) { dsn_group_set_leader(_meta_servers.group_handle(), ack.primary_node.c_addr()); switch_master(ack.this_node, ack.primary_node); } } else { ddebug("update meta server leader to [%s]", ack.this_node.to_string()); switch_master( dsn_group_get_leader(_meta_servers.group_handle()), ack.this_node.c_addr() ); dsn_group_set_leader(_meta_servers.group_handle(), ack.this_node.c_addr()); } } } } // client side void replication_failure_detector::on_master_disconnected( const std::vector< ::dsn::rpc_address>& nodes ) { bool primaryDisconnected = false; rpc_address leader = dsn_group_get_leader(_meta_servers.group_handle()); { zauto_lock l(_meta_lock); for (auto it = nodes.begin(); it != nodes.end(); it++) { if (leader == *it) primaryDisconnected = true; } } if (primaryDisconnected) { _stub->on_meta_server_disconnected(); } } void replication_failure_detector::on_master_connected(::dsn::rpc_address node) { bool is_primary = false; { zauto_lock l(_meta_lock); is_primary = dsn_group_is_leader(_meta_servers.group_handle(), node.c_addr()); } if (is_primary) { _stub->on_meta_server_connected(); } } }} // end namespace small fix to make the code more elegant /* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * Description: * What is this file about? * * Revision history: * xxxx-xx-xx, author, first version * xxxx-xx-xx, author, fix bug about xxx */ #include "replication_failure_detector.h" #include "replica_stub.h" # ifdef __TITLE__ # undef __TITLE__ # endif # define __TITLE__ "replica.FD" namespace dsn { namespace replication { replication_failure_detector::replication_failure_detector( replica_stub* stub, std::vector< ::dsn::rpc_address>& meta_servers) { _meta_servers.assign_group(dsn_group_build("meta.servers")); _stub = stub; for (auto& s : meta_servers) { dsn_group_add(_meta_servers.group_handle(), s.c_addr()); } dsn_group_set_leader(_meta_servers.group_handle(), meta_servers[random32(0, (uint32_t)meta_servers.size() - 1)].c_addr()); } replication_failure_detector::~replication_failure_detector(void) { dsn_group_destroy(_meta_servers.group_handle()); } void replication_failure_detector::end_ping(::dsn::error_code err, const fd::beacon_ack& ack, void* context) { dinfo("end ping result, error[%s], ack.this_node[%s], ack.primary_node[%s], ack.is_master[%s], ack.allowed[%s]", err.to_string(), ack.this_node.to_string(), ack.primary_node.to_string(), ack.is_master ? "true" : "false", ack.allowed ? "true" : "false"); if (!failure_detector::end_ping_internal(err, ack)) { // not applicable return; } { zauto_lock l(_meta_lock); if (dsn_group_is_leader(_meta_servers.group_handle(), ack.this_node.c_addr())) { if (err != ERR_OK) { // ping failed, switch master rpc_address node = dsn_group_next(_meta_servers.group_handle(), ack.this_node.c_addr()); if (ack.this_node != node) { dsn_group_set_leader(_meta_servers.group_handle(), node.c_addr()); switch_master(ack.this_node, node); } } else if (ack.is_master == false) { // switch master if (!ack.primary_node.is_invalid() && !dsn_group_is_leader(_meta_servers.group_handle(), ack.primary_node.c_addr())) { dsn_group_set_leader(_meta_servers.group_handle(), ack.primary_node.c_addr()); switch_master(ack.this_node, ack.primary_node); } } else { } } else // ack.this_node is not leader { if (err != ERR_OK) { // do nothing } else if (ack.is_master == false) { // switch master if (!ack.primary_node.is_invalid() && !dsn_group_is_leader(_meta_servers.group_handle(), ack.primary_node.c_addr())) { dsn_group_set_leader(_meta_servers.group_handle(), ack.primary_node.c_addr()); switch_master(ack.this_node, ack.primary_node); } } else { ddebug("update meta server leader to [%s]", ack.this_node.to_string()); rpc_address old_leader = dsn_group_get_leader(_meta_servers.group_handle()); dsn_group_set_leader(_meta_servers.group_handle(), ack.this_node.c_addr()); switch_master(old_leader, ack.this_node.c_addr() ); } } } } // client side void replication_failure_detector::on_master_disconnected( const std::vector< ::dsn::rpc_address>& nodes ) { bool primaryDisconnected = false; rpc_address leader = dsn_group_get_leader(_meta_servers.group_handle()); { zauto_lock l(_meta_lock); for (auto it = nodes.begin(); it != nodes.end(); it++) { if (leader == *it) primaryDisconnected = true; } } if (primaryDisconnected) { _stub->on_meta_server_disconnected(); } } void replication_failure_detector::on_master_connected(::dsn::rpc_address node) { bool is_primary = false; { zauto_lock l(_meta_lock); is_primary = dsn_group_is_leader(_meta_servers.group_handle(), node.c_addr()); } if (is_primary) { _stub->on_meta_server_connected(); } } }} // end namespace
#include <algorithm> #include <iterator> template <class Iterator> bool is_sorted (Iterator first, Iterator last) { if (first == last) return true; Iterator next = first; while (++next != last) { if (*next < *first) return false; ++first; } return true; } template<class Iterator> void bogosort(Iterator begin, Iterator end) { while(!is_sorted(begin, end)) random_shuffle(begin, end); } Update bogosort.cpp #include <algorithm> #include <iterator> template <class Iterator> bool is_sorted (Iterator first, Iterator last) { if (first == last) return true; Iterator next = first; while (++next != last) { if (*next < *first) return false; ++first; } return true; } template<class Iterator> void bogosort(Iterator begin, Iterator end) { while(!is_sorted(begin, end)) random_shuffle(begin, end); }
/* * Copyright (c) 2012 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <climits> #include <vector> #include "third_party/googletest/src/include/gtest/gtest.h" #include "test/codec_factory.h" #include "test/encode_test_driver.h" #include "test/i420_video_source.h" #include "test/video_source.h" #include "test/util.h" // Enable(1) or Disable(0) writing of the compressed bitstream. #define WRITE_COMPRESSED_STREAM 0 namespace { #if WRITE_COMPRESSED_STREAM static void mem_put_le16(char *const mem, const unsigned int val) { mem[0] = val; mem[1] = val >> 8; } static void mem_put_le32(char *const mem, const unsigned int val) { mem[0] = val; mem[1] = val >> 8; mem[2] = val >> 16; mem[3] = val >> 24; } static void write_ivf_file_header(const vpx_codec_enc_cfg_t *const cfg, int frame_cnt, FILE *const outfile) { char header[32]; header[0] = 'D'; header[1] = 'K'; header[2] = 'I'; header[3] = 'F'; mem_put_le16(header + 4, 0); /* version */ mem_put_le16(header + 6, 32); /* headersize */ mem_put_le32(header + 8, 0x30395056); /* fourcc (vp9) */ mem_put_le16(header + 12, cfg->g_w); /* width */ mem_put_le16(header + 14, cfg->g_h); /* height */ mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */ mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */ mem_put_le32(header + 24, frame_cnt); /* length */ mem_put_le32(header + 28, 0); /* unused */ (void)fwrite(header, 1, 32, outfile); } static void write_ivf_frame_size(FILE *const outfile, const size_t size) { char header[4]; mem_put_le32(header, static_cast<unsigned int>(size)); (void)fwrite(header, 1, 4, outfile); } static void write_ivf_frame_header(const vpx_codec_cx_pkt_t *const pkt, FILE *const outfile) { char header[12]; vpx_codec_pts_t pts; if (pkt->kind != VPX_CODEC_CX_FRAME_PKT) return; pts = pkt->data.frame.pts; mem_put_le32(header, static_cast<unsigned int>(pkt->data.frame.sz)); mem_put_le32(header + 4, pts & 0xFFFFFFFF); mem_put_le32(header + 8, pts >> 32); (void)fwrite(header, 1, 12, outfile); } #endif // WRITE_COMPRESSED_STREAM const unsigned int kInitialWidth = 320; const unsigned int kInitialHeight = 240; unsigned int ScaleForFrameNumber(unsigned int frame, unsigned int val) { if (frame < 10) return val; if (frame < 20) return val / 2; if (frame < 30) return val * 2 / 3; if (frame < 40) return val / 4; if (frame < 50) return val * 7 / 8; return val; } class ResizingVideoSource : public ::libvpx_test::DummyVideoSource { public: ResizingVideoSource() { SetSize(kInitialWidth, kInitialHeight); limit_ = 60; } virtual ~ResizingVideoSource() {} protected: virtual void Next() { ++frame_; SetSize(ScaleForFrameNumber(frame_, kInitialWidth), ScaleForFrameNumber(frame_, kInitialHeight)); FillFrame(); } }; class ResizeTest : public ::libvpx_test::EncoderTest, public ::libvpx_test::CodecTestWithParam<libvpx_test::TestMode> { protected: ResizeTest() : EncoderTest(GET_PARAM(0)) {} virtual ~ResizeTest() {} struct FrameInfo { FrameInfo(vpx_codec_pts_t _pts, unsigned int _w, unsigned int _h) : pts(_pts), w(_w), h(_h) {} vpx_codec_pts_t pts; unsigned int w; unsigned int h; }; virtual void SetUp() { InitializeConfig(); SetMode(GET_PARAM(1)); } virtual void DecompressedFrameHook(const vpx_image_t &img, vpx_codec_pts_t pts) { frame_info_list_.push_back(FrameInfo(pts, img.d_w, img.d_h)); } std::vector< FrameInfo > frame_info_list_; }; TEST_P(ResizeTest, TestExternalResizeWorks) { ResizingVideoSource video; ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); for (std::vector<FrameInfo>::iterator info = frame_info_list_.begin(); info != frame_info_list_.end(); ++info) { const vpx_codec_pts_t pts = info->pts; const unsigned int expected_w = ScaleForFrameNumber(pts, kInitialWidth); const unsigned int expected_h = ScaleForFrameNumber(pts, kInitialHeight); EXPECT_EQ(expected_w, info->w) << "Frame " << pts << "had unexpected width"; EXPECT_EQ(expected_h, info->h) << "Frame " << pts << "had unexpected height"; } } const unsigned int kStepDownFrame = 3; const unsigned int kStepUpFrame = 6; class ResizeInternalTest : public ResizeTest { protected: #if WRITE_COMPRESSED_STREAM ResizeInternalTest() : ResizeTest(), frame0_psnr_(0.0), outfile_(NULL), out_frames_(0) {} #else ResizeInternalTest() : ResizeTest(), frame0_psnr_(0.0) {} #endif virtual ~ResizeInternalTest() {} virtual void BeginPassHook(unsigned int /*pass*/) { #if WRITE_COMPRESSED_STREAM outfile_ = fopen("vp90-2-05-resize.ivf", "wb"); #endif } virtual void EndPassHook() { #if WRITE_COMPRESSED_STREAM if (outfile_) { if (!fseek(outfile_, 0, SEEK_SET)) write_ivf_file_header(&cfg_, out_frames_, outfile_); fclose(outfile_); outfile_ = NULL; } #endif } virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video, libvpx_test::Encoder *encoder) { if (video->frame() == kStepDownFrame) { struct vpx_scaling_mode mode = {VP8E_FOURFIVE, VP8E_THREEFIVE}; encoder->Control(VP8E_SET_SCALEMODE, &mode); } if (video->frame() == kStepUpFrame) { struct vpx_scaling_mode mode = {VP8E_NORMAL, VP8E_NORMAL}; encoder->Control(VP8E_SET_SCALEMODE, &mode); } } virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) { if (!frame0_psnr_) frame0_psnr_ = pkt->data.psnr.psnr[0]; EXPECT_NEAR(pkt->data.psnr.psnr[0], frame0_psnr_, 1.0); } virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) { #if WRITE_COMPRESSED_STREAM ++out_frames_; // Write initial file header if first frame. if (pkt->data.frame.pts == 0) write_ivf_file_header(&cfg_, 0, outfile_); // Write frame header and data. write_ivf_frame_header(pkt, outfile_); (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile_); #endif } double frame0_psnr_; #if WRITE_COMPRESSED_STREAM FILE *outfile_; unsigned int out_frames_; #endif }; TEST_P(ResizeInternalTest, TestInternalResizeWorks) { ::libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288, 30, 1, 0, 10); init_flags_ = VPX_CODEC_USE_PSNR; // q picked such that initial keyframe on this clip is ~30dB PSNR cfg_.rc_min_quantizer = cfg_.rc_max_quantizer = 48; // If the number of frames being encoded is smaller than g_lag_in_frames // the encoded frame is unavailable using the current API. Comparing // frames to detect mismatch would then not be possible. Set // g_lag_in_frames = 0 to get around this. cfg_.g_lag_in_frames = 0; ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); for (std::vector<FrameInfo>::iterator info = frame_info_list_.begin(); info != frame_info_list_.end(); ++info) { const vpx_codec_pts_t pts = info->pts; if (pts >= kStepDownFrame && pts < kStepUpFrame) { ASSERT_EQ(282U, info->w) << "Frame " << pts << " had unexpected width"; ASSERT_EQ(173U, info->h) << "Frame " << pts << " had unexpected height"; } else { EXPECT_EQ(352U, info->w) << "Frame " << pts << " had unexpected width"; EXPECT_EQ(288U, info->h) << "Frame " << pts << " had unexpected height"; } } } VP8_INSTANTIATE_TEST_CASE(ResizeTest, ONE_PASS_TEST_MODES); VP9_INSTANTIATE_TEST_CASE(ResizeInternalTest, ::testing::Values(::libvpx_test::kOnePassBest)); } // namespace Adjustment to allowed range in resize unit test Change-Id: I5222e3db2627a3a9f7fc34f2ab4554aa5807ed51 /* * Copyright (c) 2012 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <climits> #include <vector> #include "third_party/googletest/src/include/gtest/gtest.h" #include "test/codec_factory.h" #include "test/encode_test_driver.h" #include "test/i420_video_source.h" #include "test/video_source.h" #include "test/util.h" // Enable(1) or Disable(0) writing of the compressed bitstream. #define WRITE_COMPRESSED_STREAM 0 namespace { #if WRITE_COMPRESSED_STREAM static void mem_put_le16(char *const mem, const unsigned int val) { mem[0] = val; mem[1] = val >> 8; } static void mem_put_le32(char *const mem, const unsigned int val) { mem[0] = val; mem[1] = val >> 8; mem[2] = val >> 16; mem[3] = val >> 24; } static void write_ivf_file_header(const vpx_codec_enc_cfg_t *const cfg, int frame_cnt, FILE *const outfile) { char header[32]; header[0] = 'D'; header[1] = 'K'; header[2] = 'I'; header[3] = 'F'; mem_put_le16(header + 4, 0); /* version */ mem_put_le16(header + 6, 32); /* headersize */ mem_put_le32(header + 8, 0x30395056); /* fourcc (vp9) */ mem_put_le16(header + 12, cfg->g_w); /* width */ mem_put_le16(header + 14, cfg->g_h); /* height */ mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */ mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */ mem_put_le32(header + 24, frame_cnt); /* length */ mem_put_le32(header + 28, 0); /* unused */ (void)fwrite(header, 1, 32, outfile); } static void write_ivf_frame_size(FILE *const outfile, const size_t size) { char header[4]; mem_put_le32(header, static_cast<unsigned int>(size)); (void)fwrite(header, 1, 4, outfile); } static void write_ivf_frame_header(const vpx_codec_cx_pkt_t *const pkt, FILE *const outfile) { char header[12]; vpx_codec_pts_t pts; if (pkt->kind != VPX_CODEC_CX_FRAME_PKT) return; pts = pkt->data.frame.pts; mem_put_le32(header, static_cast<unsigned int>(pkt->data.frame.sz)); mem_put_le32(header + 4, pts & 0xFFFFFFFF); mem_put_le32(header + 8, pts >> 32); (void)fwrite(header, 1, 12, outfile); } #endif // WRITE_COMPRESSED_STREAM const unsigned int kInitialWidth = 320; const unsigned int kInitialHeight = 240; unsigned int ScaleForFrameNumber(unsigned int frame, unsigned int val) { if (frame < 10) return val; if (frame < 20) return val / 2; if (frame < 30) return val * 2 / 3; if (frame < 40) return val / 4; if (frame < 50) return val * 7 / 8; return val; } class ResizingVideoSource : public ::libvpx_test::DummyVideoSource { public: ResizingVideoSource() { SetSize(kInitialWidth, kInitialHeight); limit_ = 60; } virtual ~ResizingVideoSource() {} protected: virtual void Next() { ++frame_; SetSize(ScaleForFrameNumber(frame_, kInitialWidth), ScaleForFrameNumber(frame_, kInitialHeight)); FillFrame(); } }; class ResizeTest : public ::libvpx_test::EncoderTest, public ::libvpx_test::CodecTestWithParam<libvpx_test::TestMode> { protected: ResizeTest() : EncoderTest(GET_PARAM(0)) {} virtual ~ResizeTest() {} struct FrameInfo { FrameInfo(vpx_codec_pts_t _pts, unsigned int _w, unsigned int _h) : pts(_pts), w(_w), h(_h) {} vpx_codec_pts_t pts; unsigned int w; unsigned int h; }; virtual void SetUp() { InitializeConfig(); SetMode(GET_PARAM(1)); } virtual void DecompressedFrameHook(const vpx_image_t &img, vpx_codec_pts_t pts) { frame_info_list_.push_back(FrameInfo(pts, img.d_w, img.d_h)); } std::vector< FrameInfo > frame_info_list_; }; TEST_P(ResizeTest, TestExternalResizeWorks) { ResizingVideoSource video; ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); for (std::vector<FrameInfo>::iterator info = frame_info_list_.begin(); info != frame_info_list_.end(); ++info) { const vpx_codec_pts_t pts = info->pts; const unsigned int expected_w = ScaleForFrameNumber(pts, kInitialWidth); const unsigned int expected_h = ScaleForFrameNumber(pts, kInitialHeight); EXPECT_EQ(expected_w, info->w) << "Frame " << pts << "had unexpected width"; EXPECT_EQ(expected_h, info->h) << "Frame " << pts << "had unexpected height"; } } const unsigned int kStepDownFrame = 3; const unsigned int kStepUpFrame = 6; class ResizeInternalTest : public ResizeTest { protected: #if WRITE_COMPRESSED_STREAM ResizeInternalTest() : ResizeTest(), frame0_psnr_(0.0), outfile_(NULL), out_frames_(0) {} #else ResizeInternalTest() : ResizeTest(), frame0_psnr_(0.0) {} #endif virtual ~ResizeInternalTest() {} virtual void BeginPassHook(unsigned int /*pass*/) { #if WRITE_COMPRESSED_STREAM outfile_ = fopen("vp90-2-05-resize.ivf", "wb"); #endif } virtual void EndPassHook() { #if WRITE_COMPRESSED_STREAM if (outfile_) { if (!fseek(outfile_, 0, SEEK_SET)) write_ivf_file_header(&cfg_, out_frames_, outfile_); fclose(outfile_); outfile_ = NULL; } #endif } virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video, libvpx_test::Encoder *encoder) { if (video->frame() == kStepDownFrame) { struct vpx_scaling_mode mode = {VP8E_FOURFIVE, VP8E_THREEFIVE}; encoder->Control(VP8E_SET_SCALEMODE, &mode); } if (video->frame() == kStepUpFrame) { struct vpx_scaling_mode mode = {VP8E_NORMAL, VP8E_NORMAL}; encoder->Control(VP8E_SET_SCALEMODE, &mode); } } virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) { if (!frame0_psnr_) frame0_psnr_ = pkt->data.psnr.psnr[0]; EXPECT_NEAR(pkt->data.psnr.psnr[0], frame0_psnr_, 1.5); } virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) { #if WRITE_COMPRESSED_STREAM ++out_frames_; // Write initial file header if first frame. if (pkt->data.frame.pts == 0) write_ivf_file_header(&cfg_, 0, outfile_); // Write frame header and data. write_ivf_frame_header(pkt, outfile_); (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile_); #endif } double frame0_psnr_; #if WRITE_COMPRESSED_STREAM FILE *outfile_; unsigned int out_frames_; #endif }; TEST_P(ResizeInternalTest, TestInternalResizeWorks) { ::libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288, 30, 1, 0, 10); init_flags_ = VPX_CODEC_USE_PSNR; // q picked such that initial keyframe on this clip is ~30dB PSNR cfg_.rc_min_quantizer = cfg_.rc_max_quantizer = 48; // If the number of frames being encoded is smaller than g_lag_in_frames // the encoded frame is unavailable using the current API. Comparing // frames to detect mismatch would then not be possible. Set // g_lag_in_frames = 0 to get around this. cfg_.g_lag_in_frames = 0; ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); for (std::vector<FrameInfo>::iterator info = frame_info_list_.begin(); info != frame_info_list_.end(); ++info) { const vpx_codec_pts_t pts = info->pts; if (pts >= kStepDownFrame && pts < kStepUpFrame) { ASSERT_EQ(282U, info->w) << "Frame " << pts << " had unexpected width"; ASSERT_EQ(173U, info->h) << "Frame " << pts << " had unexpected height"; } else { EXPECT_EQ(352U, info->w) << "Frame " << pts << " had unexpected width"; EXPECT_EQ(288U, info->h) << "Frame " << pts << " had unexpected height"; } } } VP8_INSTANTIATE_TEST_CASE(ResizeTest, ONE_PASS_TEST_MODES); VP9_INSTANTIATE_TEST_CASE(ResizeInternalTest, ::testing::Values(::libvpx_test::kOnePassBest)); } // namespace
/* * qiaffine.cpp * * Copyright (c) 2015 Tobias Wood. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #include <iostream> #include "itkMetaDataObject.h" #include "QI/Util.h" #include "QI/IO.h" #include "QI/Args.h" using namespace std; template<typename TImage> void Convert(const std::string &input, const std::string &output) { auto image = QI::ReadImage<TImage>(input); QI::WriteImage<TImage>(image, output); } int main(int argc, char **argv) { args::ArgumentParser parser("Converts images between formats\nhttp://github.com/spinicist/QUIT"); args::Positional<std::string> input_file(parser, "INPUT", "Input file."); args::Positional<std::string> output_file(parser, "OUTPUT", "Output file."); args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"}); args::Flag verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"}); args::ValueFlag<std::string> out_prefix(parser, "OUTPREFIX", "Add a prefix to output filenames", {'o', "out"}); args::ValueFlagList<std::string> rename(parser, "RENAME", "Rename using specified header fields", {'r', "rename"}); QI::ParseArgs(parser, argc, argv); const std::string input = QI::CheckPos(input_file); itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(input.c_str(), itk::ImageIOFactory::ReadMode); if (!imageIO) { cerr << "Could not open: " << input << endl; return EXIT_FAILURE; } imageIO->SetFileName(input); imageIO->ReadImageInformation(); size_t dims = imageIO->GetNumberOfDimensions(); auto PixelType = imageIO->GetPixelType(); std::string output = out_prefix.Get(); if (rename) { bool first = true; for (const auto rename_field: args::get(rename)) { std::vector<std::string> string_array_value; std::string string_value; double double_value; if (first) { first = false; } else { output.append("_"); } auto dict = imageIO->GetMetaDataDictionary(); if (!dict.HasKey(rename_field)) { QI_EXCEPTION("Rename field '" << rename_field << "' not found in header."); } if (ExposeMetaData(dict, rename_field, string_array_value)) { output.append(string_array_value[0]); } else if (ExposeMetaData(dict, rename_field, string_value)) { output.append(string_value); } else if (ExposeMetaData(dict, rename_field, double_value)) { std::ostringstream formatted; formatted << double_value; output.append(formatted.str()); } else { QI_EXCEPTION("Could not determine type of rename header field:" << rename_field); } } } else { output.append(QI::Basename(input)); } output.append(QI::CheckPos(output_file)); #define DIM_SWITCH( N ) \ case N:\ switch (PixelType) {\ case itk::ImageIOBase::SCALAR: Convert<itk::Image<float, N>>(input, output); break;\ case itk::ImageIOBase::COMPLEX: Convert<itk::Image<std::complex<float>, N>>(input, output); break;\ default: std::cerr << "Unsupported PixelType: " << PixelType << std::endl; return EXIT_FAILURE;\ }\ break; switch (dims) { DIM_SWITCH( 2 ) DIM_SWITCH( 3 ) DIM_SWITCH( 4 ) } #undef DIM_SWITCH return EXIT_SUCCESS; } BUG: Fixed rename missing rename header fields. /* * qiaffine.cpp * * Copyright (c) 2015 Tobias Wood. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #include <iostream> #include "itkMetaDataObject.h" #include "QI/Util.h" #include "QI/IO.h" #include "QI/Args.h" using namespace std; template<typename TImage> void Convert(const std::string &input, const std::string &output) { auto image = QI::ReadImage<TImage>(input); QI::WriteImage<TImage>(image, output); } int main(int argc, char **argv) { args::ArgumentParser parser("Converts images between formats\nhttp://github.com/spinicist/QUIT"); args::Positional<std::string> input_file(parser, "INPUT", "Input file."); args::Positional<std::string> output_file(parser, "OUTPUT", "Output file."); args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"}); args::Flag verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"}); args::ValueFlag<std::string> out_prefix(parser, "OUTPREFIX", "Add a prefix to output filenames", {'o', "out"}); args::ValueFlagList<std::string> rename(parser, "RENAME", "Rename using specified header fields", {'r', "rename"}); QI::ParseArgs(parser, argc, argv); const std::string input = QI::CheckPos(input_file); itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(input.c_str(), itk::ImageIOFactory::ReadMode); if (!imageIO) { cerr << "Could not open: " << input << endl; return EXIT_FAILURE; } imageIO->SetFileName(input); imageIO->ReadImageInformation(); size_t dims = imageIO->GetNumberOfDimensions(); auto PixelType = imageIO->GetPixelType(); std::string output = out_prefix.Get(); if (rename) { bool append_delim = false; for (const auto rename_field: args::get(rename)) { std::vector<std::string> string_array_value; std::string string_value; double double_value; auto dict = imageIO->GetMetaDataDictionary(); if (!dict.HasKey(rename_field)) { std::cout << "Rename field '" << rename_field << "' not found in header. Ignoring" << std::endl; continue; } if (append_delim) { output.append("_"); } else { append_delim = true; } if (ExposeMetaData(dict, rename_field, string_array_value)) { output.append(string_array_value[0]); } else if (ExposeMetaData(dict, rename_field, string_value)) { output.append(string_value); } else if (ExposeMetaData(dict, rename_field, double_value)) { std::ostringstream formatted; formatted << double_value; output.append(formatted.str()); } else { QI_EXCEPTION("Could not determine type of rename header field:" << rename_field); } } } else { output.append(QI::Basename(input)); } output.append(QI::CheckPos(output_file)); #define DIM_SWITCH( N ) \ case N:\ switch (PixelType) {\ case itk::ImageIOBase::SCALAR: Convert<itk::Image<float, N>>(input, output); break;\ case itk::ImageIOBase::COMPLEX: Convert<itk::Image<std::complex<float>, N>>(input, output); break;\ default: std::cerr << "Unsupported PixelType: " << PixelType << std::endl; return EXIT_FAILURE;\ }\ break; switch (dims) { DIM_SWITCH( 2 ) DIM_SWITCH( 3 ) DIM_SWITCH( 4 ) } #undef DIM_SWITCH return EXIT_SUCCESS; }
/* * Copyright (c) 2019, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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. */ #if !DEVICE_SPI #error [NOT_SUPPORTED] SPI not supported for this target #elif !COMPONENT_FPGA_CI_TEST_SHIELD #error [NOT_SUPPORTED] FPGA CI Test Shield is needed to run this test #elif !defined(TARGET_FF_ARDUINO) && !defined(MBED_CONF_TARGET_DEFAULT_FORM_FACTOR) #error [NOT_SUPPORTED] Test not supported for this form factor #else #include "utest/utest.h" #include "unity/unity.h" #include "greentea-client/test_env.h" #include "mbed.h" #include "SPIMasterTester.h" #include "pinmap.h" #include "hal/static_pinmap.h" #include "test_utils.h" #include "spi_fpga_test.h" using namespace utest::v1; typedef enum { TRANSFER_SPI_MASTER_WRITE_SYNC, TRANSFER_SPI_MASTER_BLOCK_WRITE_SYNC, TRANSFER_SPI_MASTER_TRANSFER_ASYNC } transfer_type_t; typedef enum { BUFFERS_COMMON, // common case rx/tx buffers are defined and have the same size BUFFERS_TX_GT_RX, // tx buffer length is greater than rx buffer length BUFFERS_TX_LT_RX, // tx buffer length is less than rx buffer length BUFFERS_TX_ONE_SYM, // one symbol only is transmitted in both directions } test_buffers_t; #define FREQ_200_KHZ (200000ull) #define FREQ_500_KHZ (500000) #define FREQ_1_MHZ (1000000) #define FREQ_2_MHZ (2000000) #define FREQ_10_MHZ (10000000ull) #define FREQ_MIN ((uint32_t)0) #define FREQ_MAX ((uint32_t)-1) #define FILL_SYM (0xF5F5F5F5) #define DUMMY_SYM (0xD5D5D5D5) #define SS_ASSERT (0) #define SS_DEASSERT (!(SS_ASSERT)) #define TEST_CAPABILITY_BIT(MASK, CAP) ((1 << CAP) & (MASK)) const int TRANSFER_COUNT = 300; SPIMasterTester tester(DefaultFormFactor::pins(), DefaultFormFactor::restricted_pins()); spi_t spi; static volatile bool async_trasfer_done; #if DEVICE_SPI_ASYNCH void spi_async_handler() { int event = spi_irq_handler_asynch(&spi); if (event & SPI_EVENT_COMPLETE) { async_trasfer_done = true; } } #endif /* Function finds SS pin for manual SS handling. */ static PinName find_ss_pin(PinName mosi, PinName miso, PinName sclk) { const PinList *ff_pins_list = pinmap_ff_default_pins(); const PinList *restricted_pins_list = pinmap_restricted_pins(); uint32_t cs_pin_idx; for (cs_pin_idx = 0; cs_pin_idx < ff_pins_list->count; cs_pin_idx++) { if (ff_pins_list->pins[cs_pin_idx] == mosi || ff_pins_list->pins[cs_pin_idx] == miso || ff_pins_list->pins[cs_pin_idx] == sclk) { continue; } bool restricted_pin = false; for (uint32_t i = 0; i < restricted_pins_list->count ; i++) { if (ff_pins_list->pins[cs_pin_idx] == restricted_pins_list->pins[i]) { restricted_pin = true; } } if (restricted_pin) { continue; } else { break; } } PinName ssel = (cs_pin_idx == ff_pins_list->count ? NC : ff_pins_list->pins[cs_pin_idx]); TEST_ASSERT_MESSAGE(ssel != NC, "Unable to find pin for Chip Select"); return ssel; } /* Function handles ss line if ss is specified. */ static void handle_ss(DigitalOut *ss, bool select) { if (ss) { if (select) { *ss = SS_ASSERT; } else { *ss = SS_DEASSERT; } } } /* Auxiliary function to check platform capabilities against test case. */ static bool check_capabilities(const spi_capabilities_t *capabilities, SPITester::SpiMode spi_mode, uint32_t sym_size, transfer_type_t transfer_type, uint32_t frequency, test_buffers_t test_buffers) { // Symbol size if (!TEST_CAPABILITY_BIT(capabilities->word_length, (sym_size - 1))) { utest_printf("\n<Specified symbol size is not supported on this platform> skipped. "); return false; } // SPI clock mode if (!TEST_CAPABILITY_BIT(capabilities->clk_modes, spi_mode)) { utest_printf("\n<Specified spi clock mode is not supported on this platform> skipped. "); return false; } // Frequency if (frequency != FREQ_MAX && frequency != FREQ_MIN && frequency < capabilities->minimum_frequency && frequency > capabilities->maximum_frequency) { utest_printf("\n<Specified frequency is not supported on this platform> skipped. "); return false; } // Async mode if (transfer_type == TRANSFER_SPI_MASTER_TRANSFER_ASYNC && capabilities->async_mode == false) { utest_printf("\n<Async mode is not supported on this platform> skipped. "); return false; } if ((test_buffers == BUFFERS_TX_GT_RX || test_buffers == BUFFERS_TX_LT_RX) && capabilities->tx_rx_buffers_equal_length == true) { utest_printf("\n<RX length != TX length is not supported on this platform> skipped. "); return false; } return true; } void fpga_spi_test_init_free(PinName mosi, PinName miso, PinName sclk) { spi_init(&spi, mosi, miso, sclk, NC); spi_format(&spi, 8, 0, 0); spi_frequency(&spi, 1000000); spi_free(&spi); } void fpga_spi_test_common(PinName mosi, PinName miso, PinName sclk, PinName ssel, SPITester::SpiMode spi_mode, uint32_t sym_size, transfer_type_t transfer_type, uint32_t frequency, test_buffers_t test_buffers, bool auto_ss, bool init_direct) { spi_capabilities_t capabilities; uint32_t freq = frequency; uint32_t tx_cnt = TRANSFER_COUNT; uint32_t rx_cnt = TRANSFER_COUNT; uint8_t fill_symbol = (uint8_t)FILL_SYM; PinName ss_pin = (auto_ss ? ssel : NC); DigitalOut *ss = NULL; spi_get_capabilities(ssel, false, &capabilities); if (check_capabilities(&capabilities, spi_mode, sym_size, transfer_type, frequency, test_buffers) == false) { return; } uint32_t sym_mask = ((1 << sym_size) - 1); switch (frequency) { case (FREQ_MIN): freq = capabilities.minimum_frequency; break; case (FREQ_MAX): freq = capabilities.maximum_frequency; break; default: break; } switch (test_buffers) { case (BUFFERS_COMMON): // nothing to change break; case (BUFFERS_TX_GT_RX): rx_cnt /= 2; break; case (BUFFERS_TX_LT_RX): tx_cnt /= 2; break; case (BUFFERS_TX_ONE_SYM): tx_cnt = 1; rx_cnt = 1; break; default: break; } // Remap pins for test tester.reset(); tester.pin_map_set(mosi, MbedTester::LogicalPinSPIMosi); tester.pin_map_set(miso, MbedTester::LogicalPinSPIMiso); tester.pin_map_set(sclk, MbedTester::LogicalPinSPISclk); tester.pin_map_set(ssel, MbedTester::LogicalPinSPISsel); // Manually handle SS pin if (!auto_ss) { ss = new DigitalOut(ssel, SS_DEASSERT); } if (init_direct) { const spi_pinmap_t pinmap = get_spi_pinmap(mosi, miso, sclk, ss_pin); spi_init_direct(&spi, &pinmap); } else { spi_init(&spi, mosi, miso, sclk, ss_pin); } spi_format(&spi, sym_size, spi_mode, 0); spi_frequency(&spi, freq); // Configure spi_slave module tester.set_mode(spi_mode); tester.set_bit_order(SPITester::MSBFirst); tester.set_sym_size(sym_size); // Reset tester stats and select SPI tester.peripherals_reset(); tester.select_peripheral(SPITester::PeripheralSPI); uint32_t checksum = 0; uint32_t sym_count = TRANSFER_COUNT; int result = 0; uint8_t tx_buf[TRANSFER_COUNT] = {0}; uint8_t rx_buf[TRANSFER_COUNT] = {0}; // Send and receive test data switch (transfer_type) { case TRANSFER_SPI_MASTER_WRITE_SYNC: handle_ss(ss, true); for (int i = 0; i < TRANSFER_COUNT; i++) { uint32_t data = spi_master_write(&spi, (0 - i) & sym_mask); TEST_ASSERT_EQUAL(i & sym_mask, data); checksum += (0 - i) & sym_mask; } handle_ss(ss, false); break; case TRANSFER_SPI_MASTER_BLOCK_WRITE_SYNC: for (int i = 0; i < TRANSFER_COUNT; i++) { tx_buf[i] = (0 - i) & sym_mask; rx_buf[i] = 0xFF; switch (test_buffers) { case (BUFFERS_COMMON): case (BUFFERS_TX_GT_RX): checksum += ((0 - i) & sym_mask); break; case (BUFFERS_TX_LT_RX): if (i < tx_cnt) { checksum += ((0 - i) & sym_mask); } else { checksum += (fill_symbol & sym_mask); } break; case (BUFFERS_TX_ONE_SYM): tx_buf[0] = 0xAA; checksum = 0xAA; sym_count = 1; break; default: break; } } handle_ss(ss, true); result = spi_master_block_write(&spi, (const char *)tx_buf, tx_cnt, (char *)rx_buf, rx_cnt, 0xF5); handle_ss(ss, false); for (int i = 0; i < rx_cnt; i++) { TEST_ASSERT_EQUAL(i & sym_mask, rx_buf[i]); } for (int i = rx_cnt; i < TRANSFER_COUNT; i++) { TEST_ASSERT_EQUAL(0xFF, rx_buf[i]); } TEST_ASSERT_EQUAL(sym_count, result); break; #if DEVICE_SPI_ASYNCH case TRANSFER_SPI_MASTER_TRANSFER_ASYNC: for (int i = 0; i < TRANSFER_COUNT; i++) { tx_buf[i] = (0 - i) & sym_mask; checksum += (0 - i) & sym_mask; rx_buf[i] = 0xAA; } async_trasfer_done = false; handle_ss(ss, true); spi_master_transfer(&spi, tx_buf, TRANSFER_COUNT, rx_buf, TRANSFER_COUNT, 8, (uint32_t)spi_async_handler, SPI_EVENT_COMPLETE, DMA_USAGE_NEVER); while (!async_trasfer_done); handle_ss(ss, false); for (int i = 0; i < TRANSFER_COUNT; i++) { TEST_ASSERT_EQUAL(i & sym_mask, rx_buf[i]); } break; #endif default: TEST_ASSERT_MESSAGE(0, "Unsupported transfer type."); break; } // Verify that the transfer was successful TEST_ASSERT_EQUAL(sym_count, tester.get_transfer_count()); TEST_ASSERT_EQUAL(checksum, tester.get_receive_checksum()); spi_free(&spi); tester.reset(); } template<SPITester::SpiMode spi_mode, uint32_t sym_size, transfer_type_t transfer_type, uint32_t frequency, test_buffers_t test_buffers, bool auto_ss, bool init_direct> void fpga_spi_test_common(PinName mosi, PinName miso, PinName sclk, PinName ssel) { fpga_spi_test_common(mosi, miso, sclk, ssel, spi_mode, sym_size, transfer_type, frequency, test_buffers, auto_ss, init_direct); } template<SPITester::SpiMode spi_mode, uint32_t sym_size, transfer_type_t transfer_type, uint32_t frequency, test_buffers_t test_buffers, bool auto_ss, bool init_direct> void fpga_spi_test_common_no_ss(PinName mosi, PinName miso, PinName sclk) { PinName ssel = find_ss_pin(mosi, miso, sclk); fpga_spi_test_common(mosi, miso, sclk, ssel, spi_mode, sym_size, transfer_type, frequency, test_buffers, auto_ss, init_direct); } Case cases[] = { // This will be run for all pins Case("SPI - init/free test all pins", all_ports<SPINoCSPort, DefaultFormFactor, fpga_spi_test_init_free>), // This will be run for all peripherals Case("SPI - basic test", all_peripherals<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - basic test (direct init)", all_peripherals<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, true> >), // This will be run for single pin configuration Case("SPI - mode testing (MODE_1)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode1, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - mode testing (MODE_2)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode2, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - mode testing (MODE_3)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode3, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - symbol size testing (4)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 4, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - symbol size testing (12)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 12, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - symbol size testing (16)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 16, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - symbol size testing (24)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 24, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - symbol size testing (32)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 32, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - buffers tx > rx", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_BLOCK_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_TX_GT_RX, false, false> >), Case("SPI - buffers tx < rx", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_BLOCK_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_TX_LT_RX, false, false> >), Case("SPI - frequency testing (200 kHz)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_200_KHZ, BUFFERS_COMMON, false, false> >), Case("SPI - frequency testing (2 MHz)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_2_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - frequency testing (capabilities min)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_MIN, BUFFERS_COMMON, false, false> >), Case("SPI - frequency testing (capabilities max)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_MAX, BUFFERS_COMMON, false, false> >), Case("SPI - block write", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_BLOCK_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - block write(one sym)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_BLOCK_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_TX_ONE_SYM, false, false> >), Case("SPI - hardware ss handling", one_peripheral<SPIPort, DefaultFormFactor, fpga_spi_test_common<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, true, false> >), Case("SPI - hardware ss handling(block)", one_peripheral<SPIPort, DefaultFormFactor, fpga_spi_test_common<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_BLOCK_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, true, false> >), #if DEVICE_SPI_ASYNCH Case("SPI - async mode (sw ss)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_TRANSFER_ASYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - async mode (hw ss)", one_peripheral<SPIPort, DefaultFormFactor, fpga_spi_test_common<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_TRANSFER_ASYNC, FREQ_1_MHZ, BUFFERS_COMMON, true, false> >) #endif }; utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { GREENTEA_SETUP(60, "default_auto"); return greentea_test_setup_handler(number_of_cases); } Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); int main() { Harness::run(specification); } #endif /* !DEVICE_SPI */ SPI FPGA test: Test all possible pin configurations to init SPI /* * Copyright (c) 2019, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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. */ #if !DEVICE_SPI #error [NOT_SUPPORTED] SPI not supported for this target #elif !COMPONENT_FPGA_CI_TEST_SHIELD #error [NOT_SUPPORTED] FPGA CI Test Shield is needed to run this test #elif !defined(TARGET_FF_ARDUINO) && !defined(MBED_CONF_TARGET_DEFAULT_FORM_FACTOR) #error [NOT_SUPPORTED] Test not supported for this form factor #else #include "utest/utest.h" #include "unity/unity.h" #include "greentea-client/test_env.h" #include "mbed.h" #include "SPIMasterTester.h" #include "pinmap.h" #include "hal/static_pinmap.h" #include "test_utils.h" #include "spi_fpga_test.h" using namespace utest::v1; typedef enum { TRANSFER_SPI_MASTER_WRITE_SYNC, TRANSFER_SPI_MASTER_BLOCK_WRITE_SYNC, TRANSFER_SPI_MASTER_TRANSFER_ASYNC } transfer_type_t; typedef enum { BUFFERS_COMMON, // common case rx/tx buffers are defined and have the same size BUFFERS_TX_GT_RX, // tx buffer length is greater than rx buffer length BUFFERS_TX_LT_RX, // tx buffer length is less than rx buffer length BUFFERS_TX_ONE_SYM, // one symbol only is transmitted in both directions } test_buffers_t; #define FREQ_200_KHZ (200000ull) #define FREQ_500_KHZ (500000) #define FREQ_1_MHZ (1000000) #define FREQ_2_MHZ (2000000) #define FREQ_10_MHZ (10000000ull) #define FREQ_MIN ((uint32_t)0) #define FREQ_MAX ((uint32_t)-1) #define FILL_SYM (0xF5F5F5F5) #define DUMMY_SYM (0xD5D5D5D5) #define SS_ASSERT (0) #define SS_DEASSERT (!(SS_ASSERT)) #define TEST_CAPABILITY_BIT(MASK, CAP) ((1 << CAP) & (MASK)) const int TRANSFER_COUNT = 300; SPIMasterTester tester(DefaultFormFactor::pins(), DefaultFormFactor::restricted_pins()); spi_t spi; static volatile bool async_trasfer_done; #if DEVICE_SPI_ASYNCH void spi_async_handler() { int event = spi_irq_handler_asynch(&spi); if (event & SPI_EVENT_COMPLETE) { async_trasfer_done = true; } } #endif /* Function finds SS pin for manual SS handling. */ static PinName find_ss_pin(PinName mosi, PinName miso, PinName sclk) { const PinList *ff_pins_list = pinmap_ff_default_pins(); const PinList *restricted_pins_list = pinmap_restricted_pins(); uint32_t cs_pin_idx; for (cs_pin_idx = 0; cs_pin_idx < ff_pins_list->count; cs_pin_idx++) { if (ff_pins_list->pins[cs_pin_idx] == mosi || ff_pins_list->pins[cs_pin_idx] == miso || ff_pins_list->pins[cs_pin_idx] == sclk) { continue; } bool restricted_pin = false; for (uint32_t i = 0; i < restricted_pins_list->count ; i++) { if (ff_pins_list->pins[cs_pin_idx] == restricted_pins_list->pins[i]) { restricted_pin = true; } } if (restricted_pin) { continue; } else { break; } } PinName ssel = (cs_pin_idx == ff_pins_list->count ? NC : ff_pins_list->pins[cs_pin_idx]); TEST_ASSERT_MESSAGE(ssel != NC, "Unable to find pin for Chip Select"); return ssel; } /* Function handles ss line if ss is specified. */ static void handle_ss(DigitalOut *ss, bool select) { if (ss) { if (select) { *ss = SS_ASSERT; } else { *ss = SS_DEASSERT; } } } /* Auxiliary function to check platform capabilities against test case. */ static bool check_capabilities(const spi_capabilities_t *capabilities, SPITester::SpiMode spi_mode, uint32_t sym_size, transfer_type_t transfer_type, uint32_t frequency, test_buffers_t test_buffers) { // Symbol size if (!TEST_CAPABILITY_BIT(capabilities->word_length, (sym_size - 1))) { utest_printf("\n<Specified symbol size is not supported on this platform> skipped. "); return false; } // SPI clock mode if (!TEST_CAPABILITY_BIT(capabilities->clk_modes, spi_mode)) { utest_printf("\n<Specified spi clock mode is not supported on this platform> skipped. "); return false; } // Frequency if (frequency != FREQ_MAX && frequency != FREQ_MIN && frequency < capabilities->minimum_frequency && frequency > capabilities->maximum_frequency) { utest_printf("\n<Specified frequency is not supported on this platform> skipped. "); return false; } // Async mode if (transfer_type == TRANSFER_SPI_MASTER_TRANSFER_ASYNC && capabilities->async_mode == false) { utest_printf("\n<Async mode is not supported on this platform> skipped. "); return false; } if ((test_buffers == BUFFERS_TX_GT_RX || test_buffers == BUFFERS_TX_LT_RX) && capabilities->tx_rx_buffers_equal_length == true) { utest_printf("\n<RX length != TX length is not supported on this platform> skipped. "); return false; } return true; } void fpga_spi_test_init_free(PinName mosi, PinName miso, PinName sclk, PinName ssel) { spi_init(&spi, mosi, miso, sclk, ssel); spi_format(&spi, 8, 0, 0); spi_frequency(&spi, 1000000); spi_free(&spi); } void fpga_spi_test_init_free_cs_nc(PinName mosi, PinName miso, PinName sclk) { spi_init(&spi, mosi, miso, sclk, NC); spi_format(&spi, 8, 0, 0); spi_frequency(&spi, 1000000); spi_free(&spi); } void fpga_spi_test_init_free_cs_nc_miso_nc_mosi_nc(PinName mosi, PinName miso, PinName sclk) { utest_printf("\nTesting: MOSI = NC. "); spi_init(&spi, NC, miso, sclk, NC); spi_format(&spi, 8, 0, 0); spi_frequency(&spi, 1000000); spi_free(&spi); utest_printf("Testing: MISO = NC. "); spi_init(&spi, mosi, NC, sclk, NC); spi_format(&spi, 8, 0, 0); spi_frequency(&spi, 1000000); spi_free(&spi); } void fpga_spi_test_common(PinName mosi, PinName miso, PinName sclk, PinName ssel, SPITester::SpiMode spi_mode, uint32_t sym_size, transfer_type_t transfer_type, uint32_t frequency, test_buffers_t test_buffers, bool auto_ss, bool init_direct) { spi_capabilities_t capabilities; uint32_t freq = frequency; uint32_t tx_cnt = TRANSFER_COUNT; uint32_t rx_cnt = TRANSFER_COUNT; uint8_t fill_symbol = (uint8_t)FILL_SYM; PinName ss_pin = (auto_ss ? ssel : NC); DigitalOut *ss = NULL; spi_get_capabilities(ssel, false, &capabilities); if (check_capabilities(&capabilities, spi_mode, sym_size, transfer_type, frequency, test_buffers) == false) { return; } uint32_t sym_mask = ((1 << sym_size) - 1); switch (frequency) { case (FREQ_MIN): freq = capabilities.minimum_frequency; break; case (FREQ_MAX): freq = capabilities.maximum_frequency; break; default: break; } switch (test_buffers) { case (BUFFERS_COMMON): // nothing to change break; case (BUFFERS_TX_GT_RX): rx_cnt /= 2; break; case (BUFFERS_TX_LT_RX): tx_cnt /= 2; break; case (BUFFERS_TX_ONE_SYM): tx_cnt = 1; rx_cnt = 1; break; default: break; } // Remap pins for test tester.reset(); tester.pin_map_set(mosi, MbedTester::LogicalPinSPIMosi); tester.pin_map_set(miso, MbedTester::LogicalPinSPIMiso); tester.pin_map_set(sclk, MbedTester::LogicalPinSPISclk); tester.pin_map_set(ssel, MbedTester::LogicalPinSPISsel); // Manually handle SS pin if (!auto_ss) { ss = new DigitalOut(ssel, SS_DEASSERT); } if (init_direct) { const spi_pinmap_t pinmap = get_spi_pinmap(mosi, miso, sclk, ss_pin); spi_init_direct(&spi, &pinmap); } else { spi_init(&spi, mosi, miso, sclk, ss_pin); } spi_format(&spi, sym_size, spi_mode, 0); spi_frequency(&spi, freq); // Configure spi_slave module tester.set_mode(spi_mode); tester.set_bit_order(SPITester::MSBFirst); tester.set_sym_size(sym_size); // Reset tester stats and select SPI tester.peripherals_reset(); tester.select_peripheral(SPITester::PeripheralSPI); uint32_t checksum = 0; uint32_t sym_count = TRANSFER_COUNT; int result = 0; uint8_t tx_buf[TRANSFER_COUNT] = {0}; uint8_t rx_buf[TRANSFER_COUNT] = {0}; // Send and receive test data switch (transfer_type) { case TRANSFER_SPI_MASTER_WRITE_SYNC: handle_ss(ss, true); for (int i = 0; i < TRANSFER_COUNT; i++) { uint32_t data = spi_master_write(&spi, (0 - i) & sym_mask); TEST_ASSERT_EQUAL(i & sym_mask, data); checksum += (0 - i) & sym_mask; } handle_ss(ss, false); break; case TRANSFER_SPI_MASTER_BLOCK_WRITE_SYNC: for (int i = 0; i < TRANSFER_COUNT; i++) { tx_buf[i] = (0 - i) & sym_mask; rx_buf[i] = 0xFF; switch (test_buffers) { case (BUFFERS_COMMON): case (BUFFERS_TX_GT_RX): checksum += ((0 - i) & sym_mask); break; case (BUFFERS_TX_LT_RX): if (i < tx_cnt) { checksum += ((0 - i) & sym_mask); } else { checksum += (fill_symbol & sym_mask); } break; case (BUFFERS_TX_ONE_SYM): tx_buf[0] = 0xAA; checksum = 0xAA; sym_count = 1; break; default: break; } } handle_ss(ss, true); result = spi_master_block_write(&spi, (const char *)tx_buf, tx_cnt, (char *)rx_buf, rx_cnt, 0xF5); handle_ss(ss, false); for (int i = 0; i < rx_cnt; i++) { TEST_ASSERT_EQUAL(i & sym_mask, rx_buf[i]); } for (int i = rx_cnt; i < TRANSFER_COUNT; i++) { TEST_ASSERT_EQUAL(0xFF, rx_buf[i]); } TEST_ASSERT_EQUAL(sym_count, result); break; #if DEVICE_SPI_ASYNCH case TRANSFER_SPI_MASTER_TRANSFER_ASYNC: for (int i = 0; i < TRANSFER_COUNT; i++) { tx_buf[i] = (0 - i) & sym_mask; checksum += (0 - i) & sym_mask; rx_buf[i] = 0xAA; } async_trasfer_done = false; handle_ss(ss, true); spi_master_transfer(&spi, tx_buf, TRANSFER_COUNT, rx_buf, TRANSFER_COUNT, 8, (uint32_t)spi_async_handler, SPI_EVENT_COMPLETE, DMA_USAGE_NEVER); while (!async_trasfer_done); handle_ss(ss, false); for (int i = 0; i < TRANSFER_COUNT; i++) { TEST_ASSERT_EQUAL(i & sym_mask, rx_buf[i]); } break; #endif default: TEST_ASSERT_MESSAGE(0, "Unsupported transfer type."); break; } // Verify that the transfer was successful TEST_ASSERT_EQUAL(sym_count, tester.get_transfer_count()); TEST_ASSERT_EQUAL(checksum, tester.get_receive_checksum()); spi_free(&spi); tester.reset(); } template<SPITester::SpiMode spi_mode, uint32_t sym_size, transfer_type_t transfer_type, uint32_t frequency, test_buffers_t test_buffers, bool auto_ss, bool init_direct> void fpga_spi_test_common(PinName mosi, PinName miso, PinName sclk, PinName ssel) { fpga_spi_test_common(mosi, miso, sclk, ssel, spi_mode, sym_size, transfer_type, frequency, test_buffers, auto_ss, init_direct); } template<SPITester::SpiMode spi_mode, uint32_t sym_size, transfer_type_t transfer_type, uint32_t frequency, test_buffers_t test_buffers, bool auto_ss, bool init_direct> void fpga_spi_test_common_no_ss(PinName mosi, PinName miso, PinName sclk) { PinName ssel = find_ss_pin(mosi, miso, sclk); fpga_spi_test_common(mosi, miso, sclk, ssel, spi_mode, sym_size, transfer_type, frequency, test_buffers, auto_ss, init_direct); } Case cases[] = { // This will be run for all pins Case("SPI - init/free test all pins", all_ports<SPIPort, DefaultFormFactor, fpga_spi_test_init_free>), Case("SPI - init/free test all pins (CS == NC)", all_ports<SPINoCSPort, DefaultFormFactor, fpga_spi_test_init_free_cs_nc>), Case("SPI - init/free test all pins (CS == NC, MISO/MOSI == NC)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_init_free_cs_nc_miso_nc_mosi_nc>), // This will be run for all peripherals Case("SPI - basic test", all_peripherals<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - basic test (direct init)", all_peripherals<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, true> >), // This will be run for single pin configuration Case("SPI - mode testing (MODE_1)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode1, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - mode testing (MODE_2)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode2, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - mode testing (MODE_3)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode3, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - symbol size testing (4)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 4, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - symbol size testing (12)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 12, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - symbol size testing (16)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 16, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - symbol size testing (24)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 24, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - symbol size testing (32)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 32, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - buffers tx > rx", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_BLOCK_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_TX_GT_RX, false, false> >), Case("SPI - buffers tx < rx", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_BLOCK_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_TX_LT_RX, false, false> >), Case("SPI - frequency testing (200 kHz)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_200_KHZ, BUFFERS_COMMON, false, false> >), Case("SPI - frequency testing (2 MHz)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_2_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - frequency testing (capabilities min)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_MIN, BUFFERS_COMMON, false, false> >), Case("SPI - frequency testing (capabilities max)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_MAX, BUFFERS_COMMON, false, false> >), Case("SPI - block write", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_BLOCK_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - block write(one sym)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_BLOCK_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_TX_ONE_SYM, false, false> >), Case("SPI - hardware ss handling", one_peripheral<SPIPort, DefaultFormFactor, fpga_spi_test_common<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, true, false> >), Case("SPI - hardware ss handling(block)", one_peripheral<SPIPort, DefaultFormFactor, fpga_spi_test_common<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_BLOCK_WRITE_SYNC, FREQ_1_MHZ, BUFFERS_COMMON, true, false> >), #if DEVICE_SPI_ASYNCH Case("SPI - async mode (sw ss)", one_peripheral<SPINoCSPort, DefaultFormFactor, fpga_spi_test_common_no_ss<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_TRANSFER_ASYNC, FREQ_1_MHZ, BUFFERS_COMMON, false, false> >), Case("SPI - async mode (hw ss)", one_peripheral<SPIPort, DefaultFormFactor, fpga_spi_test_common<SPITester::Mode0, 8, TRANSFER_SPI_MASTER_TRANSFER_ASYNC, FREQ_1_MHZ, BUFFERS_COMMON, true, false> >) #endif }; utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { GREENTEA_SETUP(60, "default_auto"); return greentea_test_setup_handler(number_of_cases); } Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); int main() { Harness::run(specification); } #endif /* !DEVICE_SPI */
#include <stdio.h> #include <stdexcept> #include <QMutexLocker> #include <Utils.hpp> #include "../firmware/common2015/drivers/cc1201/ti/defines.hpp" #include "USBRadio.hpp" // Include this file for base station usb vendor/product ids #include "../firmware/base2015/usb-interface.hpp" using namespace std; using namespace Packet; // Timeout for control transfers, in milliseconds static const int Control_Timeout = 1000; USBRadio::USBRadio() : _mutex(QMutex::Recursive) { _sequence = 0; _printedError = false; _device = nullptr; _usb_context = nullptr; libusb_init(&_usb_context); for (int i = 0; i < NumRXTransfers; ++i) { _rxTransfers[i] = libusb_alloc_transfer(0); } } USBRadio::~USBRadio() { if (_device) { libusb_close(_device); } for (int i = 0; i < NumRXTransfers; ++i) { libusb_free_transfer(_rxTransfers[i]); } libusb_exit(_usb_context); } bool USBRadio::open() { libusb_device** devices = nullptr; ssize_t numDevices = libusb_get_device_list(_usb_context, &devices); if (numDevices < 0) { fprintf(stderr, "libusb_get_device_list failed\n"); return false; } int numRadios = 0; for (int i = 0; i < numDevices; ++i) { struct libusb_device_descriptor desc; int err = libusb_get_device_descriptor(devices[i], &desc); if (err == 0 && desc.idVendor == RJ_BASE2015_VENDOR_ID && desc.idProduct == RJ_BASE2015_PRODUCT_ID) { ++numRadios; int err = libusb_open(devices[i], &_device); if (err == 0) { break; } } } libusb_free_device_list(devices, 1); if (!numRadios) { if (!_printedError) { fprintf(stderr, "USBRadio: No radio is connected\n"); _printedError = true; } return false; } if (!_device) { if (!_printedError) { fprintf(stderr, "USBRadio: All radios are in use\n"); _printedError = true; } return false; } if (libusb_set_configuration(_device, 1)) { if (!_printedError) { fprintf(stderr, "USBRadio: Can't set configuration\n"); _printedError = true; } return false; } if (libusb_claim_interface(_device, 0)) { if (!_printedError) { fprintf(stderr, "USBRadio: Can't claim interface\n"); _printedError = true; } return false; } channel(_channel); // Start the receive transfers for (int i = 0; i < NumRXTransfers; ++i) { // Populate the required libusb_transfer fields for a bulk transfer. libusb_fill_bulk_transfer( _rxTransfers[i], // the transfer to populate _device, // handle of the device that will handle the transfer LIBUSB_ENDPOINT_IN | 2, // address of the endpoint where this transfer will be sent _rxBuffers[i], // data buffer rtp::Reverse_Size + 2, // length of data buffer rxCompleted, // callback function to be invoked on transfer // completion this, // user data to pass to callback function 0); // timeout for the transfer in milliseconds libusb_submit_transfer(_rxTransfers[i]); } _printedError = false; return true; } void USBRadio::rxCompleted(libusb_transfer* transfer) { USBRadio* radio = (USBRadio*)transfer->user_data; if (transfer->status == LIBUSB_TRANSFER_COMPLETED && transfer->actual_length == sizeof(rtp::RobotStatusMessage)) { // Parse the packet and add to the list of RadioRx's radio->handleRxData(transfer->buffer); } else { cerr << "bad rx from usbradio" << endl; // TODO: remove } // Restart the transfer libusb_submit_transfer(transfer); } void USBRadio::command(uint8_t cmd) { if (libusb_control_transfer(_device, LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR, Base2015ControlCommand::RadioStrobe, 0, cmd, nullptr, 0, Control_Timeout)) { throw runtime_error("USBRadio::command control write failed"); } } void USBRadio::write(uint8_t reg, uint8_t value) { if (libusb_control_transfer(_device, LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR, Base2015ControlCommand::RadioWriteRegister, value, reg, nullptr, 0, Control_Timeout)) { throw runtime_error("USBRadio::write control write failed"); } } uint8_t USBRadio::read(uint8_t reg) { uint8_t value = 0; if (libusb_control_transfer(_device, LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR, Base2015ControlCommand::RadioReadRegister, 0, reg, &value, 1, Control_Timeout)) { throw runtime_error("USBRadio::read control write failed"); } return value; } bool USBRadio::isOpen() const { return _device; } void USBRadio::send(Packet::RadioTx& packet) { QMutexLocker lock(&_mutex); if (!_device) { if (!open()) { return; } } uint8_t forward_packet[rtp::Forward_Size]; // ensure Forward_Size is correct static_assert(sizeof(rtp::header_data) + 6 * sizeof(rtp::ControlMessage) == rtp::Forward_Size, "Forward packet contents exceeds buffer size"); // Unit conversions static const float Seconds_Per_Cycle = 0.005f; static const float Meters_Per_Tick = 0.026f * 2 * M_PI / 6480.0f; static const float Radians_Per_Tick = 0.026f * M_PI / (0.0812f * 3240.0f); rtp::header_data* header = (rtp::header_data*)forward_packet; header->port = rtp::Port::CONTROL; header->address = rtp::BROADCAST_ADDRESS; header->type = rtp::header_data::Type::Control; // Build a forward packet for (int slot = 0; slot < 6; ++slot) { // Calculate the offset into the @forward_packet for this robot's // control message and cast it to a ControlMessage pointer for easy // access size_t offset = sizeof(rtp::header_data) + slot * sizeof(rtp::ControlMessage); rtp::ControlMessage* msg = (rtp::ControlMessage*)(forward_packet + offset); if (slot < packet.robots_size()) { const Packet::Control& robot = packet.robots(slot).control(); // TODO: clarify units/resolution float bodyVelX = robot.xvelocity() * Seconds_Per_Cycle / Meters_Per_Tick / sqrtf(2); float bodyVelY = robot.yvelocity() * Seconds_Per_Cycle / Meters_Per_Tick / sqrtf(2); float bodyVelW = robot.avelocity() * Seconds_Per_Cycle / Radians_Per_Tick; msg->uid = packet.robots(slot).uid(); msg->bodyX = clamp((int)roundf(bodyVelX), -511, 511); msg->bodyY = clamp((int)roundf(bodyVelY), -511, 511); msg->bodyW = clamp((int)roundf(bodyVelW), -511, 511); msg->dribbler = max(0, min(255, static_cast<uint16_t>(robot.dvelocity()) * 2)); msg->kickStrength = robot.kcstrength(); msg->shootMode = robot.shootmode(); msg->triggerMode = robot.triggermode(); msg->song = robot.song(); } else { // empty slot msg->uid = 0; } } _sequence = (_sequence + 1) & 7; // TODO(justin): remove this. skip every other packet because the system // can't handle 60Hz. Not sure exactly where the bottleneck is - this // definitely needs to be invesitgated. If this rate-limit is removed and // we try to send at 60Hz, we get TX buffer overflows in the base station. if (_sequence % 2 == 0) return; // Send the forward packet int sent = 0; int transferRetCode = libusb_bulk_transfer(_device, LIBUSB_ENDPOINT_OUT | 2, forward_packet, sizeof(forward_packet), &sent, Control_Timeout); if (transferRetCode != LIBUSB_SUCCESS || sent != sizeof(forward_packet)) { fprintf(stderr, "USBRadio: Bulk write failed\n"); if (transferRetCode != LIBUSB_SUCCESS) fprintf(stderr, " Error: '%s'\n", libusb_error_name(transferRetCode)); libusb_close(_device); _device = nullptr; } } void USBRadio::receive() { QMutexLocker lock(&_mutex); if (!_device) { if (!open()) { return; } } // Handle USB events. This will call callbacks. struct timeval tv = {0, 0}; libusb_handle_events_timeout(_usb_context, &tv); } void USBRadio::handleRxData(uint8_t* buf) { RJ::Time rx_time = RJ::timestamp(); // TODO(justin): should the packet be populated before putting into the // queue? _reversePackets.push_back(RadioRx()); RadioRx& packet = _reversePackets.back(); // TODO(justin): check size of buf? rtp::RobotStatusMessage* msg = (rtp::RobotStatusMessage*)buf; // TODO(justin): add back missing fields packet.set_timestamp(rx_time); packet.set_robot_id(msg->uid); // packet.set_rssi((int8_t)buf[1] / 2.0 - 74); packet.set_battery(msg->battVoltage); // packet.set_kicker_status(buf[3]); // // Drive motor status // for (int i = 0; i < 4; ++i) { // packet.add_motor_status(MotorStatus((buf[4] >> (i * 2)) & 3)); // } // Dribbler status // packet.add_motor_status(MotorStatus(buf[5] & 3)); // Hardware version // if (buf[5] & (1 << 4)) { // packet.set_hardware_version(RJ2008); // } else { // packet.set_hardware_version(RJ2011); // } // packet.set_ball_sense_status(BallSenseStatus((buf[5] >> 2) & 3)); // packet.set_kicker_voltage(buf[6]); #if 0 // Encoders for (int i = 0; i < 4; ++i) { int high = (buf[10] >> (i * 2)) & 3; int16_t value = buf[6 + i] | (high << 8); if (high & 2) { value |= 0xfc00; } packet.add_encoders(value); } #endif #if 0 if (buf[5] & (1 << 5)) { // Quaternion int16_t q0 = buf[7] | (buf[8] << 8); int16_t q1 = buf[9] | (buf[10] << 8); int16_t q2 = buf[11] | (buf[12] << 8); int16_t q3 = buf[13] | (buf[14] << 8); packet.mutable_quaternion()->set_q0(q0 / 16384.0); packet.mutable_quaternion()->set_q1(q1 / 16384.0); packet.mutable_quaternion()->set_q2(q2 / 16384.0); packet.mutable_quaternion()->set_q3(q3 / 16384.0); } #endif } void USBRadio::channel(int n) { QMutexLocker lock(&_mutex); if (_device) { // TODO(justin): fix // write(CHANNR, n); // throw std::runtime_error("Channel-setting not implemented for // cc1201"); command(CC1201_STROBE_SIDLE); command(CC1201_STROBE_SRX); } Radio::channel(n); } remove old encoder and quaternion packet data handling #include <stdio.h> #include <stdexcept> #include <QMutexLocker> #include <Utils.hpp> #include "../firmware/common2015/drivers/cc1201/ti/defines.hpp" #include "USBRadio.hpp" // Include this file for base station usb vendor/product ids #include "../firmware/base2015/usb-interface.hpp" using namespace std; using namespace Packet; // Timeout for control transfers, in milliseconds static const int Control_Timeout = 1000; USBRadio::USBRadio() : _mutex(QMutex::Recursive) { _sequence = 0; _printedError = false; _device = nullptr; _usb_context = nullptr; libusb_init(&_usb_context); for (int i = 0; i < NumRXTransfers; ++i) { _rxTransfers[i] = libusb_alloc_transfer(0); } } USBRadio::~USBRadio() { if (_device) { libusb_close(_device); } for (int i = 0; i < NumRXTransfers; ++i) { libusb_free_transfer(_rxTransfers[i]); } libusb_exit(_usb_context); } bool USBRadio::open() { libusb_device** devices = nullptr; ssize_t numDevices = libusb_get_device_list(_usb_context, &devices); if (numDevices < 0) { fprintf(stderr, "libusb_get_device_list failed\n"); return false; } int numRadios = 0; for (int i = 0; i < numDevices; ++i) { struct libusb_device_descriptor desc; int err = libusb_get_device_descriptor(devices[i], &desc); if (err == 0 && desc.idVendor == RJ_BASE2015_VENDOR_ID && desc.idProduct == RJ_BASE2015_PRODUCT_ID) { ++numRadios; int err = libusb_open(devices[i], &_device); if (err == 0) { break; } } } libusb_free_device_list(devices, 1); if (!numRadios) { if (!_printedError) { fprintf(stderr, "USBRadio: No radio is connected\n"); _printedError = true; } return false; } if (!_device) { if (!_printedError) { fprintf(stderr, "USBRadio: All radios are in use\n"); _printedError = true; } return false; } if (libusb_set_configuration(_device, 1)) { if (!_printedError) { fprintf(stderr, "USBRadio: Can't set configuration\n"); _printedError = true; } return false; } if (libusb_claim_interface(_device, 0)) { if (!_printedError) { fprintf(stderr, "USBRadio: Can't claim interface\n"); _printedError = true; } return false; } channel(_channel); // Start the receive transfers for (int i = 0; i < NumRXTransfers; ++i) { // Populate the required libusb_transfer fields for a bulk transfer. libusb_fill_bulk_transfer( _rxTransfers[i], // the transfer to populate _device, // handle of the device that will handle the transfer LIBUSB_ENDPOINT_IN | 2, // address of the endpoint where this transfer will be sent _rxBuffers[i], // data buffer rtp::Reverse_Size + 2, // length of data buffer rxCompleted, // callback function to be invoked on transfer // completion this, // user data to pass to callback function 0); // timeout for the transfer in milliseconds libusb_submit_transfer(_rxTransfers[i]); } _printedError = false; return true; } void USBRadio::rxCompleted(libusb_transfer* transfer) { USBRadio* radio = (USBRadio*)transfer->user_data; if (transfer->status == LIBUSB_TRANSFER_COMPLETED && transfer->actual_length == sizeof(rtp::RobotStatusMessage)) { // Parse the packet and add to the list of RadioRx's radio->handleRxData(transfer->buffer); } else { cerr << "bad rx from usbradio" << endl; // TODO: remove } // Restart the transfer libusb_submit_transfer(transfer); } void USBRadio::command(uint8_t cmd) { if (libusb_control_transfer(_device, LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR, Base2015ControlCommand::RadioStrobe, 0, cmd, nullptr, 0, Control_Timeout)) { throw runtime_error("USBRadio::command control write failed"); } } void USBRadio::write(uint8_t reg, uint8_t value) { if (libusb_control_transfer(_device, LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR, Base2015ControlCommand::RadioWriteRegister, value, reg, nullptr, 0, Control_Timeout)) { throw runtime_error("USBRadio::write control write failed"); } } uint8_t USBRadio::read(uint8_t reg) { uint8_t value = 0; if (libusb_control_transfer(_device, LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR, Base2015ControlCommand::RadioReadRegister, 0, reg, &value, 1, Control_Timeout)) { throw runtime_error("USBRadio::read control write failed"); } return value; } bool USBRadio::isOpen() const { return _device; } void USBRadio::send(Packet::RadioTx& packet) { QMutexLocker lock(&_mutex); if (!_device) { if (!open()) { return; } } uint8_t forward_packet[rtp::Forward_Size]; // ensure Forward_Size is correct static_assert(sizeof(rtp::header_data) + 6 * sizeof(rtp::ControlMessage) == rtp::Forward_Size, "Forward packet contents exceeds buffer size"); // Unit conversions static const float Seconds_Per_Cycle = 0.005f; static const float Meters_Per_Tick = 0.026f * 2 * M_PI / 6480.0f; static const float Radians_Per_Tick = 0.026f * M_PI / (0.0812f * 3240.0f); rtp::header_data* header = (rtp::header_data*)forward_packet; header->port = rtp::Port::CONTROL; header->address = rtp::BROADCAST_ADDRESS; header->type = rtp::header_data::Type::Control; // Build a forward packet for (int slot = 0; slot < 6; ++slot) { // Calculate the offset into the @forward_packet for this robot's // control message and cast it to a ControlMessage pointer for easy // access size_t offset = sizeof(rtp::header_data) + slot * sizeof(rtp::ControlMessage); rtp::ControlMessage* msg = (rtp::ControlMessage*)(forward_packet + offset); if (slot < packet.robots_size()) { const Packet::Control& robot = packet.robots(slot).control(); // TODO: clarify units/resolution float bodyVelX = robot.xvelocity() * Seconds_Per_Cycle / Meters_Per_Tick / sqrtf(2); float bodyVelY = robot.yvelocity() * Seconds_Per_Cycle / Meters_Per_Tick / sqrtf(2); float bodyVelW = robot.avelocity() * Seconds_Per_Cycle / Radians_Per_Tick; msg->uid = packet.robots(slot).uid(); msg->bodyX = clamp((int)roundf(bodyVelX), -511, 511); msg->bodyY = clamp((int)roundf(bodyVelY), -511, 511); msg->bodyW = clamp((int)roundf(bodyVelW), -511, 511); msg->dribbler = max(0, min(255, static_cast<uint16_t>(robot.dvelocity()) * 2)); msg->kickStrength = robot.kcstrength(); msg->shootMode = robot.shootmode(); msg->triggerMode = robot.triggermode(); msg->song = robot.song(); } else { // empty slot msg->uid = 0; } } _sequence = (_sequence + 1) & 7; // TODO(justin): remove this. skip every other packet because the system // can't handle 60Hz. Not sure exactly where the bottleneck is - this // definitely needs to be invesitgated. If this rate-limit is removed and // we try to send at 60Hz, we get TX buffer overflows in the base station. if (_sequence % 2 == 0) return; // Send the forward packet int sent = 0; int transferRetCode = libusb_bulk_transfer(_device, LIBUSB_ENDPOINT_OUT | 2, forward_packet, sizeof(forward_packet), &sent, Control_Timeout); if (transferRetCode != LIBUSB_SUCCESS || sent != sizeof(forward_packet)) { fprintf(stderr, "USBRadio: Bulk write failed\n"); if (transferRetCode != LIBUSB_SUCCESS) fprintf(stderr, " Error: '%s'\n", libusb_error_name(transferRetCode)); libusb_close(_device); _device = nullptr; } } void USBRadio::receive() { QMutexLocker lock(&_mutex); if (!_device) { if (!open()) { return; } } // Handle USB events. This will call callbacks. struct timeval tv = {0, 0}; libusb_handle_events_timeout(_usb_context, &tv); } void USBRadio::handleRxData(uint8_t* buf) { RJ::Time rx_time = RJ::timestamp(); // TODO(justin): should the packet be populated before putting into the // queue? _reversePackets.push_back(RadioRx()); RadioRx& packet = _reversePackets.back(); // TODO(justin): check size of buf? rtp::RobotStatusMessage* msg = (rtp::RobotStatusMessage*)buf; // TODO(justin): add back missing fields packet.set_timestamp(rx_time); packet.set_robot_id(msg->uid); // packet.set_rssi((int8_t)buf[1] / 2.0 - 74); packet.set_battery(msg->battVoltage); // packet.set_kicker_status(buf[3]); // // Drive motor status // for (int i = 0; i < 4; ++i) { // packet.add_motor_status(MotorStatus((buf[4] >> (i * 2)) & 3)); // } // Dribbler status // packet.add_motor_status(MotorStatus(buf[5] & 3)); // Hardware version // if (buf[5] & (1 << 4)) { // packet.set_hardware_version(RJ2008); // } else { // packet.set_hardware_version(RJ2011); // } // packet.set_ball_sense_status(BallSenseStatus((buf[5] >> 2) & 3)); // packet.set_kicker_voltage(buf[6]); } void USBRadio::channel(int n) { QMutexLocker lock(&_mutex); if (_device) { // TODO(justin): fix // write(CHANNR, n); // throw std::runtime_error("Channel-setting not implemented for // cc1201"); command(CC1201_STROBE_SIDLE); command(CC1201_STROBE_SRX); } Radio::channel(n); }
#include "clockUtils/sockets/TcpSocket.h" #if CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_WIN32 #include <WinSock2.h> typedef int32_t socklen_t; #elif CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_LINUX #include <arpa/inet.h> #include <cstring> #include <fcntl.h> #include <netdb.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #endif #include <errno.h> #include <thread> #include "clockUtils/errors.h" namespace clockUtils { namespace sockets { TcpSocket::TcpSocket(int fd) : TcpSocket() { _sock = fd; _status = SocketStatus::CONNECTED; std::thread thrd([this]() { while (1) { _todoLock.lock(); while(_todo.size() > 0) { std::vector<uint8_t> tmp = _todo.front(); _todo.pop(); _todoLock.unlock(); writePacket(const_cast<const unsigned char *>(&tmp[0]), tmp.size()); _todoLock.lock(); } _todoLock.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } }); thrd.detach(); } ClockError TcpSocket::listen(uint16_t listenPort, int maxParallelConnections, bool acceptMultiple, const acceptCallback acb) { if (listenPort == 0) { return ClockError::INVALID_PORT; } if (_status != SocketStatus::INACTIVE) { return ClockError::INVALID_USAGE; } if (maxParallelConnections < 0) { return ClockError::INVALID_ARGUMENT; } _sock = socket(PF_INET, SOCK_STREAM, 0); if (-1 == _sock) { return ClockError::CONNECTION_FAILED; } // set reusable #if CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_WIN32 char flag = 1; #elif CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_LINUX int flag = 1; #endif setsockopt(_sock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)); struct sockaddr_in name = { AF_INET, htons(listenPort), INADDR_ANY, {0} }; errno = 0; if (-1 == bind(_sock, reinterpret_cast<struct sockaddr *>(&name), sizeof(name))) { ClockError error = getLastError(); close(); return error; } errno = 0; if (-1 == ::listen(_sock, maxParallelConnections)) { ClockError error = getLastError(); close(); return error; } std::thread thrd([acceptMultiple, acb, this]() { if (acceptMultiple) { while(1) { errno = 0; int clientSock = ::accept(_sock, nullptr, nullptr); if (clientSock == -1) { close(); return; } std::thread thrd2(std::bind(acb, new TcpSocket(clientSock))); thrd2.detach(); } } else { int clientSock = ::accept(_sock, nullptr, nullptr); close(); if (clientSock == -1) { return; } acb(new TcpSocket(clientSock)); } }); thrd.detach(); _status = SocketStatus::LISTENING; return ClockError::SUCCESS; } ClockError TcpSocket::connect(const std::string & remoteIP, uint16_t remotePort, unsigned int timeout) { if (_status != SocketStatus::INACTIVE) { return ClockError::INVALID_USAGE; } if (remotePort == 0) { return ClockError::INVALID_PORT; } if (remoteIP.length() < 8) { return ClockError::INVALID_IP; } errno = 0; _sock = socket(PF_INET, SOCK_STREAM, 0); if (_sock == -1) { return getLastError(); } sockaddr_in addr; memset(&addr, 0, sizeof(sockaddr_in)); addr.sin_family = AF_INET; addr.sin_port = htons(remotePort); addr.sin_addr.s_addr = inet_addr(remoteIP.c_str()); if (addr.sin_addr.s_addr == INADDR_NONE || addr.sin_addr.s_addr == INADDR_ANY) { close(); return ClockError::INVALID_IP; } // set socket non-blockable #if CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_WIN32 u_long iMode = 1; ioctlsocket(_sock, FIONBIO, &iMode); #elif CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_LINUX long arg = fcntl(_sock, F_GETFL, NULL); arg |= O_NONBLOCK; fcntl(_sock, F_SETFL, arg); #endif // connect errno = 0; if (-1 == ::connect(_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(sockaddr))) { ClockError error = getLastError(); if (error == ClockError::IN_PROGRESS) { // connect still in progress. wait for completion with timeout struct timeval tv; fd_set myset; tv.tv_sec = timeout / 1000; tv.tv_usec = (timeout % 1000) * 1000; FD_ZERO(&myset); FD_SET(_sock, &myset); if (select(_sock + 1, NULL, &myset, NULL, &tv) > 0) { socklen_t lon = sizeof(int); int valopt; #if CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_WIN32 getsockopt(_sock, SOL_SOCKET, SO_ERROR, reinterpret_cast<char *>(&valopt), &lon); #elif CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_LINUX getsockopt(_sock, SOL_SOCKET, SO_ERROR, static_cast<void *>(&valopt), &lon); #endif if (valopt) { close(); return ClockError::CONNECTION_FAILED; } } else { close(); return ClockError::TIMEOUT; } } else { close(); return error; } } #if CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_WIN32 iMode = 0; #elif CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_LINUX arg &= (~O_NONBLOCK); fcntl(_sock, F_SETFL, arg); #endif _status = SocketStatus::CONNECTED; return ClockError::SUCCESS; } std::string TcpSocket::getRemoteIP() const { if (_status == SocketStatus::INACTIVE) { return ""; } struct sockaddr_in localAddress; socklen_t addressLength = sizeof(localAddress); getpeername(_sock, reinterpret_cast<struct sockaddr *>(&localAddress), &addressLength); return inet_ntoa(localAddress.sin_addr); } uint16_t TcpSocket::getRemotePort() const { if (_status == SocketStatus::INACTIVE) { return 0; } struct sockaddr_in localAddress; socklen_t addressLength = sizeof(localAddress); getpeername(_sock, reinterpret_cast<struct sockaddr *>(&localAddress), &addressLength); return static_cast<uint16_t>(ntohs(localAddress.sin_port)); } std::vector<std::pair<std::string, std::string>> TcpSocket::enumerateLocalIPs() { char buffer[256]; gethostname(buffer, 256); hostent * localHost = gethostbyname(buffer); std::vector<std::pair<std::string, std::string>> result; for (int i = 0; *(localHost->h_addr_list + i) != nullptr; i++) { char * localIP = inet_ntoa(*reinterpret_cast<struct in_addr *>(*(localHost->h_addr_list + i))); result.push_back(std::make_pair(std::string(localHost->h_name), std::string(localIP))); } return result; } std::string TcpSocket::getLocalIP() const { char buffer[256]; gethostname(buffer, 256); hostent * localHost = gethostbyname(buffer); char * localIP = inet_ntoa(*reinterpret_cast<struct in_addr *>(*localHost->h_addr_list)); std::string ip(localIP); return ip; } std::string TcpSocket::getPublicIP() const { if (_status == SocketStatus::INACTIVE) { return ""; } struct sockaddr_in localAddress; socklen_t addressLength = sizeof(localAddress); getsockname(_sock, reinterpret_cast<struct sockaddr *>(&localAddress), &addressLength); return inet_ntoa(localAddress.sin_addr); } uint16_t TcpSocket::getLocalPort() const { if (_status == SocketStatus::INACTIVE) { return 0; } struct sockaddr_in localAddress; socklen_t addressLength = sizeof(localAddress); getsockname(_sock, reinterpret_cast<struct sockaddr *>(&localAddress), &addressLength); return static_cast<uint16_t>(ntohs(localAddress.sin_port)); } ClockError TcpSocket::writePacket(const void * str, const uint32_t length) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } // | + size + str + | char * buf = new char[length + 6]; buf[0] = '|'; buf[1] = ((((length / 256) / 256) / 256) % 256); buf[2] = (((length / 256) / 256) % 256); buf[3] = ((length / 256) % 256); buf[4] = (length % 256); memcpy(reinterpret_cast<void *>(&buf[5]), str, length); buf[length + 5] = '|'; ClockError error = write(buf, length + 6); delete[] buf; return error; } ClockError TcpSocket::writePacket(const std::vector<uint8_t> & str) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } return writePacket(const_cast<const unsigned char *>(&str[0]), str.size()); } ClockError TcpSocket::writePacketAsync(const std::vector<uint8_t> & str) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } _todoLock.lock(); _todo.push(str); _todoLock.unlock(); return ClockError::SUCCESS; } ClockError TcpSocket::receivePacket(std::vector<uint8_t> & buffer) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } std::string s; ClockError error = receivePacket(s); if (error == ClockError::SUCCESS) { buffer = std::vector<uint8_t>(s.begin(), s.end()); } return error; } ClockError TcpSocket::receivePacket(std::string & buffer) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } std::vector<uint8_t> result(_buffer); bool skipFirstRead = !result.empty(); uint32_t length = 0; while (true) { std::vector<uint8_t> s; ClockError error = ClockError::SUCCESS; if (!skipFirstRead) { error = read(s); } if (error != ClockError::SUCCESS) { return error; } if (!skipFirstRead && s.empty()) { continue; } skipFirstRead = false; if (result.size() == 0) { if (s[0] == '|') { result = s; } else { return ClockError::UNKNOWN; } } else { result.insert(result.end(), s.begin(), s.end()); } if (length == 0) { if (result.size() >= 5) { length = static_cast<uint32_t>(result[1] * 256 * 256 * 256 + result[2] * 256 * 256 + result[3] * 256 + result[4]); } } if (result.size() >= length + 6) { buffer = std::string(result.begin() + 5, result.begin() + 5 + length); if (result.size() > length + 6) { _buffer = std::vector<uint8_t>(result.begin() + length + 6, result.end()); } else { _buffer.clear(); } return ClockError::SUCCESS; } } return ClockError::SUCCESS; } ClockError TcpSocket::write(const void * str, uint32_t length) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } #if CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_LINUX int rc = send(_sock, reinterpret_cast<const char *>(str), length, MSG_NOSIGNAL); #elif CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_WIN32 int rc = send(_sock, reinterpret_cast<const char *>(str), length, 0); #endif if (rc == -1) { return getLastError(); } else if (rc == 0) { return ClockError::NOT_CONNECTED; } return ClockError::SUCCESS; } ClockError TcpSocket::write(const std::vector<uint8_t> & str) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } return write(const_cast<const unsigned char *>(&str[0]), str.size()); } ClockError TcpSocket::read(std::vector<uint8_t> & buffer) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } unsigned char buf[256]; buffer.resize(260); int rc = -1; do { #if CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_LINUX rc = recv(_sock, &buffer[0], 256, 0); #elif CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_WIN32 rc = recv(_sock, reinterpret_cast<char *>(&buffer[0]), 256, 0); #endif if (rc == -1) { ClockError error = getLastError(); if (error == ClockError::IN_PROGRESS) { continue; } return error; } else if (rc == 0) { return ClockError::NOT_CONNECTED; } break; } while (true); buffer.resize(rc); // +1 for '\0' return ClockError::SUCCESS; } ClockError TcpSocket::read(std::string & buffer) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } char buf[256]; do { int rc = recv(_sock, buf, 256, 0); if (rc == -1) { ClockError error = getLastError(); if (error == ClockError::IN_PROGRESS) { continue; } return error; } else if (rc == 0) { return ClockError::NOT_CONNECTED; } break; } while (true); buffer = std::string(buf); return ClockError::SUCCESS; } ClockError TcpSocket::receiveCallback(packetCallback pcb) { std::thread thrd([pcb, this]() { while (1) { std::vector<uint8_t> buffer; ClockError err = receivePacket(buffer); pcb(buffer, this, err); if (err != ClockError::SUCCESS) { break; } } }); thrd.detach(); return ClockError::SUCCESS; } } /* namespace sockets */ } /* namespace clockUtils */ CU-21 cleanup after huge speed increase #include "clockUtils/sockets/TcpSocket.h" #if CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_WIN32 #include <WinSock2.h> typedef int32_t socklen_t; #elif CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_LINUX #include <arpa/inet.h> #include <cstring> #include <fcntl.h> #include <netdb.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #endif #include <errno.h> #include <thread> #include "clockUtils/errors.h" namespace clockUtils { namespace sockets { TcpSocket::TcpSocket(int fd) : TcpSocket() { _sock = fd; _status = SocketStatus::CONNECTED; std::thread thrd([this]() { while (1) { _todoLock.lock(); while(_todo.size() > 0) { std::vector<uint8_t> tmp = _todo.front(); _todo.pop(); _todoLock.unlock(); writePacket(const_cast<const unsigned char *>(&tmp[0]), tmp.size()); _todoLock.lock(); } _todoLock.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } }); thrd.detach(); } ClockError TcpSocket::listen(uint16_t listenPort, int maxParallelConnections, bool acceptMultiple, const acceptCallback acb) { if (listenPort == 0) { return ClockError::INVALID_PORT; } if (_status != SocketStatus::INACTIVE) { return ClockError::INVALID_USAGE; } if (maxParallelConnections < 0) { return ClockError::INVALID_ARGUMENT; } _sock = socket(PF_INET, SOCK_STREAM, 0); if (-1 == _sock) { return ClockError::CONNECTION_FAILED; } // set reusable #if CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_WIN32 char flag = 1; #elif CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_LINUX int flag = 1; #endif setsockopt(_sock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)); struct sockaddr_in name = { AF_INET, htons(listenPort), INADDR_ANY, {0} }; errno = 0; if (-1 == bind(_sock, reinterpret_cast<struct sockaddr *>(&name), sizeof(name))) { ClockError error = getLastError(); close(); return error; } errno = 0; if (-1 == ::listen(_sock, maxParallelConnections)) { ClockError error = getLastError(); close(); return error; } std::thread thrd([acceptMultiple, acb, this]() { if (acceptMultiple) { while(1) { errno = 0; int clientSock = ::accept(_sock, nullptr, nullptr); if (clientSock == -1) { close(); return; } std::thread thrd2(std::bind(acb, new TcpSocket(clientSock))); thrd2.detach(); } } else { int clientSock = ::accept(_sock, nullptr, nullptr); close(); if (clientSock == -1) { return; } acb(new TcpSocket(clientSock)); } }); thrd.detach(); _status = SocketStatus::LISTENING; return ClockError::SUCCESS; } ClockError TcpSocket::connect(const std::string & remoteIP, uint16_t remotePort, unsigned int timeout) { if (_status != SocketStatus::INACTIVE) { return ClockError::INVALID_USAGE; } if (remotePort == 0) { return ClockError::INVALID_PORT; } if (remoteIP.length() < 8) { return ClockError::INVALID_IP; } errno = 0; _sock = socket(PF_INET, SOCK_STREAM, 0); if (_sock == -1) { return getLastError(); } sockaddr_in addr; memset(&addr, 0, sizeof(sockaddr_in)); addr.sin_family = AF_INET; addr.sin_port = htons(remotePort); addr.sin_addr.s_addr = inet_addr(remoteIP.c_str()); if (addr.sin_addr.s_addr == INADDR_NONE || addr.sin_addr.s_addr == INADDR_ANY) { close(); return ClockError::INVALID_IP; } // set socket non-blockable #if CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_WIN32 u_long iMode = 1; ioctlsocket(_sock, FIONBIO, &iMode); #elif CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_LINUX long arg = fcntl(_sock, F_GETFL, NULL); arg |= O_NONBLOCK; fcntl(_sock, F_SETFL, arg); #endif // connect errno = 0; if (-1 == ::connect(_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(sockaddr))) { ClockError error = getLastError(); if (error == ClockError::IN_PROGRESS) { // connect still in progress. wait for completion with timeout struct timeval tv; fd_set myset; tv.tv_sec = timeout / 1000; tv.tv_usec = (timeout % 1000) * 1000; FD_ZERO(&myset); FD_SET(_sock, &myset); if (select(_sock + 1, NULL, &myset, NULL, &tv) > 0) { socklen_t lon = sizeof(int); int valopt; #if CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_WIN32 getsockopt(_sock, SOL_SOCKET, SO_ERROR, reinterpret_cast<char *>(&valopt), &lon); #elif CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_LINUX getsockopt(_sock, SOL_SOCKET, SO_ERROR, static_cast<void *>(&valopt), &lon); #endif if (valopt) { close(); return ClockError::CONNECTION_FAILED; } } else { close(); return ClockError::TIMEOUT; } } else { close(); return error; } } #if CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_WIN32 iMode = 0; #elif CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_LINUX arg &= (~O_NONBLOCK); fcntl(_sock, F_SETFL, arg); #endif _status = SocketStatus::CONNECTED; return ClockError::SUCCESS; } std::string TcpSocket::getRemoteIP() const { if (_status == SocketStatus::INACTIVE) { return ""; } struct sockaddr_in localAddress; socklen_t addressLength = sizeof(localAddress); getpeername(_sock, reinterpret_cast<struct sockaddr *>(&localAddress), &addressLength); return inet_ntoa(localAddress.sin_addr); } uint16_t TcpSocket::getRemotePort() const { if (_status == SocketStatus::INACTIVE) { return 0; } struct sockaddr_in localAddress; socklen_t addressLength = sizeof(localAddress); getpeername(_sock, reinterpret_cast<struct sockaddr *>(&localAddress), &addressLength); return static_cast<uint16_t>(ntohs(localAddress.sin_port)); } std::vector<std::pair<std::string, std::string>> TcpSocket::enumerateLocalIPs() { char buffer[256]; gethostname(buffer, 256); hostent * localHost = gethostbyname(buffer); std::vector<std::pair<std::string, std::string>> result; for (int i = 0; *(localHost->h_addr_list + i) != nullptr; i++) { char * localIP = inet_ntoa(*reinterpret_cast<struct in_addr *>(*(localHost->h_addr_list + i))); result.push_back(std::make_pair(std::string(localHost->h_name), std::string(localIP))); } return result; } std::string TcpSocket::getLocalIP() const { char buffer[256]; gethostname(buffer, 256); hostent * localHost = gethostbyname(buffer); char * localIP = inet_ntoa(*reinterpret_cast<struct in_addr *>(*localHost->h_addr_list)); std::string ip(localIP); return ip; } std::string TcpSocket::getPublicIP() const { if (_status == SocketStatus::INACTIVE) { return ""; } struct sockaddr_in localAddress; socklen_t addressLength = sizeof(localAddress); getsockname(_sock, reinterpret_cast<struct sockaddr *>(&localAddress), &addressLength); return inet_ntoa(localAddress.sin_addr); } uint16_t TcpSocket::getLocalPort() const { if (_status == SocketStatus::INACTIVE) { return 0; } struct sockaddr_in localAddress; socklen_t addressLength = sizeof(localAddress); getsockname(_sock, reinterpret_cast<struct sockaddr *>(&localAddress), &addressLength); return static_cast<uint16_t>(ntohs(localAddress.sin_port)); } ClockError TcpSocket::writePacket(const void * str, const uint32_t length) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } // | + size + str + | char * buf = new char[length + 6]; buf[0] = '|'; buf[1] = ((((length / 256) / 256) / 256) % 256); buf[2] = (((length / 256) / 256) % 256); buf[3] = ((length / 256) % 256); buf[4] = (length % 256); memcpy(reinterpret_cast<void *>(&buf[5]), str, length); buf[length + 5] = '|'; ClockError error = write(buf, length + 6); delete[] buf; return error; } ClockError TcpSocket::writePacket(const std::vector<uint8_t> & str) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } return writePacket(const_cast<const unsigned char *>(&str[0]), str.size()); } ClockError TcpSocket::writePacketAsync(const std::vector<uint8_t> & str) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } _todoLock.lock(); _todo.push(str); _todoLock.unlock(); return ClockError::SUCCESS; } ClockError TcpSocket::receivePacket(std::vector<uint8_t> & buffer) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } std::string s; ClockError error = receivePacket(s); if (error == ClockError::SUCCESS) { buffer = std::vector<uint8_t>(s.begin(), s.end()); } return error; } ClockError TcpSocket::receivePacket(std::string & buffer) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } std::vector<uint8_t> result(_buffer); bool skipFirstRead = !result.empty(); uint32_t length = 0; while (true) { std::vector<uint8_t> s; ClockError error = ClockError::SUCCESS; if (!skipFirstRead) { error = read(s); } if (error != ClockError::SUCCESS) { return error; } if (!skipFirstRead && s.empty()) { continue; } skipFirstRead = false; if (result.size() == 0) { if (s[0] == '|') { result = s; } else { return ClockError::UNKNOWN; } } else { result.insert(result.end(), s.begin(), s.end()); } if (length == 0) { if (result.size() >= 5) { length = static_cast<uint32_t>(result[1] * 256 * 256 * 256 + result[2] * 256 * 256 + result[3] * 256 + result[4]); } } if (result.size() >= length + 6) { buffer = std::string(result.begin() + 5, result.begin() + 5 + length); if (result.size() > length + 6) { _buffer = std::vector<uint8_t>(result.begin() + length + 6, result.end()); } else { _buffer.clear(); } return ClockError::SUCCESS; } } return ClockError::SUCCESS; } ClockError TcpSocket::write(const void * str, uint32_t length) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } #if CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_LINUX int rc = send(_sock, reinterpret_cast<const char *>(str), length, MSG_NOSIGNAL); #elif CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_WIN32 int rc = send(_sock, reinterpret_cast<const char *>(str), length, 0); #endif if (rc == -1) { return getLastError(); } else if (rc == 0) { return ClockError::NOT_CONNECTED; } return ClockError::SUCCESS; } ClockError TcpSocket::write(const std::vector<uint8_t> & str) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } return write(const_cast<const unsigned char *>(&str[0]), str.size()); } ClockError TcpSocket::read(std::vector<uint8_t> & buffer) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } buffer.resize(260); int rc = -1; do { #if CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_LINUX rc = recv(_sock, &buffer[0], 256, 0); #elif CLOCKUTILS_PLATFORM == CLOCKUTILS_PLATFORM_WIN32 rc = recv(_sock, reinterpret_cast<char *>(&buffer[0]), 256, 0); #endif if (rc == -1) { ClockError error = getLastError(); if (error == ClockError::IN_PROGRESS) { continue; } return error; } else if (rc == 0) { return ClockError::NOT_CONNECTED; } break; } while (true); buffer.resize(size_t(rc)); return ClockError::SUCCESS; } ClockError TcpSocket::read(std::string & buffer) { if (_status != SocketStatus::CONNECTED) { return ClockError::NOT_READY; } char buf[256]; do { int rc = recv(_sock, buf, 256, 0); if (rc == -1) { ClockError error = getLastError(); if (error == ClockError::IN_PROGRESS) { continue; } return error; } else if (rc == 0) { return ClockError::NOT_CONNECTED; } break; } while (true); buffer = std::string(buf); return ClockError::SUCCESS; } ClockError TcpSocket::receiveCallback(packetCallback pcb) { std::thread thrd([pcb, this]() { while (1) { std::vector<uint8_t> buffer; ClockError err = receivePacket(buffer); pcb(buffer, this, err); if (err != ClockError::SUCCESS) { break; } } }); thrd.detach(); return ClockError::SUCCESS; } } /* namespace sockets */ } /* namespace clockUtils */
// The MIT License (MIT) // Copyright (c) 2013-2016 Rapptz and contributors // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef SOL_DEFAULT_CONSTRUCTOR_HPP #define SOL_DEFAULT_CONSTRUCTOR_HPP #include <memory> #include "traits.hpp" namespace sol { struct default_construct { template<typename T, typename... Args> void operator()(T&& obj, Args&&... args) const { std::allocator<Unqualified<T>> alloc{}; alloc.construct(obj, std::forward<Args>(args)...); } }; template <typename T> struct placement_construct { T obj; template <typename... Args> placement_construct( Args&&... args ) : obj(std::forward<Args>(args)...) { } template<typename... Args> void operator()(Args&&... args) const { std::allocator<Unqualified<T>> alloc{}; alloc.construct(obj, std::forward<Args>(args)...); } }; } // sol #endif // SOL_DEFAULT_CONSTRUCTOR_HPP Git had a sneeze and couldn't properly remove this file...
// Copyright (c) 2011 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 "chrome/browser/crash_handler_host_linux.h" #include <stdint.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/syscall.h> #include <unistd.h> #include "base/eintr_wrapper.h" #include "base/file_path.h" #include "base/format_macros.h" #include "base/linux_util.h" #include "base/logging.h" #include "base/memory/singleton.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/rand_util.h" #include "base/string_util.h" #include "base/task.h" #include "base/threading/thread.h" #include "breakpad/src/client/linux/handler/exception_handler.h" #include "breakpad/src/client/linux/minidump_writer/linux_dumper.h" #include "breakpad/src/client/linux/minidump_writer/minidump_writer.h" #include "chrome/app/breakpad_linux.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/env_vars.h" #include "content/browser/browser_thread.h" using google_breakpad::ExceptionHandler; namespace { // The length of the control message: const unsigned kControlMsgSize = CMSG_SPACE(2*sizeof(int)) + CMSG_SPACE(sizeof(struct ucred)); // The length of the regular payload: const unsigned kCrashContextSize = sizeof(ExceptionHandler::CrashContext); // Handles the crash dump and frees the allocated BreakpadInfo struct. void CrashDumpTask(CrashHandlerHostLinux* handler, BreakpadInfo* info) { if (handler->IsShuttingDown()) return; HandleCrashDump(*info); delete[] info->filename; delete[] info->process_type; delete[] info->crash_url; delete[] info->guid; delete[] info->distro; delete info; } } // namespace // Since classes derived from CrashHandlerHostLinux are singletons, it's only // destroyed at the end of the processes lifetime, which is greater in span than // the lifetime of the IO message loop. DISABLE_RUNNABLE_METHOD_REFCOUNT(CrashHandlerHostLinux); CrashHandlerHostLinux::CrashHandlerHostLinux() : shutting_down_(false) { int fds[2]; // We use SOCK_SEQPACKET rather than SOCK_DGRAM to prevent the process from // sending datagrams to other sockets on the system. The sandbox may prevent // the process from calling socket() to create new sockets, but it'll still // inherit some sockets. With PF_UNIX+SOCK_DGRAM, it can call sendmsg to send // a datagram to any (abstract) socket on the same system. With // SOCK_SEQPACKET, this is prevented. CHECK_EQ(socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fds), 0); static const int on = 1; // Enable passcred on the server end of the socket CHECK_EQ(setsockopt(fds[1], SOL_SOCKET, SO_PASSCRED, &on, sizeof(on)), 0); process_socket_ = fds[0]; browser_socket_ = fds[1]; BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &CrashHandlerHostLinux::Init)); } CrashHandlerHostLinux::~CrashHandlerHostLinux() { HANDLE_EINTR(close(process_socket_)); HANDLE_EINTR(close(browser_socket_)); } void CrashHandlerHostLinux::Init() { MessageLoopForIO* ml = MessageLoopForIO::current(); CHECK(ml->WatchFileDescriptor( browser_socket_, true /* persistent */, MessageLoopForIO::WATCH_READ, &file_descriptor_watcher_, this)); ml->AddDestructionObserver(this); } void CrashHandlerHostLinux::InitCrashUploaderThread() { SetProcessType(); uploader_thread_.reset( new base::Thread(std::string(process_type_ + "_crash_uploader").c_str())); uploader_thread_->Start(); } void CrashHandlerHostLinux::OnFileCanWriteWithoutBlocking(int fd) { DCHECK(false); } void CrashHandlerHostLinux::OnFileCanReadWithoutBlocking(int fd) { DCHECK_EQ(fd, browser_socket_); // A process has crashed and has signaled us by writing a datagram // to the death signal socket. The datagram contains the crash context needed // for writing the minidump as well as a file descriptor and a credentials // block so that they can't lie about their pid. const size_t kIovSize = 7; struct msghdr msg = {0}; struct iovec iov[kIovSize]; char crash_context[kCrashContextSize]; char* guid = new char[kGuidSize + 1]; char* crash_url = new char[kMaxActiveURLSize + 1]; char* distro = new char[kDistroSize + 1]; char* tid_buf_addr = NULL; int tid_fd = -1; uint64_t uptime; char control[kControlMsgSize]; const ssize_t expected_msg_size = sizeof(crash_context) + kGuidSize + 1 + kMaxActiveURLSize + 1 + kDistroSize + 1 + sizeof(tid_buf_addr) + sizeof(tid_fd) + sizeof(uptime); iov[0].iov_base = crash_context; iov[0].iov_len = sizeof(crash_context); iov[1].iov_base = guid; iov[1].iov_len = kGuidSize + 1; iov[2].iov_base = crash_url; iov[2].iov_len = kMaxActiveURLSize + 1; iov[3].iov_base = distro; iov[3].iov_len = kDistroSize + 1; iov[4].iov_base = &tid_buf_addr; iov[4].iov_len = sizeof(tid_buf_addr); iov[5].iov_base = &tid_fd; iov[5].iov_len = sizeof(tid_fd); iov[6].iov_base = &uptime; iov[6].iov_len = sizeof(uptime); msg.msg_iov = iov; msg.msg_iovlen = kIovSize; msg.msg_control = control; msg.msg_controllen = kControlMsgSize; const ssize_t msg_size = HANDLE_EINTR(recvmsg(browser_socket_, &msg, 0)); if (msg_size != expected_msg_size) { LOG(ERROR) << "Error reading from death signal socket. Crash dumping" << " is disabled." << " msg_size:" << msg_size << " errno:" << errno; file_descriptor_watcher_.StopWatchingFileDescriptor(); return; } if (msg.msg_controllen != kControlMsgSize || msg.msg_flags & ~MSG_TRUNC) { LOG(ERROR) << "Received death signal message with the wrong size;" << " msg.msg_controllen:" << msg.msg_controllen << " msg.msg_flags:" << msg.msg_flags << " kCrashContextSize:" << kCrashContextSize << " kControlMsgSize:" << kControlMsgSize; return; } // Walk the control payload an extract the file descriptor and validated pid. pid_t crashing_pid = -1; int partner_fd = -1; int signal_fd = -1; for (struct cmsghdr *hdr = CMSG_FIRSTHDR(&msg); hdr; hdr = CMSG_NXTHDR(&msg, hdr)) { if (hdr->cmsg_level != SOL_SOCKET) continue; if (hdr->cmsg_type == SCM_RIGHTS) { const unsigned len = hdr->cmsg_len - (((uint8_t*)CMSG_DATA(hdr)) - (uint8_t*)hdr); DCHECK_EQ(len % sizeof(int), 0u); const unsigned num_fds = len / sizeof(int); if (num_fds != 2) { // A nasty process could try and send us too many descriptors and // force a leak. LOG(ERROR) << "Death signal contained wrong number of descriptors;" << " num_fds:" << num_fds; for (unsigned i = 0; i < num_fds; ++i) HANDLE_EINTR(close(reinterpret_cast<int*>(CMSG_DATA(hdr))[i])); return; } else { partner_fd = reinterpret_cast<int*>(CMSG_DATA(hdr))[0]; signal_fd = reinterpret_cast<int*>(CMSG_DATA(hdr))[1]; } } else if (hdr->cmsg_type == SCM_CREDENTIALS) { const struct ucred *cred = reinterpret_cast<struct ucred*>(CMSG_DATA(hdr)); crashing_pid = cred->pid; } } if (crashing_pid == -1 || partner_fd == -1 || signal_fd == -1) { LOG(ERROR) << "Death signal message didn't contain all expected control" << " messages"; if (partner_fd >= 0) HANDLE_EINTR(close(partner_fd)); if (signal_fd >= 0) HANDLE_EINTR(close(signal_fd)); return; } // Kernel bug workaround (broken in 2.6.30 at least): // The kernel doesn't translate PIDs in SCM_CREDENTIALS across PID // namespaces. Thus |crashing_pid| might be garbage from our point of view. // In the future we can remove this workaround, but we have to wait a couple // of years to be sure that it's worked its way out into the world. // The crashing process closes its copy of the signal_fd immediately after // calling sendmsg(). We can thus not reliably look for with with // FindProcessHoldingSocket(). But by necessity, it has to keep the // partner_fd open until the crashdump is complete. uint64_t inode_number; if (!base::FileDescriptorGetInode(&inode_number, partner_fd)) { LOG(WARNING) << "Failed to get inode number for passed socket"; HANDLE_EINTR(close(partner_fd)); HANDLE_EINTR(close(signal_fd)); return; } HANDLE_EINTR(close(partner_fd)); pid_t actual_crashing_pid = -1; if (!base::FindProcessHoldingSocket(&actual_crashing_pid, inode_number)) { LOG(WARNING) << "Failed to find process holding other end of crash reply " "socket"; HANDLE_EINTR(close(signal_fd)); return; } if (actual_crashing_pid != crashing_pid) { crashing_pid = actual_crashing_pid; // The crashing TID set inside the compromised context via sys_gettid() // in ExceptionHandler::HandleSignal is also wrong and needs to be // translated. // // We expect the crashing thread to be in sys_read(), waiting for use to // write to |signal_fd|. Most newer kernels where we have the different pid // namespaces also have /proc/[pid]/syscall, so we can look through // |actual_crashing_pid|'s thread group and find the thread that's in the // read syscall with the right arguments. std::string expected_syscall_data; // /proc/[pid]/syscall is formatted as follows: // syscall_number arg1 ... arg6 sp pc // but we just check syscall_number through arg3. base::StringAppendF(&expected_syscall_data, "%d 0x%x %p 0x1 ", SYS_read, tid_fd, tid_buf_addr); pid_t crashing_tid = base::FindThreadIDWithSyscall(crashing_pid, expected_syscall_data); if (crashing_tid == -1) { // We didn't find the thread we want. Maybe it didn't reach sys_read() // yet, or the kernel doesn't support /proc/[pid]/syscall or the thread // went away. We'll just take a guess here and assume the crashing // thread is the thread group leader. crashing_tid = crashing_pid; } ExceptionHandler::CrashContext* bad_context = reinterpret_cast<ExceptionHandler::CrashContext*>(crash_context); bad_context->tid = crashing_tid; } // Sanitize the string data a bit more guid[kGuidSize] = crash_url[kMaxActiveURLSize] = distro[kDistroSize] = 0; BreakpadInfo* info = new BreakpadInfo; info->process_type_length = process_type_.length(); char* process_type_str = new char[info->process_type_length + 1]; process_type_.copy(process_type_str, info->process_type_length); process_type_str[info->process_type_length] = '\0'; info->process_type = process_type_str; info->crash_url_length = strlen(crash_url); info->crash_url = crash_url; info->guid_length = strlen(guid); info->guid = guid; info->distro_length = strlen(distro); info->distro = distro; info->upload = (getenv(env_vars::kHeadless) == NULL); info->process_start_time = uptime; BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod(this, &CrashHandlerHostLinux::WriteDumpFile, info, crashing_pid, reinterpret_cast<char*>(&crash_context), signal_fd)); } void CrashHandlerHostLinux::WriteDumpFile(BreakpadInfo* info, pid_t crashing_pid, char* crash_context, int signal_fd) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); FilePath dumps_path("/tmp"); PathService::Get(base::DIR_TEMP, &dumps_path); if (!info->upload) PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path); const uint64 rand = base::RandUint64(); const std::string minidump_filename = StringPrintf("%s/chromium-%s-minidump-%016" PRIx64 ".dmp", dumps_path.value().c_str(), process_type_.c_str(), rand); if (!google_breakpad::WriteMinidump(minidump_filename.c_str(), crashing_pid, crash_context, kCrashContextSize)) { LOG(ERROR) << "Failed to write crash dump for pid " << crashing_pid; } char* minidump_filename_str = new char[minidump_filename.length() + 1]; minidump_filename.copy(minidump_filename_str, minidump_filename.length()); minidump_filename_str[minidump_filename.length()] = '\0'; info->filename = minidump_filename_str; BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &CrashHandlerHostLinux::QueueCrashDumpTask, info, signal_fd)); } void CrashHandlerHostLinux::QueueCrashDumpTask(BreakpadInfo* info, int signal_fd) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // Send the done signal to the process: it can exit now. struct msghdr msg = {0}; struct iovec done_iov; done_iov.iov_base = const_cast<char*>("\x42"); done_iov.iov_len = 1; msg.msg_iov = &done_iov; msg.msg_iovlen = 1; HANDLE_EINTR(sendmsg(signal_fd, &msg, MSG_DONTWAIT | MSG_NOSIGNAL)); HANDLE_EINTR(close(signal_fd)); uploader_thread_->message_loop()->PostTask( FROM_HERE, NewRunnableFunction(&CrashDumpTask, this, info)); } void CrashHandlerHostLinux::WillDestroyCurrentMessageLoop() { file_descriptor_watcher_.StopWatchingFileDescriptor(); // If we are quitting and there are crash dumps in the queue, turn them into // no-ops. shutting_down_ = true; uploader_thread_->Stop(); } bool CrashHandlerHostLinux::IsShuttingDown() const { return shutting_down_; } GpuCrashHandlerHostLinux::GpuCrashHandlerHostLinux() { InitCrashUploaderThread(); } GpuCrashHandlerHostLinux::~GpuCrashHandlerHostLinux() { } void GpuCrashHandlerHostLinux::SetProcessType() { process_type_ = "gpu-process"; } // static GpuCrashHandlerHostLinux* GpuCrashHandlerHostLinux::GetInstance() { return Singleton<GpuCrashHandlerHostLinux>::get(); } PluginCrashHandlerHostLinux::PluginCrashHandlerHostLinux() { InitCrashUploaderThread(); } PluginCrashHandlerHostLinux::~PluginCrashHandlerHostLinux() { } void PluginCrashHandlerHostLinux::SetProcessType() { process_type_ = "plugin"; } // static PluginCrashHandlerHostLinux* PluginCrashHandlerHostLinux::GetInstance() { return Singleton<PluginCrashHandlerHostLinux>::get(); } RendererCrashHandlerHostLinux::RendererCrashHandlerHostLinux() { InitCrashUploaderThread(); } RendererCrashHandlerHostLinux::~RendererCrashHandlerHostLinux() { } void RendererCrashHandlerHostLinux::SetProcessType() { process_type_ = "renderer"; } // static RendererCrashHandlerHostLinux* RendererCrashHandlerHostLinux::GetInstance() { return Singleton<RendererCrashHandlerHostLinux>::get(); } Linux: Don't pass a variable on the stack when posting a task. BUG=none TEST=none Review URL: http://codereview.chromium.org/6873004 git-svn-id: http://src.chromium.org/svn/trunk/src@81800 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 974794ca7501b3a4ede46604ce354d87e6ec8193 // Copyright (c) 2011 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 "chrome/browser/crash_handler_host_linux.h" #include <stdint.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/syscall.h> #include <unistd.h> #include "base/eintr_wrapper.h" #include "base/file_path.h" #include "base/format_macros.h" #include "base/linux_util.h" #include "base/logging.h" #include "base/memory/singleton.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/rand_util.h" #include "base/string_util.h" #include "base/task.h" #include "base/threading/thread.h" #include "breakpad/src/client/linux/handler/exception_handler.h" #include "breakpad/src/client/linux/minidump_writer/linux_dumper.h" #include "breakpad/src/client/linux/minidump_writer/minidump_writer.h" #include "chrome/app/breakpad_linux.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/env_vars.h" #include "content/browser/browser_thread.h" using google_breakpad::ExceptionHandler; namespace { // The length of the control message: const unsigned kControlMsgSize = CMSG_SPACE(2*sizeof(int)) + CMSG_SPACE(sizeof(struct ucred)); // The length of the regular payload: const unsigned kCrashContextSize = sizeof(ExceptionHandler::CrashContext); // Handles the crash dump and frees the allocated BreakpadInfo struct. void CrashDumpTask(CrashHandlerHostLinux* handler, BreakpadInfo* info) { if (handler->IsShuttingDown()) return; HandleCrashDump(*info); delete[] info->filename; delete[] info->process_type; delete[] info->crash_url; delete[] info->guid; delete[] info->distro; delete info; } } // namespace // Since classes derived from CrashHandlerHostLinux are singletons, it's only // destroyed at the end of the processes lifetime, which is greater in span than // the lifetime of the IO message loop. DISABLE_RUNNABLE_METHOD_REFCOUNT(CrashHandlerHostLinux); CrashHandlerHostLinux::CrashHandlerHostLinux() : shutting_down_(false) { int fds[2]; // We use SOCK_SEQPACKET rather than SOCK_DGRAM to prevent the process from // sending datagrams to other sockets on the system. The sandbox may prevent // the process from calling socket() to create new sockets, but it'll still // inherit some sockets. With PF_UNIX+SOCK_DGRAM, it can call sendmsg to send // a datagram to any (abstract) socket on the same system. With // SOCK_SEQPACKET, this is prevented. CHECK_EQ(socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fds), 0); static const int on = 1; // Enable passcred on the server end of the socket CHECK_EQ(setsockopt(fds[1], SOL_SOCKET, SO_PASSCRED, &on, sizeof(on)), 0); process_socket_ = fds[0]; browser_socket_ = fds[1]; BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &CrashHandlerHostLinux::Init)); } CrashHandlerHostLinux::~CrashHandlerHostLinux() { HANDLE_EINTR(close(process_socket_)); HANDLE_EINTR(close(browser_socket_)); } void CrashHandlerHostLinux::Init() { MessageLoopForIO* ml = MessageLoopForIO::current(); CHECK(ml->WatchFileDescriptor( browser_socket_, true /* persistent */, MessageLoopForIO::WATCH_READ, &file_descriptor_watcher_, this)); ml->AddDestructionObserver(this); } void CrashHandlerHostLinux::InitCrashUploaderThread() { SetProcessType(); uploader_thread_.reset( new base::Thread(std::string(process_type_ + "_crash_uploader").c_str())); uploader_thread_->Start(); } void CrashHandlerHostLinux::OnFileCanWriteWithoutBlocking(int fd) { DCHECK(false); } void CrashHandlerHostLinux::OnFileCanReadWithoutBlocking(int fd) { DCHECK_EQ(fd, browser_socket_); // A process has crashed and has signaled us by writing a datagram // to the death signal socket. The datagram contains the crash context needed // for writing the minidump as well as a file descriptor and a credentials // block so that they can't lie about their pid. const size_t kIovSize = 7; struct msghdr msg = {0}; struct iovec iov[kIovSize]; // Freed in WriteDumpFile(); char* crash_context = new char[kCrashContextSize]; // Freed in CrashDumpTask(); char* guid = new char[kGuidSize + 1]; char* crash_url = new char[kMaxActiveURLSize + 1]; char* distro = new char[kDistroSize + 1]; char* tid_buf_addr = NULL; int tid_fd = -1; uint64_t uptime; char control[kControlMsgSize]; const ssize_t expected_msg_size = kCrashContextSize + kGuidSize + 1 + kMaxActiveURLSize + 1 + kDistroSize + 1 + sizeof(tid_buf_addr) + sizeof(tid_fd) + sizeof(uptime); iov[0].iov_base = crash_context; iov[0].iov_len = kCrashContextSize; iov[1].iov_base = guid; iov[1].iov_len = kGuidSize + 1; iov[2].iov_base = crash_url; iov[2].iov_len = kMaxActiveURLSize + 1; iov[3].iov_base = distro; iov[3].iov_len = kDistroSize + 1; iov[4].iov_base = &tid_buf_addr; iov[4].iov_len = sizeof(tid_buf_addr); iov[5].iov_base = &tid_fd; iov[5].iov_len = sizeof(tid_fd); iov[6].iov_base = &uptime; iov[6].iov_len = sizeof(uptime); msg.msg_iov = iov; msg.msg_iovlen = kIovSize; msg.msg_control = control; msg.msg_controllen = kControlMsgSize; const ssize_t msg_size = HANDLE_EINTR(recvmsg(browser_socket_, &msg, 0)); if (msg_size != expected_msg_size) { LOG(ERROR) << "Error reading from death signal socket. Crash dumping" << " is disabled." << " msg_size:" << msg_size << " errno:" << errno; file_descriptor_watcher_.StopWatchingFileDescriptor(); return; } if (msg.msg_controllen != kControlMsgSize || msg.msg_flags & ~MSG_TRUNC) { LOG(ERROR) << "Received death signal message with the wrong size;" << " msg.msg_controllen:" << msg.msg_controllen << " msg.msg_flags:" << msg.msg_flags << " kCrashContextSize:" << kCrashContextSize << " kControlMsgSize:" << kControlMsgSize; return; } // Walk the control payload an extract the file descriptor and validated pid. pid_t crashing_pid = -1; int partner_fd = -1; int signal_fd = -1; for (struct cmsghdr *hdr = CMSG_FIRSTHDR(&msg); hdr; hdr = CMSG_NXTHDR(&msg, hdr)) { if (hdr->cmsg_level != SOL_SOCKET) continue; if (hdr->cmsg_type == SCM_RIGHTS) { const unsigned len = hdr->cmsg_len - (((uint8_t*)CMSG_DATA(hdr)) - (uint8_t*)hdr); DCHECK_EQ(len % sizeof(int), 0u); const unsigned num_fds = len / sizeof(int); if (num_fds != 2) { // A nasty process could try and send us too many descriptors and // force a leak. LOG(ERROR) << "Death signal contained wrong number of descriptors;" << " num_fds:" << num_fds; for (unsigned i = 0; i < num_fds; ++i) HANDLE_EINTR(close(reinterpret_cast<int*>(CMSG_DATA(hdr))[i])); return; } else { partner_fd = reinterpret_cast<int*>(CMSG_DATA(hdr))[0]; signal_fd = reinterpret_cast<int*>(CMSG_DATA(hdr))[1]; } } else if (hdr->cmsg_type == SCM_CREDENTIALS) { const struct ucred *cred = reinterpret_cast<struct ucred*>(CMSG_DATA(hdr)); crashing_pid = cred->pid; } } if (crashing_pid == -1 || partner_fd == -1 || signal_fd == -1) { LOG(ERROR) << "Death signal message didn't contain all expected control" << " messages"; if (partner_fd >= 0) HANDLE_EINTR(close(partner_fd)); if (signal_fd >= 0) HANDLE_EINTR(close(signal_fd)); return; } // Kernel bug workaround (broken in 2.6.30 at least): // The kernel doesn't translate PIDs in SCM_CREDENTIALS across PID // namespaces. Thus |crashing_pid| might be garbage from our point of view. // In the future we can remove this workaround, but we have to wait a couple // of years to be sure that it's worked its way out into the world. // The crashing process closes its copy of the signal_fd immediately after // calling sendmsg(). We can thus not reliably look for with with // FindProcessHoldingSocket(). But by necessity, it has to keep the // partner_fd open until the crashdump is complete. uint64_t inode_number; if (!base::FileDescriptorGetInode(&inode_number, partner_fd)) { LOG(WARNING) << "Failed to get inode number for passed socket"; HANDLE_EINTR(close(partner_fd)); HANDLE_EINTR(close(signal_fd)); return; } HANDLE_EINTR(close(partner_fd)); pid_t actual_crashing_pid = -1; if (!base::FindProcessHoldingSocket(&actual_crashing_pid, inode_number)) { LOG(WARNING) << "Failed to find process holding other end of crash reply " "socket"; HANDLE_EINTR(close(signal_fd)); return; } if (actual_crashing_pid != crashing_pid) { crashing_pid = actual_crashing_pid; // The crashing TID set inside the compromised context via sys_gettid() // in ExceptionHandler::HandleSignal is also wrong and needs to be // translated. // // We expect the crashing thread to be in sys_read(), waiting for use to // write to |signal_fd|. Most newer kernels where we have the different pid // namespaces also have /proc/[pid]/syscall, so we can look through // |actual_crashing_pid|'s thread group and find the thread that's in the // read syscall with the right arguments. std::string expected_syscall_data; // /proc/[pid]/syscall is formatted as follows: // syscall_number arg1 ... arg6 sp pc // but we just check syscall_number through arg3. base::StringAppendF(&expected_syscall_data, "%d 0x%x %p 0x1 ", SYS_read, tid_fd, tid_buf_addr); pid_t crashing_tid = base::FindThreadIDWithSyscall(crashing_pid, expected_syscall_data); if (crashing_tid == -1) { // We didn't find the thread we want. Maybe it didn't reach sys_read() // yet, or the kernel doesn't support /proc/[pid]/syscall or the thread // went away. We'll just take a guess here and assume the crashing // thread is the thread group leader. crashing_tid = crashing_pid; } ExceptionHandler::CrashContext* bad_context = reinterpret_cast<ExceptionHandler::CrashContext*>(crash_context); bad_context->tid = crashing_tid; } // Sanitize the string data a bit more guid[kGuidSize] = crash_url[kMaxActiveURLSize] = distro[kDistroSize] = 0; // Freed in CrashDumpTask(); BreakpadInfo* info = new BreakpadInfo; info->process_type_length = process_type_.length(); char* process_type_str = new char[info->process_type_length + 1]; process_type_.copy(process_type_str, info->process_type_length); process_type_str[info->process_type_length] = '\0'; info->process_type = process_type_str; info->crash_url_length = strlen(crash_url); info->crash_url = crash_url; info->guid_length = strlen(guid); info->guid = guid; info->distro_length = strlen(distro); info->distro = distro; info->upload = (getenv(env_vars::kHeadless) == NULL); info->process_start_time = uptime; BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod(this, &CrashHandlerHostLinux::WriteDumpFile, info, crashing_pid, crash_context, signal_fd)); } void CrashHandlerHostLinux::WriteDumpFile(BreakpadInfo* info, pid_t crashing_pid, char* crash_context, int signal_fd) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); FilePath dumps_path("/tmp"); PathService::Get(base::DIR_TEMP, &dumps_path); if (!info->upload) PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path); const uint64 rand = base::RandUint64(); const std::string minidump_filename = StringPrintf("%s/chromium-%s-minidump-%016" PRIx64 ".dmp", dumps_path.value().c_str(), process_type_.c_str(), rand); if (!google_breakpad::WriteMinidump(minidump_filename.c_str(), crashing_pid, crash_context, kCrashContextSize)) { LOG(ERROR) << "Failed to write crash dump for pid " << crashing_pid; } delete[] crash_context; // Freed in CrashDumpTask(); char* minidump_filename_str = new char[minidump_filename.length() + 1]; minidump_filename.copy(minidump_filename_str, minidump_filename.length()); minidump_filename_str[minidump_filename.length()] = '\0'; info->filename = minidump_filename_str; BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &CrashHandlerHostLinux::QueueCrashDumpTask, info, signal_fd)); } void CrashHandlerHostLinux::QueueCrashDumpTask(BreakpadInfo* info, int signal_fd) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // Send the done signal to the process: it can exit now. struct msghdr msg = {0}; struct iovec done_iov; done_iov.iov_base = const_cast<char*>("\x42"); done_iov.iov_len = 1; msg.msg_iov = &done_iov; msg.msg_iovlen = 1; HANDLE_EINTR(sendmsg(signal_fd, &msg, MSG_DONTWAIT | MSG_NOSIGNAL)); HANDLE_EINTR(close(signal_fd)); uploader_thread_->message_loop()->PostTask( FROM_HERE, NewRunnableFunction(&CrashDumpTask, this, info)); } void CrashHandlerHostLinux::WillDestroyCurrentMessageLoop() { file_descriptor_watcher_.StopWatchingFileDescriptor(); // If we are quitting and there are crash dumps in the queue, turn them into // no-ops. shutting_down_ = true; uploader_thread_->Stop(); } bool CrashHandlerHostLinux::IsShuttingDown() const { return shutting_down_; } GpuCrashHandlerHostLinux::GpuCrashHandlerHostLinux() { InitCrashUploaderThread(); } GpuCrashHandlerHostLinux::~GpuCrashHandlerHostLinux() { } void GpuCrashHandlerHostLinux::SetProcessType() { process_type_ = "gpu-process"; } // static GpuCrashHandlerHostLinux* GpuCrashHandlerHostLinux::GetInstance() { return Singleton<GpuCrashHandlerHostLinux>::get(); } PluginCrashHandlerHostLinux::PluginCrashHandlerHostLinux() { InitCrashUploaderThread(); } PluginCrashHandlerHostLinux::~PluginCrashHandlerHostLinux() { } void PluginCrashHandlerHostLinux::SetProcessType() { process_type_ = "plugin"; } // static PluginCrashHandlerHostLinux* PluginCrashHandlerHostLinux::GetInstance() { return Singleton<PluginCrashHandlerHostLinux>::get(); } RendererCrashHandlerHostLinux::RendererCrashHandlerHostLinux() { InitCrashUploaderThread(); } RendererCrashHandlerHostLinux::~RendererCrashHandlerHostLinux() { } void RendererCrashHandlerHostLinux::SetProcessType() { process_type_ = "renderer"; } // static RendererCrashHandlerHostLinux* RendererCrashHandlerHostLinux::GetInstance() { return Singleton<RendererCrashHandlerHostLinux>::get(); }
// Copyright (c) 2009 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 "base/command_line.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_theme_provider.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/navigation_controller.h" #include "chrome/browser/tab_contents/navigation_entry.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/common/bindings_policy.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/render_messages.h" #include "chrome/common/url_constants.h" #include "grit/generated_resources.h" const std::wstring DevToolsWindow::kDevToolsApp = L"DevToolsApp"; // static TabContents* DevToolsWindow::GetDevToolsContents(TabContents* inspected_tab) { if (!inspected_tab) { return NULL; } if (!DevToolsManager::GetInstance()) return NULL; // Happens only in tests. DevToolsClientHost* client_host = DevToolsManager::GetInstance()-> GetDevToolsClientHostFor(inspected_tab->render_view_host()); if (!client_host) { return NULL; } DevToolsWindow* window = client_host->AsDevToolsWindow(); if (!window || !window->is_docked()) { return NULL; } return window->tab_contents(); } DevToolsWindow::DevToolsWindow(Profile* profile, RenderViewHost* inspected_rvh, bool docked) : profile_(profile), browser_(NULL), docked_(docked), is_loaded_(false), action_on_load_(DEVTOOLS_TOGGLE_ACTION_NONE) { // Create TabContents with devtools. tab_contents_ = new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL); tab_contents_->render_view_host()->AllowBindings(BindingsPolicy::DOM_UI); tab_contents_->controller().LoadURL( GetDevToolsUrl(), GURL(), PageTransition::START_PAGE); // Wipe out page icon so that the default application icon is used. NavigationEntry* entry = tab_contents_->controller().GetActiveEntry(); entry->favicon().set_bitmap(SkBitmap()); entry->favicon().set_is_valid(true); // Register on-load actions. registrar_.Add(this, NotificationType::LOAD_STOP, Source<NavigationController>(&tab_contents_->controller())); registrar_.Add(this, NotificationType::TAB_CLOSING, Source<NavigationController>(&tab_contents_->controller())); registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED, NotificationService::AllSources()); inspected_tab_ = inspected_rvh->delegate()->GetAsTabContents(); } DevToolsWindow::~DevToolsWindow() { } DevToolsWindow* DevToolsWindow::AsDevToolsWindow() { return this; } void DevToolsWindow::SendMessageToClient(const IPC::Message& message) { RenderViewHost* target_host = tab_contents_->render_view_host(); IPC::Message* m = new IPC::Message(message); m->set_routing_id(target_host->routing_id()); target_host->Send(m); } void DevToolsWindow::InspectedTabClosing() { if (docked_) { // Update dev tools to reflect removed dev tools window. BrowserWindow* inspected_window = GetInspectedBrowserWindow(); if (inspected_window) inspected_window->UpdateDevTools(); // In case of docked tab_contents we own it, so delete here. delete tab_contents_; delete this; } else { // First, initiate self-destruct to free all the registrars. // Then close all tabs. Browser will take care of deleting tab_contents // for us. Browser* browser = browser_; delete this; browser->CloseAllTabs(); } } void DevToolsWindow::Show(DevToolsToggleAction action) { if (docked_) { // Just tell inspected browser to update splitter. BrowserWindow* inspected_window = GetInspectedBrowserWindow(); if (inspected_window) { tab_contents_->set_delegate(this); inspected_window->UpdateDevTools(); SetAttachedWindow(); tab_contents_->view()->SetInitialFocus(); ScheduleAction(action); return; } else { // Sometimes we don't know where to dock. Stay undocked. docked_ = false; } } if (!browser_) CreateDevToolsBrowser(); // Avoid consecutive window switching if the devtools window has been opened // and the Inspect Element shortcut is pressed in the inspected tab. bool should_show_window = !browser_ || action != DEVTOOLS_TOGGLE_ACTION_INSPECT; if (should_show_window) browser_->window()->Show(); SetAttachedWindow(); if (should_show_window) tab_contents_->view()->SetInitialFocus(); ScheduleAction(action); } void DevToolsWindow::Activate() { if (!docked_) { if (!browser_->window()->IsActive()) { browser_->window()->Activate(); } } else { BrowserWindow* inspected_window = GetInspectedBrowserWindow(); if (inspected_window) tab_contents_->view()->Focus(); } } void DevToolsWindow::SetDocked(bool docked) { if (docked_ == docked) return; if (docked && !GetInspectedBrowserWindow()) { // Cannot dock, avoid window flashing due to close-reopen cycle. return; } docked_ = docked; if (docked) { // Detach window from the external devtools browser. It will lead to // the browser object's close and delete. Remove observer first. TabStripModel* tabstrip_model = browser_->tabstrip_model(); tabstrip_model->DetachTabContentsAt( tabstrip_model->GetIndexOfTabContents(tab_contents_)); browser_ = NULL; } else { // Update inspected window to hide split and reset it. BrowserWindow* inspected_window = GetInspectedBrowserWindow(); if (inspected_window) { inspected_window->UpdateDevTools(); inspected_window = NULL; } } Show(DEVTOOLS_TOGGLE_ACTION_NONE); } RenderViewHost* DevToolsWindow::GetRenderViewHost() { return tab_contents_->render_view_host(); } void DevToolsWindow::CreateDevToolsBrowser() { // TODO(pfeldman): Make browser's getter for this key static. std::wstring wp_key = L""; wp_key.append(prefs::kBrowserWindowPlacement); wp_key.append(L"_"); wp_key.append(kDevToolsApp); PrefService* prefs = g_browser_process->local_state(); if (!prefs->FindPreference(wp_key.c_str())) { prefs->RegisterDictionaryPref(wp_key.c_str()); } const DictionaryValue* wp_pref = prefs->GetDictionary(wp_key.c_str()); if (!wp_pref) { DictionaryValue* defaults = prefs->GetMutableDictionary(wp_key.c_str()); defaults->SetInteger(L"left", 100); defaults->SetInteger(L"top", 100); defaults->SetInteger(L"right", 740); defaults->SetInteger(L"bottom", 740); defaults->SetBoolean(L"maximized", false); defaults->SetBoolean(L"always_on_top", false); } browser_ = Browser::CreateForDevTools(profile_); browser_->tabstrip_model()->AddTabContents( tab_contents_, -1, PageTransition::START_PAGE, TabStripModel::ADD_SELECTED); } BrowserWindow* DevToolsWindow::GetInspectedBrowserWindow() { for (BrowserList::const_iterator it = BrowserList::begin(); it != BrowserList::end(); ++it) { Browser* browser = *it; for (int i = 0; i < browser->tab_count(); ++i) { TabContents* tab_contents = browser->GetTabContentsAt(i); if (tab_contents == inspected_tab_) { return browser->window(); } } } return NULL; } void DevToolsWindow::SetAttachedWindow() { tab_contents_->render_view_host()-> ExecuteJavascriptInWebFrame( L"", docked_ ? L"WebInspector.setAttachedWindow(true);" : L"WebInspector.setAttachedWindow(false);"); } void DevToolsWindow::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::LOAD_STOP) { SetAttachedWindow(); is_loaded_ = true; UpdateTheme(); DoAction(); } else if (type == NotificationType::TAB_CLOSING) { if (Source<NavigationController>(source).ptr() == &tab_contents_->controller()) { // This happens when browser closes all of its tabs as a result // of window.Close event. // Notify manager that this DevToolsClientHost no longer exists and // initiate self-destuct here. NotifyCloseListener(); delete this; } } else if (type == NotificationType::BROWSER_THEME_CHANGED) { UpdateTheme(); } } void DevToolsWindow::ScheduleAction(DevToolsToggleAction action) { action_on_load_ = action; if (is_loaded_) DoAction(); } void DevToolsWindow::DoAction() { // TODO: these messages should be pushed through the WebKit API instead. switch (action_on_load_) { case DEVTOOLS_TOGGLE_ACTION_SHOW_CONSOLE: tab_contents_->render_view_host()-> ExecuteJavascriptInWebFrame(L"", L"WebInspector.showConsole();"); break; case DEVTOOLS_TOGGLE_ACTION_INSPECT: tab_contents_->render_view_host()-> ExecuteJavascriptInWebFrame( L"", L"WebInspector.toggleSearchingForNode();"); case DEVTOOLS_TOGGLE_ACTION_NONE: // Do nothing. break; default: NOTREACHED(); } action_on_load_ = DEVTOOLS_TOGGLE_ACTION_NONE; } std::string SkColorToRGBAString(SkColor color) { // We convert the alpha using DoubleToString because StringPrintf will use // locale specific formatters (e.g., use , instead of . in German). return StringPrintf("rgba(%d,%d,%d,%s)", SkColorGetR(color), SkColorGetG(color), SkColorGetB(color), DoubleToString(SkColorGetA(color) / 255.0).c_str()); } GURL DevToolsWindow::GetDevToolsUrl() { BrowserThemeProvider* tp = profile_->GetThemeProvider(); CHECK(tp); SkColor color_toolbar = tp->GetColor(BrowserThemeProvider::COLOR_TOOLBAR); SkColor color_tab_text = tp->GetColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT); std::string url_string = StringPrintf( "%sdevtools.html?docked=%s&toolbar_color=%s&text_color=%s", chrome::kChromeUIDevToolsURL, docked_ ? "true" : "false", SkColorToRGBAString(color_toolbar).c_str(), SkColorToRGBAString(color_tab_text).c_str()); return GURL(url_string); } void DevToolsWindow::UpdateTheme() { BrowserThemeProvider* tp = profile_->GetThemeProvider(); CHECK(tp); SkColor color_toolbar = tp->GetColor(BrowserThemeProvider::COLOR_TOOLBAR); SkColor color_tab_text = tp->GetColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT); std::string command = StringPrintf( "WebInspector.setToolbarColors(\"%s\", \"%s\")", SkColorToRGBAString(color_toolbar).c_str(), SkColorToRGBAString(color_tab_text).c_str()); tab_contents_->render_view_host()-> ExecuteJavascriptInWebFrame(L"", UTF8ToWide(command)); } bool DevToolsWindow::PreHandleKeyboardEvent( const NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) { if (docked_) { BrowserWindow* inspected_window = GetInspectedBrowserWindow(); if (inspected_window) return inspected_window->PreHandleKeyboardEvent( event, is_keyboard_shortcut); } return false; } void DevToolsWindow::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) { if (docked_) { BrowserWindow* inspected_window = GetInspectedBrowserWindow(); if (inspected_window) inspected_window->HandleKeyboardEvent(event); } } Show DevTools window when the Inspect shortcut is hit for the first time BUG=50724 TEST=manual Review URL: http://codereview.chromium.org/2819081 git-svn-id: http://src.chromium.org/svn/trunk/src@54300 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 38c7f8671099288bf4fcf7b5aea4cca91775983f // Copyright (c) 2009 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 "base/command_line.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_theme_provider.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/navigation_controller.h" #include "chrome/browser/tab_contents/navigation_entry.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/common/bindings_policy.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/render_messages.h" #include "chrome/common/url_constants.h" #include "grit/generated_resources.h" const std::wstring DevToolsWindow::kDevToolsApp = L"DevToolsApp"; // static TabContents* DevToolsWindow::GetDevToolsContents(TabContents* inspected_tab) { if (!inspected_tab) { return NULL; } if (!DevToolsManager::GetInstance()) return NULL; // Happens only in tests. DevToolsClientHost* client_host = DevToolsManager::GetInstance()-> GetDevToolsClientHostFor(inspected_tab->render_view_host()); if (!client_host) { return NULL; } DevToolsWindow* window = client_host->AsDevToolsWindow(); if (!window || !window->is_docked()) { return NULL; } return window->tab_contents(); } DevToolsWindow::DevToolsWindow(Profile* profile, RenderViewHost* inspected_rvh, bool docked) : profile_(profile), browser_(NULL), docked_(docked), is_loaded_(false), action_on_load_(DEVTOOLS_TOGGLE_ACTION_NONE) { // Create TabContents with devtools. tab_contents_ = new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL); tab_contents_->render_view_host()->AllowBindings(BindingsPolicy::DOM_UI); tab_contents_->controller().LoadURL( GetDevToolsUrl(), GURL(), PageTransition::START_PAGE); // Wipe out page icon so that the default application icon is used. NavigationEntry* entry = tab_contents_->controller().GetActiveEntry(); entry->favicon().set_bitmap(SkBitmap()); entry->favicon().set_is_valid(true); // Register on-load actions. registrar_.Add(this, NotificationType::LOAD_STOP, Source<NavigationController>(&tab_contents_->controller())); registrar_.Add(this, NotificationType::TAB_CLOSING, Source<NavigationController>(&tab_contents_->controller())); registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED, NotificationService::AllSources()); inspected_tab_ = inspected_rvh->delegate()->GetAsTabContents(); } DevToolsWindow::~DevToolsWindow() { } DevToolsWindow* DevToolsWindow::AsDevToolsWindow() { return this; } void DevToolsWindow::SendMessageToClient(const IPC::Message& message) { RenderViewHost* target_host = tab_contents_->render_view_host(); IPC::Message* m = new IPC::Message(message); m->set_routing_id(target_host->routing_id()); target_host->Send(m); } void DevToolsWindow::InspectedTabClosing() { if (docked_) { // Update dev tools to reflect removed dev tools window. BrowserWindow* inspected_window = GetInspectedBrowserWindow(); if (inspected_window) inspected_window->UpdateDevTools(); // In case of docked tab_contents we own it, so delete here. delete tab_contents_; delete this; } else { // First, initiate self-destruct to free all the registrars. // Then close all tabs. Browser will take care of deleting tab_contents // for us. Browser* browser = browser_; delete this; browser->CloseAllTabs(); } } void DevToolsWindow::Show(DevToolsToggleAction action) { if (docked_) { // Just tell inspected browser to update splitter. BrowserWindow* inspected_window = GetInspectedBrowserWindow(); if (inspected_window) { tab_contents_->set_delegate(this); inspected_window->UpdateDevTools(); SetAttachedWindow(); tab_contents_->view()->SetInitialFocus(); ScheduleAction(action); return; } else { // Sometimes we don't know where to dock. Stay undocked. docked_ = false; } } // Avoid consecutive window switching if the devtools window has been opened // and the Inspect Element shortcut is pressed in the inspected tab. bool should_show_window = !browser_ || action != DEVTOOLS_TOGGLE_ACTION_INSPECT; if (!browser_) CreateDevToolsBrowser(); if (should_show_window) browser_->window()->Show(); SetAttachedWindow(); if (should_show_window) tab_contents_->view()->SetInitialFocus(); ScheduleAction(action); } void DevToolsWindow::Activate() { if (!docked_) { if (!browser_->window()->IsActive()) { browser_->window()->Activate(); } } else { BrowserWindow* inspected_window = GetInspectedBrowserWindow(); if (inspected_window) tab_contents_->view()->Focus(); } } void DevToolsWindow::SetDocked(bool docked) { if (docked_ == docked) return; if (docked && !GetInspectedBrowserWindow()) { // Cannot dock, avoid window flashing due to close-reopen cycle. return; } docked_ = docked; if (docked) { // Detach window from the external devtools browser. It will lead to // the browser object's close and delete. Remove observer first. TabStripModel* tabstrip_model = browser_->tabstrip_model(); tabstrip_model->DetachTabContentsAt( tabstrip_model->GetIndexOfTabContents(tab_contents_)); browser_ = NULL; } else { // Update inspected window to hide split and reset it. BrowserWindow* inspected_window = GetInspectedBrowserWindow(); if (inspected_window) { inspected_window->UpdateDevTools(); inspected_window = NULL; } } Show(DEVTOOLS_TOGGLE_ACTION_NONE); } RenderViewHost* DevToolsWindow::GetRenderViewHost() { return tab_contents_->render_view_host(); } void DevToolsWindow::CreateDevToolsBrowser() { // TODO(pfeldman): Make browser's getter for this key static. std::wstring wp_key = L""; wp_key.append(prefs::kBrowserWindowPlacement); wp_key.append(L"_"); wp_key.append(kDevToolsApp); PrefService* prefs = g_browser_process->local_state(); if (!prefs->FindPreference(wp_key.c_str())) { prefs->RegisterDictionaryPref(wp_key.c_str()); } const DictionaryValue* wp_pref = prefs->GetDictionary(wp_key.c_str()); if (!wp_pref) { DictionaryValue* defaults = prefs->GetMutableDictionary(wp_key.c_str()); defaults->SetInteger(L"left", 100); defaults->SetInteger(L"top", 100); defaults->SetInteger(L"right", 740); defaults->SetInteger(L"bottom", 740); defaults->SetBoolean(L"maximized", false); defaults->SetBoolean(L"always_on_top", false); } browser_ = Browser::CreateForDevTools(profile_); browser_->tabstrip_model()->AddTabContents( tab_contents_, -1, PageTransition::START_PAGE, TabStripModel::ADD_SELECTED); } BrowserWindow* DevToolsWindow::GetInspectedBrowserWindow() { for (BrowserList::const_iterator it = BrowserList::begin(); it != BrowserList::end(); ++it) { Browser* browser = *it; for (int i = 0; i < browser->tab_count(); ++i) { TabContents* tab_contents = browser->GetTabContentsAt(i); if (tab_contents == inspected_tab_) { return browser->window(); } } } return NULL; } void DevToolsWindow::SetAttachedWindow() { tab_contents_->render_view_host()-> ExecuteJavascriptInWebFrame( L"", docked_ ? L"WebInspector.setAttachedWindow(true);" : L"WebInspector.setAttachedWindow(false);"); } void DevToolsWindow::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::LOAD_STOP) { SetAttachedWindow(); is_loaded_ = true; UpdateTheme(); DoAction(); } else if (type == NotificationType::TAB_CLOSING) { if (Source<NavigationController>(source).ptr() == &tab_contents_->controller()) { // This happens when browser closes all of its tabs as a result // of window.Close event. // Notify manager that this DevToolsClientHost no longer exists and // initiate self-destuct here. NotifyCloseListener(); delete this; } } else if (type == NotificationType::BROWSER_THEME_CHANGED) { UpdateTheme(); } } void DevToolsWindow::ScheduleAction(DevToolsToggleAction action) { action_on_load_ = action; if (is_loaded_) DoAction(); } void DevToolsWindow::DoAction() { // TODO: these messages should be pushed through the WebKit API instead. switch (action_on_load_) { case DEVTOOLS_TOGGLE_ACTION_SHOW_CONSOLE: tab_contents_->render_view_host()-> ExecuteJavascriptInWebFrame(L"", L"WebInspector.showConsole();"); break; case DEVTOOLS_TOGGLE_ACTION_INSPECT: tab_contents_->render_view_host()-> ExecuteJavascriptInWebFrame( L"", L"WebInspector.toggleSearchingForNode();"); case DEVTOOLS_TOGGLE_ACTION_NONE: // Do nothing. break; default: NOTREACHED(); } action_on_load_ = DEVTOOLS_TOGGLE_ACTION_NONE; } std::string SkColorToRGBAString(SkColor color) { // We convert the alpha using DoubleToString because StringPrintf will use // locale specific formatters (e.g., use , instead of . in German). return StringPrintf("rgba(%d,%d,%d,%s)", SkColorGetR(color), SkColorGetG(color), SkColorGetB(color), DoubleToString(SkColorGetA(color) / 255.0).c_str()); } GURL DevToolsWindow::GetDevToolsUrl() { BrowserThemeProvider* tp = profile_->GetThemeProvider(); CHECK(tp); SkColor color_toolbar = tp->GetColor(BrowserThemeProvider::COLOR_TOOLBAR); SkColor color_tab_text = tp->GetColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT); std::string url_string = StringPrintf( "%sdevtools.html?docked=%s&toolbar_color=%s&text_color=%s", chrome::kChromeUIDevToolsURL, docked_ ? "true" : "false", SkColorToRGBAString(color_toolbar).c_str(), SkColorToRGBAString(color_tab_text).c_str()); return GURL(url_string); } void DevToolsWindow::UpdateTheme() { BrowserThemeProvider* tp = profile_->GetThemeProvider(); CHECK(tp); SkColor color_toolbar = tp->GetColor(BrowserThemeProvider::COLOR_TOOLBAR); SkColor color_tab_text = tp->GetColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT); std::string command = StringPrintf( "WebInspector.setToolbarColors(\"%s\", \"%s\")", SkColorToRGBAString(color_toolbar).c_str(), SkColorToRGBAString(color_tab_text).c_str()); tab_contents_->render_view_host()-> ExecuteJavascriptInWebFrame(L"", UTF8ToWide(command)); } bool DevToolsWindow::PreHandleKeyboardEvent( const NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) { if (docked_) { BrowserWindow* inspected_window = GetInspectedBrowserWindow(); if (inspected_window) return inspected_window->PreHandleKeyboardEvent( event, is_keyboard_shortcut); } return false; } void DevToolsWindow::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) { if (docked_) { BrowserWindow* inspected_window = GetInspectedBrowserWindow(); if (inspected_window) inspected_window->HandleKeyboardEvent(event); } }
// Copyright (c) 2006-2009 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 "chrome/browser/extensions/extensions_ui.h" #include "app/gfx/codec/png_codec.h" #include "app/gfx/color_utils.h" #include "app/gfx/skbitmap_operations.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/file_util.h" #include "base/string_util.h" #include "base/thread.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/extensions/extension_function_dispatcher.h" #include "chrome/browser/extensions/extension_message_service.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/extension_updater.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/render_widget_host.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_error_reporter.h" #include "chrome/common/extensions/user_script.h" #include "chrome/common/extensions/url_pattern.h" #include "chrome/common/jstemplate_builder.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "chrome/common/url_constants.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "net/base/base64.h" #include "net/base/net_util.h" #include "webkit/glue/image_decoder.h" //////////////////////////////////////////////////////////////////////////////// // // ExtensionsHTMLSource // //////////////////////////////////////////////////////////////////////////////// ExtensionsUIHTMLSource::ExtensionsUIHTMLSource() : DataSource(chrome::kChromeUIExtensionsHost, MessageLoop::current()) { } void ExtensionsUIHTMLSource::StartDataRequest(const std::string& path, int request_id) { DictionaryValue localized_strings; localized_strings.SetString(L"title", l10n_util::GetString(IDS_EXTENSIONS_TITLE)); localized_strings.SetString(L"devModeLink", l10n_util::GetString(IDS_EXTENSIONS_DEVELOPER_MODE_LINK)); localized_strings.SetString(L"devModePrefix", l10n_util::GetString(IDS_EXTENSIONS_DEVELOPER_MODE_PREFIX)); localized_strings.SetString(L"loadUnpackedButton", l10n_util::GetString(IDS_EXTENSIONS_LOAD_UNPACKED_BUTTON)); localized_strings.SetString(L"packButton", l10n_util::GetString(IDS_EXTENSIONS_PACK_BUTTON)); localized_strings.SetString(L"updateButton", l10n_util::GetString(IDS_EXTENSIONS_UPDATE_BUTTON)); localized_strings.SetString(L"noExtensions", l10n_util::GetString(IDS_EXTENSIONS_NONE_INSTALLED)); localized_strings.SetString(L"extensionDisabled", l10n_util::GetString(IDS_EXTENSIONS_DISABLED_EXTENSION)); localized_strings.SetString(L"inDevelopment", l10n_util::GetString(IDS_EXTENSIONS_IN_DEVELOPMENT)); localized_strings.SetString(L"extensionId", l10n_util::GetString(IDS_EXTENSIONS_ID)); localized_strings.SetString(L"extensionVersion", l10n_util::GetString(IDS_EXTENSIONS_VERSION)); localized_strings.SetString(L"inspectViews", l10n_util::GetString(IDS_EXTENSIONS_INSPECT_VIEWS)); localized_strings.SetString(L"disable", l10n_util::GetString(IDS_EXTENSIONS_DISABLE)); localized_strings.SetString(L"enable", l10n_util::GetString(IDS_EXTENSIONS_ENABLE)); localized_strings.SetString(L"reload", l10n_util::GetString(IDS_EXTENSIONS_RELOAD)); localized_strings.SetString(L"uninstall", l10n_util::GetString(IDS_EXTENSIONS_UNINSTALL)); localized_strings.SetString(L"options", l10n_util::GetString(IDS_EXTENSIONS_OPTIONS)); localized_strings.SetString(L"packDialogTitle", l10n_util::GetString(IDS_EXTENSION_PACK_DIALOG_TITLE)); localized_strings.SetString(L"packDialogHeading", l10n_util::GetString(IDS_EXTENSION_PACK_DIALOG_HEADING)); localized_strings.SetString(L"rootDirectoryLabel", l10n_util::GetString(IDS_EXTENSION_PACK_DIALOG_ROOT_DIRECTORY_LABEL)); localized_strings.SetString(L"packDialogBrowse", l10n_util::GetString(IDS_EXTENSION_PACK_DIALOG_BROWSE)); localized_strings.SetString(L"privateKeyLabel", l10n_util::GetString(IDS_EXTENSION_PACK_DIALOG_PRIVATE_KEY_LABEL)); localized_strings.SetString(L"okButton", l10n_util::GetString(IDS_OK)); localized_strings.SetString(L"cancelButton", l10n_util::GetString(IDS_CANCEL)); static const base::StringPiece extensions_html( ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_EXTENSIONS_UI_HTML)); std::string full_html(extensions_html.data(), extensions_html.size()); jstemplate_builder::AppendJsonHtml(&localized_strings, &full_html); jstemplate_builder::AppendI18nTemplateSourceHtml(&full_html); jstemplate_builder::AppendI18nTemplateProcessHtml(&full_html); jstemplate_builder::AppendJsTemplateSourceHtml(&full_html); scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes); html_bytes->data.resize(full_html.size()); std::copy(full_html.begin(), full_html.end(), html_bytes->data.begin()); SendResponse(request_id, html_bytes); } //////////////////////////////////////////////////////////////////////////////// // // ExtensionsDOMHandler::IconLoader // //////////////////////////////////////////////////////////////////////////////// ExtensionsDOMHandler::IconLoader::IconLoader(ExtensionsDOMHandler* handler) : handler_(handler) { } void ExtensionsDOMHandler::IconLoader::LoadIcons( std::vector<ExtensionResource>* icons, DictionaryValue* json) { ChromeThread::PostTask( ChromeThread::FILE, FROM_HERE, NewRunnableMethod(this, &IconLoader::LoadIconsOnFileThread, icons, json)); } void ExtensionsDOMHandler::IconLoader::Cancel() { handler_ = NULL; } void ExtensionsDOMHandler::IconLoader::LoadIconsOnFileThread( std::vector<ExtensionResource>* icons, DictionaryValue* json) { scoped_ptr<std::vector<ExtensionResource> > icons_deleter(icons); scoped_ptr<DictionaryValue> json_deleter(json); ListValue* extensions = NULL; CHECK(json->GetList(L"extensions", &extensions)); for (size_t i = 0; i < icons->size(); ++i) { DictionaryValue* extension = NULL; CHECK(extensions->GetDictionary(static_cast<int>(i), &extension)); // Read the file. std::string file_contents; if (icons->at(i).relative_path().empty() || !file_util::ReadFileToString(icons->at(i).GetFilePath(), &file_contents)) { // If there's no icon, default to the puzzle icon. This is safe to do from // the file thread. file_contents = ResourceBundle::GetSharedInstance().GetDataResource( IDR_INFOBAR_PLUGIN_INSTALL); } // If the extension is disabled, we desaturate the icon to add to the // disabledness effect. bool enabled = false; CHECK(extension->GetBoolean(L"enabled", &enabled)); if (!enabled) { const unsigned char* data = reinterpret_cast<const unsigned char*>(file_contents.data()); webkit_glue::ImageDecoder decoder; scoped_ptr<SkBitmap> decoded(new SkBitmap()); *decoded = decoder.Decode(data, file_contents.length()); // Desaturate the icon and lighten it a bit. color_utils::HSL shift = {-1, 0, 0.6}; *decoded = SkBitmapOperations::CreateHSLShiftedBitmap(*decoded, shift); std::vector<unsigned char> output; gfx::PNGCodec::EncodeBGRASkBitmap(*decoded, false, &output); // Lame, but we must make a copy of this now, because base64 doesn't take // the same input type. file_contents.assign(reinterpret_cast<char*>(&output.front()), output.size()); } // Create a data URL (all icons are converted to PNGs during unpacking). std::string base64_encoded; net::Base64Encode(file_contents, &base64_encoded); GURL icon_url("data:image/png;base64," + base64_encoded); extension->SetString(L"icon", icon_url.spec()); } ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod(this, &IconLoader::ReportResultOnUIThread, json_deleter.release())); } void ExtensionsDOMHandler::IconLoader::ReportResultOnUIThread( DictionaryValue* json) { if (handler_) handler_->OnIconsLoaded(json); } /////////////////////////////////////////////////////////////////////////////// // // ExtensionsDOMHandler // /////////////////////////////////////////////////////////////////////////////// ExtensionsDOMHandler::ExtensionsDOMHandler(ExtensionsService* extension_service) : extensions_service_(extension_service) { } void ExtensionsDOMHandler::RegisterMessages() { dom_ui_->RegisterMessageCallback("requestExtensionsData", NewCallback(this, &ExtensionsDOMHandler::HandleRequestExtensionsData)); dom_ui_->RegisterMessageCallback("toggleDeveloperMode", NewCallback(this, &ExtensionsDOMHandler::HandleToggleDeveloperMode)); dom_ui_->RegisterMessageCallback("inspect", NewCallback(this, &ExtensionsDOMHandler::HandleInspectMessage)); dom_ui_->RegisterMessageCallback("reload", NewCallback(this, &ExtensionsDOMHandler::HandleReloadMessage)); dom_ui_->RegisterMessageCallback("enable", NewCallback(this, &ExtensionsDOMHandler::HandleEnableMessage)); dom_ui_->RegisterMessageCallback("uninstall", NewCallback(this, &ExtensionsDOMHandler::HandleUninstallMessage)); dom_ui_->RegisterMessageCallback("options", NewCallback(this, &ExtensionsDOMHandler::HandleOptionsMessage)); dom_ui_->RegisterMessageCallback("load", NewCallback(this, &ExtensionsDOMHandler::HandleLoadMessage)); dom_ui_->RegisterMessageCallback("pack", NewCallback(this, &ExtensionsDOMHandler::HandlePackMessage)); dom_ui_->RegisterMessageCallback("autoupdate", NewCallback(this, &ExtensionsDOMHandler::HandleAutoUpdateMessage)); dom_ui_->RegisterMessageCallback("selectFilePath", NewCallback(this, &ExtensionsDOMHandler::HandleSelectFilePathMessage)); } void ExtensionsDOMHandler::HandleRequestExtensionsData(const Value* value) { DictionaryValue* results = new DictionaryValue(); // Add the extensions to the results structure. ListValue *extensions_list = new ListValue(); // Stores the icon resource for each of the extensions in extensions_list. We // build up a list of them here, then load them on the file thread in // ::LoadIcons(). std::vector<ExtensionResource>* extension_icons = new std::vector<ExtensionResource>(); const ExtensionList* extensions = extensions_service_->extensions(); for (ExtensionList::const_iterator extension = extensions->begin(); extension != extensions->end(); ++extension) { // Don't show the themes since this page's UI isn't really useful for // themes. if (!(*extension)->IsTheme()) { extensions_list->Append(CreateExtensionDetailValue( *extension, GetActivePagesForExtension((*extension)->id()), true)); extension_icons->push_back(PickExtensionIcon(*extension)); } } extensions = extensions_service_->disabled_extensions(); for (ExtensionList::const_iterator extension = extensions->begin(); extension != extensions->end(); ++extension) { if (!(*extension)->IsTheme()) { extensions_list->Append(CreateExtensionDetailValue( *extension, GetActivePagesForExtension((*extension)->id()), false)); extension_icons->push_back(PickExtensionIcon(*extension)); } } results->Set(L"extensions", extensions_list); bool developer_mode = dom_ui_->GetProfile()->GetPrefs() ->GetBoolean(prefs::kExtensionsUIDeveloperMode); results->SetBoolean(L"developerMode", developer_mode); if (icon_loader_.get()) icon_loader_->Cancel(); icon_loader_ = new IconLoader(this); icon_loader_->LoadIcons(extension_icons, results); } void ExtensionsDOMHandler::OnIconsLoaded(DictionaryValue* json) { dom_ui_->CallJavascriptFunction(L"returnExtensionsData", *json); delete json; // Register for notifications that we need to reload the page. registrar_.RemoveAll(); registrar_.Add(this, NotificationType::EXTENSION_PROCESS_CREATED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::EXTENSION_UNLOADED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::EXTENSION_UPDATE_DISABLED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::EXTENSION_UNLOADED_DISABLED, NotificationService::AllSources()); } ExtensionResource ExtensionsDOMHandler::PickExtensionIcon( Extension* extension) { // Try to fetch the medium sized icon, then (if missing) go for the large one. const std::map<int, std::string>& icons = extension->icons(); std::map<int, std::string>::const_iterator iter = icons.find(Extension::EXTENSION_ICON_MEDIUM); if (iter == icons.end()) iter = icons.find(Extension::EXTENSION_ICON_LARGE); if (iter != icons.end()) return extension->GetResource(iter->second); else return ExtensionResource(); } void ExtensionsDOMHandler::HandleToggleDeveloperMode(const Value* value) { bool developer_mode = dom_ui_->GetProfile()->GetPrefs() ->GetBoolean(prefs::kExtensionsUIDeveloperMode); dom_ui_->GetProfile()->GetPrefs()->SetBoolean( prefs::kExtensionsUIDeveloperMode, !developer_mode); } void ExtensionsDOMHandler::HandleInspectMessage(const Value* value) { std::string render_process_id_str; std::string render_view_id_str; int render_process_id; int render_view_id; CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 2); CHECK(list->GetString(0, &render_process_id_str)); CHECK(list->GetString(1, &render_view_id_str)); CHECK(StringToInt(render_process_id_str, &render_process_id)); CHECK(StringToInt(render_view_id_str, &render_view_id)); RenderViewHost* host = RenderViewHost::FromID(render_process_id, render_view_id); if (!host) { // This can happen if the host has gone away since the page was displayed. return; } DevToolsManager::GetInstance()->OpenDevToolsWindow(host); } void ExtensionsDOMHandler::HandleReloadMessage(const Value* value) { CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 1); std::string extension_id; CHECK(list->GetString(0, &extension_id)); extensions_service_->ReloadExtension(extension_id); } void ExtensionsDOMHandler::HandleEnableMessage(const Value* value) { CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 2); std::string extension_id, enable_str; CHECK(list->GetString(0, &extension_id)); CHECK(list->GetString(1, &enable_str)); if (enable_str == "true") { extensions_service_->EnableExtension(extension_id); } else { extensions_service_->DisableExtension(extension_id); } } void ExtensionsDOMHandler::HandleUninstallMessage(const Value* value) { CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 1); std::string extension_id; CHECK(list->GetString(0, &extension_id)); extensions_service_->UninstallExtension(extension_id, false); } void ExtensionsDOMHandler::HandleOptionsMessage(const Value* value) { CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 1); std::string extension_id; CHECK(list->GetString(0, &extension_id)); Extension *extension = extensions_service_->GetExtensionById(extension_id); if (!extension || extension->options_url().is_empty()) { return; } Browser* browser = Browser::GetOrCreateTabbedBrowser(dom_ui_->GetProfile()); CHECK(browser); browser->OpenURL(extension->options_url(), GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK); } void ExtensionsDOMHandler::HandleLoadMessage(const Value* value) { std::string string_path; CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 1) << list->GetSize(); CHECK(list->GetString(0, &string_path)); FilePath file_path = FilePath::FromWStringHack(ASCIIToWide(string_path)); extensions_service_->LoadExtension(file_path); } void ExtensionsDOMHandler::ShowAlert(const std::string& message) { ListValue arguments; arguments.Append(Value::CreateStringValue(message)); dom_ui_->CallJavascriptFunction(L"alert", arguments); } void ExtensionsDOMHandler::HandlePackMessage(const Value* value) { std::string extension_path; std::string private_key_path; CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 2); CHECK(list->GetString(0, &extension_path)); CHECK(list->GetString(1, &private_key_path)); FilePath root_directory = FilePath::FromWStringHack(ASCIIToWide( extension_path)); FilePath key_file = FilePath::FromWStringHack(ASCIIToWide(private_key_path)); if (root_directory.empty()) { if (extension_path.empty()) { ShowAlert(l10n_util::GetStringUTF8( IDS_EXTENSION_PACK_DIALOG_ERROR_ROOT_REQUIRED)); } else { ShowAlert(l10n_util::GetStringUTF8( IDS_EXTENSION_PACK_DIALOG_ERROR_ROOT_INVALID)); } return; } if (!private_key_path.empty() && key_file.empty()) { ShowAlert(l10n_util::GetStringUTF8( IDS_EXTENSION_PACK_DIALOG_ERROR_KEY_INVALID)); return; } pack_job_ = new PackExtensionJob(this, root_directory, key_file); } void ExtensionsDOMHandler::OnPackSuccess(const FilePath& crx_file, const FilePath& pem_file) { std::string message; if (!pem_file.empty()) { message = WideToASCII(l10n_util::GetStringF( IDS_EXTENSION_PACK_DIALOG_SUCCESS_BODY_NEW, crx_file.ToWStringHack(), pem_file.ToWStringHack())); } else { message = WideToASCII(l10n_util::GetStringF( IDS_EXTENSION_PACK_DIALOG_SUCCESS_BODY_UPDATE, crx_file.ToWStringHack())); } ShowAlert(message); ListValue results; dom_ui_->CallJavascriptFunction(L"hidePackDialog", results); } void ExtensionsDOMHandler::OnPackFailure(const std::wstring& error) { ShowAlert(WideToASCII(error)); } void ExtensionsDOMHandler::HandleAutoUpdateMessage(const Value* value) { ExtensionUpdater* updater = extensions_service_->updater(); if (updater) { updater->CheckNow(); } } void ExtensionsDOMHandler::HandleSelectFilePathMessage(const Value* value) { std::string select_type; std::string operation; CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 2); CHECK(list->GetString(0, &select_type)); CHECK(list->GetString(1, &operation)); SelectFileDialog::Type type = SelectFileDialog::SELECT_FOLDER; static SelectFileDialog::FileTypeInfo info; int file_type_index = 0; if (select_type == "file") type = SelectFileDialog::SELECT_OPEN_FILE; string16 select_title; if (operation == "load") select_title = l10n_util::GetStringUTF16(IDS_EXTENSION_LOAD_FROM_DIRECTORY); else if (operation == "packRoot") select_title = l10n_util::GetStringUTF16( IDS_EXTENSION_PACK_DIALOG_SELECT_ROOT); else if (operation == "pem") { select_title = l10n_util::GetStringUTF16( IDS_EXTENSION_PACK_DIALOG_SELECT_KEY); info.extensions.push_back(std::vector<FilePath::StringType>()); info.extensions.front().push_back(FILE_PATH_LITERAL("pem")); info.extension_description_overrides.push_back(WideToUTF16( l10n_util::GetString( IDS_EXTENSION_PACK_DIALOG_KEY_FILE_TYPE_DESCRIPTION))); info.include_all_files = true; file_type_index = 1; } else { NOTREACHED(); return; } load_extension_dialog_ = SelectFileDialog::Create(this); load_extension_dialog_->SelectFile(type, select_title, FilePath(), &info, file_type_index, FILE_PATH_LITERAL(""), dom_ui_->tab_contents()->view()->GetTopLevelNativeWindow(), NULL); } void ExtensionsDOMHandler::FileSelected(const FilePath& path, int index, void* params) { // Add the extensions to the results structure. ListValue results; results.Append(Value::CreateStringValue(path.value())); dom_ui_->CallJavascriptFunction(L"window.handleFilePathSelected", results); } void ExtensionsDOMHandler::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::EXTENSION_PROCESS_CREATED: case NotificationType::EXTENSION_UNLOADED: case NotificationType::EXTENSION_UPDATE_DISABLED: case NotificationType::EXTENSION_UNLOADED_DISABLED: if (dom_ui_->tab_contents()) HandleRequestExtensionsData(NULL); break; default: NOTREACHED(); } } static void CreateScriptFileDetailValue( const FilePath& extension_path, const UserScript::FileList& scripts, const wchar_t* key, DictionaryValue* script_data) { if (scripts.empty()) return; ListValue *list = new ListValue(); for (size_t i = 0; i < scripts.size(); ++i) { const UserScript::File& file = scripts[i]; // TODO(cira): this information is not used on extension page yet. We // may want to display actual resource that got loaded, not default. list->Append( new StringValue(file.relative_path().value())); } script_data->Set(key, list); } // Static DictionaryValue* ExtensionsDOMHandler::CreateContentScriptDetailValue( const UserScript& script, const FilePath& extension_path) { DictionaryValue* script_data = new DictionaryValue(); CreateScriptFileDetailValue(extension_path, script.js_scripts(), L"js", script_data); CreateScriptFileDetailValue(extension_path, script.css_scripts(), L"css", script_data); // Get list of glob "matches" strings ListValue *url_pattern_list = new ListValue(); const std::vector<URLPattern>& url_patterns = script.url_patterns(); for (std::vector<URLPattern>::const_iterator url_pattern = url_patterns.begin(); url_pattern != url_patterns.end(); ++url_pattern) { url_pattern_list->Append(new StringValue(url_pattern->GetAsString())); } script_data->Set(L"matches", url_pattern_list); return script_data; } // Static DictionaryValue* ExtensionsDOMHandler::CreateExtensionDetailValue( const Extension *extension, const std::vector<ExtensionPage>& pages, bool enabled) { DictionaryValue* extension_data = new DictionaryValue(); extension_data->SetString(L"id", extension->id()); extension_data->SetString(L"name", extension->name()); extension_data->SetString(L"description", extension->description()); extension_data->SetString(L"version", extension->version()->GetString()); extension_data->SetBoolean(L"enabled", enabled); // Determine the sort order: Extensions loaded through --load-extensions show // up at the top. Disabled extensions show up at the bottom. if (extension->location() == Extension::LOAD) extension_data->SetInteger(L"order", 1); else extension_data->SetInteger(L"order", 2); if (!extension->options_url().is_empty()) extension_data->SetString(L"options_url", extension->options_url().spec()); // Add list of content_script detail DictionaryValues ListValue *content_script_list = new ListValue(); UserScriptList content_scripts = extension->content_scripts(); for (UserScriptList::const_iterator script = content_scripts.begin(); script != content_scripts.end(); ++script) { content_script_list->Append( CreateContentScriptDetailValue(*script, extension->path())); } extension_data->Set(L"content_scripts", content_script_list); // Add permissions ListValue *permission_list = new ListValue; std::vector<URLPattern> permissions = extension->host_permissions(); for (std::vector<URLPattern>::iterator permission = permissions.begin(); permission != permissions.end(); ++permission) { permission_list->Append(Value::CreateStringValue( permission->GetAsString())); } extension_data->Set(L"permissions", permission_list); // Add views ListValue* views = new ListValue; for (std::vector<ExtensionPage>::const_iterator iter = pages.begin(); iter != pages.end(); ++iter) { DictionaryValue* view_value = new DictionaryValue; view_value->SetString(L"path", iter->url.path().substr(1, std::string::npos)); // no leading slash view_value->SetInteger(L"renderViewId", iter->render_view_id); view_value->SetInteger(L"renderProcessId", iter->render_process_id); views->Append(view_value); } extension_data->Set(L"views", views); return extension_data; } std::vector<ExtensionPage> ExtensionsDOMHandler::GetActivePagesForExtension( const std::string& extension_id) { std::vector<ExtensionPage> result; std::set<ExtensionFunctionDispatcher*>* all_instances = ExtensionFunctionDispatcher::all_instances(); for (std::set<ExtensionFunctionDispatcher*>::iterator iter = all_instances->begin(); iter != all_instances->end(); ++iter) { RenderViewHost* view = (*iter)->render_view_host(); if ((*iter)->extension_id() == extension_id && view) { result.push_back(ExtensionPage((*iter)->url(), view->process()->id(), view->routing_id())); } } return result; } ExtensionsDOMHandler::~ExtensionsDOMHandler() { if (pack_job_.get()) pack_job_->ClearClient(); if (icon_loader_.get()) icon_loader_->Cancel(); } // ExtensionsDOMHandler, public: ----------------------------------------------- ExtensionsUI::ExtensionsUI(TabContents* contents) : DOMUI(contents) { ExtensionsService *exstension_service = GetProfile()->GetOriginalProfile()->GetExtensionsService(); ExtensionsDOMHandler* handler = new ExtensionsDOMHandler(exstension_service); AddMessageHandler(handler); handler->Attach(this); ExtensionsUIHTMLSource* html_source = new ExtensionsUIHTMLSource(); // Set up the chrome://extensions/ source. ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod( Singleton<ChromeURLDataManager>::get(), &ChromeURLDataManager::AddDataSource, html_source)); } // static RefCountedMemory* ExtensionsUI::GetFaviconResourceBytes() { return ResourceBundle::GetSharedInstance(). LoadImageResourceBytes(IDR_PLUGIN); } // static void ExtensionsUI::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kExtensionsUIDeveloperMode, false); } Change prevents multiple instances of an extension's option page from being opened within one window when teh "Options" button is pressed on the extensions settings page. BUG=none TEST=Install an extension that specifies an options_page in it's manifest file. Open the extensions page (wrench menu) and click the "Options" button for that extension. The options page will open and come to the forefront. Go back to the extensions tab and click "Options" again. The same tab as before should be brought to the forefront. Review URL: http://codereview.chromium.org/366026 Patch from Akira <akira@yayakoshi.net>. git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@31170 4ff67af0-8c30-449e-8e8b-ad334ec8d88c // Copyright (c) 2006-2009 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 "chrome/browser/extensions/extensions_ui.h" #include "app/gfx/codec/png_codec.h" #include "app/gfx/color_utils.h" #include "app/gfx/skbitmap_operations.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/file_util.h" #include "base/string_util.h" #include "base/thread.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/extensions/extension_function_dispatcher.h" #include "chrome/browser/extensions/extension_message_service.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/extension_updater.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/render_widget_host.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_error_reporter.h" #include "chrome/common/extensions/user_script.h" #include "chrome/common/extensions/url_pattern.h" #include "chrome/common/jstemplate_builder.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "chrome/common/url_constants.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "net/base/base64.h" #include "net/base/net_util.h" #include "webkit/glue/image_decoder.h" //////////////////////////////////////////////////////////////////////////////// // // ExtensionsHTMLSource // //////////////////////////////////////////////////////////////////////////////// ExtensionsUIHTMLSource::ExtensionsUIHTMLSource() : DataSource(chrome::kChromeUIExtensionsHost, MessageLoop::current()) { } void ExtensionsUIHTMLSource::StartDataRequest(const std::string& path, int request_id) { DictionaryValue localized_strings; localized_strings.SetString(L"title", l10n_util::GetString(IDS_EXTENSIONS_TITLE)); localized_strings.SetString(L"devModeLink", l10n_util::GetString(IDS_EXTENSIONS_DEVELOPER_MODE_LINK)); localized_strings.SetString(L"devModePrefix", l10n_util::GetString(IDS_EXTENSIONS_DEVELOPER_MODE_PREFIX)); localized_strings.SetString(L"loadUnpackedButton", l10n_util::GetString(IDS_EXTENSIONS_LOAD_UNPACKED_BUTTON)); localized_strings.SetString(L"packButton", l10n_util::GetString(IDS_EXTENSIONS_PACK_BUTTON)); localized_strings.SetString(L"updateButton", l10n_util::GetString(IDS_EXTENSIONS_UPDATE_BUTTON)); localized_strings.SetString(L"noExtensions", l10n_util::GetString(IDS_EXTENSIONS_NONE_INSTALLED)); localized_strings.SetString(L"extensionDisabled", l10n_util::GetString(IDS_EXTENSIONS_DISABLED_EXTENSION)); localized_strings.SetString(L"inDevelopment", l10n_util::GetString(IDS_EXTENSIONS_IN_DEVELOPMENT)); localized_strings.SetString(L"extensionId", l10n_util::GetString(IDS_EXTENSIONS_ID)); localized_strings.SetString(L"extensionVersion", l10n_util::GetString(IDS_EXTENSIONS_VERSION)); localized_strings.SetString(L"inspectViews", l10n_util::GetString(IDS_EXTENSIONS_INSPECT_VIEWS)); localized_strings.SetString(L"disable", l10n_util::GetString(IDS_EXTENSIONS_DISABLE)); localized_strings.SetString(L"enable", l10n_util::GetString(IDS_EXTENSIONS_ENABLE)); localized_strings.SetString(L"reload", l10n_util::GetString(IDS_EXTENSIONS_RELOAD)); localized_strings.SetString(L"uninstall", l10n_util::GetString(IDS_EXTENSIONS_UNINSTALL)); localized_strings.SetString(L"options", l10n_util::GetString(IDS_EXTENSIONS_OPTIONS)); localized_strings.SetString(L"packDialogTitle", l10n_util::GetString(IDS_EXTENSION_PACK_DIALOG_TITLE)); localized_strings.SetString(L"packDialogHeading", l10n_util::GetString(IDS_EXTENSION_PACK_DIALOG_HEADING)); localized_strings.SetString(L"rootDirectoryLabel", l10n_util::GetString(IDS_EXTENSION_PACK_DIALOG_ROOT_DIRECTORY_LABEL)); localized_strings.SetString(L"packDialogBrowse", l10n_util::GetString(IDS_EXTENSION_PACK_DIALOG_BROWSE)); localized_strings.SetString(L"privateKeyLabel", l10n_util::GetString(IDS_EXTENSION_PACK_DIALOG_PRIVATE_KEY_LABEL)); localized_strings.SetString(L"okButton", l10n_util::GetString(IDS_OK)); localized_strings.SetString(L"cancelButton", l10n_util::GetString(IDS_CANCEL)); static const base::StringPiece extensions_html( ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_EXTENSIONS_UI_HTML)); std::string full_html(extensions_html.data(), extensions_html.size()); jstemplate_builder::AppendJsonHtml(&localized_strings, &full_html); jstemplate_builder::AppendI18nTemplateSourceHtml(&full_html); jstemplate_builder::AppendI18nTemplateProcessHtml(&full_html); jstemplate_builder::AppendJsTemplateSourceHtml(&full_html); scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes); html_bytes->data.resize(full_html.size()); std::copy(full_html.begin(), full_html.end(), html_bytes->data.begin()); SendResponse(request_id, html_bytes); } //////////////////////////////////////////////////////////////////////////////// // // ExtensionsDOMHandler::IconLoader // //////////////////////////////////////////////////////////////////////////////// ExtensionsDOMHandler::IconLoader::IconLoader(ExtensionsDOMHandler* handler) : handler_(handler) { } void ExtensionsDOMHandler::IconLoader::LoadIcons( std::vector<ExtensionResource>* icons, DictionaryValue* json) { ChromeThread::PostTask( ChromeThread::FILE, FROM_HERE, NewRunnableMethod(this, &IconLoader::LoadIconsOnFileThread, icons, json)); } void ExtensionsDOMHandler::IconLoader::Cancel() { handler_ = NULL; } void ExtensionsDOMHandler::IconLoader::LoadIconsOnFileThread( std::vector<ExtensionResource>* icons, DictionaryValue* json) { scoped_ptr<std::vector<ExtensionResource> > icons_deleter(icons); scoped_ptr<DictionaryValue> json_deleter(json); ListValue* extensions = NULL; CHECK(json->GetList(L"extensions", &extensions)); for (size_t i = 0; i < icons->size(); ++i) { DictionaryValue* extension = NULL; CHECK(extensions->GetDictionary(static_cast<int>(i), &extension)); // Read the file. std::string file_contents; if (icons->at(i).relative_path().empty() || !file_util::ReadFileToString(icons->at(i).GetFilePath(), &file_contents)) { // If there's no icon, default to the puzzle icon. This is safe to do from // the file thread. file_contents = ResourceBundle::GetSharedInstance().GetDataResource( IDR_INFOBAR_PLUGIN_INSTALL); } // If the extension is disabled, we desaturate the icon to add to the // disabledness effect. bool enabled = false; CHECK(extension->GetBoolean(L"enabled", &enabled)); if (!enabled) { const unsigned char* data = reinterpret_cast<const unsigned char*>(file_contents.data()); webkit_glue::ImageDecoder decoder; scoped_ptr<SkBitmap> decoded(new SkBitmap()); *decoded = decoder.Decode(data, file_contents.length()); // Desaturate the icon and lighten it a bit. color_utils::HSL shift = {-1, 0, 0.6}; *decoded = SkBitmapOperations::CreateHSLShiftedBitmap(*decoded, shift); std::vector<unsigned char> output; gfx::PNGCodec::EncodeBGRASkBitmap(*decoded, false, &output); // Lame, but we must make a copy of this now, because base64 doesn't take // the same input type. file_contents.assign(reinterpret_cast<char*>(&output.front()), output.size()); } // Create a data URL (all icons are converted to PNGs during unpacking). std::string base64_encoded; net::Base64Encode(file_contents, &base64_encoded); GURL icon_url("data:image/png;base64," + base64_encoded); extension->SetString(L"icon", icon_url.spec()); } ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod(this, &IconLoader::ReportResultOnUIThread, json_deleter.release())); } void ExtensionsDOMHandler::IconLoader::ReportResultOnUIThread( DictionaryValue* json) { if (handler_) handler_->OnIconsLoaded(json); } /////////////////////////////////////////////////////////////////////////////// // // ExtensionsDOMHandler // /////////////////////////////////////////////////////////////////////////////// ExtensionsDOMHandler::ExtensionsDOMHandler(ExtensionsService* extension_service) : extensions_service_(extension_service) { } void ExtensionsDOMHandler::RegisterMessages() { dom_ui_->RegisterMessageCallback("requestExtensionsData", NewCallback(this, &ExtensionsDOMHandler::HandleRequestExtensionsData)); dom_ui_->RegisterMessageCallback("toggleDeveloperMode", NewCallback(this, &ExtensionsDOMHandler::HandleToggleDeveloperMode)); dom_ui_->RegisterMessageCallback("inspect", NewCallback(this, &ExtensionsDOMHandler::HandleInspectMessage)); dom_ui_->RegisterMessageCallback("reload", NewCallback(this, &ExtensionsDOMHandler::HandleReloadMessage)); dom_ui_->RegisterMessageCallback("enable", NewCallback(this, &ExtensionsDOMHandler::HandleEnableMessage)); dom_ui_->RegisterMessageCallback("uninstall", NewCallback(this, &ExtensionsDOMHandler::HandleUninstallMessage)); dom_ui_->RegisterMessageCallback("options", NewCallback(this, &ExtensionsDOMHandler::HandleOptionsMessage)); dom_ui_->RegisterMessageCallback("load", NewCallback(this, &ExtensionsDOMHandler::HandleLoadMessage)); dom_ui_->RegisterMessageCallback("pack", NewCallback(this, &ExtensionsDOMHandler::HandlePackMessage)); dom_ui_->RegisterMessageCallback("autoupdate", NewCallback(this, &ExtensionsDOMHandler::HandleAutoUpdateMessage)); dom_ui_->RegisterMessageCallback("selectFilePath", NewCallback(this, &ExtensionsDOMHandler::HandleSelectFilePathMessage)); } void ExtensionsDOMHandler::HandleRequestExtensionsData(const Value* value) { DictionaryValue* results = new DictionaryValue(); // Add the extensions to the results structure. ListValue *extensions_list = new ListValue(); // Stores the icon resource for each of the extensions in extensions_list. We // build up a list of them here, then load them on the file thread in // ::LoadIcons(). std::vector<ExtensionResource>* extension_icons = new std::vector<ExtensionResource>(); const ExtensionList* extensions = extensions_service_->extensions(); for (ExtensionList::const_iterator extension = extensions->begin(); extension != extensions->end(); ++extension) { // Don't show the themes since this page's UI isn't really useful for // themes. if (!(*extension)->IsTheme()) { extensions_list->Append(CreateExtensionDetailValue( *extension, GetActivePagesForExtension((*extension)->id()), true)); extension_icons->push_back(PickExtensionIcon(*extension)); } } extensions = extensions_service_->disabled_extensions(); for (ExtensionList::const_iterator extension = extensions->begin(); extension != extensions->end(); ++extension) { if (!(*extension)->IsTheme()) { extensions_list->Append(CreateExtensionDetailValue( *extension, GetActivePagesForExtension((*extension)->id()), false)); extension_icons->push_back(PickExtensionIcon(*extension)); } } results->Set(L"extensions", extensions_list); bool developer_mode = dom_ui_->GetProfile()->GetPrefs() ->GetBoolean(prefs::kExtensionsUIDeveloperMode); results->SetBoolean(L"developerMode", developer_mode); if (icon_loader_.get()) icon_loader_->Cancel(); icon_loader_ = new IconLoader(this); icon_loader_->LoadIcons(extension_icons, results); } void ExtensionsDOMHandler::OnIconsLoaded(DictionaryValue* json) { dom_ui_->CallJavascriptFunction(L"returnExtensionsData", *json); delete json; // Register for notifications that we need to reload the page. registrar_.RemoveAll(); registrar_.Add(this, NotificationType::EXTENSION_PROCESS_CREATED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::EXTENSION_UNLOADED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::EXTENSION_UPDATE_DISABLED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::EXTENSION_UNLOADED_DISABLED, NotificationService::AllSources()); } ExtensionResource ExtensionsDOMHandler::PickExtensionIcon( Extension* extension) { // Try to fetch the medium sized icon, then (if missing) go for the large one. const std::map<int, std::string>& icons = extension->icons(); std::map<int, std::string>::const_iterator iter = icons.find(Extension::EXTENSION_ICON_MEDIUM); if (iter == icons.end()) iter = icons.find(Extension::EXTENSION_ICON_LARGE); if (iter != icons.end()) return extension->GetResource(iter->second); else return ExtensionResource(); } void ExtensionsDOMHandler::HandleToggleDeveloperMode(const Value* value) { bool developer_mode = dom_ui_->GetProfile()->GetPrefs() ->GetBoolean(prefs::kExtensionsUIDeveloperMode); dom_ui_->GetProfile()->GetPrefs()->SetBoolean( prefs::kExtensionsUIDeveloperMode, !developer_mode); } void ExtensionsDOMHandler::HandleInspectMessage(const Value* value) { std::string render_process_id_str; std::string render_view_id_str; int render_process_id; int render_view_id; CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 2); CHECK(list->GetString(0, &render_process_id_str)); CHECK(list->GetString(1, &render_view_id_str)); CHECK(StringToInt(render_process_id_str, &render_process_id)); CHECK(StringToInt(render_view_id_str, &render_view_id)); RenderViewHost* host = RenderViewHost::FromID(render_process_id, render_view_id); if (!host) { // This can happen if the host has gone away since the page was displayed. return; } DevToolsManager::GetInstance()->OpenDevToolsWindow(host); } void ExtensionsDOMHandler::HandleReloadMessage(const Value* value) { CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 1); std::string extension_id; CHECK(list->GetString(0, &extension_id)); extensions_service_->ReloadExtension(extension_id); } void ExtensionsDOMHandler::HandleEnableMessage(const Value* value) { CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 2); std::string extension_id, enable_str; CHECK(list->GetString(0, &extension_id)); CHECK(list->GetString(1, &enable_str)); if (enable_str == "true") { extensions_service_->EnableExtension(extension_id); } else { extensions_service_->DisableExtension(extension_id); } } void ExtensionsDOMHandler::HandleUninstallMessage(const Value* value) { CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 1); std::string extension_id; CHECK(list->GetString(0, &extension_id)); extensions_service_->UninstallExtension(extension_id, false); } void ExtensionsDOMHandler::HandleOptionsMessage(const Value* value) { CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 1); std::string extension_id; CHECK(list->GetString(0, &extension_id)); Extension *extension = extensions_service_->GetExtensionById(extension_id); if (!extension || extension->options_url().is_empty()) { return; } Browser* browser = Browser::GetOrCreateTabbedBrowser(dom_ui_->GetProfile()); CHECK(browser); browser->OpenURL(extension->options_url(), GURL(), SINGLETON_TAB, PageTransition::LINK); } void ExtensionsDOMHandler::HandleLoadMessage(const Value* value) { std::string string_path; CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 1) << list->GetSize(); CHECK(list->GetString(0, &string_path)); FilePath file_path = FilePath::FromWStringHack(ASCIIToWide(string_path)); extensions_service_->LoadExtension(file_path); } void ExtensionsDOMHandler::ShowAlert(const std::string& message) { ListValue arguments; arguments.Append(Value::CreateStringValue(message)); dom_ui_->CallJavascriptFunction(L"alert", arguments); } void ExtensionsDOMHandler::HandlePackMessage(const Value* value) { std::string extension_path; std::string private_key_path; CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 2); CHECK(list->GetString(0, &extension_path)); CHECK(list->GetString(1, &private_key_path)); FilePath root_directory = FilePath::FromWStringHack(ASCIIToWide( extension_path)); FilePath key_file = FilePath::FromWStringHack(ASCIIToWide(private_key_path)); if (root_directory.empty()) { if (extension_path.empty()) { ShowAlert(l10n_util::GetStringUTF8( IDS_EXTENSION_PACK_DIALOG_ERROR_ROOT_REQUIRED)); } else { ShowAlert(l10n_util::GetStringUTF8( IDS_EXTENSION_PACK_DIALOG_ERROR_ROOT_INVALID)); } return; } if (!private_key_path.empty() && key_file.empty()) { ShowAlert(l10n_util::GetStringUTF8( IDS_EXTENSION_PACK_DIALOG_ERROR_KEY_INVALID)); return; } pack_job_ = new PackExtensionJob(this, root_directory, key_file); } void ExtensionsDOMHandler::OnPackSuccess(const FilePath& crx_file, const FilePath& pem_file) { std::string message; if (!pem_file.empty()) { message = WideToASCII(l10n_util::GetStringF( IDS_EXTENSION_PACK_DIALOG_SUCCESS_BODY_NEW, crx_file.ToWStringHack(), pem_file.ToWStringHack())); } else { message = WideToASCII(l10n_util::GetStringF( IDS_EXTENSION_PACK_DIALOG_SUCCESS_BODY_UPDATE, crx_file.ToWStringHack())); } ShowAlert(message); ListValue results; dom_ui_->CallJavascriptFunction(L"hidePackDialog", results); } void ExtensionsDOMHandler::OnPackFailure(const std::wstring& error) { ShowAlert(WideToASCII(error)); } void ExtensionsDOMHandler::HandleAutoUpdateMessage(const Value* value) { ExtensionUpdater* updater = extensions_service_->updater(); if (updater) { updater->CheckNow(); } } void ExtensionsDOMHandler::HandleSelectFilePathMessage(const Value* value) { std::string select_type; std::string operation; CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 2); CHECK(list->GetString(0, &select_type)); CHECK(list->GetString(1, &operation)); SelectFileDialog::Type type = SelectFileDialog::SELECT_FOLDER; static SelectFileDialog::FileTypeInfo info; int file_type_index = 0; if (select_type == "file") type = SelectFileDialog::SELECT_OPEN_FILE; string16 select_title; if (operation == "load") select_title = l10n_util::GetStringUTF16(IDS_EXTENSION_LOAD_FROM_DIRECTORY); else if (operation == "packRoot") select_title = l10n_util::GetStringUTF16( IDS_EXTENSION_PACK_DIALOG_SELECT_ROOT); else if (operation == "pem") { select_title = l10n_util::GetStringUTF16( IDS_EXTENSION_PACK_DIALOG_SELECT_KEY); info.extensions.push_back(std::vector<FilePath::StringType>()); info.extensions.front().push_back(FILE_PATH_LITERAL("pem")); info.extension_description_overrides.push_back(WideToUTF16( l10n_util::GetString( IDS_EXTENSION_PACK_DIALOG_KEY_FILE_TYPE_DESCRIPTION))); info.include_all_files = true; file_type_index = 1; } else { NOTREACHED(); return; } load_extension_dialog_ = SelectFileDialog::Create(this); load_extension_dialog_->SelectFile(type, select_title, FilePath(), &info, file_type_index, FILE_PATH_LITERAL(""), dom_ui_->tab_contents()->view()->GetTopLevelNativeWindow(), NULL); } void ExtensionsDOMHandler::FileSelected(const FilePath& path, int index, void* params) { // Add the extensions to the results structure. ListValue results; results.Append(Value::CreateStringValue(path.value())); dom_ui_->CallJavascriptFunction(L"window.handleFilePathSelected", results); } void ExtensionsDOMHandler::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::EXTENSION_PROCESS_CREATED: case NotificationType::EXTENSION_UNLOADED: case NotificationType::EXTENSION_UPDATE_DISABLED: case NotificationType::EXTENSION_UNLOADED_DISABLED: if (dom_ui_->tab_contents()) HandleRequestExtensionsData(NULL); break; default: NOTREACHED(); } } static void CreateScriptFileDetailValue( const FilePath& extension_path, const UserScript::FileList& scripts, const wchar_t* key, DictionaryValue* script_data) { if (scripts.empty()) return; ListValue *list = new ListValue(); for (size_t i = 0; i < scripts.size(); ++i) { const UserScript::File& file = scripts[i]; // TODO(cira): this information is not used on extension page yet. We // may want to display actual resource that got loaded, not default. list->Append( new StringValue(file.relative_path().value())); } script_data->Set(key, list); } // Static DictionaryValue* ExtensionsDOMHandler::CreateContentScriptDetailValue( const UserScript& script, const FilePath& extension_path) { DictionaryValue* script_data = new DictionaryValue(); CreateScriptFileDetailValue(extension_path, script.js_scripts(), L"js", script_data); CreateScriptFileDetailValue(extension_path, script.css_scripts(), L"css", script_data); // Get list of glob "matches" strings ListValue *url_pattern_list = new ListValue(); const std::vector<URLPattern>& url_patterns = script.url_patterns(); for (std::vector<URLPattern>::const_iterator url_pattern = url_patterns.begin(); url_pattern != url_patterns.end(); ++url_pattern) { url_pattern_list->Append(new StringValue(url_pattern->GetAsString())); } script_data->Set(L"matches", url_pattern_list); return script_data; } // Static DictionaryValue* ExtensionsDOMHandler::CreateExtensionDetailValue( const Extension *extension, const std::vector<ExtensionPage>& pages, bool enabled) { DictionaryValue* extension_data = new DictionaryValue(); extension_data->SetString(L"id", extension->id()); extension_data->SetString(L"name", extension->name()); extension_data->SetString(L"description", extension->description()); extension_data->SetString(L"version", extension->version()->GetString()); extension_data->SetBoolean(L"enabled", enabled); // Determine the sort order: Extensions loaded through --load-extensions show // up at the top. Disabled extensions show up at the bottom. if (extension->location() == Extension::LOAD) extension_data->SetInteger(L"order", 1); else extension_data->SetInteger(L"order", 2); if (!extension->options_url().is_empty()) extension_data->SetString(L"options_url", extension->options_url().spec()); // Add list of content_script detail DictionaryValues ListValue *content_script_list = new ListValue(); UserScriptList content_scripts = extension->content_scripts(); for (UserScriptList::const_iterator script = content_scripts.begin(); script != content_scripts.end(); ++script) { content_script_list->Append( CreateContentScriptDetailValue(*script, extension->path())); } extension_data->Set(L"content_scripts", content_script_list); // Add permissions ListValue *permission_list = new ListValue; std::vector<URLPattern> permissions = extension->host_permissions(); for (std::vector<URLPattern>::iterator permission = permissions.begin(); permission != permissions.end(); ++permission) { permission_list->Append(Value::CreateStringValue( permission->GetAsString())); } extension_data->Set(L"permissions", permission_list); // Add views ListValue* views = new ListValue; for (std::vector<ExtensionPage>::const_iterator iter = pages.begin(); iter != pages.end(); ++iter) { DictionaryValue* view_value = new DictionaryValue; view_value->SetString(L"path", iter->url.path().substr(1, std::string::npos)); // no leading slash view_value->SetInteger(L"renderViewId", iter->render_view_id); view_value->SetInteger(L"renderProcessId", iter->render_process_id); views->Append(view_value); } extension_data->Set(L"views", views); return extension_data; } std::vector<ExtensionPage> ExtensionsDOMHandler::GetActivePagesForExtension( const std::string& extension_id) { std::vector<ExtensionPage> result; std::set<ExtensionFunctionDispatcher*>* all_instances = ExtensionFunctionDispatcher::all_instances(); for (std::set<ExtensionFunctionDispatcher*>::iterator iter = all_instances->begin(); iter != all_instances->end(); ++iter) { RenderViewHost* view = (*iter)->render_view_host(); if ((*iter)->extension_id() == extension_id && view) { result.push_back(ExtensionPage((*iter)->url(), view->process()->id(), view->routing_id())); } } return result; } ExtensionsDOMHandler::~ExtensionsDOMHandler() { if (pack_job_.get()) pack_job_->ClearClient(); if (icon_loader_.get()) icon_loader_->Cancel(); } // ExtensionsDOMHandler, public: ----------------------------------------------- ExtensionsUI::ExtensionsUI(TabContents* contents) : DOMUI(contents) { ExtensionsService *exstension_service = GetProfile()->GetOriginalProfile()->GetExtensionsService(); ExtensionsDOMHandler* handler = new ExtensionsDOMHandler(exstension_service); AddMessageHandler(handler); handler->Attach(this); ExtensionsUIHTMLSource* html_source = new ExtensionsUIHTMLSource(); // Set up the chrome://extensions/ source. ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod( Singleton<ChromeURLDataManager>::get(), &ChromeURLDataManager::AddDataSource, html_source)); } // static RefCountedMemory* ExtensionsUI::GetFaviconResourceBytes() { return ResourceBundle::GetSharedInstance(). LoadImageResourceBytes(IDR_PLUGIN); } // static void ExtensionsUI::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kExtensionsUIDeveloperMode, false); }
// 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 "chrome/browser/gtk/gtk_custom_menu_item.h" #include "base/i18n/rtl.h" #include "base/logging.h" #include "chrome/browser/gtk/gtk_custom_menu.h" enum { BUTTON_PUSHED, LAST_SIGNAL }; static guint custom_menu_item_signals[LAST_SIGNAL] = { 0 }; G_DEFINE_TYPE(GtkCustomMenuItem, gtk_custom_menu_item, GTK_TYPE_MENU_ITEM) static void set_selected(GtkCustomMenuItem* item, GtkWidget* selected) { if (selected != item->currently_selected_button) { if (item->currently_selected_button) { gtk_widget_set_state(item->currently_selected_button, GTK_STATE_NORMAL); gtk_widget_set_state( gtk_bin_get_child(GTK_BIN(item->currently_selected_button)), GTK_STATE_NORMAL); } item->currently_selected_button = selected; if (item->currently_selected_button) { gtk_widget_set_state(item->currently_selected_button, GTK_STATE_SELECTED); gtk_widget_set_state( gtk_bin_get_child(GTK_BIN(item->currently_selected_button)), GTK_STATE_PRELIGHT); } } } // When GtkButtons set the label text, they rebuild the widget hierarchy each // and every time. Therefore, we can't just fish out the label from the button // and set some properties; we have to create this callback function that // listens on the button's "notify" signal, which is emitted right after the // label has been (re)created. (Label values can change dynamically.) static void on_button_label_set(GObject* object) { GtkButton* button = GTK_BUTTON(object); gtk_widget_set_sensitive(GTK_BIN(button)->child, FALSE); gtk_misc_set_padding(GTK_MISC(GTK_BIN(button)->child), 2, 0); } static void gtk_custom_menu_item_finalize(GObject *object); static gint gtk_custom_menu_item_expose(GtkWidget* widget, GdkEventExpose* event); static gboolean gtk_custom_menu_item_hbox_expose(GtkWidget* widget, GdkEventExpose* event, GtkCustomMenuItem* menu_item); static void gtk_custom_menu_item_select(GtkItem *item); static void gtk_custom_menu_item_deselect(GtkItem *item); static void gtk_custom_menu_item_activate(GtkMenuItem* menu_item); static void gtk_custom_menu_item_init(GtkCustomMenuItem* item) { item->all_widgets = NULL; item->button_widgets = NULL; item->currently_selected_button = NULL; item->previously_selected_button = NULL; GtkWidget* menu_hbox = gtk_hbox_new(FALSE, 0); gtk_container_add(GTK_CONTAINER(item), menu_hbox); item->label = gtk_label_new(NULL); gtk_misc_set_alignment(GTK_MISC(item->label), 0.0, 0.5); gtk_box_pack_start(GTK_BOX(menu_hbox), item->label, TRUE, TRUE, 0); item->hbox = gtk_hbox_new(FALSE, 0); gtk_box_pack_end(GTK_BOX(menu_hbox), item->hbox, FALSE, FALSE, 0); g_signal_connect(item->hbox, "expose-event", G_CALLBACK(gtk_custom_menu_item_hbox_expose), item); gtk_widget_show_all(menu_hbox); } static void gtk_custom_menu_item_class_init(GtkCustomMenuItemClass* klass) { GObjectClass* gobject_class = G_OBJECT_CLASS(klass); GtkWidgetClass* widget_class = GTK_WIDGET_CLASS(klass); GtkItemClass* item_class = GTK_ITEM_CLASS(klass); GtkMenuItemClass* menu_item_class = GTK_MENU_ITEM_CLASS(klass); gobject_class->finalize = gtk_custom_menu_item_finalize; widget_class->expose_event = gtk_custom_menu_item_expose; item_class->select = gtk_custom_menu_item_select; item_class->deselect = gtk_custom_menu_item_deselect; menu_item_class->activate = gtk_custom_menu_item_activate; custom_menu_item_signals[BUTTON_PUSHED] = g_signal_new("button-pushed", G_OBJECT_CLASS_TYPE(gobject_class), G_SIGNAL_RUN_FIRST, 0, NULL, NULL, gtk_marshal_NONE__INT, G_TYPE_NONE, 1, GTK_TYPE_INT); } static void gtk_custom_menu_item_finalize(GObject *object) { GtkCustomMenuItem* item = GTK_CUSTOM_MENU_ITEM(object); g_list_free(item->all_widgets); g_list_free(item->button_widgets); G_OBJECT_CLASS(gtk_custom_menu_item_parent_class)->finalize(object); } static gint gtk_custom_menu_item_expose(GtkWidget* widget, GdkEventExpose* event) { if (GTK_WIDGET_VISIBLE(widget) && GTK_WIDGET_MAPPED(widget) && gtk_bin_get_child(GTK_BIN(widget))) { // We skip the drawing in the GtkMenuItem class it draws the highlighted // background and we don't want that. gtk_container_propagate_expose(GTK_CONTAINER(widget), gtk_bin_get_child(GTK_BIN(widget)), event); } return FALSE; } static void gtk_custom_menu_item_expose_button(GtkWidget* hbox, GdkEventExpose* event, GList* button_item) { // We search backwards to find the leftmost and rightmost buttons. The // current button may be that button. GtkWidget* current_button = GTK_WIDGET(button_item->data); GtkWidget* first_button = current_button; for (GList* i = button_item; i && GTK_IS_BUTTON(i->data); i = g_list_previous(i)) { first_button = GTK_WIDGET(i->data); } GtkWidget* last_button = current_button; for (GList* i = button_item; i && GTK_IS_BUTTON(i->data); i = g_list_next(i)) { last_button = GTK_WIDGET(i->data); } if (base::i18n::IsRTL()) std::swap(first_button, last_button); int x = first_button->allocation.x; int y = first_button->allocation.y; int width = last_button->allocation.width + last_button->allocation.x - first_button->allocation.x; int height = last_button->allocation.height; gtk_paint_box(hbox->style, hbox->window, static_cast<GtkStateType>( GTK_WIDGET_STATE(current_button)), GTK_SHADOW_OUT, &current_button->allocation, hbox, "button", x, y, width, height); // Propagate to the button's children. gtk_container_propagate_expose( GTK_CONTAINER(current_button), gtk_bin_get_child(GTK_BIN(current_button)), event); } static gboolean gtk_custom_menu_item_hbox_expose(GtkWidget* widget, GdkEventExpose* event, GtkCustomMenuItem* menu_item) { // First render all the buttons that aren't the currently selected item. for (GList* current_item = menu_item->all_widgets; current_item != NULL; current_item = g_list_next(current_item)) { if (GTK_IS_BUTTON(current_item->data)) { if (GTK_WIDGET(current_item->data) != menu_item->currently_selected_button) { gtk_custom_menu_item_expose_button(widget, event, current_item); } } } // As a separate pass, draw the buton separators above. We need to draw the // separators in a separate pass because we are drawing on top of the // buttons. Otherwise, the vlines are overwritten by the next button. for (GList* current_item = menu_item->all_widgets; current_item != NULL; current_item = g_list_next(current_item)) { if (GTK_IS_BUTTON(current_item->data)) { // Check to see if this is the last button in a run. GList* next_item = g_list_next(current_item); if (next_item && GTK_IS_BUTTON(next_item->data)) { GtkWidget* current_button = GTK_WIDGET(current_item->data); GtkAllocation child_alloc = gtk_bin_get_child(GTK_BIN(current_button))->allocation; int half_offset = widget->style->xthickness / 2; gtk_paint_vline(widget->style, widget->window, static_cast<GtkStateType>( GTK_WIDGET_STATE(current_button)), &event->area, widget, "button", child_alloc.y, child_alloc.y + child_alloc.height, current_button->allocation.x + current_button->allocation.width - half_offset); } } } // Finally, draw the selected item on top of the separators so there are no // artifacts inside the button area. GList* selected = g_list_find(menu_item->all_widgets, menu_item->currently_selected_button); if (selected) { gtk_custom_menu_item_expose_button(widget, event, selected); } return TRUE; } static void gtk_custom_menu_item_select(GtkItem* item) { GtkCustomMenuItem* custom_item = GTK_CUSTOM_MENU_ITEM(item); // When we are selected, the only thing we do is clear information from // previous selections. Actual selection of a button is done either in the // "mouse-motion-event" or is manually set from GtkCustomMenu's overridden // "move-current" handler. custom_item->previously_selected_button = NULL; gtk_widget_queue_draw(GTK_WIDGET(item)); } static void gtk_custom_menu_item_deselect(GtkItem* item) { GtkCustomMenuItem* custom_item = GTK_CUSTOM_MENU_ITEM(item); // When we are deselected, we store the item that was currently selected so // that it can be acted on. Menu items are first deselected before they are // activated. custom_item->previously_selected_button = custom_item->currently_selected_button; if (custom_item->currently_selected_button) set_selected(custom_item, NULL); gtk_widget_queue_draw(GTK_WIDGET(item)); } static void gtk_custom_menu_item_activate(GtkMenuItem* menu_item) { GtkCustomMenuItem* custom_item = GTK_CUSTOM_MENU_ITEM(menu_item); // We look at |previously_selected_button| because by the time we've been // activated, we've already gone through our deselect handler. if (custom_item->previously_selected_button) { gpointer id_ptr = g_object_get_data( G_OBJECT(custom_item->previously_selected_button), "command-id"); if (id_ptr != NULL) { int command_id = GPOINTER_TO_INT(id_ptr); g_signal_emit(custom_item, custom_menu_item_signals[BUTTON_PUSHED], 0, command_id); set_selected(custom_item, NULL); } } } GtkWidget* gtk_custom_menu_item_new(const char* title) { GtkCustomMenuItem* item = GTK_CUSTOM_MENU_ITEM( g_object_new(GTK_TYPE_CUSTOM_MENU_ITEM, NULL)); char* markup = g_markup_printf_escaped("<b>%s</b>", title); gtk_label_set_markup(GTK_LABEL(item->label), markup); g_free(markup); return GTK_WIDGET(item); } GtkWidget* gtk_custom_menu_item_add_button(GtkCustomMenuItem* menu_item, int command_id) { GtkWidget* button = gtk_button_new(); g_object_set_data(G_OBJECT(button), "command-id", GINT_TO_POINTER(command_id)); gtk_box_pack_start(GTK_BOX(menu_item->hbox), button, FALSE, FALSE, 0); gtk_widget_show(button); menu_item->all_widgets = g_list_append(menu_item->all_widgets, button); menu_item->button_widgets = g_list_append(menu_item->button_widgets, button); return button; } GtkWidget* gtk_custom_menu_item_add_button_label(GtkCustomMenuItem* menu_item, int command_id) { GtkWidget* button = gtk_button_new_with_label(""); g_object_set_data(G_OBJECT(button), "command-id", GINT_TO_POINTER(command_id)); gtk_box_pack_start(GTK_BOX(menu_item->hbox), button, FALSE, FALSE, 0); g_signal_connect(button, "notify::label", G_CALLBACK(on_button_label_set), NULL); gtk_widget_show(button); menu_item->all_widgets = g_list_append(menu_item->all_widgets, button); return button; } void gtk_custom_menu_item_add_space(GtkCustomMenuItem* menu_item) { GtkWidget* fixed = gtk_fixed_new(); gtk_widget_set_size_request(fixed, 5, -1); gtk_box_pack_start(GTK_BOX(menu_item->hbox), fixed, FALSE, FALSE, 0); gtk_widget_show(fixed); menu_item->all_widgets = g_list_append(menu_item->all_widgets, fixed); } void gtk_custom_menu_item_receive_motion_event(GtkCustomMenuItem* menu_item, gdouble x, gdouble y) { GtkWidget* new_selected_widget = NULL; GList* current = menu_item->button_widgets; for (; current != NULL; current = current->next) { GtkWidget* current_widget = GTK_WIDGET(current->data); GtkAllocation alloc = current_widget->allocation; int offset_x, offset_y; gtk_widget_translate_coordinates(current_widget, GTK_WIDGET(menu_item), 0, 0, &offset_x, &offset_y); if (x >= offset_x && x < (offset_x + alloc.width) && y >= offset_y && y < (offset_y + alloc.height)) { new_selected_widget = current_widget; break; } } set_selected(menu_item, new_selected_widget); } gboolean gtk_custom_menu_item_handle_move(GtkCustomMenuItem* menu_item, GtkMenuDirectionType direction) { GtkWidget* current = menu_item->currently_selected_button; if (menu_item->button_widgets && current) { switch (direction) { case GTK_MENU_DIR_PREV: { if (g_list_first(menu_item->button_widgets)->data == current) return FALSE; set_selected(menu_item, GTK_WIDGET(g_list_previous(g_list_find( menu_item->button_widgets, current))->data)); break; } case GTK_MENU_DIR_NEXT: { if (g_list_last(menu_item->button_widgets)->data == current) return FALSE; set_selected(menu_item, GTK_WIDGET(g_list_next(g_list_find( menu_item->button_widgets, current))->data)); break; } default: break; } } return TRUE; } void gtk_custom_menu_item_select_item_by_direction( GtkCustomMenuItem* menu_item, GtkMenuDirectionType direction) { menu_item->previously_selected_button = NULL; // If we're just told to be selected by the menu system, select the first // item. if (menu_item->button_widgets) { switch (direction) { case GTK_MENU_DIR_PREV: { GtkWidget* last_button = GTK_WIDGET(g_list_last(menu_item->button_widgets)->data); if (last_button) set_selected(menu_item, last_button); break; } case GTK_MENU_DIR_NEXT: { GtkWidget* first_button = GTK_WIDGET(g_list_first(menu_item->button_widgets)->data); if (first_button) set_selected(menu_item, first_button); break; } default: break; } } gtk_widget_queue_draw(GTK_WIDGET(menu_item)); } gboolean gtk_custom_menu_item_is_in_clickable_region( GtkCustomMenuItem* menu_item) { return menu_item->currently_selected_button != NULL; } GTK: Unbold the labels in the crazy menu. BUG=50240 TEST=none Review URL: http://codereview.chromium.org/3039030 git-svn-id: http://src.chromium.org/svn/trunk/src@53654 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: c3dc28dad03d3df8bea929b8eb8fb1445adae293 // 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 "chrome/browser/gtk/gtk_custom_menu_item.h" #include "base/i18n/rtl.h" #include "base/logging.h" #include "chrome/browser/gtk/gtk_custom_menu.h" enum { BUTTON_PUSHED, LAST_SIGNAL }; static guint custom_menu_item_signals[LAST_SIGNAL] = { 0 }; G_DEFINE_TYPE(GtkCustomMenuItem, gtk_custom_menu_item, GTK_TYPE_MENU_ITEM) static void set_selected(GtkCustomMenuItem* item, GtkWidget* selected) { if (selected != item->currently_selected_button) { if (item->currently_selected_button) { gtk_widget_set_state(item->currently_selected_button, GTK_STATE_NORMAL); gtk_widget_set_state( gtk_bin_get_child(GTK_BIN(item->currently_selected_button)), GTK_STATE_NORMAL); } item->currently_selected_button = selected; if (item->currently_selected_button) { gtk_widget_set_state(item->currently_selected_button, GTK_STATE_SELECTED); gtk_widget_set_state( gtk_bin_get_child(GTK_BIN(item->currently_selected_button)), GTK_STATE_PRELIGHT); } } } // When GtkButtons set the label text, they rebuild the widget hierarchy each // and every time. Therefore, we can't just fish out the label from the button // and set some properties; we have to create this callback function that // listens on the button's "notify" signal, which is emitted right after the // label has been (re)created. (Label values can change dynamically.) static void on_button_label_set(GObject* object) { GtkButton* button = GTK_BUTTON(object); gtk_widget_set_sensitive(GTK_BIN(button)->child, FALSE); gtk_misc_set_padding(GTK_MISC(GTK_BIN(button)->child), 2, 0); } static void gtk_custom_menu_item_finalize(GObject *object); static gint gtk_custom_menu_item_expose(GtkWidget* widget, GdkEventExpose* event); static gboolean gtk_custom_menu_item_hbox_expose(GtkWidget* widget, GdkEventExpose* event, GtkCustomMenuItem* menu_item); static void gtk_custom_menu_item_select(GtkItem *item); static void gtk_custom_menu_item_deselect(GtkItem *item); static void gtk_custom_menu_item_activate(GtkMenuItem* menu_item); static void gtk_custom_menu_item_init(GtkCustomMenuItem* item) { item->all_widgets = NULL; item->button_widgets = NULL; item->currently_selected_button = NULL; item->previously_selected_button = NULL; GtkWidget* menu_hbox = gtk_hbox_new(FALSE, 0); gtk_container_add(GTK_CONTAINER(item), menu_hbox); item->label = gtk_label_new(NULL); gtk_misc_set_alignment(GTK_MISC(item->label), 0.0, 0.5); gtk_box_pack_start(GTK_BOX(menu_hbox), item->label, TRUE, TRUE, 0); item->hbox = gtk_hbox_new(FALSE, 0); gtk_box_pack_end(GTK_BOX(menu_hbox), item->hbox, FALSE, FALSE, 0); g_signal_connect(item->hbox, "expose-event", G_CALLBACK(gtk_custom_menu_item_hbox_expose), item); gtk_widget_show_all(menu_hbox); } static void gtk_custom_menu_item_class_init(GtkCustomMenuItemClass* klass) { GObjectClass* gobject_class = G_OBJECT_CLASS(klass); GtkWidgetClass* widget_class = GTK_WIDGET_CLASS(klass); GtkItemClass* item_class = GTK_ITEM_CLASS(klass); GtkMenuItemClass* menu_item_class = GTK_MENU_ITEM_CLASS(klass); gobject_class->finalize = gtk_custom_menu_item_finalize; widget_class->expose_event = gtk_custom_menu_item_expose; item_class->select = gtk_custom_menu_item_select; item_class->deselect = gtk_custom_menu_item_deselect; menu_item_class->activate = gtk_custom_menu_item_activate; custom_menu_item_signals[BUTTON_PUSHED] = g_signal_new("button-pushed", G_OBJECT_CLASS_TYPE(gobject_class), G_SIGNAL_RUN_FIRST, 0, NULL, NULL, gtk_marshal_NONE__INT, G_TYPE_NONE, 1, GTK_TYPE_INT); } static void gtk_custom_menu_item_finalize(GObject *object) { GtkCustomMenuItem* item = GTK_CUSTOM_MENU_ITEM(object); g_list_free(item->all_widgets); g_list_free(item->button_widgets); G_OBJECT_CLASS(gtk_custom_menu_item_parent_class)->finalize(object); } static gint gtk_custom_menu_item_expose(GtkWidget* widget, GdkEventExpose* event) { if (GTK_WIDGET_VISIBLE(widget) && GTK_WIDGET_MAPPED(widget) && gtk_bin_get_child(GTK_BIN(widget))) { // We skip the drawing in the GtkMenuItem class it draws the highlighted // background and we don't want that. gtk_container_propagate_expose(GTK_CONTAINER(widget), gtk_bin_get_child(GTK_BIN(widget)), event); } return FALSE; } static void gtk_custom_menu_item_expose_button(GtkWidget* hbox, GdkEventExpose* event, GList* button_item) { // We search backwards to find the leftmost and rightmost buttons. The // current button may be that button. GtkWidget* current_button = GTK_WIDGET(button_item->data); GtkWidget* first_button = current_button; for (GList* i = button_item; i && GTK_IS_BUTTON(i->data); i = g_list_previous(i)) { first_button = GTK_WIDGET(i->data); } GtkWidget* last_button = current_button; for (GList* i = button_item; i && GTK_IS_BUTTON(i->data); i = g_list_next(i)) { last_button = GTK_WIDGET(i->data); } if (base::i18n::IsRTL()) std::swap(first_button, last_button); int x = first_button->allocation.x; int y = first_button->allocation.y; int width = last_button->allocation.width + last_button->allocation.x - first_button->allocation.x; int height = last_button->allocation.height; gtk_paint_box(hbox->style, hbox->window, static_cast<GtkStateType>( GTK_WIDGET_STATE(current_button)), GTK_SHADOW_OUT, &current_button->allocation, hbox, "button", x, y, width, height); // Propagate to the button's children. gtk_container_propagate_expose( GTK_CONTAINER(current_button), gtk_bin_get_child(GTK_BIN(current_button)), event); } static gboolean gtk_custom_menu_item_hbox_expose(GtkWidget* widget, GdkEventExpose* event, GtkCustomMenuItem* menu_item) { // First render all the buttons that aren't the currently selected item. for (GList* current_item = menu_item->all_widgets; current_item != NULL; current_item = g_list_next(current_item)) { if (GTK_IS_BUTTON(current_item->data)) { if (GTK_WIDGET(current_item->data) != menu_item->currently_selected_button) { gtk_custom_menu_item_expose_button(widget, event, current_item); } } } // As a separate pass, draw the buton separators above. We need to draw the // separators in a separate pass because we are drawing on top of the // buttons. Otherwise, the vlines are overwritten by the next button. for (GList* current_item = menu_item->all_widgets; current_item != NULL; current_item = g_list_next(current_item)) { if (GTK_IS_BUTTON(current_item->data)) { // Check to see if this is the last button in a run. GList* next_item = g_list_next(current_item); if (next_item && GTK_IS_BUTTON(next_item->data)) { GtkWidget* current_button = GTK_WIDGET(current_item->data); GtkAllocation child_alloc = gtk_bin_get_child(GTK_BIN(current_button))->allocation; int half_offset = widget->style->xthickness / 2; gtk_paint_vline(widget->style, widget->window, static_cast<GtkStateType>( GTK_WIDGET_STATE(current_button)), &event->area, widget, "button", child_alloc.y, child_alloc.y + child_alloc.height, current_button->allocation.x + current_button->allocation.width - half_offset); } } } // Finally, draw the selected item on top of the separators so there are no // artifacts inside the button area. GList* selected = g_list_find(menu_item->all_widgets, menu_item->currently_selected_button); if (selected) { gtk_custom_menu_item_expose_button(widget, event, selected); } return TRUE; } static void gtk_custom_menu_item_select(GtkItem* item) { GtkCustomMenuItem* custom_item = GTK_CUSTOM_MENU_ITEM(item); // When we are selected, the only thing we do is clear information from // previous selections. Actual selection of a button is done either in the // "mouse-motion-event" or is manually set from GtkCustomMenu's overridden // "move-current" handler. custom_item->previously_selected_button = NULL; gtk_widget_queue_draw(GTK_WIDGET(item)); } static void gtk_custom_menu_item_deselect(GtkItem* item) { GtkCustomMenuItem* custom_item = GTK_CUSTOM_MENU_ITEM(item); // When we are deselected, we store the item that was currently selected so // that it can be acted on. Menu items are first deselected before they are // activated. custom_item->previously_selected_button = custom_item->currently_selected_button; if (custom_item->currently_selected_button) set_selected(custom_item, NULL); gtk_widget_queue_draw(GTK_WIDGET(item)); } static void gtk_custom_menu_item_activate(GtkMenuItem* menu_item) { GtkCustomMenuItem* custom_item = GTK_CUSTOM_MENU_ITEM(menu_item); // We look at |previously_selected_button| because by the time we've been // activated, we've already gone through our deselect handler. if (custom_item->previously_selected_button) { gpointer id_ptr = g_object_get_data( G_OBJECT(custom_item->previously_selected_button), "command-id"); if (id_ptr != NULL) { int command_id = GPOINTER_TO_INT(id_ptr); g_signal_emit(custom_item, custom_menu_item_signals[BUTTON_PUSHED], 0, command_id); set_selected(custom_item, NULL); } } } GtkWidget* gtk_custom_menu_item_new(const char* title) { GtkCustomMenuItem* item = GTK_CUSTOM_MENU_ITEM( g_object_new(GTK_TYPE_CUSTOM_MENU_ITEM, NULL)); gtk_label_set_text(GTK_LABEL(item->label), title); return GTK_WIDGET(item); } GtkWidget* gtk_custom_menu_item_add_button(GtkCustomMenuItem* menu_item, int command_id) { GtkWidget* button = gtk_button_new(); g_object_set_data(G_OBJECT(button), "command-id", GINT_TO_POINTER(command_id)); gtk_box_pack_start(GTK_BOX(menu_item->hbox), button, FALSE, FALSE, 0); gtk_widget_show(button); menu_item->all_widgets = g_list_append(menu_item->all_widgets, button); menu_item->button_widgets = g_list_append(menu_item->button_widgets, button); return button; } GtkWidget* gtk_custom_menu_item_add_button_label(GtkCustomMenuItem* menu_item, int command_id) { GtkWidget* button = gtk_button_new_with_label(""); g_object_set_data(G_OBJECT(button), "command-id", GINT_TO_POINTER(command_id)); gtk_box_pack_start(GTK_BOX(menu_item->hbox), button, FALSE, FALSE, 0); g_signal_connect(button, "notify::label", G_CALLBACK(on_button_label_set), NULL); gtk_widget_show(button); menu_item->all_widgets = g_list_append(menu_item->all_widgets, button); return button; } void gtk_custom_menu_item_add_space(GtkCustomMenuItem* menu_item) { GtkWidget* fixed = gtk_fixed_new(); gtk_widget_set_size_request(fixed, 5, -1); gtk_box_pack_start(GTK_BOX(menu_item->hbox), fixed, FALSE, FALSE, 0); gtk_widget_show(fixed); menu_item->all_widgets = g_list_append(menu_item->all_widgets, fixed); } void gtk_custom_menu_item_receive_motion_event(GtkCustomMenuItem* menu_item, gdouble x, gdouble y) { GtkWidget* new_selected_widget = NULL; GList* current = menu_item->button_widgets; for (; current != NULL; current = current->next) { GtkWidget* current_widget = GTK_WIDGET(current->data); GtkAllocation alloc = current_widget->allocation; int offset_x, offset_y; gtk_widget_translate_coordinates(current_widget, GTK_WIDGET(menu_item), 0, 0, &offset_x, &offset_y); if (x >= offset_x && x < (offset_x + alloc.width) && y >= offset_y && y < (offset_y + alloc.height)) { new_selected_widget = current_widget; break; } } set_selected(menu_item, new_selected_widget); } gboolean gtk_custom_menu_item_handle_move(GtkCustomMenuItem* menu_item, GtkMenuDirectionType direction) { GtkWidget* current = menu_item->currently_selected_button; if (menu_item->button_widgets && current) { switch (direction) { case GTK_MENU_DIR_PREV: { if (g_list_first(menu_item->button_widgets)->data == current) return FALSE; set_selected(menu_item, GTK_WIDGET(g_list_previous(g_list_find( menu_item->button_widgets, current))->data)); break; } case GTK_MENU_DIR_NEXT: { if (g_list_last(menu_item->button_widgets)->data == current) return FALSE; set_selected(menu_item, GTK_WIDGET(g_list_next(g_list_find( menu_item->button_widgets, current))->data)); break; } default: break; } } return TRUE; } void gtk_custom_menu_item_select_item_by_direction( GtkCustomMenuItem* menu_item, GtkMenuDirectionType direction) { menu_item->previously_selected_button = NULL; // If we're just told to be selected by the menu system, select the first // item. if (menu_item->button_widgets) { switch (direction) { case GTK_MENU_DIR_PREV: { GtkWidget* last_button = GTK_WIDGET(g_list_last(menu_item->button_widgets)->data); if (last_button) set_selected(menu_item, last_button); break; } case GTK_MENU_DIR_NEXT: { GtkWidget* first_button = GTK_WIDGET(g_list_first(menu_item->button_widgets)->data); if (first_button) set_selected(menu_item, first_button); break; } default: break; } } gtk_widget_queue_draw(GTK_WIDGET(menu_item)); } gboolean gtk_custom_menu_item_is_in_clickable_region( GtkCustomMenuItem* menu_item) { return menu_item->currently_selected_button != NULL; }
#include <algorithm> #include <fstream> #include <iomanip> #include <iostream> #include <limits> #include <string> #include <sstream> #include <cmath> #include "filtrations/Data.hh" #include "geometry/RipsExpander.hh" #include "persistentHomology/ConnectedComponents.hh" #include "topology/CliqueGraph.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include "topology/io/EdgeLists.hh" #include "topology/io/GML.hh" #include "utilities/Filesystem.hh" using DataType = double; using VertexType = unsigned; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; using PersistenceDiagram = aleph::PersistenceDiagram<DataType>; std::string formatOutput( const std::string& prefix, unsigned k, unsigned K ) { std::ostringstream stream; stream << prefix; stream << std::setw( int( std::log10( K ) + 1 ) ) << std::setfill( '0' ) << k; stream << ".txt"; return stream.str(); } void usage() { std::cerr << "Usage: clique-persistence-diagram FILE K\n" << "\n" << "Calculates the clique persistence diagram for FILE, which is\n" << "supposed to be a weighted graph. The K parameter denotes the\n" << "maximum dimension of a simplex for extracting a clique graph\n" << "and tracking persistence of clique communities.\n\n"; } int main( int argc, char** argv ) { if( argc <= 2 ) { usage(); return -1; } std::string filename = argv[1]; unsigned maxK = static_cast<unsigned>( std::stoul( argv[2] ) ); SimplicialComplex K; // Input ------------------------------------------------------------- std::cerr << "* Reading '" << filename << "'..."; if( aleph::utilities::extension( filename ) == ".gml" ) { aleph::topology::io::GMLReader reader; reader( filename, K ); } else { aleph::io::EdgeListReader reader; reader.setReadWeights( true ); reader.setTrimLines( true ); reader( filename, K ); } std::cerr << "finished\n"; DataType maxWeight = std::numeric_limits<DataType>::lowest(); for( auto&& simplex : K ) maxWeight = std::max( maxWeight, simplex.data() ); // Expansion --------------------------------------------------------- aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander; K = ripsExpander( K, maxK ); K = ripsExpander.assignMaximumWeight( K ); K.sort( aleph::filtrations::Data<Simplex>() ); for( unsigned k = 1; k <= maxK; k++ ) { std::cerr << "* Extracting " << k << "-cliques graph..."; auto C = aleph::topology::getCliqueGraph( K, k ); C.sort( aleph::filtrations::Data<Simplex>() ); std::cerr << "finished\n"; std::cerr << "* " << k << "-cliques graph has " << C.size() << " simplices\n"; if( C.empty() ) { std::cerr << "* Stopping here because no further cliques for processing exist\n"; break; } auto pd = aleph::calculateZeroDimensionalPersistenceDiagram( C ); { using namespace aleph::utilities; auto outputFilename = formatOutput( "/tmp/" + stem( basename( filename ) ) + "_k", k, maxK ); std::cerr << "* Storing output in '" << outputFilename << "'...\n"; pd.removeDiagonal(); std::transform( pd.begin(), pd.end(), pd.begin(), [&maxWeight] ( const PersistenceDiagram::Point& p ) { if( !std::isfinite( p.y() ) ) return PersistenceDiagram::Point( p.x(), maxWeight ); else return p; } ); std::ofstream out( outputFilename ); out << "# Original filename: " << filename << "\n"; out << "# k : " << k << "\n"; out << pd << "\n"; } } } Prepared calculation of clique-based centrality measure #include <algorithm> #include <fstream> #include <iomanip> #include <iostream> #include <limits> #include <string> #include <sstream> #include <cmath> #include "filtrations/Data.hh" #include "geometry/RipsExpander.hh" #include "persistentHomology/ConnectedComponents.hh" #include "topology/CliqueGraph.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include "topology/io/EdgeLists.hh" #include "topology/io/GML.hh" #include "utilities/Filesystem.hh" using DataType = double; using VertexType = unsigned; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; using PersistenceDiagram = aleph::PersistenceDiagram<DataType>; SimplicialComplex filterSimplicialComplex( const SimplicialComplex& K, DataType threshold ) { std::vector<Simplex> simplices; std::copy_if( K.begin(), K.end(), std::back_inserter( simplices ), [&threshold] ( const Simplex& s ) { // TODO: Less than or equal vs. less than? return s.data() <= threshold; } ); return SimplicialComplex( simplices.begin(), simplices.end() ); } std::string formatOutput( const std::string& prefix, unsigned k, unsigned K ) { std::ostringstream stream; stream << prefix; stream << std::setw( int( std::log10( K ) + 1 ) ) << std::setfill( '0' ) << k; stream << ".txt"; return stream.str(); } void usage() { std::cerr << "Usage: clique-persistence-diagram FILE K\n" << "\n" << "Calculates the clique persistence diagram for FILE, which is\n" << "supposed to be a weighted graph. The K parameter denotes the\n" << "maximum dimension of a simplex for extracting a clique graph\n" << "and tracking persistence of clique communities.\n\n"; } int main( int argc, char** argv ) { if( argc <= 2 ) { usage(); return -1; } std::string filename = argv[1]; unsigned maxK = static_cast<unsigned>( std::stoul( argv[2] ) ); SimplicialComplex K; // Input ------------------------------------------------------------- std::cerr << "* Reading '" << filename << "'..."; if( aleph::utilities::extension( filename ) == ".gml" ) { aleph::topology::io::GMLReader reader; reader( filename, K ); } else { aleph::io::EdgeListReader reader; reader.setReadWeights( true ); reader.setTrimLines( true ); reader( filename, K ); } std::cerr << "finished\n"; DataType maxWeight = std::numeric_limits<DataType>::lowest(); for( auto&& simplex : K ) maxWeight = std::max( maxWeight, simplex.data() ); // Expansion --------------------------------------------------------- aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander; K = ripsExpander( K, maxK ); K = ripsExpander.assignMaximumWeight( K ); K.sort( aleph::filtrations::Data<Simplex>() ); for( unsigned k = 1; k <= maxK; k++ ) { std::cerr << "* Extracting " << k << "-cliques graph..."; auto C = aleph::topology::getCliqueGraph( K, k ); C.sort( aleph::filtrations::Data<Simplex>() ); std::cerr << "finished\n"; std::cerr << "* " << k << "-cliques graph has " << C.size() << " simplices\n"; if( C.empty() ) { std::cerr << "* Stopping here because no further cliques for processing exist\n"; break; } auto pd = aleph::calculateZeroDimensionalPersistenceDiagram( C ); // Stores the accumulated persistence of vertices. Persistence // accumulates if a vertex participates in a clique community. std::map<VertexType, double> accumulatedPersistenceMap; { for( auto&& point : pd ) { // TODO: // - Extract simplicial complex of given threshold // - Calculate connected components // - Extract connected component containing the creator simplex // - Traverse the connected component and assign persistence auto epsilon = point.x(); } } { using namespace aleph::utilities; auto outputFilename = formatOutput( "/tmp/" + stem( basename( filename ) ) + "_k", k, maxK ); std::cerr << "* Storing output in '" << outputFilename << "'...\n"; pd.removeDiagonal(); std::transform( pd.begin(), pd.end(), pd.begin(), [&maxWeight] ( const PersistenceDiagram::Point& p ) { if( !std::isfinite( p.y() ) ) return PersistenceDiagram::Point( p.x(), maxWeight ); else return p; } ); std::ofstream out( outputFilename ); out << "# Original filename: " << filename << "\n"; out << "# k : " << k << "\n"; out << pd << "\n"; } } }
// Copyright (c) 2011 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 "chrome/browser/sessions/session_service.h" #include <algorithm> #include <limits> #include <set> #include <vector> #include "base/file_util.h" #include "base/memory/scoped_vector.h" #include "base/message_loop.h" #include "base/metrics/histogram.h" #include "base/pickle.h" #include "base/threading/thread.h" #include "chrome/browser/extensions/extension_tab_helper.h" #include "chrome/browser/prefs/session_startup_pref.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/restore_tab_helper.h" #include "chrome/browser/sessions/session_backend.h" #include "chrome/browser/sessions/session_command.h" #include "chrome/browser/sessions/session_restore.h" #include "chrome/browser/sessions/session_types.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser_init.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/extensions/extension.h" #include "content/browser/tab_contents/navigation_details.h" #include "content/browser/tab_contents/navigation_entry.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/notification_details.h" #include "content/common/notification_service.h" #if defined(OS_MACOSX) #include "chrome/browser/app_controller_cppsafe_mac.h" #endif using base::Time; // Identifier for commands written to file. static const SessionCommand::id_type kCommandSetTabWindow = 0; // OBSOLETE Superseded by kCommandSetWindowBounds3. // static const SessionCommand::id_type kCommandSetWindowBounds = 1; static const SessionCommand::id_type kCommandSetTabIndexInWindow = 2; static const SessionCommand::id_type kCommandTabClosed = 3; static const SessionCommand::id_type kCommandWindowClosed = 4; static const SessionCommand::id_type kCommandTabNavigationPathPrunedFromBack = 5; static const SessionCommand::id_type kCommandUpdateTabNavigation = 6; static const SessionCommand::id_type kCommandSetSelectedNavigationIndex = 7; static const SessionCommand::id_type kCommandSetSelectedTabInIndex = 8; static const SessionCommand::id_type kCommandSetWindowType = 9; // OBSOLETE Superseded by kCommandSetWindowBounds3. Except for data migration. // static const SessionCommand::id_type kCommandSetWindowBounds2 = 10; static const SessionCommand::id_type kCommandTabNavigationPathPrunedFromFront = 11; static const SessionCommand::id_type kCommandSetPinnedState = 12; static const SessionCommand::id_type kCommandSetExtensionAppID = 13; static const SessionCommand::id_type kCommandSetWindowBounds3 = 14; // Every kWritesPerReset commands triggers recreating the file. static const int kWritesPerReset = 250; namespace { // The callback from GetLastSession is internally routed to SessionService // first and then the caller. This is done so that the SessionWindows can be // recreated from the SessionCommands and the SessionWindows passed to the // caller. The following class is used for this. class InternalSessionRequest : public BaseSessionService::InternalGetCommandsRequest { public: InternalSessionRequest( CallbackType* callback, SessionService::SessionCallback* real_callback) : BaseSessionService::InternalGetCommandsRequest(callback), real_callback(real_callback) { } // The callback supplied to GetLastSession and GetCurrentSession. scoped_ptr<SessionService::SessionCallback> real_callback; private: ~InternalSessionRequest() {} DISALLOW_COPY_AND_ASSIGN(InternalSessionRequest); }; // Various payload structures. struct ClosedPayload { SessionID::id_type id; int64 close_time; }; struct WindowBoundsPayload2 { SessionID::id_type window_id; int32 x; int32 y; int32 w; int32 h; bool is_maximized; }; struct WindowBoundsPayload3 { SessionID::id_type window_id; int32 x; int32 y; int32 w; int32 h; int32 show_state; }; struct IDAndIndexPayload { SessionID::id_type id; int32 index; }; typedef IDAndIndexPayload TabIndexInWindowPayload; typedef IDAndIndexPayload TabNavigationPathPrunedFromBackPayload; typedef IDAndIndexPayload SelectedNavigationIndexPayload; typedef IDAndIndexPayload SelectedTabInIndexPayload; typedef IDAndIndexPayload WindowTypePayload; typedef IDAndIndexPayload TabNavigationPathPrunedFromFrontPayload; struct PinnedStatePayload { SessionID::id_type tab_id; bool pinned_state; }; } // namespace // SessionService ------------------------------------------------------------- SessionService::SessionService(Profile* profile) : BaseSessionService(SESSION_RESTORE, profile, FilePath()), has_open_trackable_browsers_(false), move_on_new_browser_(false), save_delay_in_millis_(base::TimeDelta::FromMilliseconds(2500)), save_delay_in_mins_(base::TimeDelta::FromMinutes(10)), save_delay_in_hrs_(base::TimeDelta::FromHours(8)) { Init(); } SessionService::SessionService(const FilePath& save_path) : BaseSessionService(SESSION_RESTORE, NULL, save_path), has_open_trackable_browsers_(false), move_on_new_browser_(false), save_delay_in_millis_(base::TimeDelta::FromMilliseconds(2500)), save_delay_in_mins_(base::TimeDelta::FromMinutes(10)), save_delay_in_hrs_(base::TimeDelta::FromHours(8)) { Init(); } SessionService::~SessionService() { Save(); } bool SessionService::RestoreIfNecessary(const std::vector<GURL>& urls_to_open) { return RestoreIfNecessary(urls_to_open, NULL); } void SessionService::ResetFromCurrentBrowsers() { ScheduleReset(); } void SessionService::MoveCurrentSessionToLastSession() { pending_tab_close_ids_.clear(); window_closing_ids_.clear(); pending_window_close_ids_.clear(); Save(); if (!backend_thread()) { backend()->MoveCurrentSessionToLastSession(); } else { backend_thread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( backend(), &SessionBackend::MoveCurrentSessionToLastSession)); } } void SessionService::SetTabWindow(const SessionID& window_id, const SessionID& tab_id) { if (!ShouldTrackChangesToWindow(window_id)) return; ScheduleCommand(CreateSetTabWindowCommand(window_id, tab_id)); } void SessionService::SetWindowBounds(const SessionID& window_id, const gfx::Rect& bounds, ui::WindowShowState show_state) { if (!ShouldTrackChangesToWindow(window_id)) return; ScheduleCommand(CreateSetWindowBoundsCommand(window_id, bounds, show_state)); } void SessionService::SetTabIndexInWindow(const SessionID& window_id, const SessionID& tab_id, int new_index) { if (!ShouldTrackChangesToWindow(window_id)) return; ScheduleCommand(CreateSetTabIndexInWindowCommand(tab_id, new_index)); } void SessionService::SetPinnedState(const SessionID& window_id, const SessionID& tab_id, bool is_pinned) { if (!ShouldTrackChangesToWindow(window_id)) return; ScheduleCommand(CreatePinnedStateCommand(tab_id, is_pinned)); } void SessionService::TabClosed(const SessionID& window_id, const SessionID& tab_id, bool closed_by_user_gesture) { if (!tab_id.id()) return; // Hapens when the tab is replaced. if (!ShouldTrackChangesToWindow(window_id)) return; IdToRange::iterator i = tab_to_available_range_.find(tab_id.id()); if (i != tab_to_available_range_.end()) tab_to_available_range_.erase(i); if (find(pending_window_close_ids_.begin(), pending_window_close_ids_.end(), window_id.id()) != pending_window_close_ids_.end()) { // Tab is in last window. Don't commit it immediately, instead add it to the // list of tabs to close. If the user creates another window, the close is // committed. pending_tab_close_ids_.insert(tab_id.id()); } else if (find(window_closing_ids_.begin(), window_closing_ids_.end(), window_id.id()) != window_closing_ids_.end() || !IsOnlyOneTabLeft() || closed_by_user_gesture) { // Close is the result of one of the following: // . window close (and it isn't the last window). // . closing a tab and there are other windows/tabs open. // . closed by a user gesture. // In all cases we need to mark the tab as explicitly closed. ScheduleCommand(CreateTabClosedCommand(tab_id.id())); } else { // User closed the last tab in the last tabbed browser. Don't mark the // tab closed. pending_tab_close_ids_.insert(tab_id.id()); has_open_trackable_browsers_ = false; } } void SessionService::WindowClosing(const SessionID& window_id) { if (!ShouldTrackChangesToWindow(window_id)) return; // The window is about to close. If there are other tabbed browsers with the // same original profile commit the close immediately. // // NOTE: if the user chooses the exit menu item session service is destroyed // and this code isn't hit. if (has_open_trackable_browsers_) { // Closing a window can never make has_open_trackable_browsers_ go from // false to true, so only update it if already true. has_open_trackable_browsers_ = HasOpenTrackableBrowsers(window_id); } if (should_record_close_as_pending()) pending_window_close_ids_.insert(window_id.id()); else window_closing_ids_.insert(window_id.id()); } void SessionService::WindowClosed(const SessionID& window_id) { if (!ShouldTrackChangesToWindow(window_id)) return; windows_tracking_.erase(window_id.id()); if (window_closing_ids_.find(window_id.id()) != window_closing_ids_.end()) { window_closing_ids_.erase(window_id.id()); ScheduleCommand(CreateWindowClosedCommand(window_id.id())); } else if (pending_window_close_ids_.find(window_id.id()) == pending_window_close_ids_.end()) { // We'll hit this if user closed the last tab in a window. has_open_trackable_browsers_ = HasOpenTrackableBrowsers(window_id); if (should_record_close_as_pending()) pending_window_close_ids_.insert(window_id.id()); else ScheduleCommand(CreateWindowClosedCommand(window_id.id())); } } void SessionService::SetWindowType(const SessionID& window_id, Browser::Type type) { if (!should_track_changes_for_browser_type(type)) return; windows_tracking_.insert(window_id.id()); // The user created a new tabbed browser with our profile. Commit any // pending closes. CommitPendingCloses(); has_open_trackable_browsers_ = true; move_on_new_browser_ = true; ScheduleCommand( CreateSetWindowTypeCommand(window_id, WindowTypeForBrowserType(type))); } void SessionService::TabNavigationPathPrunedFromBack(const SessionID& window_id, const SessionID& tab_id, int count) { if (!ShouldTrackChangesToWindow(window_id)) return; TabNavigationPathPrunedFromBackPayload payload = { 0 }; payload.id = tab_id.id(); payload.index = count; SessionCommand* command = new SessionCommand(kCommandTabNavigationPathPrunedFromBack, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); ScheduleCommand(command); } void SessionService::TabNavigationPathPrunedFromFront( const SessionID& window_id, const SessionID& tab_id, int count) { if (!ShouldTrackChangesToWindow(window_id)) return; // Update the range of indices. if (tab_to_available_range_.find(tab_id.id()) != tab_to_available_range_.end()) { std::pair<int, int>& range = tab_to_available_range_[tab_id.id()]; range.first = std::max(0, range.first - count); range.second = std::max(0, range.second - count); } TabNavigationPathPrunedFromFrontPayload payload = { 0 }; payload.id = tab_id.id(); payload.index = count; SessionCommand* command = new SessionCommand(kCommandTabNavigationPathPrunedFromFront, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); ScheduleCommand(command); } void SessionService::UpdateTabNavigation(const SessionID& window_id, const SessionID& tab_id, int index, const NavigationEntry& entry) { if (!ShouldTrackEntry(entry.virtual_url()) || !ShouldTrackChangesToWindow(window_id)) { return; } if (tab_to_available_range_.find(tab_id.id()) != tab_to_available_range_.end()) { std::pair<int, int>& range = tab_to_available_range_[tab_id.id()]; range.first = std::min(index, range.first); range.second = std::max(index, range.second); } ScheduleCommand(CreateUpdateTabNavigationCommand(kCommandUpdateTabNavigation, tab_id.id(), index, entry)); } void SessionService::TabRestored(TabContentsWrapper* tab, bool pinned) { if (!ShouldTrackChangesToWindow(tab->restore_tab_helper()->window_id())) return; BuildCommandsForTab(tab->restore_tab_helper()->window_id(), tab, -1, pinned, &pending_commands(), NULL); StartSaveTimer(); } void SessionService::SetSelectedNavigationIndex(const SessionID& window_id, const SessionID& tab_id, int index) { if (!ShouldTrackChangesToWindow(window_id)) return; if (tab_to_available_range_.find(tab_id.id()) != tab_to_available_range_.end()) { if (index < tab_to_available_range_[tab_id.id()].first || index > tab_to_available_range_[tab_id.id()].second) { // The new index is outside the range of what we've archived, schedule // a reset. ResetFromCurrentBrowsers(); return; } } ScheduleCommand(CreateSetSelectedNavigationIndexCommand(tab_id, index)); } void SessionService::SetSelectedTabInWindow(const SessionID& window_id, int index) { if (!ShouldTrackChangesToWindow(window_id)) return; ScheduleCommand(CreateSetSelectedTabInWindow(window_id, index)); } SessionService::Handle SessionService::GetLastSession( CancelableRequestConsumerBase* consumer, SessionCallback* callback) { return ScheduleGetLastSessionCommands( new InternalSessionRequest( NewCallback(this, &SessionService::OnGotSessionCommands), callback), consumer); } SessionService::Handle SessionService::GetCurrentSession( CancelableRequestConsumerBase* consumer, SessionCallback* callback) { if (pending_window_close_ids_.empty()) { // If there are no pending window closes, we can get the current session // from memory. scoped_refptr<InternalSessionRequest> request(new InternalSessionRequest( NewCallback(this, &SessionService::OnGotSessionCommands), callback)); AddRequest(request, consumer); IdToRange tab_to_available_range; std::set<SessionID::id_type> windows_to_track; BuildCommandsFromBrowsers(&(request->commands), &tab_to_available_range, &windows_to_track); request->ForwardResult( BaseSessionService::InternalGetCommandsRequest::TupleType( request->handle(), request)); return request->handle(); } else { // If there are pending window closes, read the current session from disk. return ScheduleGetCurrentSessionCommands( new InternalSessionRequest( NewCallback(this, &SessionService::OnGotSessionCommands), callback), consumer); } } void SessionService::Save() { bool had_commands = !pending_commands().empty(); BaseSessionService::Save(); if (had_commands) { RecordSessionUpdateHistogramData( chrome::NOTIFICATION_SESSION_SERVICE_SAVED, &last_updated_save_time_); NotificationService::current()->Notify( chrome::NOTIFICATION_SESSION_SERVICE_SAVED, Source<Profile>(profile()), NotificationService::NoDetails()); } } void SessionService::Init() { // Register for the notifications we're interested in. registrar_.Add(this, content::NOTIFICATION_TAB_PARENTED, NotificationService::AllSources()); registrar_.Add(this, content::NOTIFICATION_TAB_CLOSED, NotificationService::AllSources()); registrar_.Add(this, content::NOTIFICATION_NAV_LIST_PRUNED, NotificationService::AllSources()); registrar_.Add(this, content::NOTIFICATION_NAV_ENTRY_CHANGED, NotificationService::AllSources()); registrar_.Add(this, content::NOTIFICATION_NAV_ENTRY_COMMITTED, NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_BROWSER_OPENED, NotificationService::AllBrowserContextsAndSources()); registrar_.Add( this, chrome::NOTIFICATION_TAB_CONTENTS_APPLICATION_EXTENSION_CHANGED, NotificationService::AllSources()); } bool SessionService::ShouldNewWindowStartSession() { if (!has_open_trackable_browsers_ && !BrowserInit::InProcessStartup() && !SessionRestore::IsRestoring() #if defined(OS_MACOSX) // OSX has a fairly different idea of application lifetime than the // other platforms. We need to check that we aren't opening a window // from the dock or the menubar. && !app_controller_mac::IsOpeningNewWindow() #endif ) { return true; } return false; } bool SessionService::RestoreIfNecessary(const std::vector<GURL>& urls_to_open, Browser* browser) { if (ShouldNewWindowStartSession()) { // We're going from no tabbed browsers to a tabbed browser (and not in // process startup), restore the last session. if (move_on_new_browser_) { // Make the current session the last. MoveCurrentSessionToLastSession(); move_on_new_browser_ = false; } SessionStartupPref pref = SessionStartupPref::GetStartupPref(profile()); if (pref.type == SessionStartupPref::LAST) { SessionRestore::RestoreSession( profile(), browser, browser ? 0 : SessionRestore::ALWAYS_CREATE_TABBED_BROWSER, urls_to_open); return true; } } return false; } void SessionService::Observe(int type, const NotificationSource& source, const NotificationDetails& details) { // All of our messages have the NavigationController as the source. switch (type) { case chrome::NOTIFICATION_BROWSER_OPENED: { Browser* browser = Source<Browser>(source).ptr(); if (browser->profile() != profile() || !should_track_changes_for_browser_type(browser->type())) { return; } RestoreIfNecessary(std::vector<GURL>(), browser); SetWindowType(browser->session_id(), browser->type()); break; } case content::NOTIFICATION_TAB_PARENTED: { TabContentsWrapper* tab = Source<TabContentsWrapper>(source).ptr(); if (tab->profile() != profile()) return; SetTabWindow(tab->restore_tab_helper()->window_id(), tab->restore_tab_helper()->session_id()); if (tab->extension_tab_helper()->extension_app()) { SetTabExtensionAppID( tab->restore_tab_helper()->window_id(), tab->restore_tab_helper()->session_id(), tab->extension_tab_helper()->extension_app()->id()); } break; } case content::NOTIFICATION_TAB_CLOSED: { TabContentsWrapper* tab = TabContentsWrapper::GetCurrentWrapperForContents( Source<NavigationController>(source).ptr()->tab_contents()); if (!tab || tab->profile() != profile()) return; TabClosed(tab->restore_tab_helper()->window_id(), tab->restore_tab_helper()->session_id(), tab->tab_contents()->closed_by_user_gesture()); RecordSessionUpdateHistogramData(content::NOTIFICATION_TAB_CLOSED, &last_updated_tab_closed_time_); break; } case content::NOTIFICATION_NAV_LIST_PRUNED: { TabContentsWrapper* tab = TabContentsWrapper::GetCurrentWrapperForContents( Source<NavigationController>(source).ptr()->tab_contents()); if (!tab || tab->profile() != profile()) return; Details<content::PrunedDetails> pruned_details(details); if (pruned_details->from_front) { TabNavigationPathPrunedFromFront( tab->restore_tab_helper()->window_id(), tab->restore_tab_helper()->session_id(), pruned_details->count); } else { TabNavigationPathPrunedFromBack( tab->restore_tab_helper()->window_id(), tab->restore_tab_helper()->session_id(), tab->controller().entry_count()); } RecordSessionUpdateHistogramData(content::NOTIFICATION_NAV_LIST_PRUNED, &last_updated_nav_list_pruned_time_); break; } case content::NOTIFICATION_NAV_ENTRY_CHANGED: { TabContentsWrapper* tab = TabContentsWrapper::GetCurrentWrapperForContents( Source<NavigationController>(source).ptr()->tab_contents()); if (!tab || tab->profile() != profile()) return; Details<content::EntryChangedDetails> changed(details); UpdateTabNavigation( tab->restore_tab_helper()->window_id(), tab->restore_tab_helper()->session_id(), changed->index, *changed->changed_entry); break; } case content::NOTIFICATION_NAV_ENTRY_COMMITTED: { TabContentsWrapper* tab = TabContentsWrapper::GetCurrentWrapperForContents( Source<NavigationController>(source).ptr()->tab_contents()); if (!tab || tab->profile() != profile()) return; int current_entry_index = tab->controller().GetCurrentEntryIndex(); SetSelectedNavigationIndex(tab->restore_tab_helper()->window_id(), tab->restore_tab_helper()->session_id(), current_entry_index); UpdateTabNavigation( tab->restore_tab_helper()->window_id(), tab->restore_tab_helper()->session_id(), current_entry_index, *tab->controller().GetEntryAtIndex(current_entry_index)); Details<content::LoadCommittedDetails> changed(details); if (changed->type == NavigationType::NEW_PAGE || changed->type == NavigationType::EXISTING_PAGE) { RecordSessionUpdateHistogramData( content::NOTIFICATION_NAV_ENTRY_COMMITTED, &last_updated_nav_entry_commit_time_); } break; } case chrome::NOTIFICATION_TAB_CONTENTS_APPLICATION_EXTENSION_CHANGED: { ExtensionTabHelper* extension_tab_helper = Source<ExtensionTabHelper>(source).ptr(); if (extension_tab_helper->tab_contents_wrapper()->profile() != profile()) return; if (extension_tab_helper->extension_app()) { RestoreTabHelper* helper = extension_tab_helper->tab_contents_wrapper()->restore_tab_helper(); SetTabExtensionAppID(helper->window_id(), helper->session_id(), extension_tab_helper->extension_app()->id()); } break; } default: NOTREACHED(); } } void SessionService::SetTabExtensionAppID( const SessionID& window_id, const SessionID& tab_id, const std::string& extension_app_id) { if (!ShouldTrackChangesToWindow(window_id)) return; ScheduleCommand(CreateSetTabExtensionAppIDCommand( kCommandSetExtensionAppID, tab_id.id(), extension_app_id)); } SessionCommand* SessionService::CreateSetSelectedTabInWindow( const SessionID& window_id, int index) { SelectedTabInIndexPayload payload = { 0 }; payload.id = window_id.id(); payload.index = index; SessionCommand* command = new SessionCommand(kCommandSetSelectedTabInIndex, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); return command; } SessionCommand* SessionService::CreateSetTabWindowCommand( const SessionID& window_id, const SessionID& tab_id) { SessionID::id_type payload[] = { window_id.id(), tab_id.id() }; SessionCommand* command = new SessionCommand(kCommandSetTabWindow, sizeof(payload)); memcpy(command->contents(), payload, sizeof(payload)); return command; } SessionCommand* SessionService::CreateSetWindowBoundsCommand( const SessionID& window_id, const gfx::Rect& bounds, ui::WindowShowState show_state) { WindowBoundsPayload3 payload = { 0 }; payload.window_id = window_id.id(); payload.x = bounds.x(); payload.y = bounds.y(); payload.w = bounds.width(); payload.h = bounds.height(); payload.show_state = show_state; SessionCommand* command = new SessionCommand(kCommandSetWindowBounds3, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); return command; } SessionCommand* SessionService::CreateSetTabIndexInWindowCommand( const SessionID& tab_id, int new_index) { TabIndexInWindowPayload payload = { 0 }; payload.id = tab_id.id(); payload.index = new_index; SessionCommand* command = new SessionCommand(kCommandSetTabIndexInWindow, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); return command; } SessionCommand* SessionService::CreateTabClosedCommand( const SessionID::id_type tab_id) { ClosedPayload payload; // Because of what appears to be a compiler bug setting payload to {0} doesn't // set the padding to 0, resulting in Purify reporting an UMR when we write // the structure to disk. To avoid this we explicitly memset the struct. memset(&payload, 0, sizeof(payload)); payload.id = tab_id; payload.close_time = Time::Now().ToInternalValue(); SessionCommand* command = new SessionCommand(kCommandTabClosed, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); return command; } SessionCommand* SessionService::CreateWindowClosedCommand( const SessionID::id_type window_id) { ClosedPayload payload; // See comment in CreateTabClosedCommand as to why we do this. memset(&payload, 0, sizeof(payload)); payload.id = window_id; payload.close_time = Time::Now().ToInternalValue(); SessionCommand* command = new SessionCommand(kCommandWindowClosed, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); return command; } SessionCommand* SessionService::CreateSetSelectedNavigationIndexCommand( const SessionID& tab_id, int index) { SelectedNavigationIndexPayload payload = { 0 }; payload.id = tab_id.id(); payload.index = index; SessionCommand* command = new SessionCommand( kCommandSetSelectedNavigationIndex, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); return command; } SessionCommand* SessionService::CreateSetWindowTypeCommand( const SessionID& window_id, WindowType type) { WindowTypePayload payload = { 0 }; payload.id = window_id.id(); payload.index = static_cast<int32>(type); SessionCommand* command = new SessionCommand( kCommandSetWindowType, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); return command; } SessionCommand* SessionService::CreatePinnedStateCommand( const SessionID& tab_id, bool is_pinned) { PinnedStatePayload payload = { 0 }; payload.tab_id = tab_id.id(); payload.pinned_state = is_pinned; SessionCommand* command = new SessionCommand(kCommandSetPinnedState, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); return command; } void SessionService::OnGotSessionCommands( Handle handle, scoped_refptr<InternalGetCommandsRequest> request) { if (request->canceled()) return; ScopedVector<SessionWindow> valid_windows; RestoreSessionFromCommands( request->commands, &(valid_windows.get())); static_cast<InternalSessionRequest*>(request.get())-> real_callback->RunWithParams( SessionCallback::TupleType(request->handle(), &(valid_windows.get()))); } void SessionService::RestoreSessionFromCommands( const std::vector<SessionCommand*>& commands, std::vector<SessionWindow*>* valid_windows) { std::map<int, SessionTab*> tabs; std::map<int, SessionWindow*> windows; if (CreateTabsAndWindows(commands, &tabs, &windows)) { AddTabsToWindows(&tabs, &windows); SortTabsBasedOnVisualOrderAndPrune(&windows, valid_windows); UpdateSelectedTabIndex(valid_windows); } STLDeleteValues(&tabs); // Don't delete conents of windows, that is done by the caller as all // valid windows are added to valid_windows. } void SessionService::UpdateSelectedTabIndex( std::vector<SessionWindow*>* windows) { for (std::vector<SessionWindow*>::const_iterator i = windows->begin(); i != windows->end(); ++i) { // See note in SessionWindow as to why we do this. int new_index = 0; for (std::vector<SessionTab*>::const_iterator j = (*i)->tabs.begin(); j != (*i)->tabs.end(); ++j) { if ((*j)->tab_visual_index == (*i)->selected_tab_index) { new_index = static_cast<int>(j - (*i)->tabs.begin()); break; } } (*i)->selected_tab_index = new_index; } } SessionWindow* SessionService::GetWindow( SessionID::id_type window_id, IdToSessionWindow* windows) { std::map<int, SessionWindow*>::iterator i = windows->find(window_id); if (i == windows->end()) { SessionWindow* window = new SessionWindow(); window->window_id.set_id(window_id); (*windows)[window_id] = window; return window; } return i->second; } SessionTab* SessionService::GetTab( SessionID::id_type tab_id, IdToSessionTab* tabs) { DCHECK(tabs); std::map<int, SessionTab*>::iterator i = tabs->find(tab_id); if (i == tabs->end()) { SessionTab* tab = new SessionTab(); tab->tab_id.set_id(tab_id); (*tabs)[tab_id] = tab; return tab; } return i->second; } std::vector<TabNavigation>::iterator SessionService::FindClosestNavigationWithIndex( std::vector<TabNavigation>* navigations, int index) { DCHECK(navigations); for (std::vector<TabNavigation>::iterator i = navigations->begin(); i != navigations->end(); ++i) { if (i->index() >= index) return i; } return navigations->end(); } // Function used in sorting windows. Sorting is done based on window id. As // window ids increment for each new window, this effectively sorts by creation // time. static bool WindowOrderSortFunction(const SessionWindow* w1, const SessionWindow* w2) { return w1->window_id.id() < w2->window_id.id(); } // Compares the two tabs based on visual index. static bool TabVisualIndexSortFunction(const SessionTab* t1, const SessionTab* t2) { const int delta = t1->tab_visual_index - t2->tab_visual_index; return delta == 0 ? (t1->tab_id.id() < t2->tab_id.id()) : (delta < 0); } void SessionService::SortTabsBasedOnVisualOrderAndPrune( std::map<int, SessionWindow*>* windows, std::vector<SessionWindow*>* valid_windows) { std::map<int, SessionWindow*>::iterator i = windows->begin(); while (i != windows->end()) { if (i->second->tabs.empty() || i->second->is_constrained || !should_track_changes_for_browser_type( static_cast<Browser::Type>(i->second->type))) { delete i->second; windows->erase(i++); } else { // Valid window; sort the tabs and add it to the list of valid windows. std::sort(i->second->tabs.begin(), i->second->tabs.end(), &TabVisualIndexSortFunction); // Add the window such that older windows appear first. if (valid_windows->empty()) { valid_windows->push_back(i->second); } else { valid_windows->insert( std::upper_bound(valid_windows->begin(), valid_windows->end(), i->second, &WindowOrderSortFunction), i->second); } ++i; } } } void SessionService::AddTabsToWindows(std::map<int, SessionTab*>* tabs, std::map<int, SessionWindow*>* windows) { std::map<int, SessionTab*>::iterator i = tabs->begin(); while (i != tabs->end()) { SessionTab* tab = i->second; if (tab->window_id.id() && !tab->navigations.empty()) { SessionWindow* window = GetWindow(tab->window_id.id(), windows); window->tabs.push_back(tab); tabs->erase(i++); // See note in SessionTab as to why we do this. std::vector<TabNavigation>::iterator j = FindClosestNavigationWithIndex(&(tab->navigations), tab->current_navigation_index); if (j == tab->navigations.end()) { tab->current_navigation_index = static_cast<int>(tab->navigations.size() - 1); } else { tab->current_navigation_index = static_cast<int>(j - tab->navigations.begin()); } } else { // Never got a set tab index in window, or tabs are empty, nothing // to do. ++i; } } } bool SessionService::CreateTabsAndWindows( const std::vector<SessionCommand*>& data, std::map<int, SessionTab*>* tabs, std::map<int, SessionWindow*>* windows) { // If the file is corrupt (command with wrong size, or unknown command), we // still return true and attempt to restore what we we can. for (std::vector<SessionCommand*>::const_iterator i = data.begin(); i != data.end(); ++i) { const SessionCommand::id_type kCommandSetWindowBounds2 = 10; const SessionCommand* command = *i; switch (command->id()) { case kCommandSetTabWindow: { SessionID::id_type payload[2]; if (!command->GetPayload(payload, sizeof(payload))) return true; GetTab(payload[1], tabs)->window_id.set_id(payload[0]); break; } // This is here for forward migration only. New data is saved with // |kCommandSetWindowBounds3|. case kCommandSetWindowBounds2: { WindowBoundsPayload2 payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetWindow(payload.window_id, windows)->bounds.SetRect(payload.x, payload.y, payload.w, payload.h); GetWindow(payload.window_id, windows)->show_state = payload.is_maximized ? ui::SHOW_STATE_MAXIMIZED : ui::SHOW_STATE_NORMAL; break; } case kCommandSetWindowBounds3: { WindowBoundsPayload3 payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetWindow(payload.window_id, windows)->bounds.SetRect(payload.x, payload.y, payload.w, payload.h); // SHOW_STATE_INACTIVE is not persisted. ui::WindowShowState show_state = ui::SHOW_STATE_NORMAL; if (payload.show_state > ui::SHOW_STATE_DEFAULT && payload.show_state < ui::SHOW_STATE_MAX && payload.show_state != ui::SHOW_STATE_INACTIVE) { show_state = static_cast<ui::WindowShowState>(payload.show_state); } else { NOTREACHED(); } GetWindow(payload.window_id, windows)->show_state = show_state; break; } case kCommandSetTabIndexInWindow: { TabIndexInWindowPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetTab(payload.id, tabs)->tab_visual_index = payload.index; break; } case kCommandTabClosed: case kCommandWindowClosed: { ClosedPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; if (command->id() == kCommandTabClosed) { delete GetTab(payload.id, tabs); tabs->erase(payload.id); } else { delete GetWindow(payload.id, windows); windows->erase(payload.id); } break; } case kCommandTabNavigationPathPrunedFromBack: { TabNavigationPathPrunedFromBackPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; SessionTab* tab = GetTab(payload.id, tabs); tab->navigations.erase( FindClosestNavigationWithIndex(&(tab->navigations), payload.index), tab->navigations.end()); break; } case kCommandTabNavigationPathPrunedFromFront: { TabNavigationPathPrunedFromFrontPayload payload; if (!command->GetPayload(&payload, sizeof(payload)) || payload.index <= 0) { return true; } SessionTab* tab = GetTab(payload.id, tabs); // Update the selected navigation index. tab->current_navigation_index = std::max(-1, tab->current_navigation_index - payload.index); // And update the index of existing navigations. for (std::vector<TabNavigation>::iterator i = tab->navigations.begin(); i != tab->navigations.end();) { i->set_index(i->index() - payload.index); if (i->index() < 0) i = tab->navigations.erase(i); else ++i; } break; } case kCommandUpdateTabNavigation: { TabNavigation navigation; SessionID::id_type tab_id; if (!RestoreUpdateTabNavigationCommand(*command, &navigation, &tab_id)) return true; SessionTab* tab = GetTab(tab_id, tabs); std::vector<TabNavigation>::iterator i = FindClosestNavigationWithIndex(&(tab->navigations), navigation.index()); if (i != tab->navigations.end() && i->index() == navigation.index()) *i = navigation; else tab->navigations.insert(i, navigation); break; } case kCommandSetSelectedNavigationIndex: { SelectedNavigationIndexPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetTab(payload.id, tabs)->current_navigation_index = payload.index; break; } case kCommandSetSelectedTabInIndex: { SelectedTabInIndexPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetWindow(payload.id, windows)->selected_tab_index = payload.index; break; } case kCommandSetWindowType: { WindowTypePayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetWindow(payload.id, windows)->is_constrained = false; GetWindow(payload.id, windows)->type = BrowserTypeForWindowType( static_cast<WindowType>(payload.index)); break; } case kCommandSetPinnedState: { PinnedStatePayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetTab(payload.tab_id, tabs)->pinned = payload.pinned_state; break; } case kCommandSetExtensionAppID: { SessionID::id_type tab_id; std::string extension_app_id; if (!RestoreSetTabExtensionAppIDCommand( *command, &tab_id, &extension_app_id)) { return true; } GetTab(tab_id, tabs)->extension_app_id.swap(extension_app_id); break; } default: return true; } } return true; } void SessionService::BuildCommandsForTab( const SessionID& window_id, TabContentsWrapper* tab, int index_in_window, bool is_pinned, std::vector<SessionCommand*>* commands, IdToRange* tab_to_available_range) { DCHECK(tab && commands && window_id.id()); const SessionID& session_id(tab->restore_tab_helper()->session_id()); commands->push_back(CreateSetTabWindowCommand(window_id, session_id)); const int current_index = tab->controller().GetCurrentEntryIndex(); const int min_index = std::max(0, current_index - max_persist_navigation_count); const int max_index = std::min(current_index + max_persist_navigation_count, tab->controller().entry_count()); const int pending_index = tab->controller().pending_entry_index(); if (tab_to_available_range) { (*tab_to_available_range)[session_id.id()] = std::pair<int, int>(min_index, max_index); } if (is_pinned) { commands->push_back(CreatePinnedStateCommand(session_id, true)); } TabContentsWrapper* wrapper = TabContentsWrapper::GetCurrentWrapperForContents(tab->tab_contents()); if (wrapper->extension_tab_helper()->extension_app()) { commands->push_back( CreateSetTabExtensionAppIDCommand( kCommandSetExtensionAppID, session_id.id(), wrapper->extension_tab_helper()->extension_app()->id())); } for (int i = min_index; i < max_index; ++i) { const NavigationEntry* entry = (i == pending_index) ? tab->controller().pending_entry() : tab->controller().GetEntryAtIndex(i); DCHECK(entry); if (ShouldTrackEntry(entry->virtual_url())) { commands->push_back( CreateUpdateTabNavigationCommand( kCommandUpdateTabNavigation, session_id.id(), i, *entry)); } } commands->push_back( CreateSetSelectedNavigationIndexCommand(session_id, current_index)); if (index_in_window != -1) { commands->push_back( CreateSetTabIndexInWindowCommand(session_id, index_in_window)); } } void SessionService::BuildCommandsForBrowser( Browser* browser, std::vector<SessionCommand*>* commands, IdToRange* tab_to_available_range, std::set<SessionID::id_type>* windows_to_track) { DCHECK(browser && commands); DCHECK(browser->session_id().id()); ui::WindowShowState show_state = ui::SHOW_STATE_NORMAL; if (browser->window()->IsMaximized()) show_state = ui::SHOW_STATE_MAXIMIZED; else if (browser->window()->IsMinimized()) show_state = ui::SHOW_STATE_MINIMIZED; commands->push_back( CreateSetWindowBoundsCommand(browser->session_id(), browser->window()->GetRestoredBounds(), show_state)); commands->push_back(CreateSetWindowTypeCommand( browser->session_id(), WindowTypeForBrowserType(browser->type()))); bool added_to_windows_to_track = false; for (int i = 0; i < browser->tab_count(); ++i) { TabContentsWrapper* tab = browser->GetTabContentsWrapperAt(i); DCHECK(tab); if (tab->profile() == profile() || profile() == NULL) { BuildCommandsForTab(browser->session_id(), tab, i, browser->tabstrip_model()->IsTabPinned(i), commands, tab_to_available_range); if (windows_to_track && !added_to_windows_to_track) { windows_to_track->insert(browser->session_id().id()); added_to_windows_to_track = true; } } } commands->push_back( CreateSetSelectedTabInWindow(browser->session_id(), browser->active_index())); } void SessionService::BuildCommandsFromBrowsers( std::vector<SessionCommand*>* commands, IdToRange* tab_to_available_range, std::set<SessionID::id_type>* windows_to_track) { DCHECK(commands); for (BrowserList::const_iterator i = BrowserList::begin(); i != BrowserList::end(); ++i) { // Make sure the browser has tabs and a window. Browsers destructor // removes itself from the BrowserList. When a browser is closed the // destructor is not necessarily run immediately. This means its possible // for us to get a handle to a browser that is about to be removed. If // the tab count is 0 or the window is NULL, the browser is about to be // deleted, so we ignore it. if (should_track_changes_for_browser_type((*i)->type()) && (*i)->tab_count() && (*i)->window()) { BuildCommandsForBrowser(*i, commands, tab_to_available_range, windows_to_track); } } } void SessionService::ScheduleReset() { set_pending_reset(true); STLDeleteElements(&pending_commands()); tab_to_available_range_.clear(); windows_tracking_.clear(); BuildCommandsFromBrowsers(&pending_commands(), &tab_to_available_range_, &windows_tracking_); if (!windows_tracking_.empty()) { // We're lazily created on startup and won't get an initial batch of // SetWindowType messages. Set these here to make sure our state is correct. has_open_trackable_browsers_ = true; move_on_new_browser_ = true; } StartSaveTimer(); } bool SessionService::ReplacePendingCommand(SessionCommand* command) { // We only optimize page navigations, which can happen quite frequently and // are expensive. If necessary, other commands could be searched for as // well. if (command->id() != kCommandUpdateTabNavigation) return false; void* iterator = NULL; scoped_ptr<Pickle> command_pickle(command->PayloadAsPickle()); SessionID::id_type command_tab_id; int command_nav_index; if (!command_pickle->ReadInt(&iterator, &command_tab_id) || !command_pickle->ReadInt(&iterator, &command_nav_index)) { return false; } for (std::vector<SessionCommand*>::reverse_iterator i = pending_commands().rbegin(); i != pending_commands().rend(); ++i) { SessionCommand* existing_command = *i; if (existing_command->id() == kCommandUpdateTabNavigation) { SessionID::id_type existing_tab_id; int existing_nav_index; { // Creating a pickle like this means the Pickle references the data from // the command. Make sure we delete the pickle before the command, else // the pickle references deleted memory. scoped_ptr<Pickle> existing_pickle(existing_command->PayloadAsPickle()); iterator = NULL; if (!existing_pickle->ReadInt(&iterator, &existing_tab_id) || !existing_pickle->ReadInt(&iterator, &existing_nav_index)) { return false; } } if (existing_tab_id == command_tab_id && existing_nav_index == command_nav_index) { // existing_command is an update for the same tab/index pair. Replace // it with the new one. We need to add to the end of the list just in // case there is a prune command after the update command. delete existing_command; pending_commands().erase(i.base() - 1); pending_commands().push_back(command); return true; } return false; } } return false; } void SessionService::ScheduleCommand(SessionCommand* command) { DCHECK(command); if (ReplacePendingCommand(command)) return; BaseSessionService::ScheduleCommand(command); // Don't schedule a reset on tab closed/window closed. Otherwise we may // lose tabs/windows we want to restore from if we exit right after this. if (!pending_reset() && pending_window_close_ids_.empty() && commands_since_reset() >= kWritesPerReset && (command->id() != kCommandTabClosed && command->id() != kCommandWindowClosed)) { ScheduleReset(); } } void SessionService::CommitPendingCloses() { for (PendingTabCloseIDs::iterator i = pending_tab_close_ids_.begin(); i != pending_tab_close_ids_.end(); ++i) { ScheduleCommand(CreateTabClosedCommand(*i)); } pending_tab_close_ids_.clear(); for (PendingWindowCloseIDs::iterator i = pending_window_close_ids_.begin(); i != pending_window_close_ids_.end(); ++i) { ScheduleCommand(CreateWindowClosedCommand(*i)); } pending_window_close_ids_.clear(); } bool SessionService::IsOnlyOneTabLeft() { if (!profile()) { // We're testing, always return false. return false; } int window_count = 0; for (BrowserList::const_iterator i = BrowserList::begin(); i != BrowserList::end(); ++i) { const SessionID::id_type window_id = (*i)->session_id().id(); if (should_track_changes_for_browser_type((*i)->type()) && (*i)->profile() == profile() && window_closing_ids_.find(window_id) == window_closing_ids_.end()) { if (++window_count > 1) return false; // By the time this is invoked the tab has been removed. As such, we use // > 0 here rather than > 1. if ((*i)->tab_count() > 0) return false; } } return true; } bool SessionService::HasOpenTrackableBrowsers(const SessionID& window_id) { if (!profile()) { // We're testing, always return false. return true; } for (BrowserList::const_iterator i = BrowserList::begin(); i != BrowserList::end(); ++i) { Browser* browser = *i; const SessionID::id_type browser_id = browser->session_id().id(); if (browser_id != window_id.id() && window_closing_ids_.find(browser_id) == window_closing_ids_.end() && should_track_changes_for_browser_type(browser->type()) && browser->profile() == profile()) { return true; } } return false; } bool SessionService::ShouldTrackChangesToWindow(const SessionID& window_id) { return windows_tracking_.find(window_id.id()) != windows_tracking_.end(); } bool SessionService::should_track_changes_for_browser_type(Browser::Type type) { return type == Browser::TYPE_TABBED || (type == Browser::TYPE_POPUP && browser_defaults::kRestorePopups); } SessionService::WindowType SessionService::WindowTypeForBrowserType( Browser::Type type) { switch (type) { case Browser::TYPE_POPUP: return TYPE_POPUP; case Browser::TYPE_TABBED: return TYPE_TABBED; default: DCHECK(false); return TYPE_TABBED; } } Browser::Type SessionService::BrowserTypeForWindowType(WindowType type) { switch (type) { case TYPE_POPUP: return Browser::TYPE_POPUP; case TYPE_TABBED: default: return Browser::TYPE_TABBED; } } void SessionService::RecordSessionUpdateHistogramData(int type, base::TimeTicks* last_updated_time) { if (!last_updated_time->is_null()) { base::TimeDelta delta = base::TimeTicks::Now() - *last_updated_time; // We're interested in frequent updates periods longer than // 10 minutes. bool use_long_period = false; if (delta >= save_delay_in_mins_) { use_long_period = true; } switch (type) { case chrome::NOTIFICATION_SESSION_SERVICE_SAVED : RecordUpdatedSaveTime(delta, use_long_period); RecordUpdatedSessionNavigationOrTab(delta, use_long_period); break; case content::NOTIFICATION_TAB_CLOSED: RecordUpdatedTabClosed(delta, use_long_period); RecordUpdatedSessionNavigationOrTab(delta, use_long_period); break; case content::NOTIFICATION_NAV_LIST_PRUNED: RecordUpdatedNavListPruned(delta, use_long_period); RecordUpdatedSessionNavigationOrTab(delta, use_long_period); break; case content::NOTIFICATION_NAV_ENTRY_COMMITTED: RecordUpdatedNavEntryCommit(delta, use_long_period); RecordUpdatedSessionNavigationOrTab(delta, use_long_period); break; default: NOTREACHED() << "Bad type sent to RecordSessionUpdateHistogramData"; break; } } (*last_updated_time) = base::TimeTicks::Now(); } void SessionService::RecordUpdatedTabClosed(base::TimeDelta delta, bool use_long_period) { std::string name("SessionRestore.TabClosedPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(name, delta, // 2500ms is the default save delay. save_delay_in_millis_, save_delay_in_mins_, 50); if (use_long_period) { std::string long_name_("SessionRestore.TabClosedLongPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(long_name_, delta, save_delay_in_mins_, save_delay_in_hrs_, 50); } } void SessionService::RecordUpdatedNavListPruned(base::TimeDelta delta, bool use_long_period) { std::string name("SessionRestore.NavigationListPrunedPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(name, delta, // 2500ms is the default save delay. save_delay_in_millis_, save_delay_in_mins_, 50); if (use_long_period) { std::string long_name_("SessionRestore.NavigationListPrunedLongPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(long_name_, delta, save_delay_in_mins_, save_delay_in_hrs_, 50); } } void SessionService::RecordUpdatedNavEntryCommit(base::TimeDelta delta, bool use_long_period) { std::string name("SessionRestore.NavEntryCommittedPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(name, delta, // 2500ms is the default save delay. save_delay_in_millis_, save_delay_in_mins_, 50); if (use_long_period) { std::string long_name_("SessionRestore.NavEntryCommittedLongPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(long_name_, delta, save_delay_in_mins_, save_delay_in_hrs_, 50); } } void SessionService::RecordUpdatedSessionNavigationOrTab(base::TimeDelta delta, bool use_long_period) { std::string name("SessionRestore.NavOrTabUpdatePeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(name, delta, // 2500ms is the default save delay. save_delay_in_millis_, save_delay_in_mins_, 50); if (use_long_period) { std::string long_name_("SessionRestore.NavOrTabUpdateLongPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(long_name_, delta, save_delay_in_mins_, save_delay_in_hrs_, 50); } } void SessionService::RecordUpdatedSaveTime(base::TimeDelta delta, bool use_long_period) { std::string name("SessionRestore.SavePeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(name, delta, // 2500ms is the default save delay. save_delay_in_millis_, save_delay_in_mins_, 50); if (use_long_period) { std::string long_name_("SessionRestore.SaveLongPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(long_name_, delta, save_delay_in_mins_, save_delay_in_hrs_, 50); } } Fix build bustage TBR=ben@chromium.org BUG=none TEST=none Review URL: http://codereview.chromium.org/8166015 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@104247 0039d316-1c4b-4281-b951-d872f2087c98 // Copyright (c) 2011 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 "chrome/browser/sessions/session_service.h" #include <algorithm> #include <limits> #include <set> #include <vector> #include "base/file_util.h" #include "base/memory/scoped_vector.h" #include "base/message_loop.h" #include "base/metrics/histogram.h" #include "base/pickle.h" #include "base/threading/thread.h" #include "chrome/browser/extensions/extension_tab_helper.h" #include "chrome/browser/prefs/session_startup_pref.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/restore_tab_helper.h" #include "chrome/browser/sessions/session_backend.h" #include "chrome/browser/sessions/session_command.h" #include "chrome/browser/sessions/session_restore.h" #include "chrome/browser/sessions/session_types.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser_init.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/extensions/extension.h" #include "content/browser/tab_contents/navigation_details.h" #include "content/browser/tab_contents/navigation_entry.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/notification_details.h" #include "content/common/notification_service.h" #if defined(OS_MACOSX) #include "chrome/browser/app_controller_cppsafe_mac.h" #endif using base::Time; // Identifier for commands written to file. static const SessionCommand::id_type kCommandSetTabWindow = 0; // OBSOLETE Superseded by kCommandSetWindowBounds3. // static const SessionCommand::id_type kCommandSetWindowBounds = 1; static const SessionCommand::id_type kCommandSetTabIndexInWindow = 2; static const SessionCommand::id_type kCommandTabClosed = 3; static const SessionCommand::id_type kCommandWindowClosed = 4; static const SessionCommand::id_type kCommandTabNavigationPathPrunedFromBack = 5; static const SessionCommand::id_type kCommandUpdateTabNavigation = 6; static const SessionCommand::id_type kCommandSetSelectedNavigationIndex = 7; static const SessionCommand::id_type kCommandSetSelectedTabInIndex = 8; static const SessionCommand::id_type kCommandSetWindowType = 9; // OBSOLETE Superseded by kCommandSetWindowBounds3. Except for data migration. // static const SessionCommand::id_type kCommandSetWindowBounds2 = 10; static const SessionCommand::id_type kCommandTabNavigationPathPrunedFromFront = 11; static const SessionCommand::id_type kCommandSetPinnedState = 12; static const SessionCommand::id_type kCommandSetExtensionAppID = 13; static const SessionCommand::id_type kCommandSetWindowBounds3 = 14; // Every kWritesPerReset commands triggers recreating the file. static const int kWritesPerReset = 250; namespace { // The callback from GetLastSession is internally routed to SessionService // first and then the caller. This is done so that the SessionWindows can be // recreated from the SessionCommands and the SessionWindows passed to the // caller. The following class is used for this. class InternalSessionRequest : public BaseSessionService::InternalGetCommandsRequest { public: InternalSessionRequest( CallbackType* callback, SessionService::SessionCallback* real_callback) : BaseSessionService::InternalGetCommandsRequest(callback), real_callback(real_callback) { } // The callback supplied to GetLastSession and GetCurrentSession. scoped_ptr<SessionService::SessionCallback> real_callback; private: ~InternalSessionRequest() {} DISALLOW_COPY_AND_ASSIGN(InternalSessionRequest); }; // Various payload structures. struct ClosedPayload { SessionID::id_type id; int64 close_time; }; struct WindowBoundsPayload2 { SessionID::id_type window_id; int32 x; int32 y; int32 w; int32 h; bool is_maximized; }; struct WindowBoundsPayload3 { SessionID::id_type window_id; int32 x; int32 y; int32 w; int32 h; int32 show_state; }; struct IDAndIndexPayload { SessionID::id_type id; int32 index; }; typedef IDAndIndexPayload TabIndexInWindowPayload; typedef IDAndIndexPayload TabNavigationPathPrunedFromBackPayload; typedef IDAndIndexPayload SelectedNavigationIndexPayload; typedef IDAndIndexPayload SelectedTabInIndexPayload; typedef IDAndIndexPayload WindowTypePayload; typedef IDAndIndexPayload TabNavigationPathPrunedFromFrontPayload; struct PinnedStatePayload { SessionID::id_type tab_id; bool pinned_state; }; } // namespace // SessionService ------------------------------------------------------------- SessionService::SessionService(Profile* profile) : BaseSessionService(SESSION_RESTORE, profile, FilePath()), has_open_trackable_browsers_(false), move_on_new_browser_(false), save_delay_in_millis_(base::TimeDelta::FromMilliseconds(2500)), save_delay_in_mins_(base::TimeDelta::FromMinutes(10)), save_delay_in_hrs_(base::TimeDelta::FromHours(8)) { Init(); } SessionService::SessionService(const FilePath& save_path) : BaseSessionService(SESSION_RESTORE, NULL, save_path), has_open_trackable_browsers_(false), move_on_new_browser_(false), save_delay_in_millis_(base::TimeDelta::FromMilliseconds(2500)), save_delay_in_mins_(base::TimeDelta::FromMinutes(10)), save_delay_in_hrs_(base::TimeDelta::FromHours(8)) { Init(); } SessionService::~SessionService() { Save(); } bool SessionService::RestoreIfNecessary(const std::vector<GURL>& urls_to_open) { return RestoreIfNecessary(urls_to_open, NULL); } void SessionService::ResetFromCurrentBrowsers() { ScheduleReset(); } void SessionService::MoveCurrentSessionToLastSession() { pending_tab_close_ids_.clear(); window_closing_ids_.clear(); pending_window_close_ids_.clear(); Save(); if (!backend_thread()) { backend()->MoveCurrentSessionToLastSession(); } else { backend_thread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( backend(), &SessionBackend::MoveCurrentSessionToLastSession)); } } void SessionService::SetTabWindow(const SessionID& window_id, const SessionID& tab_id) { if (!ShouldTrackChangesToWindow(window_id)) return; ScheduleCommand(CreateSetTabWindowCommand(window_id, tab_id)); } void SessionService::SetWindowBounds(const SessionID& window_id, const gfx::Rect& bounds, ui::WindowShowState show_state) { if (!ShouldTrackChangesToWindow(window_id)) return; ScheduleCommand(CreateSetWindowBoundsCommand(window_id, bounds, show_state)); } void SessionService::SetTabIndexInWindow(const SessionID& window_id, const SessionID& tab_id, int new_index) { if (!ShouldTrackChangesToWindow(window_id)) return; ScheduleCommand(CreateSetTabIndexInWindowCommand(tab_id, new_index)); } void SessionService::SetPinnedState(const SessionID& window_id, const SessionID& tab_id, bool is_pinned) { if (!ShouldTrackChangesToWindow(window_id)) return; ScheduleCommand(CreatePinnedStateCommand(tab_id, is_pinned)); } void SessionService::TabClosed(const SessionID& window_id, const SessionID& tab_id, bool closed_by_user_gesture) { if (!tab_id.id()) return; // Hapens when the tab is replaced. if (!ShouldTrackChangesToWindow(window_id)) return; IdToRange::iterator i = tab_to_available_range_.find(tab_id.id()); if (i != tab_to_available_range_.end()) tab_to_available_range_.erase(i); if (find(pending_window_close_ids_.begin(), pending_window_close_ids_.end(), window_id.id()) != pending_window_close_ids_.end()) { // Tab is in last window. Don't commit it immediately, instead add it to the // list of tabs to close. If the user creates another window, the close is // committed. pending_tab_close_ids_.insert(tab_id.id()); } else if (find(window_closing_ids_.begin(), window_closing_ids_.end(), window_id.id()) != window_closing_ids_.end() || !IsOnlyOneTabLeft() || closed_by_user_gesture) { // Close is the result of one of the following: // . window close (and it isn't the last window). // . closing a tab and there are other windows/tabs open. // . closed by a user gesture. // In all cases we need to mark the tab as explicitly closed. ScheduleCommand(CreateTabClosedCommand(tab_id.id())); } else { // User closed the last tab in the last tabbed browser. Don't mark the // tab closed. pending_tab_close_ids_.insert(tab_id.id()); has_open_trackable_browsers_ = false; } } void SessionService::WindowClosing(const SessionID& window_id) { if (!ShouldTrackChangesToWindow(window_id)) return; // The window is about to close. If there are other tabbed browsers with the // same original profile commit the close immediately. // // NOTE: if the user chooses the exit menu item session service is destroyed // and this code isn't hit. if (has_open_trackable_browsers_) { // Closing a window can never make has_open_trackable_browsers_ go from // false to true, so only update it if already true. has_open_trackable_browsers_ = HasOpenTrackableBrowsers(window_id); } if (should_record_close_as_pending()) pending_window_close_ids_.insert(window_id.id()); else window_closing_ids_.insert(window_id.id()); } void SessionService::WindowClosed(const SessionID& window_id) { if (!ShouldTrackChangesToWindow(window_id)) return; windows_tracking_.erase(window_id.id()); if (window_closing_ids_.find(window_id.id()) != window_closing_ids_.end()) { window_closing_ids_.erase(window_id.id()); ScheduleCommand(CreateWindowClosedCommand(window_id.id())); } else if (pending_window_close_ids_.find(window_id.id()) == pending_window_close_ids_.end()) { // We'll hit this if user closed the last tab in a window. has_open_trackable_browsers_ = HasOpenTrackableBrowsers(window_id); if (should_record_close_as_pending()) pending_window_close_ids_.insert(window_id.id()); else ScheduleCommand(CreateWindowClosedCommand(window_id.id())); } } void SessionService::SetWindowType(const SessionID& window_id, Browser::Type type) { if (!should_track_changes_for_browser_type(type)) return; windows_tracking_.insert(window_id.id()); // The user created a new tabbed browser with our profile. Commit any // pending closes. CommitPendingCloses(); has_open_trackable_browsers_ = true; move_on_new_browser_ = true; ScheduleCommand( CreateSetWindowTypeCommand(window_id, WindowTypeForBrowserType(type))); } void SessionService::TabNavigationPathPrunedFromBack(const SessionID& window_id, const SessionID& tab_id, int count) { if (!ShouldTrackChangesToWindow(window_id)) return; TabNavigationPathPrunedFromBackPayload payload = { 0 }; payload.id = tab_id.id(); payload.index = count; SessionCommand* command = new SessionCommand(kCommandTabNavigationPathPrunedFromBack, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); ScheduleCommand(command); } void SessionService::TabNavigationPathPrunedFromFront( const SessionID& window_id, const SessionID& tab_id, int count) { if (!ShouldTrackChangesToWindow(window_id)) return; // Update the range of indices. if (tab_to_available_range_.find(tab_id.id()) != tab_to_available_range_.end()) { std::pair<int, int>& range = tab_to_available_range_[tab_id.id()]; range.first = std::max(0, range.first - count); range.second = std::max(0, range.second - count); } TabNavigationPathPrunedFromFrontPayload payload = { 0 }; payload.id = tab_id.id(); payload.index = count; SessionCommand* command = new SessionCommand(kCommandTabNavigationPathPrunedFromFront, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); ScheduleCommand(command); } void SessionService::UpdateTabNavigation(const SessionID& window_id, const SessionID& tab_id, int index, const NavigationEntry& entry) { if (!ShouldTrackEntry(entry.virtual_url()) || !ShouldTrackChangesToWindow(window_id)) { return; } if (tab_to_available_range_.find(tab_id.id()) != tab_to_available_range_.end()) { std::pair<int, int>& range = tab_to_available_range_[tab_id.id()]; range.first = std::min(index, range.first); range.second = std::max(index, range.second); } ScheduleCommand(CreateUpdateTabNavigationCommand(kCommandUpdateTabNavigation, tab_id.id(), index, entry)); } void SessionService::TabRestored(TabContentsWrapper* tab, bool pinned) { if (!ShouldTrackChangesToWindow(tab->restore_tab_helper()->window_id())) return; BuildCommandsForTab(tab->restore_tab_helper()->window_id(), tab, -1, pinned, &pending_commands(), NULL); StartSaveTimer(); } void SessionService::SetSelectedNavigationIndex(const SessionID& window_id, const SessionID& tab_id, int index) { if (!ShouldTrackChangesToWindow(window_id)) return; if (tab_to_available_range_.find(tab_id.id()) != tab_to_available_range_.end()) { if (index < tab_to_available_range_[tab_id.id()].first || index > tab_to_available_range_[tab_id.id()].second) { // The new index is outside the range of what we've archived, schedule // a reset. ResetFromCurrentBrowsers(); return; } } ScheduleCommand(CreateSetSelectedNavigationIndexCommand(tab_id, index)); } void SessionService::SetSelectedTabInWindow(const SessionID& window_id, int index) { if (!ShouldTrackChangesToWindow(window_id)) return; ScheduleCommand(CreateSetSelectedTabInWindow(window_id, index)); } SessionService::Handle SessionService::GetLastSession( CancelableRequestConsumerBase* consumer, SessionCallback* callback) { return ScheduleGetLastSessionCommands( new InternalSessionRequest( NewCallback(this, &SessionService::OnGotSessionCommands), callback), consumer); } SessionService::Handle SessionService::GetCurrentSession( CancelableRequestConsumerBase* consumer, SessionCallback* callback) { if (pending_window_close_ids_.empty()) { // If there are no pending window closes, we can get the current session // from memory. scoped_refptr<InternalSessionRequest> request(new InternalSessionRequest( NewCallback(this, &SessionService::OnGotSessionCommands), callback)); AddRequest(request, consumer); IdToRange tab_to_available_range; std::set<SessionID::id_type> windows_to_track; BuildCommandsFromBrowsers(&(request->commands), &tab_to_available_range, &windows_to_track); request->ForwardResult( BaseSessionService::InternalGetCommandsRequest::TupleType( request->handle(), request)); return request->handle(); } else { // If there are pending window closes, read the current session from disk. return ScheduleGetCurrentSessionCommands( new InternalSessionRequest( NewCallback(this, &SessionService::OnGotSessionCommands), callback), consumer); } } void SessionService::Save() { bool had_commands = !pending_commands().empty(); BaseSessionService::Save(); if (had_commands) { RecordSessionUpdateHistogramData( chrome::NOTIFICATION_SESSION_SERVICE_SAVED, &last_updated_save_time_); NotificationService::current()->Notify( chrome::NOTIFICATION_SESSION_SERVICE_SAVED, Source<Profile>(profile()), NotificationService::NoDetails()); } } void SessionService::Init() { // Register for the notifications we're interested in. registrar_.Add(this, content::NOTIFICATION_TAB_PARENTED, NotificationService::AllSources()); registrar_.Add(this, content::NOTIFICATION_TAB_CLOSED, NotificationService::AllSources()); registrar_.Add(this, content::NOTIFICATION_NAV_LIST_PRUNED, NotificationService::AllSources()); registrar_.Add(this, content::NOTIFICATION_NAV_ENTRY_CHANGED, NotificationService::AllSources()); registrar_.Add(this, content::NOTIFICATION_NAV_ENTRY_COMMITTED, NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_BROWSER_OPENED, NotificationService::AllBrowserContextsAndSources()); registrar_.Add( this, chrome::NOTIFICATION_TAB_CONTENTS_APPLICATION_EXTENSION_CHANGED, NotificationService::AllSources()); } bool SessionService::ShouldNewWindowStartSession() { if (!has_open_trackable_browsers_ && !BrowserInit::InProcessStartup() && !SessionRestore::IsRestoring() #if defined(OS_MACOSX) // OSX has a fairly different idea of application lifetime than the // other platforms. We need to check that we aren't opening a window // from the dock or the menubar. && !app_controller_mac::IsOpeningNewWindow() #endif ) { return true; } return false; } bool SessionService::RestoreIfNecessary(const std::vector<GURL>& urls_to_open, Browser* browser) { if (ShouldNewWindowStartSession()) { // We're going from no tabbed browsers to a tabbed browser (and not in // process startup), restore the last session. if (move_on_new_browser_) { // Make the current session the last. MoveCurrentSessionToLastSession(); move_on_new_browser_ = false; } SessionStartupPref pref = SessionStartupPref::GetStartupPref(profile()); if (pref.type == SessionStartupPref::LAST) { SessionRestore::RestoreSession( profile(), browser, browser ? 0 : SessionRestore::ALWAYS_CREATE_TABBED_BROWSER, urls_to_open); return true; } } return false; } void SessionService::Observe(int type, const NotificationSource& source, const NotificationDetails& details) { // All of our messages have the NavigationController as the source. switch (type) { case chrome::NOTIFICATION_BROWSER_OPENED: { Browser* browser = Source<Browser>(source).ptr(); if (browser->profile() != profile() || !should_track_changes_for_browser_type(browser->type())) { return; } RestoreIfNecessary(std::vector<GURL>(), browser); SetWindowType(browser->session_id(), browser->type()); break; } case content::NOTIFICATION_TAB_PARENTED: { TabContentsWrapper* tab = Source<TabContentsWrapper>(source).ptr(); if (tab->profile() != profile()) return; SetTabWindow(tab->restore_tab_helper()->window_id(), tab->restore_tab_helper()->session_id()); if (tab->extension_tab_helper()->extension_app()) { SetTabExtensionAppID( tab->restore_tab_helper()->window_id(), tab->restore_tab_helper()->session_id(), tab->extension_tab_helper()->extension_app()->id()); } break; } case content::NOTIFICATION_TAB_CLOSED: { TabContentsWrapper* tab = TabContentsWrapper::GetCurrentWrapperForContents( Source<NavigationController>(source).ptr()->tab_contents()); if (!tab || tab->profile() != profile()) return; TabClosed(tab->restore_tab_helper()->window_id(), tab->restore_tab_helper()->session_id(), tab->tab_contents()->closed_by_user_gesture()); RecordSessionUpdateHistogramData(content::NOTIFICATION_TAB_CLOSED, &last_updated_tab_closed_time_); break; } case content::NOTIFICATION_NAV_LIST_PRUNED: { TabContentsWrapper* tab = TabContentsWrapper::GetCurrentWrapperForContents( Source<NavigationController>(source).ptr()->tab_contents()); if (!tab || tab->profile() != profile()) return; Details<content::PrunedDetails> pruned_details(details); if (pruned_details->from_front) { TabNavigationPathPrunedFromFront( tab->restore_tab_helper()->window_id(), tab->restore_tab_helper()->session_id(), pruned_details->count); } else { TabNavigationPathPrunedFromBack( tab->restore_tab_helper()->window_id(), tab->restore_tab_helper()->session_id(), tab->controller().entry_count()); } RecordSessionUpdateHistogramData(content::NOTIFICATION_NAV_LIST_PRUNED, &last_updated_nav_list_pruned_time_); break; } case content::NOTIFICATION_NAV_ENTRY_CHANGED: { TabContentsWrapper* tab = TabContentsWrapper::GetCurrentWrapperForContents( Source<NavigationController>(source).ptr()->tab_contents()); if (!tab || tab->profile() != profile()) return; Details<content::EntryChangedDetails> changed(details); UpdateTabNavigation( tab->restore_tab_helper()->window_id(), tab->restore_tab_helper()->session_id(), changed->index, *changed->changed_entry); break; } case content::NOTIFICATION_NAV_ENTRY_COMMITTED: { TabContentsWrapper* tab = TabContentsWrapper::GetCurrentWrapperForContents( Source<NavigationController>(source).ptr()->tab_contents()); if (!tab || tab->profile() != profile()) return; int current_entry_index = tab->controller().GetCurrentEntryIndex(); SetSelectedNavigationIndex(tab->restore_tab_helper()->window_id(), tab->restore_tab_helper()->session_id(), current_entry_index); UpdateTabNavigation( tab->restore_tab_helper()->window_id(), tab->restore_tab_helper()->session_id(), current_entry_index, *tab->controller().GetEntryAtIndex(current_entry_index)); Details<content::LoadCommittedDetails> changed(details); if (changed->type == NavigationType::NEW_PAGE || changed->type == NavigationType::EXISTING_PAGE) { RecordSessionUpdateHistogramData( content::NOTIFICATION_NAV_ENTRY_COMMITTED, &last_updated_nav_entry_commit_time_); } break; } case chrome::NOTIFICATION_TAB_CONTENTS_APPLICATION_EXTENSION_CHANGED: { ExtensionTabHelper* extension_tab_helper = Source<ExtensionTabHelper>(source).ptr(); if (extension_tab_helper->tab_contents_wrapper()->profile() != profile()) return; if (extension_tab_helper->extension_app()) { RestoreTabHelper* helper = extension_tab_helper->tab_contents_wrapper()->restore_tab_helper(); SetTabExtensionAppID(helper->window_id(), helper->session_id(), extension_tab_helper->extension_app()->id()); } break; } default: NOTREACHED(); } } void SessionService::SetTabExtensionAppID( const SessionID& window_id, const SessionID& tab_id, const std::string& extension_app_id) { if (!ShouldTrackChangesToWindow(window_id)) return; ScheduleCommand(CreateSetTabExtensionAppIDCommand( kCommandSetExtensionAppID, tab_id.id(), extension_app_id)); } SessionCommand* SessionService::CreateSetSelectedTabInWindow( const SessionID& window_id, int index) { SelectedTabInIndexPayload payload = { 0 }; payload.id = window_id.id(); payload.index = index; SessionCommand* command = new SessionCommand(kCommandSetSelectedTabInIndex, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); return command; } SessionCommand* SessionService::CreateSetTabWindowCommand( const SessionID& window_id, const SessionID& tab_id) { SessionID::id_type payload[] = { window_id.id(), tab_id.id() }; SessionCommand* command = new SessionCommand(kCommandSetTabWindow, sizeof(payload)); memcpy(command->contents(), payload, sizeof(payload)); return command; } SessionCommand* SessionService::CreateSetWindowBoundsCommand( const SessionID& window_id, const gfx::Rect& bounds, ui::WindowShowState show_state) { WindowBoundsPayload3 payload = { 0 }; payload.window_id = window_id.id(); payload.x = bounds.x(); payload.y = bounds.y(); payload.w = bounds.width(); payload.h = bounds.height(); payload.show_state = show_state; SessionCommand* command = new SessionCommand(kCommandSetWindowBounds3, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); return command; } SessionCommand* SessionService::CreateSetTabIndexInWindowCommand( const SessionID& tab_id, int new_index) { TabIndexInWindowPayload payload = { 0 }; payload.id = tab_id.id(); payload.index = new_index; SessionCommand* command = new SessionCommand(kCommandSetTabIndexInWindow, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); return command; } SessionCommand* SessionService::CreateTabClosedCommand( const SessionID::id_type tab_id) { ClosedPayload payload; // Because of what appears to be a compiler bug setting payload to {0} doesn't // set the padding to 0, resulting in Purify reporting an UMR when we write // the structure to disk. To avoid this we explicitly memset the struct. memset(&payload, 0, sizeof(payload)); payload.id = tab_id; payload.close_time = Time::Now().ToInternalValue(); SessionCommand* command = new SessionCommand(kCommandTabClosed, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); return command; } SessionCommand* SessionService::CreateWindowClosedCommand( const SessionID::id_type window_id) { ClosedPayload payload; // See comment in CreateTabClosedCommand as to why we do this. memset(&payload, 0, sizeof(payload)); payload.id = window_id; payload.close_time = Time::Now().ToInternalValue(); SessionCommand* command = new SessionCommand(kCommandWindowClosed, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); return command; } SessionCommand* SessionService::CreateSetSelectedNavigationIndexCommand( const SessionID& tab_id, int index) { SelectedNavigationIndexPayload payload = { 0 }; payload.id = tab_id.id(); payload.index = index; SessionCommand* command = new SessionCommand( kCommandSetSelectedNavigationIndex, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); return command; } SessionCommand* SessionService::CreateSetWindowTypeCommand( const SessionID& window_id, WindowType type) { WindowTypePayload payload = { 0 }; payload.id = window_id.id(); payload.index = static_cast<int32>(type); SessionCommand* command = new SessionCommand( kCommandSetWindowType, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); return command; } SessionCommand* SessionService::CreatePinnedStateCommand( const SessionID& tab_id, bool is_pinned) { PinnedStatePayload payload = { 0 }; payload.tab_id = tab_id.id(); payload.pinned_state = is_pinned; SessionCommand* command = new SessionCommand(kCommandSetPinnedState, sizeof(payload)); memcpy(command->contents(), &payload, sizeof(payload)); return command; } void SessionService::OnGotSessionCommands( Handle handle, scoped_refptr<InternalGetCommandsRequest> request) { if (request->canceled()) return; ScopedVector<SessionWindow> valid_windows; RestoreSessionFromCommands( request->commands, &(valid_windows.get())); static_cast<InternalSessionRequest*>(request.get())-> real_callback->RunWithParams( SessionCallback::TupleType(request->handle(), &(valid_windows.get()))); } void SessionService::RestoreSessionFromCommands( const std::vector<SessionCommand*>& commands, std::vector<SessionWindow*>* valid_windows) { std::map<int, SessionTab*> tabs; std::map<int, SessionWindow*> windows; if (CreateTabsAndWindows(commands, &tabs, &windows)) { AddTabsToWindows(&tabs, &windows); SortTabsBasedOnVisualOrderAndPrune(&windows, valid_windows); UpdateSelectedTabIndex(valid_windows); } STLDeleteValues(&tabs); // Don't delete conents of windows, that is done by the caller as all // valid windows are added to valid_windows. } void SessionService::UpdateSelectedTabIndex( std::vector<SessionWindow*>* windows) { for (std::vector<SessionWindow*>::const_iterator i = windows->begin(); i != windows->end(); ++i) { // See note in SessionWindow as to why we do this. int new_index = 0; for (std::vector<SessionTab*>::const_iterator j = (*i)->tabs.begin(); j != (*i)->tabs.end(); ++j) { if ((*j)->tab_visual_index == (*i)->selected_tab_index) { new_index = static_cast<int>(j - (*i)->tabs.begin()); break; } } (*i)->selected_tab_index = new_index; } } SessionWindow* SessionService::GetWindow( SessionID::id_type window_id, IdToSessionWindow* windows) { std::map<int, SessionWindow*>::iterator i = windows->find(window_id); if (i == windows->end()) { SessionWindow* window = new SessionWindow(); window->window_id.set_id(window_id); (*windows)[window_id] = window; return window; } return i->second; } SessionTab* SessionService::GetTab( SessionID::id_type tab_id, IdToSessionTab* tabs) { DCHECK(tabs); std::map<int, SessionTab*>::iterator i = tabs->find(tab_id); if (i == tabs->end()) { SessionTab* tab = new SessionTab(); tab->tab_id.set_id(tab_id); (*tabs)[tab_id] = tab; return tab; } return i->second; } std::vector<TabNavigation>::iterator SessionService::FindClosestNavigationWithIndex( std::vector<TabNavigation>* navigations, int index) { DCHECK(navigations); for (std::vector<TabNavigation>::iterator i = navigations->begin(); i != navigations->end(); ++i) { if (i->index() >= index) return i; } return navigations->end(); } // Function used in sorting windows. Sorting is done based on window id. As // window ids increment for each new window, this effectively sorts by creation // time. static bool WindowOrderSortFunction(const SessionWindow* w1, const SessionWindow* w2) { return w1->window_id.id() < w2->window_id.id(); } // Compares the two tabs based on visual index. static bool TabVisualIndexSortFunction(const SessionTab* t1, const SessionTab* t2) { const int delta = t1->tab_visual_index - t2->tab_visual_index; return delta == 0 ? (t1->tab_id.id() < t2->tab_id.id()) : (delta < 0); } void SessionService::SortTabsBasedOnVisualOrderAndPrune( std::map<int, SessionWindow*>* windows, std::vector<SessionWindow*>* valid_windows) { std::map<int, SessionWindow*>::iterator i = windows->begin(); while (i != windows->end()) { if (i->second->tabs.empty() || i->second->is_constrained || !should_track_changes_for_browser_type( static_cast<Browser::Type>(i->second->type))) { delete i->second; windows->erase(i++); } else { // Valid window; sort the tabs and add it to the list of valid windows. std::sort(i->second->tabs.begin(), i->second->tabs.end(), &TabVisualIndexSortFunction); // Add the window such that older windows appear first. if (valid_windows->empty()) { valid_windows->push_back(i->second); } else { valid_windows->insert( std::upper_bound(valid_windows->begin(), valid_windows->end(), i->second, &WindowOrderSortFunction), i->second); } ++i; } } } void SessionService::AddTabsToWindows(std::map<int, SessionTab*>* tabs, std::map<int, SessionWindow*>* windows) { std::map<int, SessionTab*>::iterator i = tabs->begin(); while (i != tabs->end()) { SessionTab* tab = i->second; if (tab->window_id.id() && !tab->navigations.empty()) { SessionWindow* window = GetWindow(tab->window_id.id(), windows); window->tabs.push_back(tab); tabs->erase(i++); // See note in SessionTab as to why we do this. std::vector<TabNavigation>::iterator j = FindClosestNavigationWithIndex(&(tab->navigations), tab->current_navigation_index); if (j == tab->navigations.end()) { tab->current_navigation_index = static_cast<int>(tab->navigations.size() - 1); } else { tab->current_navigation_index = static_cast<int>(j - tab->navigations.begin()); } } else { // Never got a set tab index in window, or tabs are empty, nothing // to do. ++i; } } } bool SessionService::CreateTabsAndWindows( const std::vector<SessionCommand*>& data, std::map<int, SessionTab*>* tabs, std::map<int, SessionWindow*>* windows) { // If the file is corrupt (command with wrong size, or unknown command), we // still return true and attempt to restore what we we can. for (std::vector<SessionCommand*>::const_iterator i = data.begin(); i != data.end(); ++i) { const SessionCommand::id_type kCommandSetWindowBounds2 = 10; const SessionCommand* command = *i; switch (command->id()) { case kCommandSetTabWindow: { SessionID::id_type payload[2]; if (!command->GetPayload(payload, sizeof(payload))) return true; GetTab(payload[1], tabs)->window_id.set_id(payload[0]); break; } // This is here for forward migration only. New data is saved with // |kCommandSetWindowBounds3|. case kCommandSetWindowBounds2: { WindowBoundsPayload2 payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetWindow(payload.window_id, windows)->bounds.SetRect(payload.x, payload.y, payload.w, payload.h); GetWindow(payload.window_id, windows)->show_state = payload.is_maximized ? ui::SHOW_STATE_MAXIMIZED : ui::SHOW_STATE_NORMAL; break; } case kCommandSetWindowBounds3: { WindowBoundsPayload3 payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetWindow(payload.window_id, windows)->bounds.SetRect(payload.x, payload.y, payload.w, payload.h); // SHOW_STATE_INACTIVE is not persisted. ui::WindowShowState show_state = ui::SHOW_STATE_NORMAL; if (payload.show_state > ui::SHOW_STATE_DEFAULT && payload.show_state < ui::SHOW_STATE_END && payload.show_state != ui::SHOW_STATE_INACTIVE) { show_state = static_cast<ui::WindowShowState>(payload.show_state); } else { NOTREACHED(); } GetWindow(payload.window_id, windows)->show_state = show_state; break; } case kCommandSetTabIndexInWindow: { TabIndexInWindowPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetTab(payload.id, tabs)->tab_visual_index = payload.index; break; } case kCommandTabClosed: case kCommandWindowClosed: { ClosedPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; if (command->id() == kCommandTabClosed) { delete GetTab(payload.id, tabs); tabs->erase(payload.id); } else { delete GetWindow(payload.id, windows); windows->erase(payload.id); } break; } case kCommandTabNavigationPathPrunedFromBack: { TabNavigationPathPrunedFromBackPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; SessionTab* tab = GetTab(payload.id, tabs); tab->navigations.erase( FindClosestNavigationWithIndex(&(tab->navigations), payload.index), tab->navigations.end()); break; } case kCommandTabNavigationPathPrunedFromFront: { TabNavigationPathPrunedFromFrontPayload payload; if (!command->GetPayload(&payload, sizeof(payload)) || payload.index <= 0) { return true; } SessionTab* tab = GetTab(payload.id, tabs); // Update the selected navigation index. tab->current_navigation_index = std::max(-1, tab->current_navigation_index - payload.index); // And update the index of existing navigations. for (std::vector<TabNavigation>::iterator i = tab->navigations.begin(); i != tab->navigations.end();) { i->set_index(i->index() - payload.index); if (i->index() < 0) i = tab->navigations.erase(i); else ++i; } break; } case kCommandUpdateTabNavigation: { TabNavigation navigation; SessionID::id_type tab_id; if (!RestoreUpdateTabNavigationCommand(*command, &navigation, &tab_id)) return true; SessionTab* tab = GetTab(tab_id, tabs); std::vector<TabNavigation>::iterator i = FindClosestNavigationWithIndex(&(tab->navigations), navigation.index()); if (i != tab->navigations.end() && i->index() == navigation.index()) *i = navigation; else tab->navigations.insert(i, navigation); break; } case kCommandSetSelectedNavigationIndex: { SelectedNavigationIndexPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetTab(payload.id, tabs)->current_navigation_index = payload.index; break; } case kCommandSetSelectedTabInIndex: { SelectedTabInIndexPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetWindow(payload.id, windows)->selected_tab_index = payload.index; break; } case kCommandSetWindowType: { WindowTypePayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetWindow(payload.id, windows)->is_constrained = false; GetWindow(payload.id, windows)->type = BrowserTypeForWindowType( static_cast<WindowType>(payload.index)); break; } case kCommandSetPinnedState: { PinnedStatePayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetTab(payload.tab_id, tabs)->pinned = payload.pinned_state; break; } case kCommandSetExtensionAppID: { SessionID::id_type tab_id; std::string extension_app_id; if (!RestoreSetTabExtensionAppIDCommand( *command, &tab_id, &extension_app_id)) { return true; } GetTab(tab_id, tabs)->extension_app_id.swap(extension_app_id); break; } default: return true; } } return true; } void SessionService::BuildCommandsForTab( const SessionID& window_id, TabContentsWrapper* tab, int index_in_window, bool is_pinned, std::vector<SessionCommand*>* commands, IdToRange* tab_to_available_range) { DCHECK(tab && commands && window_id.id()); const SessionID& session_id(tab->restore_tab_helper()->session_id()); commands->push_back(CreateSetTabWindowCommand(window_id, session_id)); const int current_index = tab->controller().GetCurrentEntryIndex(); const int min_index = std::max(0, current_index - max_persist_navigation_count); const int max_index = std::min(current_index + max_persist_navigation_count, tab->controller().entry_count()); const int pending_index = tab->controller().pending_entry_index(); if (tab_to_available_range) { (*tab_to_available_range)[session_id.id()] = std::pair<int, int>(min_index, max_index); } if (is_pinned) { commands->push_back(CreatePinnedStateCommand(session_id, true)); } TabContentsWrapper* wrapper = TabContentsWrapper::GetCurrentWrapperForContents(tab->tab_contents()); if (wrapper->extension_tab_helper()->extension_app()) { commands->push_back( CreateSetTabExtensionAppIDCommand( kCommandSetExtensionAppID, session_id.id(), wrapper->extension_tab_helper()->extension_app()->id())); } for (int i = min_index; i < max_index; ++i) { const NavigationEntry* entry = (i == pending_index) ? tab->controller().pending_entry() : tab->controller().GetEntryAtIndex(i); DCHECK(entry); if (ShouldTrackEntry(entry->virtual_url())) { commands->push_back( CreateUpdateTabNavigationCommand( kCommandUpdateTabNavigation, session_id.id(), i, *entry)); } } commands->push_back( CreateSetSelectedNavigationIndexCommand(session_id, current_index)); if (index_in_window != -1) { commands->push_back( CreateSetTabIndexInWindowCommand(session_id, index_in_window)); } } void SessionService::BuildCommandsForBrowser( Browser* browser, std::vector<SessionCommand*>* commands, IdToRange* tab_to_available_range, std::set<SessionID::id_type>* windows_to_track) { DCHECK(browser && commands); DCHECK(browser->session_id().id()); ui::WindowShowState show_state = ui::SHOW_STATE_NORMAL; if (browser->window()->IsMaximized()) show_state = ui::SHOW_STATE_MAXIMIZED; else if (browser->window()->IsMinimized()) show_state = ui::SHOW_STATE_MINIMIZED; commands->push_back( CreateSetWindowBoundsCommand(browser->session_id(), browser->window()->GetRestoredBounds(), show_state)); commands->push_back(CreateSetWindowTypeCommand( browser->session_id(), WindowTypeForBrowserType(browser->type()))); bool added_to_windows_to_track = false; for (int i = 0; i < browser->tab_count(); ++i) { TabContentsWrapper* tab = browser->GetTabContentsWrapperAt(i); DCHECK(tab); if (tab->profile() == profile() || profile() == NULL) { BuildCommandsForTab(browser->session_id(), tab, i, browser->tabstrip_model()->IsTabPinned(i), commands, tab_to_available_range); if (windows_to_track && !added_to_windows_to_track) { windows_to_track->insert(browser->session_id().id()); added_to_windows_to_track = true; } } } commands->push_back( CreateSetSelectedTabInWindow(browser->session_id(), browser->active_index())); } void SessionService::BuildCommandsFromBrowsers( std::vector<SessionCommand*>* commands, IdToRange* tab_to_available_range, std::set<SessionID::id_type>* windows_to_track) { DCHECK(commands); for (BrowserList::const_iterator i = BrowserList::begin(); i != BrowserList::end(); ++i) { // Make sure the browser has tabs and a window. Browsers destructor // removes itself from the BrowserList. When a browser is closed the // destructor is not necessarily run immediately. This means its possible // for us to get a handle to a browser that is about to be removed. If // the tab count is 0 or the window is NULL, the browser is about to be // deleted, so we ignore it. if (should_track_changes_for_browser_type((*i)->type()) && (*i)->tab_count() && (*i)->window()) { BuildCommandsForBrowser(*i, commands, tab_to_available_range, windows_to_track); } } } void SessionService::ScheduleReset() { set_pending_reset(true); STLDeleteElements(&pending_commands()); tab_to_available_range_.clear(); windows_tracking_.clear(); BuildCommandsFromBrowsers(&pending_commands(), &tab_to_available_range_, &windows_tracking_); if (!windows_tracking_.empty()) { // We're lazily created on startup and won't get an initial batch of // SetWindowType messages. Set these here to make sure our state is correct. has_open_trackable_browsers_ = true; move_on_new_browser_ = true; } StartSaveTimer(); } bool SessionService::ReplacePendingCommand(SessionCommand* command) { // We only optimize page navigations, which can happen quite frequently and // are expensive. If necessary, other commands could be searched for as // well. if (command->id() != kCommandUpdateTabNavigation) return false; void* iterator = NULL; scoped_ptr<Pickle> command_pickle(command->PayloadAsPickle()); SessionID::id_type command_tab_id; int command_nav_index; if (!command_pickle->ReadInt(&iterator, &command_tab_id) || !command_pickle->ReadInt(&iterator, &command_nav_index)) { return false; } for (std::vector<SessionCommand*>::reverse_iterator i = pending_commands().rbegin(); i != pending_commands().rend(); ++i) { SessionCommand* existing_command = *i; if (existing_command->id() == kCommandUpdateTabNavigation) { SessionID::id_type existing_tab_id; int existing_nav_index; { // Creating a pickle like this means the Pickle references the data from // the command. Make sure we delete the pickle before the command, else // the pickle references deleted memory. scoped_ptr<Pickle> existing_pickle(existing_command->PayloadAsPickle()); iterator = NULL; if (!existing_pickle->ReadInt(&iterator, &existing_tab_id) || !existing_pickle->ReadInt(&iterator, &existing_nav_index)) { return false; } } if (existing_tab_id == command_tab_id && existing_nav_index == command_nav_index) { // existing_command is an update for the same tab/index pair. Replace // it with the new one. We need to add to the end of the list just in // case there is a prune command after the update command. delete existing_command; pending_commands().erase(i.base() - 1); pending_commands().push_back(command); return true; } return false; } } return false; } void SessionService::ScheduleCommand(SessionCommand* command) { DCHECK(command); if (ReplacePendingCommand(command)) return; BaseSessionService::ScheduleCommand(command); // Don't schedule a reset on tab closed/window closed. Otherwise we may // lose tabs/windows we want to restore from if we exit right after this. if (!pending_reset() && pending_window_close_ids_.empty() && commands_since_reset() >= kWritesPerReset && (command->id() != kCommandTabClosed && command->id() != kCommandWindowClosed)) { ScheduleReset(); } } void SessionService::CommitPendingCloses() { for (PendingTabCloseIDs::iterator i = pending_tab_close_ids_.begin(); i != pending_tab_close_ids_.end(); ++i) { ScheduleCommand(CreateTabClosedCommand(*i)); } pending_tab_close_ids_.clear(); for (PendingWindowCloseIDs::iterator i = pending_window_close_ids_.begin(); i != pending_window_close_ids_.end(); ++i) { ScheduleCommand(CreateWindowClosedCommand(*i)); } pending_window_close_ids_.clear(); } bool SessionService::IsOnlyOneTabLeft() { if (!profile()) { // We're testing, always return false. return false; } int window_count = 0; for (BrowserList::const_iterator i = BrowserList::begin(); i != BrowserList::end(); ++i) { const SessionID::id_type window_id = (*i)->session_id().id(); if (should_track_changes_for_browser_type((*i)->type()) && (*i)->profile() == profile() && window_closing_ids_.find(window_id) == window_closing_ids_.end()) { if (++window_count > 1) return false; // By the time this is invoked the tab has been removed. As such, we use // > 0 here rather than > 1. if ((*i)->tab_count() > 0) return false; } } return true; } bool SessionService::HasOpenTrackableBrowsers(const SessionID& window_id) { if (!profile()) { // We're testing, always return false. return true; } for (BrowserList::const_iterator i = BrowserList::begin(); i != BrowserList::end(); ++i) { Browser* browser = *i; const SessionID::id_type browser_id = browser->session_id().id(); if (browser_id != window_id.id() && window_closing_ids_.find(browser_id) == window_closing_ids_.end() && should_track_changes_for_browser_type(browser->type()) && browser->profile() == profile()) { return true; } } return false; } bool SessionService::ShouldTrackChangesToWindow(const SessionID& window_id) { return windows_tracking_.find(window_id.id()) != windows_tracking_.end(); } bool SessionService::should_track_changes_for_browser_type(Browser::Type type) { return type == Browser::TYPE_TABBED || (type == Browser::TYPE_POPUP && browser_defaults::kRestorePopups); } SessionService::WindowType SessionService::WindowTypeForBrowserType( Browser::Type type) { switch (type) { case Browser::TYPE_POPUP: return TYPE_POPUP; case Browser::TYPE_TABBED: return TYPE_TABBED; default: DCHECK(false); return TYPE_TABBED; } } Browser::Type SessionService::BrowserTypeForWindowType(WindowType type) { switch (type) { case TYPE_POPUP: return Browser::TYPE_POPUP; case TYPE_TABBED: default: return Browser::TYPE_TABBED; } } void SessionService::RecordSessionUpdateHistogramData(int type, base::TimeTicks* last_updated_time) { if (!last_updated_time->is_null()) { base::TimeDelta delta = base::TimeTicks::Now() - *last_updated_time; // We're interested in frequent updates periods longer than // 10 minutes. bool use_long_period = false; if (delta >= save_delay_in_mins_) { use_long_period = true; } switch (type) { case chrome::NOTIFICATION_SESSION_SERVICE_SAVED : RecordUpdatedSaveTime(delta, use_long_period); RecordUpdatedSessionNavigationOrTab(delta, use_long_period); break; case content::NOTIFICATION_TAB_CLOSED: RecordUpdatedTabClosed(delta, use_long_period); RecordUpdatedSessionNavigationOrTab(delta, use_long_period); break; case content::NOTIFICATION_NAV_LIST_PRUNED: RecordUpdatedNavListPruned(delta, use_long_period); RecordUpdatedSessionNavigationOrTab(delta, use_long_period); break; case content::NOTIFICATION_NAV_ENTRY_COMMITTED: RecordUpdatedNavEntryCommit(delta, use_long_period); RecordUpdatedSessionNavigationOrTab(delta, use_long_period); break; default: NOTREACHED() << "Bad type sent to RecordSessionUpdateHistogramData"; break; } } (*last_updated_time) = base::TimeTicks::Now(); } void SessionService::RecordUpdatedTabClosed(base::TimeDelta delta, bool use_long_period) { std::string name("SessionRestore.TabClosedPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(name, delta, // 2500ms is the default save delay. save_delay_in_millis_, save_delay_in_mins_, 50); if (use_long_period) { std::string long_name_("SessionRestore.TabClosedLongPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(long_name_, delta, save_delay_in_mins_, save_delay_in_hrs_, 50); } } void SessionService::RecordUpdatedNavListPruned(base::TimeDelta delta, bool use_long_period) { std::string name("SessionRestore.NavigationListPrunedPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(name, delta, // 2500ms is the default save delay. save_delay_in_millis_, save_delay_in_mins_, 50); if (use_long_period) { std::string long_name_("SessionRestore.NavigationListPrunedLongPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(long_name_, delta, save_delay_in_mins_, save_delay_in_hrs_, 50); } } void SessionService::RecordUpdatedNavEntryCommit(base::TimeDelta delta, bool use_long_period) { std::string name("SessionRestore.NavEntryCommittedPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(name, delta, // 2500ms is the default save delay. save_delay_in_millis_, save_delay_in_mins_, 50); if (use_long_period) { std::string long_name_("SessionRestore.NavEntryCommittedLongPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(long_name_, delta, save_delay_in_mins_, save_delay_in_hrs_, 50); } } void SessionService::RecordUpdatedSessionNavigationOrTab(base::TimeDelta delta, bool use_long_period) { std::string name("SessionRestore.NavOrTabUpdatePeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(name, delta, // 2500ms is the default save delay. save_delay_in_millis_, save_delay_in_mins_, 50); if (use_long_period) { std::string long_name_("SessionRestore.NavOrTabUpdateLongPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(long_name_, delta, save_delay_in_mins_, save_delay_in_hrs_, 50); } } void SessionService::RecordUpdatedSaveTime(base::TimeDelta delta, bool use_long_period) { std::string name("SessionRestore.SavePeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(name, delta, // 2500ms is the default save delay. save_delay_in_millis_, save_delay_in_mins_, 50); if (use_long_period) { std::string long_name_("SessionRestore.SaveLongPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(long_name_, delta, save_delay_in_mins_, save_delay_in_hrs_, 50); } }
// 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 "chrome/browser/views/frame/browser_view.h" #if defined(OS_LINUX) #include <gtk/gtk.h> #endif #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/command_line.h" #include "base/i18n/rtl.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/app_modal_dialog_queue.h" #include "chrome/browser/autocomplete/autocomplete_popup_model.h" #include "chrome/browser/autocomplete/autocomplete_popup_view.h" #include "chrome/browser/automation/ui_controls.h" #include "chrome/browser/bookmarks/bookmark_utils.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_theme_provider.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/dom_ui/bug_report_ui.h" #include "chrome/browser/download/download_manager.h" #include "chrome/browser/ntp_background_util.h" #include "chrome/browser/page_info_window.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/sessions/tab_restore_service.h" #include "chrome/browser/sidebar/sidebar_container.h" #include "chrome/browser/sidebar/sidebar_manager.h" #include "chrome/browser/tab_contents/match_preview.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view.h" #include "chrome/browser/view_ids.h" #include "chrome/browser/views/accessible_view_helper.h" #include "chrome/browser/views/bookmark_bar_view.h" #include "chrome/browser/views/browser_dialogs.h" #include "chrome/browser/views/download_shelf_view.h" #include "chrome/browser/views/frame/browser_view_layout.h" #include "chrome/browser/views/fullscreen_exit_bubble.h" #include "chrome/browser/views/status_bubble_views.h" #include "chrome/browser/views/tab_contents/tab_contents_container.h" #include "chrome/browser/views/tabs/browser_tab_strip_controller.h" #include "chrome/browser/views/tabs/side_tab_strip.h" #include "chrome/browser/views/theme_install_bubble_view.h" #include "chrome/browser/views/toolbar_view.h" #include "chrome/browser/views/update_recommended_message_box.h" #include "chrome/browser/window_sizer.h" #include "chrome/browser/wrench_menu_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension_resource.h" #include "chrome/common/native_window_notification_source.h" #include "chrome/common/notification_service.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "gfx/canvas_skia.h" #include "grit/app_resources.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" #include "grit/theme_resources.h" #include "grit/webkit_resources.h" #include "views/controls/single_split_view.h" #include "views/focus/external_focus_tracker.h" #include "views/focus/view_storage.h" #include "views/grid_layout.h" #include "views/widget/root_view.h" #include "views/window/dialog_delegate.h" #include "views/window/window.h" #if defined(OS_WIN) #include "app/win_util.h" #include "chrome/browser/aeropeek_manager.h" #include "chrome/browser/jumplist_win.h" #elif defined(OS_LINUX) #include "chrome/browser/views/accelerator_table_gtk.h" #include "views/window/hit_test.h" #include "views/window/window_gtk.h" #endif using base::TimeDelta; using views::ColumnSet; using views::GridLayout; // The height of the status bubble. static const int kStatusBubbleHeight = 20; // The name of a key to store on the window handle so that other code can // locate this object using just the handle. #if defined(OS_WIN) static const wchar_t* kBrowserViewKey = L"__BROWSER_VIEW__"; #else static const char* kBrowserViewKey = "__BROWSER_VIEW__"; #endif // How frequently we check for hung plugin windows. static const int kDefaultHungPluginDetectFrequency = 2000; // How long do we wait before we consider a window hung (in ms). static const int kDefaultPluginMessageResponseTimeout = 30000; // The number of milliseconds between loading animation frames. static const int kLoadingAnimationFrameTimeMs = 30; // The amount of space we expect the window border to take up. static const int kWindowBorderWidth = 5; // If not -1, windows are shown with this state. static int explicit_show_state = -1; // How round the 'new tab' style bookmarks bar is. static const int kNewtabBarRoundness = 5; // ------------ // Returned from BrowserView::GetClassName. const char BrowserView::kViewClassName[] = "browser/views/BrowserView"; #if defined(OS_CHROMEOS) // Get a normal browser window of given |profile| to use as dialog parent // if given |browser| is not one. Otherwise, returns browser window of // |browser|. If |profile| is NULL, |browser|'s profile is used to find the // normal browser. static gfx::NativeWindow GetNormalBrowserWindowForBrowser(Browser* browser, Profile* profile) { if (browser->type() != Browser::TYPE_NORMAL) { Browser* normal_browser = BrowserList::FindBrowserWithType( profile ? profile : browser->profile(), Browser::TYPE_NORMAL, true); if (normal_browser && normal_browser->window()) return normal_browser->window()->GetNativeHandle(); } return browser->window()->GetNativeHandle(); } #endif // defined(OS_CHROMEOS) // ContentsContainer is responsible for managing the TabContents views. // ContentsContainer has up to two children: one for the currently active // TabContents and one for the match preview TabContents. class BrowserView::ContentsContainer : public views::View { public: ContentsContainer(BrowserView* browser_view, views::View* active) : browser_view_(browser_view), active_(active), preview_(NULL) { AddChildView(active_); } // Makes the preview view the active view and nulls out the old active view. // It's assumed the caller will delete or remove the old active view // separately. void MakePreviewContentsActiveContents() { active_ = preview_; preview_ = NULL; Layout(); } // Sets the preview view. This does not delete the old. void SetPreview(views::View* preview) { if (preview == preview_) return; if (preview_) RemoveChildView(preview_); preview_ = preview; if (preview_) AddChildView(preview_); Layout(); } virtual void Layout() { // The active view always gets the full bounds. active_->SetBounds(0, 0, width(), height()); if (preview_) { // The preview view gets the full width and is positioned beneath the // bottom of the autocompleted popup. int max_autocomplete_y = browser_view_->toolbar()->location_bar()-> location_entry()->model()->popup_model()->view()->GetMaxYCoordinate(); gfx::Point screen_origin; views::View::ConvertPointToScreen(this, &screen_origin); DCHECK_GT(max_autocomplete_y, screen_origin.y()); int preview_origin = max_autocomplete_y - screen_origin.y(); if (preview_origin < height()) { preview_->SetBounds(0, preview_origin, width(), height() - preview_origin); } else { preview_->SetBounds(0, 0, 0, 0); } } } private: BrowserView* browser_view_; views::View* active_; views::View* preview_; DISALLOW_COPY_AND_ASSIGN(ContentsContainer); }; /////////////////////////////////////////////////////////////////////////////// // BookmarkExtensionBackground, private: // This object serves as the views::Background object which is used to layout // and paint the bookmark bar. class BookmarkExtensionBackground : public views::Background { public: explicit BookmarkExtensionBackground(BrowserView* browser_view, DetachableToolbarView* host_view, Browser* browser); // View methods overridden from views:Background. virtual void Paint(gfx::Canvas* canvas, views::View* view) const; private: BrowserView* browser_view_; // The view hosting this background. DetachableToolbarView* host_view_; Browser* browser_; DISALLOW_COPY_AND_ASSIGN(BookmarkExtensionBackground); }; BookmarkExtensionBackground::BookmarkExtensionBackground( BrowserView* browser_view, DetachableToolbarView* host_view, Browser* browser) : browser_view_(browser_view), host_view_(host_view), browser_(browser) { } void BookmarkExtensionBackground::Paint(gfx::Canvas* canvas, views::View* view) const { ThemeProvider* tp = host_view_->GetThemeProvider(); int toolbar_overlap = host_view_->GetToolbarOverlap(); // The client edge is drawn below the toolbar bounds. if (toolbar_overlap) toolbar_overlap += views::NonClientFrameView::kClientEdgeThickness; if (host_view_->IsDetached()) { // Draw the background to match the new tab page. int height = 0; TabContents* contents = browser_->GetSelectedTabContents(); if (contents && contents->view()) height = contents->view()->GetContainerSize().height(); NtpBackgroundUtil::PaintBackgroundDetachedMode( host_view_->GetThemeProvider(), canvas, gfx::Rect(0, toolbar_overlap, host_view_->width(), host_view_->height() - toolbar_overlap), height); // As 'hidden' according to the animation is the full in-tab state, // we invert the value - when current_state is at '0', we expect the // bar to be docked. double current_state = 1 - host_view_->GetAnimationValue(); double h_padding = static_cast<double>(BookmarkBarView::kNewtabHorizontalPadding) * current_state; double v_padding = static_cast<double>(BookmarkBarView::kNewtabVerticalPadding) * current_state; SkRect rect; double roundness = 0; DetachableToolbarView::CalculateContentArea(current_state, h_padding, v_padding, &rect, &roundness, host_view_); DetachableToolbarView::PaintContentAreaBackground(canvas, tp, rect, roundness); DetachableToolbarView::PaintContentAreaBorder(canvas, tp, rect, roundness); if (!toolbar_overlap) DetachableToolbarView::PaintHorizontalBorder(canvas, host_view_); } else { DetachableToolbarView::PaintBackgroundAttachedMode(canvas, host_view_, browser_view_->OffsetPointForToolbarBackgroundImage( gfx::Point(host_view_->MirroredX(), host_view_->y()))); if (host_view_->height() >= toolbar_overlap) DetachableToolbarView::PaintHorizontalBorder(canvas, host_view_); } } /////////////////////////////////////////////////////////////////////////////// // ResizeCorner, private: class ResizeCorner : public views::View { public: ResizeCorner() { EnableCanvasFlippingForRTLUI(true); } virtual void Paint(gfx::Canvas* canvas) { views::Window* window = GetWindow(); if (!window || (window->IsMaximized() || window->IsFullscreen())) return; SkBitmap* bitmap = ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_TEXTAREA_RESIZER); bitmap->buildMipMap(false); canvas->DrawBitmapInt(*bitmap, width() - bitmap->width(), height() - bitmap->height()); } static gfx::Size GetSize() { // This is disabled until we find what makes us slower when we let // WebKit know that we have a resizer rect... // int scrollbar_thickness = gfx::scrollbar_size(); // return gfx::Size(scrollbar_thickness, scrollbar_thickness); return gfx::Size(); } virtual gfx::Size GetPreferredSize() { views::Window* window = GetWindow(); return (!window || window->IsMaximized() || window->IsFullscreen()) ? gfx::Size() : GetSize(); } virtual void Layout() { views::View* parent_view = GetParent(); if (parent_view) { gfx::Size ps = GetPreferredSize(); // No need to handle Right to left text direction here, // our parent must take care of it for us... SetBounds(parent_view->width() - ps.width(), parent_view->height() - ps.height(), ps.width(), ps.height()); } } private: // Returns the WindowWin we're displayed in. Returns NULL if we're not // currently in a window. views::Window* GetWindow() { views::Widget* widget = GetWidget(); return widget ? widget->GetWindow() : NULL; } DISALLOW_COPY_AND_ASSIGN(ResizeCorner); }; //////////////////////////////////////////////////////////////////////////////// // DownloadInProgressConfirmDialogDelegate class DownloadInProgressConfirmDialogDelegate : public views::DialogDelegate, public views::View { public: explicit DownloadInProgressConfirmDialogDelegate(Browser* browser) : browser_(browser), product_name_(l10n_util::GetString(IDS_PRODUCT_NAME)) { int download_count = browser->profile()->GetDownloadManager()-> in_progress_count(); std::wstring warning_text; std::wstring explanation_text; if (download_count == 1) { warning_text = l10n_util::GetStringF(IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_WARNING, product_name_); explanation_text = l10n_util::GetStringF(IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION, product_name_); ok_button_text_ = l10n_util::GetString( IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL); cancel_button_text_ = l10n_util::GetString( IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL); } else { warning_text = l10n_util::GetStringF(IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_WARNING, product_name_, UTF8ToWide(base::IntToString(download_count))); explanation_text = l10n_util::GetStringF( IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_EXPLANATION, product_name_); ok_button_text_ = l10n_util::GetString( IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_OK_BUTTON_LABEL); cancel_button_text_ = l10n_util::GetString( IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL); } // There are two lines of text: the bold warning label and the text // explanation label. GridLayout* layout = new GridLayout(this); SetLayoutManager(layout); const int columnset_id = 0; ColumnSet* column_set = layout->AddColumnSet(columnset_id); column_set->AddColumn(GridLayout::FILL, GridLayout::LEADING, 1, GridLayout::USE_PREF, 0, 0); gfx::Font bold_font = ResourceBundle::GetSharedInstance().GetFont( ResourceBundle::BaseFont).DeriveFont(0, gfx::Font::BOLD); warning_ = new views::Label(warning_text, bold_font); warning_->SetMultiLine(true); warning_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); warning_->set_border(views::Border::CreateEmptyBorder(10, 10, 10, 10)); layout->StartRow(0, columnset_id); layout->AddView(warning_); explanation_ = new views::Label(explanation_text); explanation_->SetMultiLine(true); explanation_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); explanation_->set_border(views::Border::CreateEmptyBorder(10, 10, 10, 10)); layout->StartRow(0, columnset_id); layout->AddView(explanation_); dialog_dimensions_ = views::Window::GetLocalizedContentsSize( IDS_DOWNLOAD_IN_PROGRESS_WIDTH_CHARS, IDS_DOWNLOAD_IN_PROGRESS_MINIMUM_HEIGHT_LINES); const int height = warning_->GetHeightForWidth(dialog_dimensions_.width()) + explanation_->GetHeightForWidth(dialog_dimensions_.width()); dialog_dimensions_.set_height(std::max(height, dialog_dimensions_.height())); } ~DownloadInProgressConfirmDialogDelegate() { } // View implementation: virtual gfx::Size GetPreferredSize() { return dialog_dimensions_; } // DialogDelegate implementation: virtual int GetDefaultDialogButton() const { return MessageBoxFlags::DIALOGBUTTON_CANCEL; } virtual std::wstring GetDialogButtonLabel( MessageBoxFlags::DialogButton button) const { if (button == MessageBoxFlags::DIALOGBUTTON_OK) return ok_button_text_; DCHECK_EQ(MessageBoxFlags::DIALOGBUTTON_CANCEL, button); return cancel_button_text_; } virtual bool Accept() { browser_->InProgressDownloadResponse(true); return true; } virtual bool Cancel() { browser_->InProgressDownloadResponse(false); return true; } // WindowDelegate implementation: virtual bool IsModal() const { return true; } virtual views::View* GetContentsView() { return this; } virtual std::wstring GetWindowTitle() const { return product_name_; } private: Browser* browser_; views::Label* warning_; views::Label* explanation_; std::wstring ok_button_text_; std::wstring cancel_button_text_; std::wstring product_name_; gfx::Size dialog_dimensions_; DISALLOW_COPY_AND_ASSIGN(DownloadInProgressConfirmDialogDelegate); }; /////////////////////////////////////////////////////////////////////////////// // BrowserView, public: // static void BrowserView::SetShowState(int state) { explicit_show_state = state; } BrowserView::BrowserView(Browser* browser) : views::ClientView(NULL, NULL), last_focused_view_storage_id_( views::ViewStorage::GetSharedInstance()->CreateStorageID()), frame_(NULL), browser_(browser), active_bookmark_bar_(NULL), tabstrip_(NULL), toolbar_(NULL), infobar_container_(NULL), sidebar_container_(NULL), sidebar_split_(NULL), contents_container_(NULL), devtools_container_(NULL), preview_container_(NULL), contents_(NULL), contents_split_(NULL), initialized_(false), ignore_layout_(true) #if defined(OS_WIN) ,hung_window_detector_(&hung_plugin_action_), ticker_(0) #endif { browser_->tabstrip_model()->AddObserver(this); registrar_.Add(this, NotificationType::SIDEBAR_CHANGED, Source<SidebarManager>(SidebarManager::GetInstance())); } BrowserView::~BrowserView() { browser_->tabstrip_model()->RemoveObserver(this); #if defined(OS_WIN) // Remove this observer. if (aeropeek_manager_.get()) browser_->tabstrip_model()->RemoveObserver(aeropeek_manager_.get()); // Stop hung plugin monitoring. ticker_.Stop(); ticker_.UnregisterTickHandler(&hung_window_detector_); #endif // We destroy the download shelf before |browser_| to remove its child // download views from the set of download observers (since the observed // downloads can be destroyed along with |browser_| and the observer // notifications will call back into deleted objects). download_shelf_.reset(); // The TabStrip attaches a listener to the model. Make sure we shut down the // TabStrip first so that it can cleanly remove the listener. tabstrip_->GetParent()->RemoveChildView(tabstrip_); delete tabstrip_; tabstrip_ = NULL; // Explicitly set browser_ to NULL. browser_.reset(); } // static BrowserView* BrowserView::GetBrowserViewForNativeWindow( gfx::NativeWindow window) { #if defined(OS_WIN) if (IsWindow(window)) { HANDLE data = GetProp(window, kBrowserViewKey); if (data) return reinterpret_cast<BrowserView*>(data); } #else if (window) { return static_cast<BrowserView*>( g_object_get_data(G_OBJECT(window), kBrowserViewKey)); } #endif return NULL; } int BrowserView::GetShowState() const { if (explicit_show_state != -1) return explicit_show_state; #if defined(OS_WIN) STARTUPINFO si = {0}; si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW; GetStartupInfo(&si); return si.wShowWindow; #else NOTIMPLEMENTED(); return 0; #endif } void BrowserView::WindowMoved() { // Cancel any tabstrip animations, some of them may be invalidated by the // window being repositioned. // Comment out for one cycle to see if this fixes dist tests. // tabstrip_->DestroyDragController(); status_bubble_->Reposition(); BrowserBubbleHost::WindowMoved(); browser::HideBookmarkBubbleView(); // Close the omnibox popup, if any. if (toolbar_->location_bar()) toolbar_->location_bar()->location_entry()->ClosePopup(); } void BrowserView::WindowMoveOrResizeStarted() { TabContents* tab_contents = GetSelectedTabContents(); if (tab_contents) tab_contents->WindowMoveOrResizeStarted(); } gfx::Rect BrowserView::GetToolbarBounds() const { gfx::Rect toolbar_bounds(toolbar_->bounds()); if (toolbar_bounds.IsEmpty()) return toolbar_bounds; // When using vertical tabs, the toolbar appears to extend behind the tab // column. if (UseVerticalTabs()) toolbar_bounds.Inset(tabstrip_->x() - toolbar_bounds.x(), 0, 0, 0); // The apparent toolbar edges are outside the "real" toolbar edges. toolbar_bounds.Inset(-views::NonClientFrameView::kClientEdgeThickness, 0); return toolbar_bounds; } gfx::Rect BrowserView::GetClientAreaBounds() const { gfx::Rect container_bounds = contents_->bounds(); gfx::Point container_origin = container_bounds.origin(); ConvertPointToView(this, GetParent(), &container_origin); container_bounds.set_origin(container_origin); return container_bounds; } bool BrowserView::ShouldFindBarBlendWithBookmarksBar() const { if (bookmark_bar_view_.get()) return bookmark_bar_view_->IsAlwaysShown(); return false; } gfx::Rect BrowserView::GetFindBarBoundingBox() const { return GetBrowserViewLayout()->GetFindBarBoundingBox(); } int BrowserView::GetTabStripHeight() const { // We want to return tabstrip_->height(), but we might be called in the midst // of layout, when that hasn't yet been updated to reflect the current state. // So return what the tabstrip height _ought_ to be right now. return IsTabStripVisible() ? tabstrip_->GetPreferredSize().height() : 0; } gfx::Point BrowserView::OffsetPointForToolbarBackgroundImage( const gfx::Point& point) const { // The background image starts tiling horizontally at the window left edge and // vertically at the top edge of the horizontal tab strip (or where it would // be). We expect our parent's origin to be the window origin. gfx::Point window_point(point.Add(gfx::Point(MirroredX(), y()))); window_point.Offset(0, -frame_->GetHorizontalTabStripVerticalOffset(false)); return window_point; } int BrowserView::GetSidebarWidth() const { if (!sidebar_container_ || !sidebar_container_->IsVisible()) return 0; return sidebar_split_->divider_offset(); } bool BrowserView::IsTabStripVisible() const { return browser_->SupportsWindowFeature(Browser::FEATURE_TABSTRIP); } bool BrowserView::UseVerticalTabs() const { return browser_->tabstrip_model()->delegate()->UseVerticalTabs(); } bool BrowserView::IsOffTheRecord() const { return browser_->profile()->IsOffTheRecord(); } bool BrowserView::ShouldShowOffTheRecordAvatar() const { return IsOffTheRecord() && IsBrowserTypeNormal(); } bool BrowserView::AcceleratorPressed(const views::Accelerator& accelerator) { std::map<views::Accelerator, int>::const_iterator iter = accelerator_table_.find(accelerator); DCHECK(iter != accelerator_table_.end()); int command_id = iter->second; if (browser_->command_updater()->SupportsCommand(command_id) && browser_->command_updater()->IsCommandEnabled(command_id)) { browser_->ExecuteCommand(command_id); return true; } return false; } bool BrowserView::GetAccelerator(int cmd_id, menus::Accelerator* accelerator) { // The standard Ctrl-X, Ctrl-V and Ctrl-C are not defined as accelerators // anywhere so we need to check for them explicitly here. switch (cmd_id) { case IDC_CUT: *accelerator = views::Accelerator(base::VKEY_X, false, true, false); return true; case IDC_COPY: *accelerator = views::Accelerator(base::VKEY_C, false, true, false); return true; case IDC_PASTE: *accelerator = views::Accelerator(base::VKEY_V, false, true, false); return true; } // Else, we retrieve the accelerator information from the accelerator table. std::map<views::Accelerator, int>::iterator it = accelerator_table_.begin(); for (; it != accelerator_table_.end(); ++it) { if (it->second == cmd_id) { *accelerator = it->first; return true; } } return false; } bool BrowserView::ActivateAppModalDialog() const { // If another browser is app modal, flash and activate the modal browser. if (Singleton<AppModalDialogQueue>()->HasActiveDialog()) { Browser* active_browser = BrowserList::GetLastActive(); if (active_browser && (browser_ != active_browser)) { active_browser->window()->FlashFrame(); active_browser->window()->Activate(); } Singleton<AppModalDialogQueue>()->ActivateModalDialog(); return true; } return false; } void BrowserView::ActivationChanged(bool activated) { if (activated) BrowserList::SetLastActive(browser_.get()); } TabContents* BrowserView::GetSelectedTabContents() const { return browser_->GetSelectedTabContents(); } SkBitmap BrowserView::GetOTRAvatarIcon() { static SkBitmap* otr_avatar_ = new SkBitmap(); if (otr_avatar_->isNull()) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); *otr_avatar_ = *rb.GetBitmapNamed(IDR_OTR_ICON); } return *otr_avatar_; } #if defined(OS_WIN) void BrowserView::PrepareToRunSystemMenu(HMENU menu) { system_menu_->UpdateStates(); } #endif // static void BrowserView::RegisterBrowserViewPrefs(PrefService* prefs) { prefs->RegisterIntegerPref(prefs::kPluginMessageResponseTimeout, kDefaultPluginMessageResponseTimeout); prefs->RegisterIntegerPref(prefs::kHungPluginDetectFrequency, kDefaultHungPluginDetectFrequency); } bool BrowserView::IsPositionInWindowCaption(const gfx::Point& point) { return GetBrowserViewLayout()->IsPositionInWindowCaption(point); } /////////////////////////////////////////////////////////////////////////////// // BrowserView, BrowserWindow implementation: void BrowserView::Show() { // If the window is already visible, just activate it. if (frame_->GetWindow()->IsVisible()) { frame_->GetWindow()->Activate(); return; } // Setting the focus doesn't work when the window is invisible, so any focus // initialization that happened before this will be lost. // // We really "should" restore the focus whenever the window becomes unhidden, // but I think initializing is the only time where this can happen where // there is some focus change we need to pick up, and this is easier than // plumbing through an un-hide message all the way from the frame. // // If we do find there are cases where we need to restore the focus on show, // that should be added and this should be removed. RestoreFocus(); frame_->GetWindow()->Show(); } void BrowserView::SetBounds(const gfx::Rect& bounds) { GetWidget()->SetBounds(bounds); } void BrowserView::Close() { BrowserBubbleHost::Close(); frame_->GetWindow()->Close(); } void BrowserView::Activate() { frame_->GetWindow()->Activate(); } void BrowserView::Deactivate() { frame_->GetWindow()->Deactivate(); } bool BrowserView::IsActive() const { return frame_->GetWindow()->IsActive(); } void BrowserView::FlashFrame() { #if defined(OS_WIN) FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = frame_->GetWindow()->GetNativeWindow(); fwi.dwFlags = FLASHW_ALL; fwi.uCount = 4; fwi.dwTimeout = 0; FlashWindowEx(&fwi); #else // Doesn't matter for chrome os. #endif } gfx::NativeWindow BrowserView::GetNativeHandle() { return GetWidget()->GetWindow()->GetNativeWindow(); } BrowserWindowTesting* BrowserView::GetBrowserWindowTesting() { return this; } StatusBubble* BrowserView::GetStatusBubble() { return status_bubble_.get(); } void BrowserView::SelectedTabToolbarSizeChanged(bool is_animating) { if (is_animating) { contents_container_->SetFastResize(true); UpdateUIForContents(browser_->GetSelectedTabContents()); contents_container_->SetFastResize(false); } else { UpdateUIForContents(browser_->GetSelectedTabContents()); contents_split_->Layout(); } } void BrowserView::UpdateTitleBar() { frame_->GetWindow()->UpdateWindowTitle(); if (ShouldShowWindowIcon() && !loading_animation_timer_.IsRunning()) frame_->GetWindow()->UpdateWindowIcon(); } void BrowserView::ShelfVisibilityChanged() { Layout(); } void BrowserView::UpdateDevTools() { UpdateDevToolsForContents(GetSelectedTabContents()); Layout(); } void BrowserView::UpdateLoadingAnimations(bool should_animate) { if (should_animate) { if (!loading_animation_timer_.IsRunning()) { // Loads are happening, and the timer isn't running, so start it. loading_animation_timer_.Start( TimeDelta::FromMilliseconds(kLoadingAnimationFrameTimeMs), this, &BrowserView::LoadingAnimationCallback); } } else { if (loading_animation_timer_.IsRunning()) { loading_animation_timer_.Stop(); // Loads are now complete, update the state if a task was scheduled. LoadingAnimationCallback(); } } } void BrowserView::SetStarredState(bool is_starred) { toolbar_->location_bar()->SetStarToggled(is_starred); } gfx::Rect BrowserView::GetRestoredBounds() const { return frame_->GetWindow()->GetNormalBounds(); } bool BrowserView::IsMaximized() const { return frame_->GetWindow()->IsMaximized(); } void BrowserView::SetFullscreen(bool fullscreen) { if (IsFullscreen() == fullscreen) return; // Nothing to do. #if defined(OS_WIN) ProcessFullscreen(fullscreen); #else // On Linux changing fullscreen is async. Ask the window to change it's // fullscreen state, and when done invoke ProcessFullscreen. frame_->GetWindow()->SetFullscreen(fullscreen); #endif } bool BrowserView::IsFullscreen() const { return frame_->GetWindow()->IsFullscreen(); } bool BrowserView::IsFullscreenBubbleVisible() const { return fullscreen_bubble_.get() ? true : false; } void BrowserView::FullScreenStateChanged() { ProcessFullscreen(IsFullscreen()); } void BrowserView::RestoreFocus() { TabContents* selected_tab_contents = GetSelectedTabContents(); if (selected_tab_contents) selected_tab_contents->view()->RestoreFocus(); } LocationBar* BrowserView::GetLocationBar() const { return toolbar_->location_bar(); } void BrowserView::SetFocusToLocationBar(bool select_all) { LocationBarView* location_bar = toolbar_->location_bar(); if (location_bar->IsFocusableInRootView()) { // Location bar got focus. location_bar->FocusLocation(select_all); } else { // If none of location bar/compact navigation bar got focus, // then clear focus. views::FocusManager* focus_manager = GetFocusManager(); DCHECK(focus_manager); focus_manager->ClearFocus(); } } void BrowserView::UpdateReloadStopState(bool is_loading, bool force) { toolbar_->reload_button()->ChangeMode( is_loading ? ReloadButton::MODE_STOP : ReloadButton::MODE_RELOAD, force); } void BrowserView::UpdateToolbar(TabContents* contents, bool should_restore_state) { toolbar_->Update(contents, should_restore_state); } void BrowserView::FocusToolbar() { // Start the traversal within the main toolbar, passing it the storage id // of the view where focus should be returned if the user exits the toolbar. SaveFocusedView(); toolbar_->SetToolbarFocus(last_focused_view_storage_id_, NULL); } void BrowserView::FocusBookmarksToolbar() { if (active_bookmark_bar_ && bookmark_bar_view_->IsVisible()) { SaveFocusedView(); bookmark_bar_view_->SetToolbarFocus(last_focused_view_storage_id_, NULL); } } void BrowserView::FocusAppMenu() { // Chrome doesn't have a traditional menu bar, but it has a menu button in the // main toolbar that plays the same role. If the user presses a key that // would typically focus the menu bar, tell the toolbar to focus the menu // button. Pass it the storage id of the view where focus should be returned // if the user presses escape. // // Not used on the Mac, which has a normal menu bar. SaveFocusedView(); toolbar_->SetToolbarFocusAndFocusAppMenu(last_focused_view_storage_id_); } void BrowserView::RotatePaneFocus(bool forwards) { // This gets called when the user presses F6 (forwards) or Shift+F6 // (backwards) to rotate to the next pane. Here, our "panes" are the // tab contents and each of our accessible toolbars. When a toolbar has // pane focus, all of its controls are accessible in the tab traversal, // and the tab traversal is "trapped" within that pane. // Get a vector of all panes in the order we want them to be focused - // each of the accessible toolbars, then NULL to represent the tab contents // getting focus. If one of these is currently invisible or has no // focusable children it will be automatically skipped. std::vector<AccessibleToolbarView*> accessible_toolbars; GetAccessibleToolbars(&accessible_toolbars); int toolbars_count = static_cast<int>(accessible_toolbars.size()); std::vector<views::View*> accessible_views( accessible_toolbars.begin(), accessible_toolbars.end()); accessible_views.push_back(GetTabContentsContainerView()); if (sidebar_container_ && sidebar_container_->IsVisible()) accessible_views.push_back(GetSidebarContainerView()); if (devtools_container_->IsVisible()) accessible_views.push_back(devtools_container_->GetFocusView()); int count = static_cast<int>(accessible_views.size()); // Figure out which view (if any) currently has the focus. views::View* focused_view = GetRootView()->GetFocusedView(); int index = -1; if (focused_view) { for (int i = 0; i < count; ++i) { if (accessible_views[i] == focused_view || accessible_views[i]->IsParentOf(focused_view)) { index = i; break; } } } // If the focus isn't currently in a toolbar, save the focus so we // can restore it if the user presses Escape. if (focused_view && index >= toolbars_count) SaveFocusedView(); // Try to focus the next pane; if SetToolbarFocusAndFocusDefault returns // false it means the toolbar didn't have any focusable controls, so skip // it and try the next one. for (;;) { if (forwards) index = (index + 1) % count; else index = ((index - 1) + count) % count; if (index < toolbars_count) { if (accessible_toolbars[index]->SetToolbarFocusAndFocusDefault( last_focused_view_storage_id_)) { break; } } else { accessible_views[index]->RequestFocus(); break; } } } void BrowserView::SaveFocusedView() { views::ViewStorage* view_storage = views::ViewStorage::GetSharedInstance(); if (view_storage->RetrieveView(last_focused_view_storage_id_)) view_storage->RemoveView(last_focused_view_storage_id_); views::View* focused_view = GetRootView()->GetFocusedView(); if (focused_view) view_storage->StoreView(last_focused_view_storage_id_, focused_view); } void BrowserView::DestroyBrowser() { // Explicitly delete the BookmarkBarView now. That way we don't have to // worry about the BookmarkBarView potentially outliving the Browser & // Profile. bookmark_bar_view_.reset(); browser_.reset(); } bool BrowserView::IsBookmarkBarVisible() const { return browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR) && active_bookmark_bar_ && (active_bookmark_bar_->GetPreferredSize().height() != 0); } bool BrowserView::IsBookmarkBarAnimating() const { return bookmark_bar_view_.get() && bookmark_bar_view_->is_animating(); } bool BrowserView::IsToolbarVisible() const { return browser_->SupportsWindowFeature(Browser::FEATURE_TOOLBAR) || browser_->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR); } gfx::Rect BrowserView::GetRootWindowResizerRect() const { if (frame_->GetWindow()->IsMaximized() || frame_->GetWindow()->IsFullscreen()) return gfx::Rect(); // We don't specify a resize corner size if we have a bottom shelf either. // This is because we take care of drawing the resize corner on top of that // shelf, so we don't want others to do it for us in this case. // Currently, the only visible bottom shelf is the download shelf. // Other tests should be added here if we add more bottom shelves. if (download_shelf_.get() && download_shelf_->IsShowing()) { return gfx::Rect(); } gfx::Rect client_rect = contents_split_->bounds(); gfx::Size resize_corner_size = ResizeCorner::GetSize(); int x = client_rect.width() - resize_corner_size.width(); if (base::i18n::IsRTL()) x = 0; return gfx::Rect(x, client_rect.height() - resize_corner_size.height(), resize_corner_size.width(), resize_corner_size.height()); } void BrowserView::DisableInactiveFrame() { #if defined(OS_WIN) frame_->GetWindow()->DisableInactiveRendering(); #endif // No tricks are needed to get the right behavior on Linux. } void BrowserView::ConfirmAddSearchProvider(const TemplateURL* template_url, Profile* profile) { browser::EditSearchEngine(GetWindow()->GetNativeWindow(), template_url, NULL, profile); } void BrowserView::ToggleBookmarkBar() { bookmark_utils::ToggleWhenVisible(browser_->profile()); } views::Window* BrowserView::ShowAboutChromeDialog() { return browser::ShowAboutChromeView(GetWindow()->GetNativeWindow(), browser_->profile()); } void BrowserView::ShowUpdateChromeDialog() { #if defined(OS_WIN) UpdateRecommendedMessageBox::ShowMessageBox(GetWindow()->GetNativeWindow()); #endif } void BrowserView::ShowTaskManager() { browser::ShowTaskManager(); } void BrowserView::ShowBookmarkBubble(const GURL& url, bool already_bookmarked) { toolbar_->location_bar()->ShowStarBubble(url, !already_bookmarked); } void BrowserView::SetDownloadShelfVisible(bool visible) { // This can be called from the superclass destructor, when it destroys our // child views. At that point, browser_ is already gone. if (browser_ == NULL) return; if (visible && IsDownloadShelfVisible() != visible) { // Invoke GetDownloadShelf to force the shelf to be created. GetDownloadShelf(); } if (browser_ != NULL) browser_->UpdateDownloadShelfVisibility(visible); // SetDownloadShelfVisible can force-close the shelf, so make sure we lay out // everything correctly, as if the animation had finished. This doesn't // matter for showing the shelf, as the show animation will do it. SelectedTabToolbarSizeChanged(false); } bool BrowserView::IsDownloadShelfVisible() const { return download_shelf_.get() && download_shelf_->IsShowing(); } DownloadShelf* BrowserView::GetDownloadShelf() { if (!download_shelf_.get()) { download_shelf_.reset(new DownloadShelfView(browser_.get(), this)); download_shelf_->set_parent_owned(false); } return download_shelf_.get(); } void BrowserView::ShowReportBugDialog() { browser::ShowHtmlBugReportView(GetWindow(), browser_.get()); } void BrowserView::ShowClearBrowsingDataDialog() { browser::ShowClearBrowsingDataView(GetWindow()->GetNativeWindow(), browser_->profile()); } void BrowserView::ShowImportDialog() { browser::ShowImporterView(GetWidget(), browser_->profile()); } void BrowserView::ShowSearchEnginesDialog() { browser::ShowKeywordEditorView(browser_->profile()); } void BrowserView::ShowPasswordManager() { browser::ShowPasswordsExceptionsWindowView(browser_->profile()); } void BrowserView::ShowRepostFormWarningDialog(TabContents* tab_contents) { browser::ShowRepostFormWarningDialog(GetNativeHandle(), tab_contents); } void BrowserView::ShowContentSettingsWindow(ContentSettingsType content_type, Profile* profile) { browser::ShowContentSettingsWindow(GetNativeHandle(), content_type, profile); } void BrowserView::ShowCollectedCookiesDialog(TabContents* tab_contents) { browser::ShowCollectedCookiesDialog(GetNativeHandle(), tab_contents); } void BrowserView::ShowProfileErrorDialog(int message_id) { #if defined(OS_WIN) std::wstring title = l10n_util::GetString(IDS_PRODUCT_NAME); std::wstring message = l10n_util::GetString(message_id); win_util::MessageBox(GetNativeHandle(), message, title, MB_OK | MB_ICONWARNING | MB_TOPMOST); #elif defined(OS_LINUX) std::string title = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME); std::string message = l10n_util::GetStringUTF8(message_id); GtkWidget* dialog = gtk_message_dialog_new(GetNativeHandle(), static_cast<GtkDialogFlags>(0), GTK_MESSAGE_WARNING, GTK_BUTTONS_OK, "%s", message.c_str()); gtk_window_set_title(GTK_WINDOW(dialog), title.c_str()); g_signal_connect(dialog, "response", G_CALLBACK(gtk_widget_destroy), NULL); gtk_widget_show_all(dialog); #else NOTIMPLEMENTED(); #endif } void BrowserView::ShowThemeInstallBubble() { TabContents* tab_contents = browser_->GetSelectedTabContents(); if (!tab_contents) return; ThemeInstallBubbleView::Show(tab_contents); } void BrowserView::ConfirmBrowserCloseWithPendingDownloads() { DownloadInProgressConfirmDialogDelegate* delegate = new DownloadInProgressConfirmDialogDelegate(browser_.get()); views::Window::CreateChromeWindow(GetNativeHandle(), gfx::Rect(), delegate)->Show(); } void BrowserView::ShowHTMLDialog(HtmlDialogUIDelegate* delegate, gfx::NativeWindow parent_window) { // Default to using our window as the parent if the argument is not specified. gfx::NativeWindow parent = parent_window ? parent_window : GetNativeHandle(); #if defined(OS_CHROMEOS) parent = GetNormalBrowserWindowForBrowser(browser(), NULL); #endif // defined(OS_CHROMEOS) browser::ShowHtmlDialogView(parent, browser_.get()->profile(), delegate); } void BrowserView::ShowCreateShortcutsDialog(TabContents* tab_contents) { browser::ShowCreateShortcutsDialog(GetNativeHandle(), tab_contents); } void BrowserView::ContinueDraggingDetachedTab(const gfx::Rect& tab_bounds) { tabstrip_->SetDraggedTabBounds(0, tab_bounds); frame_->ContinueDraggingDetachedTab(); } void BrowserView::UserChangedTheme() { frame_->GetWindow()->FrameTypeChanged(); } int BrowserView::GetExtraRenderViewHeight() const { // Currently this is only used on linux. return 0; } void BrowserView::TabContentsFocused(TabContents* tab_contents) { contents_container_->TabContentsFocused(tab_contents); } void BrowserView::ShowPageInfo(Profile* profile, const GURL& url, const NavigationEntry::SSLStatus& ssl, bool show_history) { gfx::NativeWindow parent = GetWindow()->GetNativeWindow(); #if defined(OS_CHROMEOS) parent = GetNormalBrowserWindowForBrowser(browser(), profile); #endif // defined(OS_CHROMEOS) #if defined(OS_WINDOWS) browser::ShowPageInfoBubble(parent, profile, url, ssl, show_history); #else browser::ShowPageInfo(parent, profile, url, ssl, show_history); #endif } void BrowserView::ShowAppMenu() { toolbar_->app_menu()->Activate(); } bool BrowserView::PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) { if (event.type != WebKit::WebInputEvent::RawKeyDown) return false; #if defined(OS_WIN) // As Alt+F4 is the close-app keyboard shortcut, it needs processing // immediately. if (event.windowsKeyCode == base::VKEY_F4 && event.modifiers == NativeWebKeyboardEvent::AltKey) { DefWindowProc(event.os_event.hwnd, event.os_event.message, event.os_event.wParam, event.os_event.lParam); return true; } #endif views::FocusManager* focus_manager = GetFocusManager(); DCHECK(focus_manager); views::Accelerator accelerator( static_cast<base::KeyboardCode>(event.windowsKeyCode), (event.modifiers & NativeWebKeyboardEvent::ShiftKey) == NativeWebKeyboardEvent::ShiftKey, (event.modifiers & NativeWebKeyboardEvent::ControlKey) == NativeWebKeyboardEvent::ControlKey, (event.modifiers & NativeWebKeyboardEvent::AltKey) == NativeWebKeyboardEvent::AltKey); // We first find out the browser command associated to the |event|. // Then if the command is a reserved one, and should be processed // immediately according to the |event|, the command will be executed // immediately. Otherwise we just set |*is_keyboard_shortcut| properly and // return false. // This piece of code is based on the fact that accelerators registered // into the |focus_manager| may only trigger a browser command execution. // // Here we need to retrieve the command id (if any) associated to the // keyboard event. Instead of looking up the command id in the // |accelerator_table_| by ourselves, we block the command execution of // the |browser_| object then send the keyboard event to the // |focus_manager| as if we are activating an accelerator key. // Then we can retrieve the command id from the |browser_| object. browser_->SetBlockCommandExecution(true); focus_manager->ProcessAccelerator(accelerator); int id = browser_->GetLastBlockedCommand(NULL); browser_->SetBlockCommandExecution(false); if (id == -1) return false; if (browser_->IsReservedCommand(id)) { // TODO(suzhe): For Linux, should we send things like Ctrl+w, Ctrl+n // to the renderer first, just like what // BrowserWindowGtk::HandleKeyboardEvent() does? // Executing the command may cause |this| object to be destroyed. browser_->ExecuteCommand(id); return true; } DCHECK(is_keyboard_shortcut != NULL); *is_keyboard_shortcut = true; return false; } void BrowserView::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) { #if defined(OS_LINUX) views::Window* window = GetWidget()->GetWindow(); if (window && event.os_event && !event.skip_in_browser) static_cast<views::WindowGtk*>(window)->HandleKeyboardEvent(event.os_event); #else unhandled_keyboard_event_handler_.HandleKeyboardEvent(event, GetFocusManager()); #endif } // TODO(devint): http://b/issue?id=1117225 Cut, Copy, and Paste are always // enabled in the page menu regardless of whether the command will do // anything. When someone selects the menu item, we just act as if they hit // the keyboard shortcut for the command by sending the associated key press // to windows. The real fix to this bug is to disable the commands when they // won't do anything. We'll need something like an overall clipboard command // manager to do that. #if !defined(OS_MACOSX) void BrowserView::Cut() { ui_controls::SendKeyPress(GetNativeHandle(), base::VKEY_X, true, false, false, false); } void BrowserView::Copy() { ui_controls::SendKeyPress(GetNativeHandle(), base::VKEY_C, true, false, false, false); } void BrowserView::Paste() { ui_controls::SendKeyPress(GetNativeHandle(), base::VKEY_V, true, false, false, false); } #else // Mac versions. Not tested by antyhing yet; // don't assume written == works. void BrowserView::Cut() { ui_controls::SendKeyPress(GetNativeHandle(), base::VKEY_X, false, false, false, true); } void BrowserView::Copy() { ui_controls::SendKeyPress(GetNativeHandle(), base::VKEY_C, false, false, false, true); } void BrowserView::Paste() { ui_controls::SendKeyPress(GetNativeHandle(), base::VKEY_V, false, false, false, true); } #endif void BrowserView::ToggleTabStripMode() { InitTabStrip(browser_->tabstrip_model()); frame_->TabStripDisplayModeChanged(); } /////////////////////////////////////////////////////////////////////////////// // BrowserView, BrowserWindowTesting implementation: BookmarkBarView* BrowserView::GetBookmarkBarView() const { return bookmark_bar_view_.get(); } LocationBarView* BrowserView::GetLocationBarView() const { return toolbar_->location_bar(); } views::View* BrowserView::GetTabContentsContainerView() const { return contents_container_->GetFocusView(); } views::View* BrowserView::GetSidebarContainerView() const { if (!sidebar_container_) return NULL; return sidebar_container_->GetFocusView(); } ToolbarView* BrowserView::GetToolbarView() const { return toolbar_; } /////////////////////////////////////////////////////////////////////////////// // BrowserView, NotificationObserver implementation: void BrowserView::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::PREF_CHANGED: if (*Details<std::string>(details).ptr() == prefs::kShowBookmarkBar && MaybeShowBookmarkBar(browser_->GetSelectedTabContents())) { Layout(); } break; case NotificationType::MATCH_PREVIEW_TAB_CONTENTS_CREATED: if (Source<TabContents>(source).ptr() == browser_->GetSelectedTabContents()) { ShowMatchPreview(); } break; case NotificationType::TAB_CONTENTS_DESTROYED: { if (MatchPreview::IsEnabled()) { TabContents* selected_contents = browser_->GetSelectedTabContents(); if (selected_contents && selected_contents->match_preview()->preview_contents() == Source<TabContents>(source).ptr()) { HideMatchPreview(); } } break; } case NotificationType::SIDEBAR_CHANGED: if (Details<SidebarContainer>(details)->tab_contents() == browser_->GetSelectedTabContents()) { UpdateSidebar(); } break; default: NOTREACHED() << "Got a notification we didn't register for!"; break; } } /////////////////////////////////////////////////////////////////////////////// // BrowserView, TabStripModelObserver implementation: void BrowserView::TabDetachedAt(TabContents* contents, int index) { // We use index here rather than comparing |contents| because by this time // the model has already removed |contents| from its list, so // browser_->GetSelectedTabContents() will return NULL or something else. if (index == browser_->tabstrip_model()->selected_index()) { // We need to reset the current tab contents to NULL before it gets // freed. This is because the focus manager performs some operations // on the selected TabContents when it is removed. contents_container_->ChangeTabContents(NULL); infobar_container_->ChangeTabContents(NULL); UpdateSidebarForContents(NULL); UpdateDevToolsForContents(NULL); } } void BrowserView::TabDeselectedAt(TabContents* contents, int index) { // We do not store the focus when closing the tab to work-around bug 4633. // Some reports seem to show that the focus manager and/or focused view can // be garbage at that point, it is not clear why. if (!contents->is_being_destroyed()) contents->view()->StoreFocus(); } void BrowserView::TabSelectedAt(TabContents* old_contents, TabContents* new_contents, int index, bool user_gesture) { DCHECK(old_contents != new_contents); ProcessTabSelected(new_contents, true); } void BrowserView::TabReplacedAt(TabContents* old_contents, TabContents* new_contents, int index, TabStripModelObserver::TabReplaceType type) { if (type != TabStripModelObserver::REPLACE_MATCH_PREVIEW || index != browser_->tabstrip_model()->selected_index()) { return; } // Swap the 'active' and 'preview' and delete what was the active. contents_->MakePreviewContentsActiveContents(); TabContentsContainer* old_container = contents_container_; contents_container_ = preview_container_; old_container->ChangeTabContents(NULL); delete old_container; preview_container_ = NULL; // Update the UI for what was the preview contents and is now active. Pass in // false to ProcessTabSelected as new_contents is already parented correctly. ProcessTabSelected(new_contents, false); } void BrowserView::TabStripEmpty() { // Make sure all optional UI is removed before we are destroyed, otherwise // there will be consequences (since our view hierarchy will still have // references to freed views). UpdateUIForContents(NULL); } /////////////////////////////////////////////////////////////////////////////// // BrowserView, menus::SimpleMenuModel::Delegate implementation: bool BrowserView::IsCommandIdChecked(int command_id) const { // TODO(beng): encoding menu. // No items in our system menu are check-able. return false; } bool BrowserView::IsCommandIdEnabled(int command_id) const { return browser_->command_updater()->IsCommandEnabled(command_id); } bool BrowserView::GetAcceleratorForCommandId(int command_id, menus::Accelerator* accelerator) { // Let's let the ToolbarView own the canonical implementation of this method. return toolbar_->GetAcceleratorForCommandId(command_id, accelerator); } bool BrowserView::IsLabelForCommandIdDynamic(int command_id) const { return command_id == IDC_RESTORE_TAB; } string16 BrowserView::GetLabelForCommandId(int command_id) const { DCHECK(command_id == IDC_RESTORE_TAB); int string_id = IDS_RESTORE_TAB; if (IsCommandIdEnabled(command_id)) { TabRestoreService* trs = browser_->profile()->GetTabRestoreService(); if (trs && trs->entries().front()->type == TabRestoreService::WINDOW) string_id = IDS_RESTORE_WINDOW; } return l10n_util::GetStringUTF16(string_id); } void BrowserView::ExecuteCommand(int command_id) { browser_->ExecuteCommand(command_id); } /////////////////////////////////////////////////////////////////////////////// // BrowserView, views::WindowDelegate implementation: bool BrowserView::CanResize() const { return true; } bool BrowserView::CanMaximize() const { return true; } bool BrowserView::IsModal() const { return false; } std::wstring BrowserView::GetWindowTitle() const { return UTF16ToWideHack(browser_->GetWindowTitleForCurrentTab()); } views::View* BrowserView::GetInitiallyFocusedView() { // We set the frame not focus on creation so this should never be called. NOTREACHED(); return NULL; } bool BrowserView::ShouldShowWindowTitle() const { return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR); } SkBitmap BrowserView::GetWindowAppIcon() { if (browser_->type() & Browser::TYPE_APP) { TabContents* contents = browser_->GetSelectedTabContents(); if (contents && !contents->app_icon().isNull()) return contents->app_icon(); } return GetWindowIcon(); } SkBitmap BrowserView::GetWindowIcon() { if (browser_->type() & Browser::TYPE_APP) return browser_->GetCurrentPageIcon(); return SkBitmap(); } bool BrowserView::ShouldShowWindowIcon() const { return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR); } bool BrowserView::ExecuteWindowsCommand(int command_id) { // This function handles WM_SYSCOMMAND, WM_APPCOMMAND, and WM_COMMAND. // Translate WM_APPCOMMAND command ids into a command id that the browser // knows how to handle. int command_id_from_app_command = GetCommandIDForAppCommandID(command_id); if (command_id_from_app_command != -1) command_id = command_id_from_app_command; if (browser_->command_updater()->SupportsCommand(command_id)) { if (browser_->command_updater()->IsCommandEnabled(command_id)) browser_->ExecuteCommand(command_id); return true; } return false; } std::wstring BrowserView::GetWindowName() const { return UTF8ToWide(browser_->GetWindowPlacementKey()); } void BrowserView::SaveWindowPlacement(const gfx::Rect& bounds, bool maximized) { // If IsFullscreen() is true, we've just changed into fullscreen mode, and // we're catching the going-into-fullscreen sizing and positioning calls, // which we want to ignore. if (!IsFullscreen() && browser_->ShouldSaveWindowPlacement()) { WindowDelegate::SaveWindowPlacement(bounds, maximized); browser_->SaveWindowPlacement(bounds, maximized); } } bool BrowserView::GetSavedWindowBounds(gfx::Rect* bounds) const { *bounds = browser_->GetSavedWindowBounds(); if (browser_->type() & Browser::TYPE_POPUP) { // We are a popup window. The value passed in |bounds| represents two // pieces of information: // - the position of the window, in screen coordinates (outer position). // - the size of the content area (inner size). // We need to use these values to determine the appropriate size and // position of the resulting window. if (IsToolbarVisible()) { // If we're showing the toolbar, we need to adjust |*bounds| to include // its desired height, since the toolbar is considered part of the // window's client area as far as GetWindowBoundsForClientBounds is // concerned... bounds->set_height( bounds->height() + toolbar_->GetPreferredSize().height()); } gfx::Rect window_rect = frame_->GetWindow()->GetNonClientView()-> GetWindowBoundsForClientBounds(*bounds); window_rect.set_origin(bounds->origin()); // When we are given x/y coordinates of 0 on a created popup window, // assume none were given by the window.open() command. if (window_rect.x() == 0 && window_rect.y() == 0) { gfx::Size size = window_rect.size(); window_rect.set_origin(WindowSizer::GetDefaultPopupOrigin(size)); } *bounds = window_rect; } // We return true because we can _always_ locate reasonable bounds using the // WindowSizer, and we don't want to trigger the Window's built-in "size to // default" handling because the browser window has no default preferred // size. return true; } bool BrowserView::GetSavedMaximizedState(bool* maximized) const { *maximized = browser_->GetSavedMaximizedState(); return true; } views::View* BrowserView::GetContentsView() { return contents_container_; } views::ClientView* BrowserView::CreateClientView(views::Window* window) { set_window(window); return this; } /////////////////////////////////////////////////////////////////////////////// // BrowserView, views::ClientView overrides: bool BrowserView::CanClose() const { // You cannot close a frame for which there is an active originating drag // session. if (tabstrip_->IsDragSessionActive()) return false; // Give beforeunload handlers the chance to cancel the close before we hide // the window below. if (!browser_->ShouldCloseWindow()) return false; if (browser_->tabstrip_model()->HasNonPhantomTabs()) { // Tab strip isn't empty. Hide the frame (so it appears to have closed // immediately) and close all the tabs, allowing the renderers to shut // down. When the tab strip is empty we'll be called back again. frame_->GetWindow()->HideWindow(); browser_->OnWindowClosing(); return false; } // Empty TabStripModel, it's now safe to allow the Window to be closed. NotificationService::current()->Notify( NotificationType::WINDOW_CLOSED, Source<gfx::NativeWindow>(frame_->GetWindow()->GetNativeWindow()), NotificationService::NoDetails()); return true; } int BrowserView::NonClientHitTest(const gfx::Point& point) { #if defined(OS_WIN) // The following code is not in the LayoutManager because it's // independent of layout and also depends on the ResizeCorner which // is private. if (!frame_->GetWindow()->IsMaximized() && !frame_->GetWindow()->IsFullscreen()) { CRect client_rect; ::GetClientRect(frame_->GetWindow()->GetNativeWindow(), &client_rect); gfx::Size resize_corner_size = ResizeCorner::GetSize(); gfx::Rect resize_corner_rect(client_rect.right - resize_corner_size.width(), client_rect.bottom - resize_corner_size.height(), resize_corner_size.width(), resize_corner_size.height()); bool rtl_dir = base::i18n::IsRTL(); if (rtl_dir) resize_corner_rect.set_x(0); if (resize_corner_rect.Contains(point)) { if (rtl_dir) return HTBOTTOMLEFT; return HTBOTTOMRIGHT; } } #endif return GetBrowserViewLayout()->NonClientHitTest(point); } gfx::Size BrowserView::GetMinimumSize() { return GetBrowserViewLayout()->GetMinimumSize(); } /////////////////////////////////////////////////////////////////////////////// // BrowserView, protected void BrowserView::GetAccessibleToolbars( std::vector<AccessibleToolbarView*>* toolbars) { // This should be in the order of pane traversal of the toolbars using F6. // If one of these is invisible or has no focusable children, it will be // automatically skipped. toolbars->push_back(toolbar_); toolbars->push_back(bookmark_bar_view_.get()); } /////////////////////////////////////////////////////////////////////////////// // BrowserView, views::View overrides: std::string BrowserView::GetClassName() const { return kViewClassName; } void BrowserView::Layout() { if (ignore_layout_) return; if (GetLayoutManager()) { GetLayoutManager()->Layout(this); SchedulePaint(); #if defined(OS_WIN) // Send the margins of the "user-perceived content area" of this // browser window so AeroPeekManager can render a background-tab image in // the area. // TODO(pkasting) correct content inset?? if (aeropeek_manager_.get()) { gfx::Insets insets(GetFindBarBoundingBox().y() + 1, 0, 0, 0); aeropeek_manager_->SetContentInsets(insets); } #endif } } void BrowserView::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { if (is_add && child == this && GetWidget() && !initialized_) { Init(); initialized_ = true; } } void BrowserView::ChildPreferredSizeChanged(View* child) { Layout(); } bool BrowserView::GetAccessibleRole(AccessibilityTypes::Role* role) { DCHECK(role); *role = AccessibilityTypes::ROLE_CLIENT; return true; } void BrowserView::InfoBarSizeChanged(bool is_animating) { SelectedTabToolbarSizeChanged(is_animating); } views::LayoutManager* BrowserView::CreateLayoutManager() const { return new BrowserViewLayout; } void BrowserView::InitTabStrip(TabStripModel* model) { // Throw away the existing tabstrip if we're switching display modes. if (tabstrip_) { tabstrip_->GetParent()->RemoveChildView(tabstrip_); delete tabstrip_; } BrowserTabStripController* tabstrip_controller = new BrowserTabStripController(browser_.get(), model); if (UseVerticalTabs()) tabstrip_ = new SideTabStrip(tabstrip_controller); else tabstrip_ = new TabStrip(tabstrip_controller); tabstrip_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_TABSTRIP)); AddChildView(tabstrip_); tabstrip_controller->InitFromModel(tabstrip_); } /////////////////////////////////////////////////////////////////////////////// // BrowserView, private: void BrowserView::Init() { accessible_view_helper_.reset(new AccessibleViewHelper( this, browser_->profile())); SetLayoutManager(CreateLayoutManager()); // Stow a pointer to this object onto the window handle so that we can get // at it later when all we have is a native view. #if defined(OS_WIN) SetProp(GetWidget()->GetNativeView(), kBrowserViewKey, this); #else g_object_set_data(G_OBJECT(GetWidget()->GetNativeView()), kBrowserViewKey, this); #endif // Start a hung plugin window detector for this browser object (as long as // hang detection is not disabled). if (!CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableHangMonitor)) { InitHangMonitor(); } LoadAccelerators(); SetAccessibleName(l10n_util::GetString(IDS_PRODUCT_NAME)); InitTabStrip(browser_->tabstrip_model()); toolbar_ = new ToolbarView(browser_.get()); AddChildView(toolbar_); toolbar_->Init(browser_->profile()); toolbar_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_TOOLBAR)); infobar_container_ = new InfoBarContainer(this); AddChildView(infobar_container_); contents_container_ = new TabContentsContainer; contents_ = new ContentsContainer(this, contents_container_); SkColor bg_color = GetWidget()->GetThemeProvider()-> GetColor(BrowserThemeProvider::COLOR_TOOLBAR); bool sidebar_allowed = SidebarManager::IsSidebarAllowed(); if (sidebar_allowed) { sidebar_container_ = new TabContentsContainer; sidebar_container_->SetID(VIEW_ID_SIDE_BAR_CONTAINER); sidebar_container_->SetVisible(false); sidebar_split_ = new views::SingleSplitView( contents_, sidebar_container_, views::SingleSplitView::HORIZONTAL_SPLIT); sidebar_split_->SetID(VIEW_ID_SIDE_BAR_SPLIT); sidebar_split_-> SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_SIDE_BAR)); sidebar_split_->set_background( views::Background::CreateSolidBackground(bg_color)); } devtools_container_ = new TabContentsContainer; devtools_container_->SetID(VIEW_ID_DEV_TOOLS_DOCKED); devtools_container_->SetVisible(false); views::View* contents_view = contents_; if (sidebar_allowed) contents_view = sidebar_split_; contents_split_ = new views::SingleSplitView( contents_view, devtools_container_, views::SingleSplitView::VERTICAL_SPLIT); contents_split_->SetID(VIEW_ID_CONTENTS_SPLIT); contents_split_-> SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_WEB_CONTENTS)); contents_split_->set_background( views::Background::CreateSolidBackground(bg_color)); AddChildView(contents_split_); set_contents_view(contents_split_); status_bubble_.reset(new StatusBubbleViews(GetWidget())); #if defined(OS_WIN) InitSystemMenu(); // Create a custom JumpList and add it to an observer of TabRestoreService // so we can update the custom JumpList when a tab is added or removed. if (JumpList::Enabled()) { jumplist_.reset(new JumpList); jumplist_->AddObserver(browser_->profile()); } if (AeroPeekManager::Enabled()) { aeropeek_manager_.reset(new AeroPeekManager( frame_->GetWindow()->GetNativeWindow())); browser_->tabstrip_model()->AddObserver(aeropeek_manager_.get()); } #endif // We're now initialized and ready to process Layout requests. ignore_layout_ = false; registrar_.Add(this, NotificationType::MATCH_PREVIEW_TAB_CONTENTS_CREATED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED, NotificationService::AllSources()); } #if defined(OS_WIN) void BrowserView::InitSystemMenu() { system_menu_contents_.reset(new views::SystemMenuModel(this)); // We add the menu items in reverse order so that insertion_index never needs // to change. if (IsBrowserTypeNormal()) BuildSystemMenuForBrowserWindow(); else BuildSystemMenuForAppOrPopupWindow(browser_->type() == Browser::TYPE_APP); system_menu_.reset( new views::NativeMenuWin(system_menu_contents_.get(), frame_->GetWindow()->GetNativeWindow())); system_menu_->Rebuild(); } #endif BrowserViewLayout* BrowserView::GetBrowserViewLayout() const { return static_cast<BrowserViewLayout*>(GetLayoutManager()); } void BrowserView::LayoutStatusBubble(int top) { // In restored mode, the client area has a client edge between it and the // frame. int overlap = StatusBubbleViews::kShadowThickness + (IsMaximized() ? 0 : views::NonClientFrameView::kClientEdgeThickness); int x = -overlap; if (UseVerticalTabs() && IsTabStripVisible()) x += tabstrip_->bounds().right(); int height = status_bubble_->GetPreferredSize().height(); gfx::Point origin(x, top - height + overlap); ConvertPointToView(this, GetParent(), &origin); status_bubble_->SetBounds(origin.x(), origin.y(), width() / 3, height); } bool BrowserView::MaybeShowBookmarkBar(TabContents* contents) { views::View* new_bookmark_bar_view = NULL; if (browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR) && contents) { if (!bookmark_bar_view_.get()) { bookmark_bar_view_.reset(new BookmarkBarView(contents->profile(), browser_.get())); bookmark_bar_view_->set_parent_owned(false); bookmark_bar_view_->set_background( new BookmarkExtensionBackground(this, bookmark_bar_view_.get(), browser_.get())); } else { bookmark_bar_view_->SetProfile(contents->profile()); } bookmark_bar_view_->SetPageNavigator(contents); bookmark_bar_view_-> SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_BOOKMARKS)); new_bookmark_bar_view = bookmark_bar_view_.get(); } return UpdateChildViewAndLayout(new_bookmark_bar_view, &active_bookmark_bar_); } bool BrowserView::MaybeShowInfoBar(TabContents* contents) { // TODO(beng): Remove this function once the interface between // InfoBarContainer, DownloadShelfView and TabContents and this // view is sorted out. return true; } void BrowserView::UpdateSidebar() { UpdateSidebarForContents(GetSelectedTabContents()); Layout(); } void BrowserView::UpdateSidebarForContents(TabContents* tab_contents) { if (!sidebar_container_) return; // Happens when sidebar is not allowed. if (!SidebarManager::GetInstance()) return; // Happens only in tests. TabContents* sidebar_contents = NULL; if (tab_contents) { SidebarContainer* client_host = SidebarManager::GetInstance()-> GetActiveSidebarContainerFor(tab_contents); if (client_host) sidebar_contents = client_host->sidebar_contents(); } bool visible = NULL != sidebar_contents && browser_->SupportsWindowFeature(Browser::FEATURE_SIDEBAR); bool should_show = visible && !sidebar_container_->IsVisible(); bool should_hide = !visible && sidebar_container_->IsVisible(); // Update sidebar content. TabContents* old_contents = sidebar_container_->tab_contents(); sidebar_container_->ChangeTabContents(sidebar_contents); SidebarManager::GetInstance()-> NotifyStateChanges(old_contents, sidebar_contents); // Update sidebar UI width. if (should_show) { // Restore split offset. int sidebar_width = g_browser_process->local_state()->GetInteger( prefs::kExtensionSidebarWidth); if (sidebar_width < 0) { // Initial load, set to default value. sidebar_width = sidebar_split_->width() / 7; } // Make sure user can see both panes. int min_sidebar_width = sidebar_split_->GetMinimumSize().width(); sidebar_width = std::min(sidebar_split_->width() - min_sidebar_width, std::max(min_sidebar_width, sidebar_width)); sidebar_split_->set_divider_offset( sidebar_split_->width() - sidebar_width); sidebar_container_->SetVisible(true); sidebar_split_->Layout(); } else if (should_hide) { // Store split offset when hiding sidebar only. g_browser_process->local_state()->SetInteger( prefs::kExtensionSidebarWidth, sidebar_split_->width() - sidebar_split_->divider_offset()); sidebar_container_->SetVisible(false); sidebar_split_->Layout(); } } void BrowserView::UpdateDevToolsForContents(TabContents* tab_contents) { TabContents* devtools_contents = DevToolsWindow::GetDevToolsContents(tab_contents); bool should_show = devtools_contents && !devtools_container_->IsVisible(); bool should_hide = !devtools_contents && devtools_container_->IsVisible(); devtools_container_->ChangeTabContents(devtools_contents); if (should_show) { if (!devtools_focus_tracker_.get()) { // Install devtools focus tracker when dev tools window is shown for the // first time. devtools_focus_tracker_.reset( new views::ExternalFocusTracker(devtools_container_, GetFocusManager())); } // Restore split offset. int split_offset = g_browser_process->local_state()->GetInteger( prefs::kDevToolsSplitLocation); if (split_offset == -1) { // Initial load, set to default value. split_offset = 2 * contents_split_->height() / 3; } // Make sure user can see both panes. int min_split_size = contents_split_->height() / 10; split_offset = std::min(contents_split_->height() - min_split_size, std::max(min_split_size, split_offset)); contents_split_->set_divider_offset(split_offset); devtools_container_->SetVisible(true); contents_split_->Layout(); } else if (should_hide) { // Store split offset when hiding devtools window only. g_browser_process->local_state()->SetInteger( prefs::kDevToolsSplitLocation, contents_split_->divider_offset()); // Restore focus to the last focused view when hiding devtools window. devtools_focus_tracker_->FocusLastFocusedExternalView(); devtools_container_->SetVisible(false); contents_split_->Layout(); } } void BrowserView::UpdateUIForContents(TabContents* contents) { bool needs_layout = MaybeShowBookmarkBar(contents); needs_layout |= MaybeShowInfoBar(contents); if (needs_layout) Layout(); } bool BrowserView::UpdateChildViewAndLayout(views::View* new_view, views::View** old_view) { DCHECK(old_view); if (*old_view == new_view) { // The views haven't changed, if the views pref changed schedule a layout. if (new_view) { if (new_view->GetPreferredSize().height() != new_view->height()) return true; } return false; } // The views differ, and one may be null (but not both). Remove the old // view (if it non-null), and add the new one (if it is non-null). If the // height has changed, schedule a layout, otherwise reuse the existing // bounds to avoid scheduling a layout. int current_height = 0; if (*old_view) { current_height = (*old_view)->height(); RemoveChildView(*old_view); } int new_height = 0; if (new_view) { new_height = new_view->GetPreferredSize().height(); AddChildView(new_view); } bool changed = false; if (new_height != current_height) { changed = true; } else if (new_view && *old_view) { // The view changed, but the new view wants the same size, give it the // bounds of the last view and have it repaint. new_view->SetBounds((*old_view)->bounds()); new_view->SchedulePaint(); } else if (new_view) { DCHECK_EQ(0, new_height); // The heights are the same, but the old view is null. This only happens // when the height is zero. Zero out the bounds. new_view->SetBounds(0, 0, 0, 0); } *old_view = new_view; return changed; } void BrowserView::ProcessFullscreen(bool fullscreen) { // Reduce jankiness during the following position changes by: // * Hiding the window until it's in the final position // * Ignoring all intervening Layout() calls, which resize the webpage and // thus are slow and look ugly ignore_layout_ = true; LocationBarView* location_bar = toolbar_->location_bar(); #if defined(OS_WIN) AutocompleteEditViewWin* edit_view = static_cast<AutocompleteEditViewWin*>(location_bar->location_entry()); #endif if (!fullscreen) { // Hide the fullscreen bubble as soon as possible, since the mode toggle can // take enough time for the user to notice. fullscreen_bubble_.reset(); } else { // Move focus out of the location bar if necessary. views::FocusManager* focus_manager = GetFocusManager(); DCHECK(focus_manager); if (focus_manager->GetFocusedView() == location_bar) focus_manager->ClearFocus(); #if defined(OS_WIN) // If we don't hide the edit and force it to not show until we come out of // fullscreen, then if the user was on the New Tab Page, the edit contents // will appear atop the web contents once we go into fullscreen mode. This // has something to do with how we move the main window while it's hidden; // if we don't hide the main window below, we don't get this problem. edit_view->set_force_hidden(true); ShowWindow(edit_view->m_hWnd, SW_HIDE); #endif } #if defined(OS_WIN) frame_->GetWindow()->PushForceHidden(); #endif // Notify bookmark bar, so it can set itself to the appropriate drawing state. if (bookmark_bar_view_.get()) bookmark_bar_view_->OnFullscreenToggled(fullscreen); // Toggle fullscreen mode. #if defined(OS_WIN) frame_->GetWindow()->SetFullscreen(fullscreen); #endif // No need to invoke SetFullscreen for linux as this code is executed // once we're already fullscreen on linux. #if defined(OS_LINUX) // Updating of commands for fullscreen mode is called from SetFullScreen on // Wndows (see just above), but for ChromeOS, this method (ProcessFullScreen) // is called after full screen has happened successfully (via GTK's // window-state-change event), so we have to update commands here. browser_->UpdateCommandsForFullscreenMode(fullscreen); #endif if (fullscreen) { bool is_kiosk = CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode); if (!is_kiosk) { fullscreen_bubble_.reset(new FullscreenExitBubble(GetWidget(), browser_.get())); } } else { #if defined(OS_WIN) // Show the edit again since we're no longer in fullscreen mode. edit_view->set_force_hidden(false); ShowWindow(edit_view->m_hWnd, SW_SHOW); #endif } // Undo our anti-jankiness hacks and force the window to relayout now that // it's in its final position. ignore_layout_ = false; Layout(); #if defined(OS_WIN) frame_->GetWindow()->PopForceHidden(); #endif } void BrowserView::LoadAccelerators() { #if defined(OS_WIN) HACCEL accelerator_table = AtlLoadAccelerators(IDR_MAINFRAME); DCHECK(accelerator_table); // We have to copy the table to access its contents. int count = CopyAcceleratorTable(accelerator_table, 0, 0); if (count == 0) { // Nothing to do in that case. return; } ACCEL* accelerators = static_cast<ACCEL*>(malloc(sizeof(ACCEL) * count)); CopyAcceleratorTable(accelerator_table, accelerators, count); views::FocusManager* focus_manager = GetFocusManager(); DCHECK(focus_manager); // Let's fill our own accelerator table. for (int i = 0; i < count; ++i) { bool alt_down = (accelerators[i].fVirt & FALT) == FALT; bool ctrl_down = (accelerators[i].fVirt & FCONTROL) == FCONTROL; bool shift_down = (accelerators[i].fVirt & FSHIFT) == FSHIFT; views::Accelerator accelerator( static_cast<base::KeyboardCode>(accelerators[i].key), shift_down, ctrl_down, alt_down); accelerator_table_[accelerator] = accelerators[i].cmd; // Also register with the focus manager. focus_manager->RegisterAccelerator(accelerator, this); } // We don't need the Windows accelerator table anymore. free(accelerators); #else views::FocusManager* focus_manager = GetFocusManager(); DCHECK(focus_manager); // Let's fill our own accelerator table. for (size_t i = 0; i < browser::kAcceleratorMapLength; ++i) { views::Accelerator accelerator(browser::kAcceleratorMap[i].keycode, browser::kAcceleratorMap[i].shift_pressed, browser::kAcceleratorMap[i].ctrl_pressed, browser::kAcceleratorMap[i].alt_pressed); accelerator_table_[accelerator] = browser::kAcceleratorMap[i].command_id; // Also register with the focus manager. focus_manager->RegisterAccelerator(accelerator, this); } #endif } #if defined(OS_WIN) void BrowserView::BuildSystemMenuForBrowserWindow() { system_menu_contents_->AddSeparator(); system_menu_contents_->AddItemWithStringId(IDC_TASK_MANAGER, IDS_TASK_MANAGER); system_menu_contents_->AddSeparator(); system_menu_contents_->AddItemWithStringId(IDC_RESTORE_TAB, IDS_RESTORE_TAB); system_menu_contents_->AddItemWithStringId(IDC_NEW_TAB, IDS_NEW_TAB); // If it's a regular browser window with tabs, we don't add any more items, // since it already has menus (Page, Chrome). } void BrowserView::BuildSystemMenuForAppOrPopupWindow(bool is_app) { if (is_app) { system_menu_contents_->AddSeparator(); system_menu_contents_->AddItemWithStringId(IDC_TASK_MANAGER, IDS_TASK_MANAGER); } system_menu_contents_->AddSeparator(); encoding_menu_contents_.reset(new EncodingMenuModel(browser_.get())); system_menu_contents_->AddSubMenuWithStringId(IDC_ENCODING_MENU, IDS_ENCODING_MENU, encoding_menu_contents_.get()); zoom_menu_contents_.reset(new ZoomMenuModel(this)); system_menu_contents_->AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_ZOOM_MENU, zoom_menu_contents_.get()); system_menu_contents_->AddItemWithStringId(IDC_PRINT, IDS_PRINT); system_menu_contents_->AddItemWithStringId(IDC_FIND, IDS_FIND); system_menu_contents_->AddSeparator(); system_menu_contents_->AddItemWithStringId(IDC_PASTE, IDS_PASTE); system_menu_contents_->AddItemWithStringId(IDC_COPY, IDS_COPY); system_menu_contents_->AddItemWithStringId(IDC_CUT, IDS_CUT); system_menu_contents_->AddSeparator(); if (is_app) { system_menu_contents_->AddItemWithStringId(IDC_NEW_TAB, IDS_APP_MENU_NEW_WEB_PAGE); } else { system_menu_contents_->AddItemWithStringId(IDC_SHOW_AS_TAB, IDS_SHOW_AS_TAB); } system_menu_contents_->AddItemWithStringId(IDC_COPY_URL, IDS_APP_MENU_COPY_URL); system_menu_contents_->AddSeparator(); system_menu_contents_->AddItemWithStringId(IDC_RELOAD, IDS_APP_MENU_RELOAD); system_menu_contents_->AddItemWithStringId(IDC_FORWARD, IDS_CONTENT_CONTEXT_FORWARD); system_menu_contents_->AddItemWithStringId(IDC_BACK, IDS_CONTENT_CONTEXT_BACK); } #endif int BrowserView::GetCommandIDForAppCommandID(int app_command_id) const { #if defined(OS_WIN) switch (app_command_id) { // NOTE: The order here matches the APPCOMMAND declaration order in the // Windows headers. case APPCOMMAND_BROWSER_BACKWARD: return IDC_BACK; case APPCOMMAND_BROWSER_FORWARD: return IDC_FORWARD; case APPCOMMAND_BROWSER_REFRESH: return IDC_RELOAD; case APPCOMMAND_BROWSER_HOME: return IDC_HOME; case APPCOMMAND_BROWSER_STOP: return IDC_STOP; case APPCOMMAND_BROWSER_SEARCH: return IDC_FOCUS_SEARCH; case APPCOMMAND_HELP: return IDC_HELP_PAGE; case APPCOMMAND_NEW: return IDC_NEW_TAB; case APPCOMMAND_OPEN: return IDC_OPEN_FILE; case APPCOMMAND_CLOSE: return IDC_CLOSE_TAB; case APPCOMMAND_SAVE: return IDC_SAVE_PAGE; case APPCOMMAND_PRINT: return IDC_PRINT; case APPCOMMAND_COPY: return IDC_COPY; case APPCOMMAND_CUT: return IDC_CUT; case APPCOMMAND_PASTE: return IDC_PASTE; // TODO(pkasting): http://b/1113069 Handle these. case APPCOMMAND_UNDO: case APPCOMMAND_REDO: case APPCOMMAND_SPELL_CHECK: default: return -1; } #else // App commands are Windows-specific so there's nothing to do here. return -1; #endif } void BrowserView::LoadingAnimationCallback() { if (browser_->type() == Browser::TYPE_NORMAL) { // Loading animations are shown in the tab for tabbed windows. We check the // browser type instead of calling IsTabStripVisible() because the latter // will return false for fullscreen windows, but we still need to update // their animations (so that when they come out of fullscreen mode they'll // be correct). tabstrip_->UpdateLoadingAnimations(); } else if (ShouldShowWindowIcon()) { // ... or in the window icon area for popups and app windows. TabContents* tab_contents = browser_->GetSelectedTabContents(); // GetSelectedTabContents can return NULL for example under Purify when // the animations are running slowly and this function is called on a timer // through LoadingAnimationCallback. frame_->UpdateThrobber(tab_contents && tab_contents->is_loading()); } } void BrowserView::InitHangMonitor() { #if defined(OS_WIN) PrefService* pref_service = g_browser_process->local_state(); if (!pref_service) return; int plugin_message_response_timeout = pref_service->GetInteger(prefs::kPluginMessageResponseTimeout); int hung_plugin_detect_freq = pref_service->GetInteger(prefs::kHungPluginDetectFrequency); if ((hung_plugin_detect_freq > 0) && hung_window_detector_.Initialize(GetWidget()->GetNativeView(), plugin_message_response_timeout)) { ticker_.set_tick_interval(hung_plugin_detect_freq); ticker_.RegisterTickHandler(&hung_window_detector_); ticker_.Start(); pref_service->SetInteger(prefs::kPluginMessageResponseTimeout, plugin_message_response_timeout); pref_service->SetInteger(prefs::kHungPluginDetectFrequency, hung_plugin_detect_freq); } #endif } void BrowserView::ShowMatchPreview() { if (!preview_container_) preview_container_ = new TabContentsContainer(); contents_->SetPreview(preview_container_); preview_container_->ChangeTabContents( browser_->GetSelectedTabContents()->match_preview()->preview_contents()); } void BrowserView::HideMatchPreview() { if (!preview_container_) return; // The contents must be changed before SetPreview is invoked. preview_container_->ChangeTabContents(NULL); contents_->SetPreview(NULL); delete preview_container_; preview_container_ = NULL; } void BrowserView::ProcessTabSelected(TabContents* new_contents, bool change_tab_contents) { // Update various elements that are interested in knowing the current // TabContents. // When we toggle the NTP floating bookmarks bar and/or the info bar, // we don't want any TabContents to be attached, so that we // avoid an unnecessary resize and re-layout of a TabContents. if (change_tab_contents) contents_container_->ChangeTabContents(NULL); infobar_container_->ChangeTabContents(new_contents); UpdateUIForContents(new_contents); if (change_tab_contents) contents_container_->ChangeTabContents(new_contents); UpdateSidebarForContents(new_contents); UpdateDevToolsForContents(new_contents); // TODO(beng): This should be called automatically by ChangeTabContents, but I // am striving for parity now rather than cleanliness. This is // required to make features like Duplicate Tab, Undo Close Tab, // etc not result in sad tab. new_contents->DidBecomeSelected(); if (BrowserList::GetLastActive() == browser_ && !browser_->tabstrip_model()->closing_all() && GetWindow()->IsVisible()) { // We only restore focus if our window is visible, to avoid invoking blur // handlers when we are eventually shown. new_contents->view()->RestoreFocus(); } // Update all the UI bits. UpdateTitleBar(); UpdateToolbar(new_contents, true); UpdateUIForContents(new_contents); } #if !defined(OS_CHROMEOS) // static BrowserWindow* BrowserWindow::CreateBrowserWindow(Browser* browser) { // Create the view and the frame. The frame will attach itself via the view // so we don't need to do anything with the pointer. BrowserView* view = new BrowserView(browser); BrowserFrame::Create(view, browser->profile()); view->GetWindow()->GetNonClientView()-> SetAccessibleName(l10n_util::GetString(IDS_PRODUCT_NAME)); return view; } #endif // static FindBar* BrowserWindow::CreateFindBar(Browser* browser) { return browser::CreateFindBar(static_cast<BrowserView*>(browser->window())); } Fixes bug where Layout might not get invoked on view hosting tabcontents after an animation that would result in a gray rect. BUG=53083 TEST=see bug Review URL: http://codereview.chromium.org/3142034 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@57205 0039d316-1c4b-4281-b951-d872f2087c98 // 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 "chrome/browser/views/frame/browser_view.h" #if defined(OS_LINUX) #include <gtk/gtk.h> #endif #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/command_line.h" #include "base/i18n/rtl.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/app_modal_dialog_queue.h" #include "chrome/browser/autocomplete/autocomplete_popup_model.h" #include "chrome/browser/autocomplete/autocomplete_popup_view.h" #include "chrome/browser/automation/ui_controls.h" #include "chrome/browser/bookmarks/bookmark_utils.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_theme_provider.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/dom_ui/bug_report_ui.h" #include "chrome/browser/download/download_manager.h" #include "chrome/browser/ntp_background_util.h" #include "chrome/browser/page_info_window.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/sessions/tab_restore_service.h" #include "chrome/browser/sidebar/sidebar_container.h" #include "chrome/browser/sidebar/sidebar_manager.h" #include "chrome/browser/tab_contents/match_preview.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view.h" #include "chrome/browser/view_ids.h" #include "chrome/browser/views/accessible_view_helper.h" #include "chrome/browser/views/bookmark_bar_view.h" #include "chrome/browser/views/browser_dialogs.h" #include "chrome/browser/views/download_shelf_view.h" #include "chrome/browser/views/frame/browser_view_layout.h" #include "chrome/browser/views/fullscreen_exit_bubble.h" #include "chrome/browser/views/status_bubble_views.h" #include "chrome/browser/views/tab_contents/tab_contents_container.h" #include "chrome/browser/views/tabs/browser_tab_strip_controller.h" #include "chrome/browser/views/tabs/side_tab_strip.h" #include "chrome/browser/views/theme_install_bubble_view.h" #include "chrome/browser/views/toolbar_view.h" #include "chrome/browser/views/update_recommended_message_box.h" #include "chrome/browser/window_sizer.h" #include "chrome/browser/wrench_menu_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension_resource.h" #include "chrome/common/native_window_notification_source.h" #include "chrome/common/notification_service.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "gfx/canvas_skia.h" #include "grit/app_resources.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" #include "grit/theme_resources.h" #include "grit/webkit_resources.h" #include "views/controls/single_split_view.h" #include "views/focus/external_focus_tracker.h" #include "views/focus/view_storage.h" #include "views/grid_layout.h" #include "views/widget/root_view.h" #include "views/window/dialog_delegate.h" #include "views/window/window.h" #if defined(OS_WIN) #include "app/win_util.h" #include "chrome/browser/aeropeek_manager.h" #include "chrome/browser/jumplist_win.h" #elif defined(OS_LINUX) #include "chrome/browser/views/accelerator_table_gtk.h" #include "views/window/hit_test.h" #include "views/window/window_gtk.h" #endif using base::TimeDelta; using views::ColumnSet; using views::GridLayout; // The height of the status bubble. static const int kStatusBubbleHeight = 20; // The name of a key to store on the window handle so that other code can // locate this object using just the handle. #if defined(OS_WIN) static const wchar_t* kBrowserViewKey = L"__BROWSER_VIEW__"; #else static const char* kBrowserViewKey = "__BROWSER_VIEW__"; #endif // How frequently we check for hung plugin windows. static const int kDefaultHungPluginDetectFrequency = 2000; // How long do we wait before we consider a window hung (in ms). static const int kDefaultPluginMessageResponseTimeout = 30000; // The number of milliseconds between loading animation frames. static const int kLoadingAnimationFrameTimeMs = 30; // The amount of space we expect the window border to take up. static const int kWindowBorderWidth = 5; // If not -1, windows are shown with this state. static int explicit_show_state = -1; // How round the 'new tab' style bookmarks bar is. static const int kNewtabBarRoundness = 5; // ------------ // Returned from BrowserView::GetClassName. const char BrowserView::kViewClassName[] = "browser/views/BrowserView"; #if defined(OS_CHROMEOS) // Get a normal browser window of given |profile| to use as dialog parent // if given |browser| is not one. Otherwise, returns browser window of // |browser|. If |profile| is NULL, |browser|'s profile is used to find the // normal browser. static gfx::NativeWindow GetNormalBrowserWindowForBrowser(Browser* browser, Profile* profile) { if (browser->type() != Browser::TYPE_NORMAL) { Browser* normal_browser = BrowserList::FindBrowserWithType( profile ? profile : browser->profile(), Browser::TYPE_NORMAL, true); if (normal_browser && normal_browser->window()) return normal_browser->window()->GetNativeHandle(); } return browser->window()->GetNativeHandle(); } #endif // defined(OS_CHROMEOS) // ContentsContainer is responsible for managing the TabContents views. // ContentsContainer has up to two children: one for the currently active // TabContents and one for the match preview TabContents. class BrowserView::ContentsContainer : public views::View { public: ContentsContainer(BrowserView* browser_view, views::View* active) : browser_view_(browser_view), active_(active), preview_(NULL) { AddChildView(active_); } // Makes the preview view the active view and nulls out the old active view. // It's assumed the caller will delete or remove the old active view // separately. void MakePreviewContentsActiveContents() { active_ = preview_; preview_ = NULL; Layout(); } // Sets the preview view. This does not delete the old. void SetPreview(views::View* preview) { if (preview == preview_) return; if (preview_) RemoveChildView(preview_); preview_ = preview; if (preview_) AddChildView(preview_); Layout(); } virtual void Layout() { // The active view always gets the full bounds. active_->SetBounds(0, 0, width(), height()); if (preview_) { // The preview view gets the full width and is positioned beneath the // bottom of the autocompleted popup. int max_autocomplete_y = browser_view_->toolbar()->location_bar()-> location_entry()->model()->popup_model()->view()->GetMaxYCoordinate(); gfx::Point screen_origin; views::View::ConvertPointToScreen(this, &screen_origin); DCHECK_GT(max_autocomplete_y, screen_origin.y()); int preview_origin = max_autocomplete_y - screen_origin.y(); if (preview_origin < height()) { preview_->SetBounds(0, preview_origin, width(), height() - preview_origin); } else { preview_->SetBounds(0, 0, 0, 0); } } // Need to invoke views::View in case any views whose bounds didn't change // still need a layout. views::View::Layout(); } private: BrowserView* browser_view_; views::View* active_; views::View* preview_; DISALLOW_COPY_AND_ASSIGN(ContentsContainer); }; /////////////////////////////////////////////////////////////////////////////// // BookmarkExtensionBackground, private: // This object serves as the views::Background object which is used to layout // and paint the bookmark bar. class BookmarkExtensionBackground : public views::Background { public: explicit BookmarkExtensionBackground(BrowserView* browser_view, DetachableToolbarView* host_view, Browser* browser); // View methods overridden from views:Background. virtual void Paint(gfx::Canvas* canvas, views::View* view) const; private: BrowserView* browser_view_; // The view hosting this background. DetachableToolbarView* host_view_; Browser* browser_; DISALLOW_COPY_AND_ASSIGN(BookmarkExtensionBackground); }; BookmarkExtensionBackground::BookmarkExtensionBackground( BrowserView* browser_view, DetachableToolbarView* host_view, Browser* browser) : browser_view_(browser_view), host_view_(host_view), browser_(browser) { } void BookmarkExtensionBackground::Paint(gfx::Canvas* canvas, views::View* view) const { ThemeProvider* tp = host_view_->GetThemeProvider(); int toolbar_overlap = host_view_->GetToolbarOverlap(); // The client edge is drawn below the toolbar bounds. if (toolbar_overlap) toolbar_overlap += views::NonClientFrameView::kClientEdgeThickness; if (host_view_->IsDetached()) { // Draw the background to match the new tab page. int height = 0; TabContents* contents = browser_->GetSelectedTabContents(); if (contents && contents->view()) height = contents->view()->GetContainerSize().height(); NtpBackgroundUtil::PaintBackgroundDetachedMode( host_view_->GetThemeProvider(), canvas, gfx::Rect(0, toolbar_overlap, host_view_->width(), host_view_->height() - toolbar_overlap), height); // As 'hidden' according to the animation is the full in-tab state, // we invert the value - when current_state is at '0', we expect the // bar to be docked. double current_state = 1 - host_view_->GetAnimationValue(); double h_padding = static_cast<double>(BookmarkBarView::kNewtabHorizontalPadding) * current_state; double v_padding = static_cast<double>(BookmarkBarView::kNewtabVerticalPadding) * current_state; SkRect rect; double roundness = 0; DetachableToolbarView::CalculateContentArea(current_state, h_padding, v_padding, &rect, &roundness, host_view_); DetachableToolbarView::PaintContentAreaBackground(canvas, tp, rect, roundness); DetachableToolbarView::PaintContentAreaBorder(canvas, tp, rect, roundness); if (!toolbar_overlap) DetachableToolbarView::PaintHorizontalBorder(canvas, host_view_); } else { DetachableToolbarView::PaintBackgroundAttachedMode(canvas, host_view_, browser_view_->OffsetPointForToolbarBackgroundImage( gfx::Point(host_view_->MirroredX(), host_view_->y()))); if (host_view_->height() >= toolbar_overlap) DetachableToolbarView::PaintHorizontalBorder(canvas, host_view_); } } /////////////////////////////////////////////////////////////////////////////// // ResizeCorner, private: class ResizeCorner : public views::View { public: ResizeCorner() { EnableCanvasFlippingForRTLUI(true); } virtual void Paint(gfx::Canvas* canvas) { views::Window* window = GetWindow(); if (!window || (window->IsMaximized() || window->IsFullscreen())) return; SkBitmap* bitmap = ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_TEXTAREA_RESIZER); bitmap->buildMipMap(false); canvas->DrawBitmapInt(*bitmap, width() - bitmap->width(), height() - bitmap->height()); } static gfx::Size GetSize() { // This is disabled until we find what makes us slower when we let // WebKit know that we have a resizer rect... // int scrollbar_thickness = gfx::scrollbar_size(); // return gfx::Size(scrollbar_thickness, scrollbar_thickness); return gfx::Size(); } virtual gfx::Size GetPreferredSize() { views::Window* window = GetWindow(); return (!window || window->IsMaximized() || window->IsFullscreen()) ? gfx::Size() : GetSize(); } virtual void Layout() { views::View* parent_view = GetParent(); if (parent_view) { gfx::Size ps = GetPreferredSize(); // No need to handle Right to left text direction here, // our parent must take care of it for us... SetBounds(parent_view->width() - ps.width(), parent_view->height() - ps.height(), ps.width(), ps.height()); } } private: // Returns the WindowWin we're displayed in. Returns NULL if we're not // currently in a window. views::Window* GetWindow() { views::Widget* widget = GetWidget(); return widget ? widget->GetWindow() : NULL; } DISALLOW_COPY_AND_ASSIGN(ResizeCorner); }; //////////////////////////////////////////////////////////////////////////////// // DownloadInProgressConfirmDialogDelegate class DownloadInProgressConfirmDialogDelegate : public views::DialogDelegate, public views::View { public: explicit DownloadInProgressConfirmDialogDelegate(Browser* browser) : browser_(browser), product_name_(l10n_util::GetString(IDS_PRODUCT_NAME)) { int download_count = browser->profile()->GetDownloadManager()-> in_progress_count(); std::wstring warning_text; std::wstring explanation_text; if (download_count == 1) { warning_text = l10n_util::GetStringF(IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_WARNING, product_name_); explanation_text = l10n_util::GetStringF(IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION, product_name_); ok_button_text_ = l10n_util::GetString( IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL); cancel_button_text_ = l10n_util::GetString( IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL); } else { warning_text = l10n_util::GetStringF(IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_WARNING, product_name_, UTF8ToWide(base::IntToString(download_count))); explanation_text = l10n_util::GetStringF( IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_EXPLANATION, product_name_); ok_button_text_ = l10n_util::GetString( IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_OK_BUTTON_LABEL); cancel_button_text_ = l10n_util::GetString( IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL); } // There are two lines of text: the bold warning label and the text // explanation label. GridLayout* layout = new GridLayout(this); SetLayoutManager(layout); const int columnset_id = 0; ColumnSet* column_set = layout->AddColumnSet(columnset_id); column_set->AddColumn(GridLayout::FILL, GridLayout::LEADING, 1, GridLayout::USE_PREF, 0, 0); gfx::Font bold_font = ResourceBundle::GetSharedInstance().GetFont( ResourceBundle::BaseFont).DeriveFont(0, gfx::Font::BOLD); warning_ = new views::Label(warning_text, bold_font); warning_->SetMultiLine(true); warning_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); warning_->set_border(views::Border::CreateEmptyBorder(10, 10, 10, 10)); layout->StartRow(0, columnset_id); layout->AddView(warning_); explanation_ = new views::Label(explanation_text); explanation_->SetMultiLine(true); explanation_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); explanation_->set_border(views::Border::CreateEmptyBorder(10, 10, 10, 10)); layout->StartRow(0, columnset_id); layout->AddView(explanation_); dialog_dimensions_ = views::Window::GetLocalizedContentsSize( IDS_DOWNLOAD_IN_PROGRESS_WIDTH_CHARS, IDS_DOWNLOAD_IN_PROGRESS_MINIMUM_HEIGHT_LINES); const int height = warning_->GetHeightForWidth(dialog_dimensions_.width()) + explanation_->GetHeightForWidth(dialog_dimensions_.width()); dialog_dimensions_.set_height(std::max(height, dialog_dimensions_.height())); } ~DownloadInProgressConfirmDialogDelegate() { } // View implementation: virtual gfx::Size GetPreferredSize() { return dialog_dimensions_; } // DialogDelegate implementation: virtual int GetDefaultDialogButton() const { return MessageBoxFlags::DIALOGBUTTON_CANCEL; } virtual std::wstring GetDialogButtonLabel( MessageBoxFlags::DialogButton button) const { if (button == MessageBoxFlags::DIALOGBUTTON_OK) return ok_button_text_; DCHECK_EQ(MessageBoxFlags::DIALOGBUTTON_CANCEL, button); return cancel_button_text_; } virtual bool Accept() { browser_->InProgressDownloadResponse(true); return true; } virtual bool Cancel() { browser_->InProgressDownloadResponse(false); return true; } // WindowDelegate implementation: virtual bool IsModal() const { return true; } virtual views::View* GetContentsView() { return this; } virtual std::wstring GetWindowTitle() const { return product_name_; } private: Browser* browser_; views::Label* warning_; views::Label* explanation_; std::wstring ok_button_text_; std::wstring cancel_button_text_; std::wstring product_name_; gfx::Size dialog_dimensions_; DISALLOW_COPY_AND_ASSIGN(DownloadInProgressConfirmDialogDelegate); }; /////////////////////////////////////////////////////////////////////////////// // BrowserView, public: // static void BrowserView::SetShowState(int state) { explicit_show_state = state; } BrowserView::BrowserView(Browser* browser) : views::ClientView(NULL, NULL), last_focused_view_storage_id_( views::ViewStorage::GetSharedInstance()->CreateStorageID()), frame_(NULL), browser_(browser), active_bookmark_bar_(NULL), tabstrip_(NULL), toolbar_(NULL), infobar_container_(NULL), sidebar_container_(NULL), sidebar_split_(NULL), contents_container_(NULL), devtools_container_(NULL), preview_container_(NULL), contents_(NULL), contents_split_(NULL), initialized_(false), ignore_layout_(true) #if defined(OS_WIN) ,hung_window_detector_(&hung_plugin_action_), ticker_(0) #endif { browser_->tabstrip_model()->AddObserver(this); registrar_.Add(this, NotificationType::SIDEBAR_CHANGED, Source<SidebarManager>(SidebarManager::GetInstance())); } BrowserView::~BrowserView() { browser_->tabstrip_model()->RemoveObserver(this); #if defined(OS_WIN) // Remove this observer. if (aeropeek_manager_.get()) browser_->tabstrip_model()->RemoveObserver(aeropeek_manager_.get()); // Stop hung plugin monitoring. ticker_.Stop(); ticker_.UnregisterTickHandler(&hung_window_detector_); #endif // We destroy the download shelf before |browser_| to remove its child // download views from the set of download observers (since the observed // downloads can be destroyed along with |browser_| and the observer // notifications will call back into deleted objects). download_shelf_.reset(); // The TabStrip attaches a listener to the model. Make sure we shut down the // TabStrip first so that it can cleanly remove the listener. tabstrip_->GetParent()->RemoveChildView(tabstrip_); delete tabstrip_; tabstrip_ = NULL; // Explicitly set browser_ to NULL. browser_.reset(); } // static BrowserView* BrowserView::GetBrowserViewForNativeWindow( gfx::NativeWindow window) { #if defined(OS_WIN) if (IsWindow(window)) { HANDLE data = GetProp(window, kBrowserViewKey); if (data) return reinterpret_cast<BrowserView*>(data); } #else if (window) { return static_cast<BrowserView*>( g_object_get_data(G_OBJECT(window), kBrowserViewKey)); } #endif return NULL; } int BrowserView::GetShowState() const { if (explicit_show_state != -1) return explicit_show_state; #if defined(OS_WIN) STARTUPINFO si = {0}; si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW; GetStartupInfo(&si); return si.wShowWindow; #else NOTIMPLEMENTED(); return 0; #endif } void BrowserView::WindowMoved() { // Cancel any tabstrip animations, some of them may be invalidated by the // window being repositioned. // Comment out for one cycle to see if this fixes dist tests. // tabstrip_->DestroyDragController(); status_bubble_->Reposition(); BrowserBubbleHost::WindowMoved(); browser::HideBookmarkBubbleView(); // Close the omnibox popup, if any. if (toolbar_->location_bar()) toolbar_->location_bar()->location_entry()->ClosePopup(); } void BrowserView::WindowMoveOrResizeStarted() { TabContents* tab_contents = GetSelectedTabContents(); if (tab_contents) tab_contents->WindowMoveOrResizeStarted(); } gfx::Rect BrowserView::GetToolbarBounds() const { gfx::Rect toolbar_bounds(toolbar_->bounds()); if (toolbar_bounds.IsEmpty()) return toolbar_bounds; // When using vertical tabs, the toolbar appears to extend behind the tab // column. if (UseVerticalTabs()) toolbar_bounds.Inset(tabstrip_->x() - toolbar_bounds.x(), 0, 0, 0); // The apparent toolbar edges are outside the "real" toolbar edges. toolbar_bounds.Inset(-views::NonClientFrameView::kClientEdgeThickness, 0); return toolbar_bounds; } gfx::Rect BrowserView::GetClientAreaBounds() const { gfx::Rect container_bounds = contents_->bounds(); gfx::Point container_origin = container_bounds.origin(); ConvertPointToView(this, GetParent(), &container_origin); container_bounds.set_origin(container_origin); return container_bounds; } bool BrowserView::ShouldFindBarBlendWithBookmarksBar() const { if (bookmark_bar_view_.get()) return bookmark_bar_view_->IsAlwaysShown(); return false; } gfx::Rect BrowserView::GetFindBarBoundingBox() const { return GetBrowserViewLayout()->GetFindBarBoundingBox(); } int BrowserView::GetTabStripHeight() const { // We want to return tabstrip_->height(), but we might be called in the midst // of layout, when that hasn't yet been updated to reflect the current state. // So return what the tabstrip height _ought_ to be right now. return IsTabStripVisible() ? tabstrip_->GetPreferredSize().height() : 0; } gfx::Point BrowserView::OffsetPointForToolbarBackgroundImage( const gfx::Point& point) const { // The background image starts tiling horizontally at the window left edge and // vertically at the top edge of the horizontal tab strip (or where it would // be). We expect our parent's origin to be the window origin. gfx::Point window_point(point.Add(gfx::Point(MirroredX(), y()))); window_point.Offset(0, -frame_->GetHorizontalTabStripVerticalOffset(false)); return window_point; } int BrowserView::GetSidebarWidth() const { if (!sidebar_container_ || !sidebar_container_->IsVisible()) return 0; return sidebar_split_->divider_offset(); } bool BrowserView::IsTabStripVisible() const { return browser_->SupportsWindowFeature(Browser::FEATURE_TABSTRIP); } bool BrowserView::UseVerticalTabs() const { return browser_->tabstrip_model()->delegate()->UseVerticalTabs(); } bool BrowserView::IsOffTheRecord() const { return browser_->profile()->IsOffTheRecord(); } bool BrowserView::ShouldShowOffTheRecordAvatar() const { return IsOffTheRecord() && IsBrowserTypeNormal(); } bool BrowserView::AcceleratorPressed(const views::Accelerator& accelerator) { std::map<views::Accelerator, int>::const_iterator iter = accelerator_table_.find(accelerator); DCHECK(iter != accelerator_table_.end()); int command_id = iter->second; if (browser_->command_updater()->SupportsCommand(command_id) && browser_->command_updater()->IsCommandEnabled(command_id)) { browser_->ExecuteCommand(command_id); return true; } return false; } bool BrowserView::GetAccelerator(int cmd_id, menus::Accelerator* accelerator) { // The standard Ctrl-X, Ctrl-V and Ctrl-C are not defined as accelerators // anywhere so we need to check for them explicitly here. switch (cmd_id) { case IDC_CUT: *accelerator = views::Accelerator(base::VKEY_X, false, true, false); return true; case IDC_COPY: *accelerator = views::Accelerator(base::VKEY_C, false, true, false); return true; case IDC_PASTE: *accelerator = views::Accelerator(base::VKEY_V, false, true, false); return true; } // Else, we retrieve the accelerator information from the accelerator table. std::map<views::Accelerator, int>::iterator it = accelerator_table_.begin(); for (; it != accelerator_table_.end(); ++it) { if (it->second == cmd_id) { *accelerator = it->first; return true; } } return false; } bool BrowserView::ActivateAppModalDialog() const { // If another browser is app modal, flash and activate the modal browser. if (Singleton<AppModalDialogQueue>()->HasActiveDialog()) { Browser* active_browser = BrowserList::GetLastActive(); if (active_browser && (browser_ != active_browser)) { active_browser->window()->FlashFrame(); active_browser->window()->Activate(); } Singleton<AppModalDialogQueue>()->ActivateModalDialog(); return true; } return false; } void BrowserView::ActivationChanged(bool activated) { if (activated) BrowserList::SetLastActive(browser_.get()); } TabContents* BrowserView::GetSelectedTabContents() const { return browser_->GetSelectedTabContents(); } SkBitmap BrowserView::GetOTRAvatarIcon() { static SkBitmap* otr_avatar_ = new SkBitmap(); if (otr_avatar_->isNull()) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); *otr_avatar_ = *rb.GetBitmapNamed(IDR_OTR_ICON); } return *otr_avatar_; } #if defined(OS_WIN) void BrowserView::PrepareToRunSystemMenu(HMENU menu) { system_menu_->UpdateStates(); } #endif // static void BrowserView::RegisterBrowserViewPrefs(PrefService* prefs) { prefs->RegisterIntegerPref(prefs::kPluginMessageResponseTimeout, kDefaultPluginMessageResponseTimeout); prefs->RegisterIntegerPref(prefs::kHungPluginDetectFrequency, kDefaultHungPluginDetectFrequency); } bool BrowserView::IsPositionInWindowCaption(const gfx::Point& point) { return GetBrowserViewLayout()->IsPositionInWindowCaption(point); } /////////////////////////////////////////////////////////////////////////////// // BrowserView, BrowserWindow implementation: void BrowserView::Show() { // If the window is already visible, just activate it. if (frame_->GetWindow()->IsVisible()) { frame_->GetWindow()->Activate(); return; } // Setting the focus doesn't work when the window is invisible, so any focus // initialization that happened before this will be lost. // // We really "should" restore the focus whenever the window becomes unhidden, // but I think initializing is the only time where this can happen where // there is some focus change we need to pick up, and this is easier than // plumbing through an un-hide message all the way from the frame. // // If we do find there are cases where we need to restore the focus on show, // that should be added and this should be removed. RestoreFocus(); frame_->GetWindow()->Show(); } void BrowserView::SetBounds(const gfx::Rect& bounds) { GetWidget()->SetBounds(bounds); } void BrowserView::Close() { BrowserBubbleHost::Close(); frame_->GetWindow()->Close(); } void BrowserView::Activate() { frame_->GetWindow()->Activate(); } void BrowserView::Deactivate() { frame_->GetWindow()->Deactivate(); } bool BrowserView::IsActive() const { return frame_->GetWindow()->IsActive(); } void BrowserView::FlashFrame() { #if defined(OS_WIN) FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = frame_->GetWindow()->GetNativeWindow(); fwi.dwFlags = FLASHW_ALL; fwi.uCount = 4; fwi.dwTimeout = 0; FlashWindowEx(&fwi); #else // Doesn't matter for chrome os. #endif } gfx::NativeWindow BrowserView::GetNativeHandle() { return GetWidget()->GetWindow()->GetNativeWindow(); } BrowserWindowTesting* BrowserView::GetBrowserWindowTesting() { return this; } StatusBubble* BrowserView::GetStatusBubble() { return status_bubble_.get(); } void BrowserView::SelectedTabToolbarSizeChanged(bool is_animating) { if (is_animating) { contents_container_->SetFastResize(true); UpdateUIForContents(browser_->GetSelectedTabContents()); contents_container_->SetFastResize(false); } else { UpdateUIForContents(browser_->GetSelectedTabContents()); // When transitioning from animating to not animating we need to make sure // the contents_container_ gets layed out. If we don't do this and the // bounds haven't changed contents_container_ won't get a Layout out and // we'll end up with a gray rect because the clip wasn't updated. contents_container_->InvalidateLayout(); contents_split_->Layout(); } } void BrowserView::UpdateTitleBar() { frame_->GetWindow()->UpdateWindowTitle(); if (ShouldShowWindowIcon() && !loading_animation_timer_.IsRunning()) frame_->GetWindow()->UpdateWindowIcon(); } void BrowserView::ShelfVisibilityChanged() { Layout(); } void BrowserView::UpdateDevTools() { UpdateDevToolsForContents(GetSelectedTabContents()); Layout(); } void BrowserView::UpdateLoadingAnimations(bool should_animate) { if (should_animate) { if (!loading_animation_timer_.IsRunning()) { // Loads are happening, and the timer isn't running, so start it. loading_animation_timer_.Start( TimeDelta::FromMilliseconds(kLoadingAnimationFrameTimeMs), this, &BrowserView::LoadingAnimationCallback); } } else { if (loading_animation_timer_.IsRunning()) { loading_animation_timer_.Stop(); // Loads are now complete, update the state if a task was scheduled. LoadingAnimationCallback(); } } } void BrowserView::SetStarredState(bool is_starred) { toolbar_->location_bar()->SetStarToggled(is_starred); } gfx::Rect BrowserView::GetRestoredBounds() const { return frame_->GetWindow()->GetNormalBounds(); } bool BrowserView::IsMaximized() const { return frame_->GetWindow()->IsMaximized(); } void BrowserView::SetFullscreen(bool fullscreen) { if (IsFullscreen() == fullscreen) return; // Nothing to do. #if defined(OS_WIN) ProcessFullscreen(fullscreen); #else // On Linux changing fullscreen is async. Ask the window to change it's // fullscreen state, and when done invoke ProcessFullscreen. frame_->GetWindow()->SetFullscreen(fullscreen); #endif } bool BrowserView::IsFullscreen() const { return frame_->GetWindow()->IsFullscreen(); } bool BrowserView::IsFullscreenBubbleVisible() const { return fullscreen_bubble_.get() ? true : false; } void BrowserView::FullScreenStateChanged() { ProcessFullscreen(IsFullscreen()); } void BrowserView::RestoreFocus() { TabContents* selected_tab_contents = GetSelectedTabContents(); if (selected_tab_contents) selected_tab_contents->view()->RestoreFocus(); } LocationBar* BrowserView::GetLocationBar() const { return toolbar_->location_bar(); } void BrowserView::SetFocusToLocationBar(bool select_all) { LocationBarView* location_bar = toolbar_->location_bar(); if (location_bar->IsFocusableInRootView()) { // Location bar got focus. location_bar->FocusLocation(select_all); } else { // If none of location bar/compact navigation bar got focus, // then clear focus. views::FocusManager* focus_manager = GetFocusManager(); DCHECK(focus_manager); focus_manager->ClearFocus(); } } void BrowserView::UpdateReloadStopState(bool is_loading, bool force) { toolbar_->reload_button()->ChangeMode( is_loading ? ReloadButton::MODE_STOP : ReloadButton::MODE_RELOAD, force); } void BrowserView::UpdateToolbar(TabContents* contents, bool should_restore_state) { toolbar_->Update(contents, should_restore_state); } void BrowserView::FocusToolbar() { // Start the traversal within the main toolbar, passing it the storage id // of the view where focus should be returned if the user exits the toolbar. SaveFocusedView(); toolbar_->SetToolbarFocus(last_focused_view_storage_id_, NULL); } void BrowserView::FocusBookmarksToolbar() { if (active_bookmark_bar_ && bookmark_bar_view_->IsVisible()) { SaveFocusedView(); bookmark_bar_view_->SetToolbarFocus(last_focused_view_storage_id_, NULL); } } void BrowserView::FocusAppMenu() { // Chrome doesn't have a traditional menu bar, but it has a menu button in the // main toolbar that plays the same role. If the user presses a key that // would typically focus the menu bar, tell the toolbar to focus the menu // button. Pass it the storage id of the view where focus should be returned // if the user presses escape. // // Not used on the Mac, which has a normal menu bar. SaveFocusedView(); toolbar_->SetToolbarFocusAndFocusAppMenu(last_focused_view_storage_id_); } void BrowserView::RotatePaneFocus(bool forwards) { // This gets called when the user presses F6 (forwards) or Shift+F6 // (backwards) to rotate to the next pane. Here, our "panes" are the // tab contents and each of our accessible toolbars. When a toolbar has // pane focus, all of its controls are accessible in the tab traversal, // and the tab traversal is "trapped" within that pane. // Get a vector of all panes in the order we want them to be focused - // each of the accessible toolbars, then NULL to represent the tab contents // getting focus. If one of these is currently invisible or has no // focusable children it will be automatically skipped. std::vector<AccessibleToolbarView*> accessible_toolbars; GetAccessibleToolbars(&accessible_toolbars); int toolbars_count = static_cast<int>(accessible_toolbars.size()); std::vector<views::View*> accessible_views( accessible_toolbars.begin(), accessible_toolbars.end()); accessible_views.push_back(GetTabContentsContainerView()); if (sidebar_container_ && sidebar_container_->IsVisible()) accessible_views.push_back(GetSidebarContainerView()); if (devtools_container_->IsVisible()) accessible_views.push_back(devtools_container_->GetFocusView()); int count = static_cast<int>(accessible_views.size()); // Figure out which view (if any) currently has the focus. views::View* focused_view = GetRootView()->GetFocusedView(); int index = -1; if (focused_view) { for (int i = 0; i < count; ++i) { if (accessible_views[i] == focused_view || accessible_views[i]->IsParentOf(focused_view)) { index = i; break; } } } // If the focus isn't currently in a toolbar, save the focus so we // can restore it if the user presses Escape. if (focused_view && index >= toolbars_count) SaveFocusedView(); // Try to focus the next pane; if SetToolbarFocusAndFocusDefault returns // false it means the toolbar didn't have any focusable controls, so skip // it and try the next one. for (;;) { if (forwards) index = (index + 1) % count; else index = ((index - 1) + count) % count; if (index < toolbars_count) { if (accessible_toolbars[index]->SetToolbarFocusAndFocusDefault( last_focused_view_storage_id_)) { break; } } else { accessible_views[index]->RequestFocus(); break; } } } void BrowserView::SaveFocusedView() { views::ViewStorage* view_storage = views::ViewStorage::GetSharedInstance(); if (view_storage->RetrieveView(last_focused_view_storage_id_)) view_storage->RemoveView(last_focused_view_storage_id_); views::View* focused_view = GetRootView()->GetFocusedView(); if (focused_view) view_storage->StoreView(last_focused_view_storage_id_, focused_view); } void BrowserView::DestroyBrowser() { // Explicitly delete the BookmarkBarView now. That way we don't have to // worry about the BookmarkBarView potentially outliving the Browser & // Profile. bookmark_bar_view_.reset(); browser_.reset(); } bool BrowserView::IsBookmarkBarVisible() const { return browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR) && active_bookmark_bar_ && (active_bookmark_bar_->GetPreferredSize().height() != 0); } bool BrowserView::IsBookmarkBarAnimating() const { return bookmark_bar_view_.get() && bookmark_bar_view_->is_animating(); } bool BrowserView::IsToolbarVisible() const { return browser_->SupportsWindowFeature(Browser::FEATURE_TOOLBAR) || browser_->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR); } gfx::Rect BrowserView::GetRootWindowResizerRect() const { if (frame_->GetWindow()->IsMaximized() || frame_->GetWindow()->IsFullscreen()) return gfx::Rect(); // We don't specify a resize corner size if we have a bottom shelf either. // This is because we take care of drawing the resize corner on top of that // shelf, so we don't want others to do it for us in this case. // Currently, the only visible bottom shelf is the download shelf. // Other tests should be added here if we add more bottom shelves. if (download_shelf_.get() && download_shelf_->IsShowing()) { return gfx::Rect(); } gfx::Rect client_rect = contents_split_->bounds(); gfx::Size resize_corner_size = ResizeCorner::GetSize(); int x = client_rect.width() - resize_corner_size.width(); if (base::i18n::IsRTL()) x = 0; return gfx::Rect(x, client_rect.height() - resize_corner_size.height(), resize_corner_size.width(), resize_corner_size.height()); } void BrowserView::DisableInactiveFrame() { #if defined(OS_WIN) frame_->GetWindow()->DisableInactiveRendering(); #endif // No tricks are needed to get the right behavior on Linux. } void BrowserView::ConfirmAddSearchProvider(const TemplateURL* template_url, Profile* profile) { browser::EditSearchEngine(GetWindow()->GetNativeWindow(), template_url, NULL, profile); } void BrowserView::ToggleBookmarkBar() { bookmark_utils::ToggleWhenVisible(browser_->profile()); } views::Window* BrowserView::ShowAboutChromeDialog() { return browser::ShowAboutChromeView(GetWindow()->GetNativeWindow(), browser_->profile()); } void BrowserView::ShowUpdateChromeDialog() { #if defined(OS_WIN) UpdateRecommendedMessageBox::ShowMessageBox(GetWindow()->GetNativeWindow()); #endif } void BrowserView::ShowTaskManager() { browser::ShowTaskManager(); } void BrowserView::ShowBookmarkBubble(const GURL& url, bool already_bookmarked) { toolbar_->location_bar()->ShowStarBubble(url, !already_bookmarked); } void BrowserView::SetDownloadShelfVisible(bool visible) { // This can be called from the superclass destructor, when it destroys our // child views. At that point, browser_ is already gone. if (browser_ == NULL) return; if (visible && IsDownloadShelfVisible() != visible) { // Invoke GetDownloadShelf to force the shelf to be created. GetDownloadShelf(); } if (browser_ != NULL) browser_->UpdateDownloadShelfVisibility(visible); // SetDownloadShelfVisible can force-close the shelf, so make sure we lay out // everything correctly, as if the animation had finished. This doesn't // matter for showing the shelf, as the show animation will do it. SelectedTabToolbarSizeChanged(false); } bool BrowserView::IsDownloadShelfVisible() const { return download_shelf_.get() && download_shelf_->IsShowing(); } DownloadShelf* BrowserView::GetDownloadShelf() { if (!download_shelf_.get()) { download_shelf_.reset(new DownloadShelfView(browser_.get(), this)); download_shelf_->set_parent_owned(false); } return download_shelf_.get(); } void BrowserView::ShowReportBugDialog() { browser::ShowHtmlBugReportView(GetWindow(), browser_.get()); } void BrowserView::ShowClearBrowsingDataDialog() { browser::ShowClearBrowsingDataView(GetWindow()->GetNativeWindow(), browser_->profile()); } void BrowserView::ShowImportDialog() { browser::ShowImporterView(GetWidget(), browser_->profile()); } void BrowserView::ShowSearchEnginesDialog() { browser::ShowKeywordEditorView(browser_->profile()); } void BrowserView::ShowPasswordManager() { browser::ShowPasswordsExceptionsWindowView(browser_->profile()); } void BrowserView::ShowRepostFormWarningDialog(TabContents* tab_contents) { browser::ShowRepostFormWarningDialog(GetNativeHandle(), tab_contents); } void BrowserView::ShowContentSettingsWindow(ContentSettingsType content_type, Profile* profile) { browser::ShowContentSettingsWindow(GetNativeHandle(), content_type, profile); } void BrowserView::ShowCollectedCookiesDialog(TabContents* tab_contents) { browser::ShowCollectedCookiesDialog(GetNativeHandle(), tab_contents); } void BrowserView::ShowProfileErrorDialog(int message_id) { #if defined(OS_WIN) std::wstring title = l10n_util::GetString(IDS_PRODUCT_NAME); std::wstring message = l10n_util::GetString(message_id); win_util::MessageBox(GetNativeHandle(), message, title, MB_OK | MB_ICONWARNING | MB_TOPMOST); #elif defined(OS_LINUX) std::string title = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME); std::string message = l10n_util::GetStringUTF8(message_id); GtkWidget* dialog = gtk_message_dialog_new(GetNativeHandle(), static_cast<GtkDialogFlags>(0), GTK_MESSAGE_WARNING, GTK_BUTTONS_OK, "%s", message.c_str()); gtk_window_set_title(GTK_WINDOW(dialog), title.c_str()); g_signal_connect(dialog, "response", G_CALLBACK(gtk_widget_destroy), NULL); gtk_widget_show_all(dialog); #else NOTIMPLEMENTED(); #endif } void BrowserView::ShowThemeInstallBubble() { TabContents* tab_contents = browser_->GetSelectedTabContents(); if (!tab_contents) return; ThemeInstallBubbleView::Show(tab_contents); } void BrowserView::ConfirmBrowserCloseWithPendingDownloads() { DownloadInProgressConfirmDialogDelegate* delegate = new DownloadInProgressConfirmDialogDelegate(browser_.get()); views::Window::CreateChromeWindow(GetNativeHandle(), gfx::Rect(), delegate)->Show(); } void BrowserView::ShowHTMLDialog(HtmlDialogUIDelegate* delegate, gfx::NativeWindow parent_window) { // Default to using our window as the parent if the argument is not specified. gfx::NativeWindow parent = parent_window ? parent_window : GetNativeHandle(); #if defined(OS_CHROMEOS) parent = GetNormalBrowserWindowForBrowser(browser(), NULL); #endif // defined(OS_CHROMEOS) browser::ShowHtmlDialogView(parent, browser_.get()->profile(), delegate); } void BrowserView::ShowCreateShortcutsDialog(TabContents* tab_contents) { browser::ShowCreateShortcutsDialog(GetNativeHandle(), tab_contents); } void BrowserView::ContinueDraggingDetachedTab(const gfx::Rect& tab_bounds) { tabstrip_->SetDraggedTabBounds(0, tab_bounds); frame_->ContinueDraggingDetachedTab(); } void BrowserView::UserChangedTheme() { frame_->GetWindow()->FrameTypeChanged(); } int BrowserView::GetExtraRenderViewHeight() const { // Currently this is only used on linux. return 0; } void BrowserView::TabContentsFocused(TabContents* tab_contents) { contents_container_->TabContentsFocused(tab_contents); } void BrowserView::ShowPageInfo(Profile* profile, const GURL& url, const NavigationEntry::SSLStatus& ssl, bool show_history) { gfx::NativeWindow parent = GetWindow()->GetNativeWindow(); #if defined(OS_CHROMEOS) parent = GetNormalBrowserWindowForBrowser(browser(), profile); #endif // defined(OS_CHROMEOS) #if defined(OS_WINDOWS) browser::ShowPageInfoBubble(parent, profile, url, ssl, show_history); #else browser::ShowPageInfo(parent, profile, url, ssl, show_history); #endif } void BrowserView::ShowAppMenu() { toolbar_->app_menu()->Activate(); } bool BrowserView::PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) { if (event.type != WebKit::WebInputEvent::RawKeyDown) return false; #if defined(OS_WIN) // As Alt+F4 is the close-app keyboard shortcut, it needs processing // immediately. if (event.windowsKeyCode == base::VKEY_F4 && event.modifiers == NativeWebKeyboardEvent::AltKey) { DefWindowProc(event.os_event.hwnd, event.os_event.message, event.os_event.wParam, event.os_event.lParam); return true; } #endif views::FocusManager* focus_manager = GetFocusManager(); DCHECK(focus_manager); views::Accelerator accelerator( static_cast<base::KeyboardCode>(event.windowsKeyCode), (event.modifiers & NativeWebKeyboardEvent::ShiftKey) == NativeWebKeyboardEvent::ShiftKey, (event.modifiers & NativeWebKeyboardEvent::ControlKey) == NativeWebKeyboardEvent::ControlKey, (event.modifiers & NativeWebKeyboardEvent::AltKey) == NativeWebKeyboardEvent::AltKey); // We first find out the browser command associated to the |event|. // Then if the command is a reserved one, and should be processed // immediately according to the |event|, the command will be executed // immediately. Otherwise we just set |*is_keyboard_shortcut| properly and // return false. // This piece of code is based on the fact that accelerators registered // into the |focus_manager| may only trigger a browser command execution. // // Here we need to retrieve the command id (if any) associated to the // keyboard event. Instead of looking up the command id in the // |accelerator_table_| by ourselves, we block the command execution of // the |browser_| object then send the keyboard event to the // |focus_manager| as if we are activating an accelerator key. // Then we can retrieve the command id from the |browser_| object. browser_->SetBlockCommandExecution(true); focus_manager->ProcessAccelerator(accelerator); int id = browser_->GetLastBlockedCommand(NULL); browser_->SetBlockCommandExecution(false); if (id == -1) return false; if (browser_->IsReservedCommand(id)) { // TODO(suzhe): For Linux, should we send things like Ctrl+w, Ctrl+n // to the renderer first, just like what // BrowserWindowGtk::HandleKeyboardEvent() does? // Executing the command may cause |this| object to be destroyed. browser_->ExecuteCommand(id); return true; } DCHECK(is_keyboard_shortcut != NULL); *is_keyboard_shortcut = true; return false; } void BrowserView::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) { #if defined(OS_LINUX) views::Window* window = GetWidget()->GetWindow(); if (window && event.os_event && !event.skip_in_browser) static_cast<views::WindowGtk*>(window)->HandleKeyboardEvent(event.os_event); #else unhandled_keyboard_event_handler_.HandleKeyboardEvent(event, GetFocusManager()); #endif } // TODO(devint): http://b/issue?id=1117225 Cut, Copy, and Paste are always // enabled in the page menu regardless of whether the command will do // anything. When someone selects the menu item, we just act as if they hit // the keyboard shortcut for the command by sending the associated key press // to windows. The real fix to this bug is to disable the commands when they // won't do anything. We'll need something like an overall clipboard command // manager to do that. #if !defined(OS_MACOSX) void BrowserView::Cut() { ui_controls::SendKeyPress(GetNativeHandle(), base::VKEY_X, true, false, false, false); } void BrowserView::Copy() { ui_controls::SendKeyPress(GetNativeHandle(), base::VKEY_C, true, false, false, false); } void BrowserView::Paste() { ui_controls::SendKeyPress(GetNativeHandle(), base::VKEY_V, true, false, false, false); } #else // Mac versions. Not tested by antyhing yet; // don't assume written == works. void BrowserView::Cut() { ui_controls::SendKeyPress(GetNativeHandle(), base::VKEY_X, false, false, false, true); } void BrowserView::Copy() { ui_controls::SendKeyPress(GetNativeHandle(), base::VKEY_C, false, false, false, true); } void BrowserView::Paste() { ui_controls::SendKeyPress(GetNativeHandle(), base::VKEY_V, false, false, false, true); } #endif void BrowserView::ToggleTabStripMode() { InitTabStrip(browser_->tabstrip_model()); frame_->TabStripDisplayModeChanged(); } /////////////////////////////////////////////////////////////////////////////// // BrowserView, BrowserWindowTesting implementation: BookmarkBarView* BrowserView::GetBookmarkBarView() const { return bookmark_bar_view_.get(); } LocationBarView* BrowserView::GetLocationBarView() const { return toolbar_->location_bar(); } views::View* BrowserView::GetTabContentsContainerView() const { return contents_container_->GetFocusView(); } views::View* BrowserView::GetSidebarContainerView() const { if (!sidebar_container_) return NULL; return sidebar_container_->GetFocusView(); } ToolbarView* BrowserView::GetToolbarView() const { return toolbar_; } /////////////////////////////////////////////////////////////////////////////// // BrowserView, NotificationObserver implementation: void BrowserView::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::PREF_CHANGED: if (*Details<std::string>(details).ptr() == prefs::kShowBookmarkBar && MaybeShowBookmarkBar(browser_->GetSelectedTabContents())) { Layout(); } break; case NotificationType::MATCH_PREVIEW_TAB_CONTENTS_CREATED: if (Source<TabContents>(source).ptr() == browser_->GetSelectedTabContents()) { ShowMatchPreview(); } break; case NotificationType::TAB_CONTENTS_DESTROYED: { if (MatchPreview::IsEnabled()) { TabContents* selected_contents = browser_->GetSelectedTabContents(); if (selected_contents && selected_contents->match_preview()->preview_contents() == Source<TabContents>(source).ptr()) { HideMatchPreview(); } } break; } case NotificationType::SIDEBAR_CHANGED: if (Details<SidebarContainer>(details)->tab_contents() == browser_->GetSelectedTabContents()) { UpdateSidebar(); } break; default: NOTREACHED() << "Got a notification we didn't register for!"; break; } } /////////////////////////////////////////////////////////////////////////////// // BrowserView, TabStripModelObserver implementation: void BrowserView::TabDetachedAt(TabContents* contents, int index) { // We use index here rather than comparing |contents| because by this time // the model has already removed |contents| from its list, so // browser_->GetSelectedTabContents() will return NULL or something else. if (index == browser_->tabstrip_model()->selected_index()) { // We need to reset the current tab contents to NULL before it gets // freed. This is because the focus manager performs some operations // on the selected TabContents when it is removed. contents_container_->ChangeTabContents(NULL); infobar_container_->ChangeTabContents(NULL); UpdateSidebarForContents(NULL); UpdateDevToolsForContents(NULL); } } void BrowserView::TabDeselectedAt(TabContents* contents, int index) { // We do not store the focus when closing the tab to work-around bug 4633. // Some reports seem to show that the focus manager and/or focused view can // be garbage at that point, it is not clear why. if (!contents->is_being_destroyed()) contents->view()->StoreFocus(); } void BrowserView::TabSelectedAt(TabContents* old_contents, TabContents* new_contents, int index, bool user_gesture) { DCHECK(old_contents != new_contents); ProcessTabSelected(new_contents, true); } void BrowserView::TabReplacedAt(TabContents* old_contents, TabContents* new_contents, int index, TabStripModelObserver::TabReplaceType type) { if (type != TabStripModelObserver::REPLACE_MATCH_PREVIEW || index != browser_->tabstrip_model()->selected_index()) { return; } // Swap the 'active' and 'preview' and delete what was the active. contents_->MakePreviewContentsActiveContents(); TabContentsContainer* old_container = contents_container_; contents_container_ = preview_container_; old_container->ChangeTabContents(NULL); delete old_container; preview_container_ = NULL; // Update the UI for what was the preview contents and is now active. Pass in // false to ProcessTabSelected as new_contents is already parented correctly. ProcessTabSelected(new_contents, false); } void BrowserView::TabStripEmpty() { // Make sure all optional UI is removed before we are destroyed, otherwise // there will be consequences (since our view hierarchy will still have // references to freed views). UpdateUIForContents(NULL); } /////////////////////////////////////////////////////////////////////////////// // BrowserView, menus::SimpleMenuModel::Delegate implementation: bool BrowserView::IsCommandIdChecked(int command_id) const { // TODO(beng): encoding menu. // No items in our system menu are check-able. return false; } bool BrowserView::IsCommandIdEnabled(int command_id) const { return browser_->command_updater()->IsCommandEnabled(command_id); } bool BrowserView::GetAcceleratorForCommandId(int command_id, menus::Accelerator* accelerator) { // Let's let the ToolbarView own the canonical implementation of this method. return toolbar_->GetAcceleratorForCommandId(command_id, accelerator); } bool BrowserView::IsLabelForCommandIdDynamic(int command_id) const { return command_id == IDC_RESTORE_TAB; } string16 BrowserView::GetLabelForCommandId(int command_id) const { DCHECK(command_id == IDC_RESTORE_TAB); int string_id = IDS_RESTORE_TAB; if (IsCommandIdEnabled(command_id)) { TabRestoreService* trs = browser_->profile()->GetTabRestoreService(); if (trs && trs->entries().front()->type == TabRestoreService::WINDOW) string_id = IDS_RESTORE_WINDOW; } return l10n_util::GetStringUTF16(string_id); } void BrowserView::ExecuteCommand(int command_id) { browser_->ExecuteCommand(command_id); } /////////////////////////////////////////////////////////////////////////////// // BrowserView, views::WindowDelegate implementation: bool BrowserView::CanResize() const { return true; } bool BrowserView::CanMaximize() const { return true; } bool BrowserView::IsModal() const { return false; } std::wstring BrowserView::GetWindowTitle() const { return UTF16ToWideHack(browser_->GetWindowTitleForCurrentTab()); } views::View* BrowserView::GetInitiallyFocusedView() { // We set the frame not focus on creation so this should never be called. NOTREACHED(); return NULL; } bool BrowserView::ShouldShowWindowTitle() const { return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR); } SkBitmap BrowserView::GetWindowAppIcon() { if (browser_->type() & Browser::TYPE_APP) { TabContents* contents = browser_->GetSelectedTabContents(); if (contents && !contents->app_icon().isNull()) return contents->app_icon(); } return GetWindowIcon(); } SkBitmap BrowserView::GetWindowIcon() { if (browser_->type() & Browser::TYPE_APP) return browser_->GetCurrentPageIcon(); return SkBitmap(); } bool BrowserView::ShouldShowWindowIcon() const { return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR); } bool BrowserView::ExecuteWindowsCommand(int command_id) { // This function handles WM_SYSCOMMAND, WM_APPCOMMAND, and WM_COMMAND. // Translate WM_APPCOMMAND command ids into a command id that the browser // knows how to handle. int command_id_from_app_command = GetCommandIDForAppCommandID(command_id); if (command_id_from_app_command != -1) command_id = command_id_from_app_command; if (browser_->command_updater()->SupportsCommand(command_id)) { if (browser_->command_updater()->IsCommandEnabled(command_id)) browser_->ExecuteCommand(command_id); return true; } return false; } std::wstring BrowserView::GetWindowName() const { return UTF8ToWide(browser_->GetWindowPlacementKey()); } void BrowserView::SaveWindowPlacement(const gfx::Rect& bounds, bool maximized) { // If IsFullscreen() is true, we've just changed into fullscreen mode, and // we're catching the going-into-fullscreen sizing and positioning calls, // which we want to ignore. if (!IsFullscreen() && browser_->ShouldSaveWindowPlacement()) { WindowDelegate::SaveWindowPlacement(bounds, maximized); browser_->SaveWindowPlacement(bounds, maximized); } } bool BrowserView::GetSavedWindowBounds(gfx::Rect* bounds) const { *bounds = browser_->GetSavedWindowBounds(); if (browser_->type() & Browser::TYPE_POPUP) { // We are a popup window. The value passed in |bounds| represents two // pieces of information: // - the position of the window, in screen coordinates (outer position). // - the size of the content area (inner size). // We need to use these values to determine the appropriate size and // position of the resulting window. if (IsToolbarVisible()) { // If we're showing the toolbar, we need to adjust |*bounds| to include // its desired height, since the toolbar is considered part of the // window's client area as far as GetWindowBoundsForClientBounds is // concerned... bounds->set_height( bounds->height() + toolbar_->GetPreferredSize().height()); } gfx::Rect window_rect = frame_->GetWindow()->GetNonClientView()-> GetWindowBoundsForClientBounds(*bounds); window_rect.set_origin(bounds->origin()); // When we are given x/y coordinates of 0 on a created popup window, // assume none were given by the window.open() command. if (window_rect.x() == 0 && window_rect.y() == 0) { gfx::Size size = window_rect.size(); window_rect.set_origin(WindowSizer::GetDefaultPopupOrigin(size)); } *bounds = window_rect; } // We return true because we can _always_ locate reasonable bounds using the // WindowSizer, and we don't want to trigger the Window's built-in "size to // default" handling because the browser window has no default preferred // size. return true; } bool BrowserView::GetSavedMaximizedState(bool* maximized) const { *maximized = browser_->GetSavedMaximizedState(); return true; } views::View* BrowserView::GetContentsView() { return contents_container_; } views::ClientView* BrowserView::CreateClientView(views::Window* window) { set_window(window); return this; } /////////////////////////////////////////////////////////////////////////////// // BrowserView, views::ClientView overrides: bool BrowserView::CanClose() const { // You cannot close a frame for which there is an active originating drag // session. if (tabstrip_->IsDragSessionActive()) return false; // Give beforeunload handlers the chance to cancel the close before we hide // the window below. if (!browser_->ShouldCloseWindow()) return false; if (browser_->tabstrip_model()->HasNonPhantomTabs()) { // Tab strip isn't empty. Hide the frame (so it appears to have closed // immediately) and close all the tabs, allowing the renderers to shut // down. When the tab strip is empty we'll be called back again. frame_->GetWindow()->HideWindow(); browser_->OnWindowClosing(); return false; } // Empty TabStripModel, it's now safe to allow the Window to be closed. NotificationService::current()->Notify( NotificationType::WINDOW_CLOSED, Source<gfx::NativeWindow>(frame_->GetWindow()->GetNativeWindow()), NotificationService::NoDetails()); return true; } int BrowserView::NonClientHitTest(const gfx::Point& point) { #if defined(OS_WIN) // The following code is not in the LayoutManager because it's // independent of layout and also depends on the ResizeCorner which // is private. if (!frame_->GetWindow()->IsMaximized() && !frame_->GetWindow()->IsFullscreen()) { CRect client_rect; ::GetClientRect(frame_->GetWindow()->GetNativeWindow(), &client_rect); gfx::Size resize_corner_size = ResizeCorner::GetSize(); gfx::Rect resize_corner_rect(client_rect.right - resize_corner_size.width(), client_rect.bottom - resize_corner_size.height(), resize_corner_size.width(), resize_corner_size.height()); bool rtl_dir = base::i18n::IsRTL(); if (rtl_dir) resize_corner_rect.set_x(0); if (resize_corner_rect.Contains(point)) { if (rtl_dir) return HTBOTTOMLEFT; return HTBOTTOMRIGHT; } } #endif return GetBrowserViewLayout()->NonClientHitTest(point); } gfx::Size BrowserView::GetMinimumSize() { return GetBrowserViewLayout()->GetMinimumSize(); } /////////////////////////////////////////////////////////////////////////////// // BrowserView, protected void BrowserView::GetAccessibleToolbars( std::vector<AccessibleToolbarView*>* toolbars) { // This should be in the order of pane traversal of the toolbars using F6. // If one of these is invisible or has no focusable children, it will be // automatically skipped. toolbars->push_back(toolbar_); toolbars->push_back(bookmark_bar_view_.get()); } /////////////////////////////////////////////////////////////////////////////// // BrowserView, views::View overrides: std::string BrowserView::GetClassName() const { return kViewClassName; } void BrowserView::Layout() { if (ignore_layout_) return; if (GetLayoutManager()) { GetLayoutManager()->Layout(this); SchedulePaint(); #if defined(OS_WIN) // Send the margins of the "user-perceived content area" of this // browser window so AeroPeekManager can render a background-tab image in // the area. // TODO(pkasting) correct content inset?? if (aeropeek_manager_.get()) { gfx::Insets insets(GetFindBarBoundingBox().y() + 1, 0, 0, 0); aeropeek_manager_->SetContentInsets(insets); } #endif } } void BrowserView::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { if (is_add && child == this && GetWidget() && !initialized_) { Init(); initialized_ = true; } } void BrowserView::ChildPreferredSizeChanged(View* child) { Layout(); } bool BrowserView::GetAccessibleRole(AccessibilityTypes::Role* role) { DCHECK(role); *role = AccessibilityTypes::ROLE_CLIENT; return true; } void BrowserView::InfoBarSizeChanged(bool is_animating) { SelectedTabToolbarSizeChanged(is_animating); } views::LayoutManager* BrowserView::CreateLayoutManager() const { return new BrowserViewLayout; } void BrowserView::InitTabStrip(TabStripModel* model) { // Throw away the existing tabstrip if we're switching display modes. if (tabstrip_) { tabstrip_->GetParent()->RemoveChildView(tabstrip_); delete tabstrip_; } BrowserTabStripController* tabstrip_controller = new BrowserTabStripController(browser_.get(), model); if (UseVerticalTabs()) tabstrip_ = new SideTabStrip(tabstrip_controller); else tabstrip_ = new TabStrip(tabstrip_controller); tabstrip_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_TABSTRIP)); AddChildView(tabstrip_); tabstrip_controller->InitFromModel(tabstrip_); } /////////////////////////////////////////////////////////////////////////////// // BrowserView, private: void BrowserView::Init() { accessible_view_helper_.reset(new AccessibleViewHelper( this, browser_->profile())); SetLayoutManager(CreateLayoutManager()); // Stow a pointer to this object onto the window handle so that we can get // at it later when all we have is a native view. #if defined(OS_WIN) SetProp(GetWidget()->GetNativeView(), kBrowserViewKey, this); #else g_object_set_data(G_OBJECT(GetWidget()->GetNativeView()), kBrowserViewKey, this); #endif // Start a hung plugin window detector for this browser object (as long as // hang detection is not disabled). if (!CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableHangMonitor)) { InitHangMonitor(); } LoadAccelerators(); SetAccessibleName(l10n_util::GetString(IDS_PRODUCT_NAME)); InitTabStrip(browser_->tabstrip_model()); toolbar_ = new ToolbarView(browser_.get()); AddChildView(toolbar_); toolbar_->Init(browser_->profile()); toolbar_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_TOOLBAR)); infobar_container_ = new InfoBarContainer(this); AddChildView(infobar_container_); contents_container_ = new TabContentsContainer; contents_ = new ContentsContainer(this, contents_container_); SkColor bg_color = GetWidget()->GetThemeProvider()-> GetColor(BrowserThemeProvider::COLOR_TOOLBAR); bool sidebar_allowed = SidebarManager::IsSidebarAllowed(); if (sidebar_allowed) { sidebar_container_ = new TabContentsContainer; sidebar_container_->SetID(VIEW_ID_SIDE_BAR_CONTAINER); sidebar_container_->SetVisible(false); sidebar_split_ = new views::SingleSplitView( contents_, sidebar_container_, views::SingleSplitView::HORIZONTAL_SPLIT); sidebar_split_->SetID(VIEW_ID_SIDE_BAR_SPLIT); sidebar_split_-> SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_SIDE_BAR)); sidebar_split_->set_background( views::Background::CreateSolidBackground(bg_color)); } devtools_container_ = new TabContentsContainer; devtools_container_->SetID(VIEW_ID_DEV_TOOLS_DOCKED); devtools_container_->SetVisible(false); views::View* contents_view = contents_; if (sidebar_allowed) contents_view = sidebar_split_; contents_split_ = new views::SingleSplitView( contents_view, devtools_container_, views::SingleSplitView::VERTICAL_SPLIT); contents_split_->SetID(VIEW_ID_CONTENTS_SPLIT); contents_split_-> SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_WEB_CONTENTS)); contents_split_->set_background( views::Background::CreateSolidBackground(bg_color)); AddChildView(contents_split_); set_contents_view(contents_split_); status_bubble_.reset(new StatusBubbleViews(GetWidget())); #if defined(OS_WIN) InitSystemMenu(); // Create a custom JumpList and add it to an observer of TabRestoreService // so we can update the custom JumpList when a tab is added or removed. if (JumpList::Enabled()) { jumplist_.reset(new JumpList); jumplist_->AddObserver(browser_->profile()); } if (AeroPeekManager::Enabled()) { aeropeek_manager_.reset(new AeroPeekManager( frame_->GetWindow()->GetNativeWindow())); browser_->tabstrip_model()->AddObserver(aeropeek_manager_.get()); } #endif // We're now initialized and ready to process Layout requests. ignore_layout_ = false; registrar_.Add(this, NotificationType::MATCH_PREVIEW_TAB_CONTENTS_CREATED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED, NotificationService::AllSources()); } #if defined(OS_WIN) void BrowserView::InitSystemMenu() { system_menu_contents_.reset(new views::SystemMenuModel(this)); // We add the menu items in reverse order so that insertion_index never needs // to change. if (IsBrowserTypeNormal()) BuildSystemMenuForBrowserWindow(); else BuildSystemMenuForAppOrPopupWindow(browser_->type() == Browser::TYPE_APP); system_menu_.reset( new views::NativeMenuWin(system_menu_contents_.get(), frame_->GetWindow()->GetNativeWindow())); system_menu_->Rebuild(); } #endif BrowserViewLayout* BrowserView::GetBrowserViewLayout() const { return static_cast<BrowserViewLayout*>(GetLayoutManager()); } void BrowserView::LayoutStatusBubble(int top) { // In restored mode, the client area has a client edge between it and the // frame. int overlap = StatusBubbleViews::kShadowThickness + (IsMaximized() ? 0 : views::NonClientFrameView::kClientEdgeThickness); int x = -overlap; if (UseVerticalTabs() && IsTabStripVisible()) x += tabstrip_->bounds().right(); int height = status_bubble_->GetPreferredSize().height(); gfx::Point origin(x, top - height + overlap); ConvertPointToView(this, GetParent(), &origin); status_bubble_->SetBounds(origin.x(), origin.y(), width() / 3, height); } bool BrowserView::MaybeShowBookmarkBar(TabContents* contents) { views::View* new_bookmark_bar_view = NULL; if (browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR) && contents) { if (!bookmark_bar_view_.get()) { bookmark_bar_view_.reset(new BookmarkBarView(contents->profile(), browser_.get())); bookmark_bar_view_->set_parent_owned(false); bookmark_bar_view_->set_background( new BookmarkExtensionBackground(this, bookmark_bar_view_.get(), browser_.get())); } else { bookmark_bar_view_->SetProfile(contents->profile()); } bookmark_bar_view_->SetPageNavigator(contents); bookmark_bar_view_-> SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_BOOKMARKS)); new_bookmark_bar_view = bookmark_bar_view_.get(); } return UpdateChildViewAndLayout(new_bookmark_bar_view, &active_bookmark_bar_); } bool BrowserView::MaybeShowInfoBar(TabContents* contents) { // TODO(beng): Remove this function once the interface between // InfoBarContainer, DownloadShelfView and TabContents and this // view is sorted out. return true; } void BrowserView::UpdateSidebar() { UpdateSidebarForContents(GetSelectedTabContents()); Layout(); } void BrowserView::UpdateSidebarForContents(TabContents* tab_contents) { if (!sidebar_container_) return; // Happens when sidebar is not allowed. if (!SidebarManager::GetInstance()) return; // Happens only in tests. TabContents* sidebar_contents = NULL; if (tab_contents) { SidebarContainer* client_host = SidebarManager::GetInstance()-> GetActiveSidebarContainerFor(tab_contents); if (client_host) sidebar_contents = client_host->sidebar_contents(); } bool visible = NULL != sidebar_contents && browser_->SupportsWindowFeature(Browser::FEATURE_SIDEBAR); bool should_show = visible && !sidebar_container_->IsVisible(); bool should_hide = !visible && sidebar_container_->IsVisible(); // Update sidebar content. TabContents* old_contents = sidebar_container_->tab_contents(); sidebar_container_->ChangeTabContents(sidebar_contents); SidebarManager::GetInstance()-> NotifyStateChanges(old_contents, sidebar_contents); // Update sidebar UI width. if (should_show) { // Restore split offset. int sidebar_width = g_browser_process->local_state()->GetInteger( prefs::kExtensionSidebarWidth); if (sidebar_width < 0) { // Initial load, set to default value. sidebar_width = sidebar_split_->width() / 7; } // Make sure user can see both panes. int min_sidebar_width = sidebar_split_->GetMinimumSize().width(); sidebar_width = std::min(sidebar_split_->width() - min_sidebar_width, std::max(min_sidebar_width, sidebar_width)); sidebar_split_->set_divider_offset( sidebar_split_->width() - sidebar_width); sidebar_container_->SetVisible(true); sidebar_split_->Layout(); } else if (should_hide) { // Store split offset when hiding sidebar only. g_browser_process->local_state()->SetInteger( prefs::kExtensionSidebarWidth, sidebar_split_->width() - sidebar_split_->divider_offset()); sidebar_container_->SetVisible(false); sidebar_split_->Layout(); } } void BrowserView::UpdateDevToolsForContents(TabContents* tab_contents) { TabContents* devtools_contents = DevToolsWindow::GetDevToolsContents(tab_contents); bool should_show = devtools_contents && !devtools_container_->IsVisible(); bool should_hide = !devtools_contents && devtools_container_->IsVisible(); devtools_container_->ChangeTabContents(devtools_contents); if (should_show) { if (!devtools_focus_tracker_.get()) { // Install devtools focus tracker when dev tools window is shown for the // first time. devtools_focus_tracker_.reset( new views::ExternalFocusTracker(devtools_container_, GetFocusManager())); } // Restore split offset. int split_offset = g_browser_process->local_state()->GetInteger( prefs::kDevToolsSplitLocation); if (split_offset == -1) { // Initial load, set to default value. split_offset = 2 * contents_split_->height() / 3; } // Make sure user can see both panes. int min_split_size = contents_split_->height() / 10; split_offset = std::min(contents_split_->height() - min_split_size, std::max(min_split_size, split_offset)); contents_split_->set_divider_offset(split_offset); devtools_container_->SetVisible(true); contents_split_->Layout(); } else if (should_hide) { // Store split offset when hiding devtools window only. g_browser_process->local_state()->SetInteger( prefs::kDevToolsSplitLocation, contents_split_->divider_offset()); // Restore focus to the last focused view when hiding devtools window. devtools_focus_tracker_->FocusLastFocusedExternalView(); devtools_container_->SetVisible(false); contents_split_->Layout(); } } void BrowserView::UpdateUIForContents(TabContents* contents) { bool needs_layout = MaybeShowBookmarkBar(contents); needs_layout |= MaybeShowInfoBar(contents); if (needs_layout) Layout(); } bool BrowserView::UpdateChildViewAndLayout(views::View* new_view, views::View** old_view) { DCHECK(old_view); if (*old_view == new_view) { // The views haven't changed, if the views pref changed schedule a layout. if (new_view) { if (new_view->GetPreferredSize().height() != new_view->height()) return true; } return false; } // The views differ, and one may be null (but not both). Remove the old // view (if it non-null), and add the new one (if it is non-null). If the // height has changed, schedule a layout, otherwise reuse the existing // bounds to avoid scheduling a layout. int current_height = 0; if (*old_view) { current_height = (*old_view)->height(); RemoveChildView(*old_view); } int new_height = 0; if (new_view) { new_height = new_view->GetPreferredSize().height(); AddChildView(new_view); } bool changed = false; if (new_height != current_height) { changed = true; } else if (new_view && *old_view) { // The view changed, but the new view wants the same size, give it the // bounds of the last view and have it repaint. new_view->SetBounds((*old_view)->bounds()); new_view->SchedulePaint(); } else if (new_view) { DCHECK_EQ(0, new_height); // The heights are the same, but the old view is null. This only happens // when the height is zero. Zero out the bounds. new_view->SetBounds(0, 0, 0, 0); } *old_view = new_view; return changed; } void BrowserView::ProcessFullscreen(bool fullscreen) { // Reduce jankiness during the following position changes by: // * Hiding the window until it's in the final position // * Ignoring all intervening Layout() calls, which resize the webpage and // thus are slow and look ugly ignore_layout_ = true; LocationBarView* location_bar = toolbar_->location_bar(); #if defined(OS_WIN) AutocompleteEditViewWin* edit_view = static_cast<AutocompleteEditViewWin*>(location_bar->location_entry()); #endif if (!fullscreen) { // Hide the fullscreen bubble as soon as possible, since the mode toggle can // take enough time for the user to notice. fullscreen_bubble_.reset(); } else { // Move focus out of the location bar if necessary. views::FocusManager* focus_manager = GetFocusManager(); DCHECK(focus_manager); if (focus_manager->GetFocusedView() == location_bar) focus_manager->ClearFocus(); #if defined(OS_WIN) // If we don't hide the edit and force it to not show until we come out of // fullscreen, then if the user was on the New Tab Page, the edit contents // will appear atop the web contents once we go into fullscreen mode. This // has something to do with how we move the main window while it's hidden; // if we don't hide the main window below, we don't get this problem. edit_view->set_force_hidden(true); ShowWindow(edit_view->m_hWnd, SW_HIDE); #endif } #if defined(OS_WIN) frame_->GetWindow()->PushForceHidden(); #endif // Notify bookmark bar, so it can set itself to the appropriate drawing state. if (bookmark_bar_view_.get()) bookmark_bar_view_->OnFullscreenToggled(fullscreen); // Toggle fullscreen mode. #if defined(OS_WIN) frame_->GetWindow()->SetFullscreen(fullscreen); #endif // No need to invoke SetFullscreen for linux as this code is executed // once we're already fullscreen on linux. #if defined(OS_LINUX) // Updating of commands for fullscreen mode is called from SetFullScreen on // Wndows (see just above), but for ChromeOS, this method (ProcessFullScreen) // is called after full screen has happened successfully (via GTK's // window-state-change event), so we have to update commands here. browser_->UpdateCommandsForFullscreenMode(fullscreen); #endif if (fullscreen) { bool is_kiosk = CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode); if (!is_kiosk) { fullscreen_bubble_.reset(new FullscreenExitBubble(GetWidget(), browser_.get())); } } else { #if defined(OS_WIN) // Show the edit again since we're no longer in fullscreen mode. edit_view->set_force_hidden(false); ShowWindow(edit_view->m_hWnd, SW_SHOW); #endif } // Undo our anti-jankiness hacks and force the window to relayout now that // it's in its final position. ignore_layout_ = false; Layout(); #if defined(OS_WIN) frame_->GetWindow()->PopForceHidden(); #endif } void BrowserView::LoadAccelerators() { #if defined(OS_WIN) HACCEL accelerator_table = AtlLoadAccelerators(IDR_MAINFRAME); DCHECK(accelerator_table); // We have to copy the table to access its contents. int count = CopyAcceleratorTable(accelerator_table, 0, 0); if (count == 0) { // Nothing to do in that case. return; } ACCEL* accelerators = static_cast<ACCEL*>(malloc(sizeof(ACCEL) * count)); CopyAcceleratorTable(accelerator_table, accelerators, count); views::FocusManager* focus_manager = GetFocusManager(); DCHECK(focus_manager); // Let's fill our own accelerator table. for (int i = 0; i < count; ++i) { bool alt_down = (accelerators[i].fVirt & FALT) == FALT; bool ctrl_down = (accelerators[i].fVirt & FCONTROL) == FCONTROL; bool shift_down = (accelerators[i].fVirt & FSHIFT) == FSHIFT; views::Accelerator accelerator( static_cast<base::KeyboardCode>(accelerators[i].key), shift_down, ctrl_down, alt_down); accelerator_table_[accelerator] = accelerators[i].cmd; // Also register with the focus manager. focus_manager->RegisterAccelerator(accelerator, this); } // We don't need the Windows accelerator table anymore. free(accelerators); #else views::FocusManager* focus_manager = GetFocusManager(); DCHECK(focus_manager); // Let's fill our own accelerator table. for (size_t i = 0; i < browser::kAcceleratorMapLength; ++i) { views::Accelerator accelerator(browser::kAcceleratorMap[i].keycode, browser::kAcceleratorMap[i].shift_pressed, browser::kAcceleratorMap[i].ctrl_pressed, browser::kAcceleratorMap[i].alt_pressed); accelerator_table_[accelerator] = browser::kAcceleratorMap[i].command_id; // Also register with the focus manager. focus_manager->RegisterAccelerator(accelerator, this); } #endif } #if defined(OS_WIN) void BrowserView::BuildSystemMenuForBrowserWindow() { system_menu_contents_->AddSeparator(); system_menu_contents_->AddItemWithStringId(IDC_TASK_MANAGER, IDS_TASK_MANAGER); system_menu_contents_->AddSeparator(); system_menu_contents_->AddItemWithStringId(IDC_RESTORE_TAB, IDS_RESTORE_TAB); system_menu_contents_->AddItemWithStringId(IDC_NEW_TAB, IDS_NEW_TAB); // If it's a regular browser window with tabs, we don't add any more items, // since it already has menus (Page, Chrome). } void BrowserView::BuildSystemMenuForAppOrPopupWindow(bool is_app) { if (is_app) { system_menu_contents_->AddSeparator(); system_menu_contents_->AddItemWithStringId(IDC_TASK_MANAGER, IDS_TASK_MANAGER); } system_menu_contents_->AddSeparator(); encoding_menu_contents_.reset(new EncodingMenuModel(browser_.get())); system_menu_contents_->AddSubMenuWithStringId(IDC_ENCODING_MENU, IDS_ENCODING_MENU, encoding_menu_contents_.get()); zoom_menu_contents_.reset(new ZoomMenuModel(this)); system_menu_contents_->AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_ZOOM_MENU, zoom_menu_contents_.get()); system_menu_contents_->AddItemWithStringId(IDC_PRINT, IDS_PRINT); system_menu_contents_->AddItemWithStringId(IDC_FIND, IDS_FIND); system_menu_contents_->AddSeparator(); system_menu_contents_->AddItemWithStringId(IDC_PASTE, IDS_PASTE); system_menu_contents_->AddItemWithStringId(IDC_COPY, IDS_COPY); system_menu_contents_->AddItemWithStringId(IDC_CUT, IDS_CUT); system_menu_contents_->AddSeparator(); if (is_app) { system_menu_contents_->AddItemWithStringId(IDC_NEW_TAB, IDS_APP_MENU_NEW_WEB_PAGE); } else { system_menu_contents_->AddItemWithStringId(IDC_SHOW_AS_TAB, IDS_SHOW_AS_TAB); } system_menu_contents_->AddItemWithStringId(IDC_COPY_URL, IDS_APP_MENU_COPY_URL); system_menu_contents_->AddSeparator(); system_menu_contents_->AddItemWithStringId(IDC_RELOAD, IDS_APP_MENU_RELOAD); system_menu_contents_->AddItemWithStringId(IDC_FORWARD, IDS_CONTENT_CONTEXT_FORWARD); system_menu_contents_->AddItemWithStringId(IDC_BACK, IDS_CONTENT_CONTEXT_BACK); } #endif int BrowserView::GetCommandIDForAppCommandID(int app_command_id) const { #if defined(OS_WIN) switch (app_command_id) { // NOTE: The order here matches the APPCOMMAND declaration order in the // Windows headers. case APPCOMMAND_BROWSER_BACKWARD: return IDC_BACK; case APPCOMMAND_BROWSER_FORWARD: return IDC_FORWARD; case APPCOMMAND_BROWSER_REFRESH: return IDC_RELOAD; case APPCOMMAND_BROWSER_HOME: return IDC_HOME; case APPCOMMAND_BROWSER_STOP: return IDC_STOP; case APPCOMMAND_BROWSER_SEARCH: return IDC_FOCUS_SEARCH; case APPCOMMAND_HELP: return IDC_HELP_PAGE; case APPCOMMAND_NEW: return IDC_NEW_TAB; case APPCOMMAND_OPEN: return IDC_OPEN_FILE; case APPCOMMAND_CLOSE: return IDC_CLOSE_TAB; case APPCOMMAND_SAVE: return IDC_SAVE_PAGE; case APPCOMMAND_PRINT: return IDC_PRINT; case APPCOMMAND_COPY: return IDC_COPY; case APPCOMMAND_CUT: return IDC_CUT; case APPCOMMAND_PASTE: return IDC_PASTE; // TODO(pkasting): http://b/1113069 Handle these. case APPCOMMAND_UNDO: case APPCOMMAND_REDO: case APPCOMMAND_SPELL_CHECK: default: return -1; } #else // App commands are Windows-specific so there's nothing to do here. return -1; #endif } void BrowserView::LoadingAnimationCallback() { if (browser_->type() == Browser::TYPE_NORMAL) { // Loading animations are shown in the tab for tabbed windows. We check the // browser type instead of calling IsTabStripVisible() because the latter // will return false for fullscreen windows, but we still need to update // their animations (so that when they come out of fullscreen mode they'll // be correct). tabstrip_->UpdateLoadingAnimations(); } else if (ShouldShowWindowIcon()) { // ... or in the window icon area for popups and app windows. TabContents* tab_contents = browser_->GetSelectedTabContents(); // GetSelectedTabContents can return NULL for example under Purify when // the animations are running slowly and this function is called on a timer // through LoadingAnimationCallback. frame_->UpdateThrobber(tab_contents && tab_contents->is_loading()); } } void BrowserView::InitHangMonitor() { #if defined(OS_WIN) PrefService* pref_service = g_browser_process->local_state(); if (!pref_service) return; int plugin_message_response_timeout = pref_service->GetInteger(prefs::kPluginMessageResponseTimeout); int hung_plugin_detect_freq = pref_service->GetInteger(prefs::kHungPluginDetectFrequency); if ((hung_plugin_detect_freq > 0) && hung_window_detector_.Initialize(GetWidget()->GetNativeView(), plugin_message_response_timeout)) { ticker_.set_tick_interval(hung_plugin_detect_freq); ticker_.RegisterTickHandler(&hung_window_detector_); ticker_.Start(); pref_service->SetInteger(prefs::kPluginMessageResponseTimeout, plugin_message_response_timeout); pref_service->SetInteger(prefs::kHungPluginDetectFrequency, hung_plugin_detect_freq); } #endif } void BrowserView::ShowMatchPreview() { if (!preview_container_) preview_container_ = new TabContentsContainer(); contents_->SetPreview(preview_container_); preview_container_->ChangeTabContents( browser_->GetSelectedTabContents()->match_preview()->preview_contents()); } void BrowserView::HideMatchPreview() { if (!preview_container_) return; // The contents must be changed before SetPreview is invoked. preview_container_->ChangeTabContents(NULL); contents_->SetPreview(NULL); delete preview_container_; preview_container_ = NULL; } void BrowserView::ProcessTabSelected(TabContents* new_contents, bool change_tab_contents) { // Update various elements that are interested in knowing the current // TabContents. // When we toggle the NTP floating bookmarks bar and/or the info bar, // we don't want any TabContents to be attached, so that we // avoid an unnecessary resize and re-layout of a TabContents. if (change_tab_contents) contents_container_->ChangeTabContents(NULL); infobar_container_->ChangeTabContents(new_contents); UpdateUIForContents(new_contents); if (change_tab_contents) contents_container_->ChangeTabContents(new_contents); UpdateSidebarForContents(new_contents); UpdateDevToolsForContents(new_contents); // TODO(beng): This should be called automatically by ChangeTabContents, but I // am striving for parity now rather than cleanliness. This is // required to make features like Duplicate Tab, Undo Close Tab, // etc not result in sad tab. new_contents->DidBecomeSelected(); if (BrowserList::GetLastActive() == browser_ && !browser_->tabstrip_model()->closing_all() && GetWindow()->IsVisible()) { // We only restore focus if our window is visible, to avoid invoking blur // handlers when we are eventually shown. new_contents->view()->RestoreFocus(); } // Update all the UI bits. UpdateTitleBar(); UpdateToolbar(new_contents, true); UpdateUIForContents(new_contents); } #if !defined(OS_CHROMEOS) // static BrowserWindow* BrowserWindow::CreateBrowserWindow(Browser* browser) { // Create the view and the frame. The frame will attach itself via the view // so we don't need to do anything with the pointer. BrowserView* view = new BrowserView(browser); BrowserFrame::Create(view, browser->profile()); view->GetWindow()->GetNonClientView()-> SetAccessibleName(l10n_util::GetString(IDS_PRODUCT_NAME)); return view; } #endif // static FindBar* BrowserWindow::CreateFindBar(Browser* browser) { return browser::CreateFindBar(static_cast<BrowserView*>(browser->window())); }
#include "npc.h" #include "room.h" #include <iostream> Npc::Npc(const char* npcName, const char* npcDescription, Room* loc) : Creature(npcName, npcDescription, loc) { name = npcName; description = npcDescription; entityType = npc; location = loc; alive = true; aware = false; } Npc::~Npc() { } void Npc::checkShip(const Room* playerLocation) { if ((playerLocation->name == "Poopdeck" || playerLocation->name == "Main deck") && !aware) { aware = true; std::cout << std::endl; std::cout << "---------------------------------------------" << std::endl; std::cout << "Slinger, The Lookout: HEY YOU! What are you doing there? Climb to the crow's nest NOW!!" << std::endl; std::cout << "---------------------------------------------" << std::endl; std::cout << ">"; } } void Npc::getMad(const Room* playerLocation) { std::cout << std::endl; std::cout << "---------------------------------------------" << std::endl; if(playerLocation != location) { switch (npcMood) { case CALM: std::cout << "Slinger, The Lookout: I told you to climb here right now. I don't like to repeat things, dog. MOVE!!" << std::endl; npcMood = MAD; break; case MAD: std::cout << "Slinger, The Lookout: Do you thing that beeing in this ship for a month gives you permision to question my orders? Don't get me mad, son..." << std::endl; npcMood = VIOLENT; break; case VIOLENT: std::cout << "Slinger, The Lookout: Your choice. This is your last oportunity. (You hear the sound of a musket beeing loaded)" << std::endl; npcMood = KILL; break; case KILL: std::cout << "BANG!!" << std::endl; break; } } else { std::cout << "Slinger, The Lookout: Bla bla bla... (Boring complains about beeing out of bed... Seems like you only have one way to go)" << std::endl; } std::cout << "---------------------------------------------" << std::endl; std::cout << ">"; } Enemy NPC now changes mood when stopping by his side #include "npc.h" #include "room.h" #include <iostream> Npc::Npc(const char* npcName, const char* npcDescription, Room* loc) : Creature(npcName, npcDescription, loc) { name = npcName; description = npcDescription; entityType = npc; location = loc; alive = true; aware = false; } Npc::~Npc() { } void Npc::checkShip(const Room* playerLocation) { if ((playerLocation->name == "Poopdeck" || playerLocation->name == "Main deck") && !aware) { aware = true; std::cout << std::endl; std::cout << "---------------------------------------------" << std::endl; std::cout << "Slinger, The Lookout: HEY YOU! What are you doing there? Climb to the crow's nest NOW!!" << std::endl; std::cout << "---------------------------------------------" << std::endl; std::cout << ">"; } } void Npc::getMad(const Room* playerLocation) { std::cout << std::endl; std::cout << "---------------------------------------------" << std::endl; if(playerLocation != location) { switch (npcMood) { case CALM: std::cout << "Slinger, The Lookout: I told you to climb here right now. I don't like to repeat things, dog. MOVE!!" << std::endl; npcMood = MAD; break; case MAD: std::cout << "Slinger, The Lookout: Do you thing that beeing in this ship for a month gives you permision to question my orders? Don't get me mad, son..." << std::endl; npcMood = VIOLENT; break; case VIOLENT: std::cout << "Slinger, The Lookout: Your choice. This is your last oportunity. (You hear the sound of a musket beeing loaded)" << std::endl; npcMood = KILL; break; case KILL: std::cout << "BANG!!" << std::endl; break; } } else { std::cout << "Slinger, The Lookout: Bla bla bla... (Boring complains about beeing out of bed... Seems like you only have one way to go)" << std::endl; if (npcMood == VIOLENT) npcMood = MAD; else if (npcMood == MAD) npcMood = CALM; } std::cout << "---------------------------------------------" << std::endl; std::cout << ">"; }
#include "StdAfx.h" #include "ArwDecoder.h" #include <arpa/inet.h> /* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post Copyright (C) 2014 Pedro Côrte-Real This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ #define get2LE(data,pos) ((((ushort16)(data)[pos+1]) << 8) | ((ushort16)(data)[pos])) #define get4BE(data,pos) ((((uint32)(data)[pos]) << 24) | (((uint32)(data)[pos+1]) << 16) | \ (((uint32)(data)[pos+2]) << 8) | ((uint32)(data)[pos+3])) #define get4LE(data,pos) ((((uint32)(data)[pos+3]) << 24) | (((uint32)(data)[pos+2]) << 16) | \ (((uint32)(data)[pos+1]) << 8) | ((uint32)(data)[pos])) namespace RawSpeed { ArwDecoder::ArwDecoder(TiffIFD *rootIFD, FileMap* file) : RawDecoder(file), mRootIFD(rootIFD) { mShiftDownScale = 0; decoderVersion = 1; } ArwDecoder::~ArwDecoder(void) { if (mRootIFD) delete mRootIFD; mRootIFD = NULL; } RawImage ArwDecoder::decodeRawInternal() { vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(STRIPOFFSETS); if (data.empty()) { TiffEntry *model = mRootIFD->getEntryRecursive(MODEL); if (model && model->getString() == "DSLR-A100") { // We've caught the elusive A100 in the wild, a transitional format // between the simple sanity of the MRW custom format and the wordly // wonderfullness of the Tiff-based ARW format, let's shoot from the hip uint32 off = mRootIFD->getEntryRecursive(SUBIFDS)->getInt(); uint32 width = 3881; uint32 height = 2608; mRaw->dim = iPoint2D(width, height); mRaw->createData(); ByteStream input(mFile->getData(off),mFile->getSize()-off); try { DecodeARW(input, width, height); } catch (IOException &e) { mRaw->setError(e.what()); // Let's ignore it, it may have delivered somewhat useful data. } // Set the whitebalance if (mRootIFD->hasEntryRecursive(DNGPRIVATEDATA)) { TiffEntry *priv = mRootIFD->getEntryRecursive(DNGPRIVATEDATA); const uchar8 *offdata = priv->getData(); uint32 off = (uint32)offdata[3] << 24 | (uint32)offdata[2] << 16 | (uint32)offdata[1] << 8 | (uint32)offdata[0]; const unsigned char* data = mFile->getData(off); uint32 length = mFile->getSize()-off; uint32 currpos = 8; while (currpos < length) { uint32 tag = get4BE(data,currpos); uint32 len = get4LE(data,currpos+4); if (tag == 0x574247) { /* WBG */ ushort16 tmp[4]; for(uint32 i=0; i<4; i++) tmp[i] = get2LE(data, currpos+12+i*2); mRaw->metadata.wbCoeffs[0] = (float) tmp[0]; mRaw->metadata.wbCoeffs[1] = (float) tmp[1]; mRaw->metadata.wbCoeffs[2] = (float) tmp[3]; break; } currpos += MAX(len+8,1); // MAX(,1) to make sure we make progress } } return mRaw; } else { ThrowRDE("ARW Decoder: No image data found"); } } // All cameras except the A100 should work with the same WB code so get it now GetWB(); TiffIFD* raw = data[0]; int compression = raw->getEntry(COMPRESSION)->getInt(); if (1 == compression) { // This is probably the SR2 format, let's pass it on try { DecodeSR2(raw); } catch (IOException &e) { mRaw->setError(e.what()); } return mRaw; } if (32767 != compression) ThrowRDE("ARW Decoder: Unsupported compression"); TiffEntry *offsets = raw->getEntry(STRIPOFFSETS); TiffEntry *counts = raw->getEntry(STRIPBYTECOUNTS); if (offsets->count != 1) { ThrowRDE("ARW Decoder: Multiple Strips found: %u", offsets->count); } if (counts->count != offsets->count) { ThrowRDE("ARW Decoder: Byte count number does not match strip size: count:%u, strips:%u ", counts->count, offsets->count); } uint32 width = raw->getEntry(IMAGEWIDTH)->getInt(); uint32 height = raw->getEntry(IMAGELENGTH)->getInt(); uint32 bitPerPixel = raw->getEntry(BITSPERSAMPLE)->getInt(); // Sony E-550 marks compressed 8bpp ARW with 12 bit per pixel // this makes the compression detect it as a ARW v1. // This camera has however another MAKER entry, so we MAY be able // to detect it this way in the future. data = mRootIFD->getIFDsWithTag(MAKE); if (data.size() > 1) { for (uint32 i = 0; i < data.size(); i++) { string make = data[i]->getEntry(MAKE)->getString(); /* Check for maker "SONY" without spaces */ if (!make.compare("SONY")) bitPerPixel = 8; } } bool arw1 = counts->getInt() * 8 != width * height * bitPerPixel; if (arw1) height += 8; mRaw->dim = iPoint2D(width, height); mRaw->createData(); ushort16 curve[0x4001]; const ushort16* c = raw->getEntry(SONY_CURVE)->getShortArray(); uint32 sony_curve[] = { 0, 0, 0, 0, 0, 4095 }; for (uint32 i = 0; i < 4; i++) sony_curve[i+1] = (c[i] >> 2) & 0xfff; for (uint32 i = 0; i < 0x4001; i++) curve[i] = i; for (uint32 i = 0; i < 5; i++) for (uint32 j = sony_curve[i] + 1; j <= sony_curve[i+1]; j++) curve[j] = curve[j-1] + (1 << i); if (!uncorrectedRawValues) mRaw->setTable(curve, 0x4000, true); uint32 c2 = counts->getInt(); uint32 off = offsets->getInt(); if (!mFile->isValid(off)) ThrowRDE("Sony ARW decoder: Data offset after EOF, file probably truncated"); if (!mFile->isValid(off + c2)) c2 = mFile->getSize() - off; ByteStream input(mFile->getData(off), c2); try { if (arw1) DecodeARW(input, width, height); else DecodeARW2(input, width, height, bitPerPixel); } catch (IOException &e) { mRaw->setError(e.what()); // Let's ignore it, it may have delivered somewhat useful data. } // Set the table, if it should be needed later. if (uncorrectedRawValues) { mRaw->setTable(curve, 0x4000, false); } else { mRaw->setTable(NULL); } return mRaw; } void ArwDecoder::DecodeSR2(TiffIFD* raw) { uint32 width = raw->getEntry(IMAGEWIDTH)->getInt(); uint32 height = raw->getEntry(IMAGELENGTH)->getInt(); uint32 off = raw->getEntry(STRIPOFFSETS)->getInt(); uint32 c2 = raw->getEntry(STRIPBYTECOUNTS)->getInt(); mRaw->dim = iPoint2D(width, height); mRaw->createData(); ByteStream input(mFile->getData(off), c2); Decode14BitRawBEunpacked(input, width, height); } void ArwDecoder::DecodeARW(ByteStream &input, uint32 w, uint32 h) { BitPumpMSB bits(&input); uchar8* data = mRaw->getData(); ushort16* dest = (ushort16*) & data[0]; uint32 pitch = mRaw->pitch / sizeof(ushort16); int sum = 0; for (uint32 x = w; x--;) for (uint32 y = 0; y < h + 1; y += 2) { bits.checkPos(); bits.fill(); if (y == h) y = 1; uint32 len = 4 - bits.getBitsNoFill(2); if (len == 3 && bits.getBitNoFill()) len = 0; if (len == 4) while (len < 17 && !bits.getBitNoFill()) len++; int diff = bits.getBits(len); if (len && (diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; sum += diff; _ASSERTE(!(sum >> 12)); if (y < h) dest[x+y*pitch] = sum; } } void ArwDecoder::DecodeARW2(ByteStream &input, uint32 w, uint32 h, uint32 bpp) { if (bpp == 8) { in = &input; this->startThreads(); return; } // End bpp = 8 if (bpp == 12) { uchar8* data = mRaw->getData(); uint32 pitch = mRaw->pitch; const uchar8 *in = input.getData(); if (input.getRemainSize() < (w * 3 / 2)) ThrowRDE("Sony Decoder: Image data section too small, file probably truncated"); if (input.getRemainSize() < (w*h*3 / 2)) h = input.getRemainSize() / (w * 3 / 2) - 1; for (uint32 y = 0; y < h; y++) { ushort16* dest = (ushort16*) & data[y*pitch]; for (uint32 x = 0 ; x < w; x += 2) { uint32 g1 = *in++; uint32 g2 = *in++; dest[x] = (g1 | ((g2 & 0xf) << 8)); uint32 g3 = *in++; dest[x+1] = ((g2 >> 4) | (g3 << 4)); } } // Shift scales, since black and white are the same as compressed precision mShiftDownScale = 2; return; } ThrowRDE("Unsupported bit depth"); } void ArwDecoder::checkSupportInternal(CameraMetaData *meta) { vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL); if (data.empty()) ThrowRDE("ARW Support check: Model name found"); string make = data[0]->getEntry(MAKE)->getString(); string model = data[0]->getEntry(MODEL)->getString(); this->checkCameraSupported(meta, make, model, ""); } void ArwDecoder::decodeMetaDataInternal(CameraMetaData *meta) { //Default int iso = 0; mRaw->cfa.setCFA(iPoint2D(2,2), CFA_RED, CFA_GREEN, CFA_GREEN2, CFA_BLUE); vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL); if (data.empty()) ThrowRDE("ARW Meta Decoder: Model name found"); if (!data[0]->hasEntry(MAKE)) ThrowRDE("ARW Decoder: Make name not found"); string make = data[0]->getEntry(MAKE)->getString(); string model = data[0]->getEntry(MODEL)->getString(); if (mRootIFD->hasEntryRecursive(ISOSPEEDRATINGS)) iso = mRootIFD->getEntryRecursive(ISOSPEEDRATINGS)->getInt(); setMetaData(meta, make, model, "", iso); mRaw->whitePoint >>= mShiftDownScale; mRaw->blackLevel >>= mShiftDownScale; } void ArwDecoder::GetWB() { // Set the whitebalance if (mRootIFD->hasEntryRecursive(DNGPRIVATEDATA)) { TiffEntry *priv = mRootIFD->getEntryRecursive(DNGPRIVATEDATA); const uchar8 *data = priv->getData(); uint32 off = (uint32)data[3] << 24 | (uint32)data[2] << 16 | (uint32)data[1] << 8 | (uint32)data[0]; TiffIFD *sony_private; if (mRootIFD->endian == getHostEndianness()) sony_private = new TiffIFD(mFile, off); else sony_private = new TiffIFDBE(mFile, off); TiffEntry *sony_offset = sony_private->getEntryRecursive(SONY_OFFSET); TiffEntry *sony_length = sony_private->getEntryRecursive(SONY_LENGTH); TiffEntry *sony_key = sony_private->getEntryRecursive(SONY_KEY); if(!sony_offset || !sony_length || !sony_key || sony_key->count != 4) ThrowRDE("ARW: couldn't find the correct metadata for WB decoding"); off = sony_offset->getInt(); uint32 len = sony_length->getInt(); data = sony_key->getData(); uint32 key = (uint32)data[3] << 24 | (uint32)data[2] << 16 | (uint32)data[1] << 8 | (uint32)data[0]; if (sony_private) delete(sony_private); if (mFile->getSize() < off+len) ThrowRDE("ARW: Sony WB block out of range, corrupted file?"); uint32 *ifp_data = (uint32 *) mFile->getDataWrt(off); uint32 pad[128]; uint32 p; // Initialize the decryption for (p=0; p < 4; p++) pad[p] = key = key * 48828125 + 1; pad[3] = pad[3] << 1 | (pad[0]^pad[2]) >> 31; for (p=4; p < 127; p++) pad[p] = (pad[p-4]^pad[p-2]) << 1 | (pad[p-3]^pad[p-1]) >> 31; for (p=0; p < 127; p++) pad[p] = htonl(pad[p]); pad[127] = 0; // Decrypt the buffer in place uint32 count = len/4; while (count--) *ifp_data++ ^= (pad[p++ & 127] = pad[p & 127] ^ pad[(p+64) & 127]); if (mRootIFD->endian == getHostEndianness()) sony_private = new TiffIFD(mFile, off); else sony_private = new TiffIFDBE(mFile, off); if (sony_private->hasEntry(SONYGRBGLEVELS)){ TiffEntry *wb = sony_private->getEntry(SONYGRBGLEVELS); if (wb->count != 4) ThrowRDE("ARW: WB has %d entries instead of 4", wb->count); if (wb->type == TIFF_SHORT) { // We're probably in the SR2 format const ushort16 *tmp = wb->getShortArray(); mRaw->metadata.wbCoeffs[0] = (float)tmp[1]; mRaw->metadata.wbCoeffs[1] = (float)tmp[0]; mRaw->metadata.wbCoeffs[2] = (float)tmp[2]; } else { const short16 *tmp = wb->getSignedShortArray(); mRaw->metadata.wbCoeffs[0] = (float)tmp[1]; mRaw->metadata.wbCoeffs[1] = (float)tmp[0]; mRaw->metadata.wbCoeffs[2] = (float)tmp[2]; } } else if (sony_private->hasEntry(SONYRGGBLEVELS)){ TiffEntry *wb = sony_private->getEntry(SONYRGGBLEVELS); if (wb->count != 4) ThrowRDE("ARW: WB has %d entries instead of 4", wb->count); const short16 *tmp = wb->getSignedShortArray(); mRaw->metadata.wbCoeffs[0] = (float)tmp[0]; mRaw->metadata.wbCoeffs[1] = (float)tmp[1]; mRaw->metadata.wbCoeffs[2] = (float)tmp[3]; } if (sony_private) delete(sony_private); } } /* Since ARW2 compressed images have predictable offsets, we decode them threaded */ void ArwDecoder::decodeThreaded(RawDecoderThread * t) { uchar8* data = mRaw->getData(); uint32 pitch = mRaw->pitch; uint32 w = mRaw->dim.x; BitPumpPlain bits(in); for (uint32 y = t->start_y; y < t->end_y; y++) { ushort16* dest = (ushort16*) & data[y*pitch]; // Realign bits.setAbsoluteOffset((w*8*y) >> 3); uint32 random = bits.peekBits(24); // Process 32 pixels (16x2) per loop. for (uint32 x = 0; x < w - 30;) { bits.checkPos(); int _max = bits.getBits(11); int _min = bits.getBits(11); int _imax = bits.getBits(4); int _imin = bits.getBits(4); int sh; for (sh = 0; sh < 4 && 0x80 << sh <= _max - _min; sh++); for (int i = 0; i < 16; i++) { int p; if (i == _imax) p = _max; else if (i == _imin) p = _min; else { p = (bits.getBits(7) << sh) + _min; if (p > 0x7ff) p = 0x7ff; } mRaw->setWithLookUp(p << 1, (uchar8*)&dest[x+i*2], &random); } x += x & 1 ? 31 : 1; // Skip to next 32 pixels } } } } // namespace RawSpeed Cleanup ARW WB #include "StdAfx.h" #include "ArwDecoder.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post Copyright (C) 2014 Pedro Côrte-Real This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ #define get2LE(data,pos) ((((ushort16)(data)[pos+1]) << 8) | ((ushort16)(data)[pos])) #define get4BE(data,pos) ((((uint32)(data)[pos]) << 24) | (((uint32)(data)[pos+1]) << 16) | \ (((uint32)(data)[pos+2]) << 8) | ((uint32)(data)[pos+3])) #define get4LE(data,pos) ((((uint32)(data)[pos+3]) << 24) | (((uint32)(data)[pos+2]) << 16) | \ (((uint32)(data)[pos+1]) << 8) | ((uint32)(data)[pos])) namespace RawSpeed { ArwDecoder::ArwDecoder(TiffIFD *rootIFD, FileMap* file) : RawDecoder(file), mRootIFD(rootIFD) { mShiftDownScale = 0; decoderVersion = 1; } ArwDecoder::~ArwDecoder(void) { if (mRootIFD) delete mRootIFD; mRootIFD = NULL; } RawImage ArwDecoder::decodeRawInternal() { vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(STRIPOFFSETS); if (data.empty()) { TiffEntry *model = mRootIFD->getEntryRecursive(MODEL); if (model && model->getString() == "DSLR-A100") { // We've caught the elusive A100 in the wild, a transitional format // between the simple sanity of the MRW custom format and the wordly // wonderfullness of the Tiff-based ARW format, let's shoot from the hip uint32 off = mRootIFD->getEntryRecursive(SUBIFDS)->getInt(); uint32 width = 3881; uint32 height = 2608; mRaw->dim = iPoint2D(width, height); mRaw->createData(); ByteStream input(mFile->getData(off),mFile->getSize()-off); try { DecodeARW(input, width, height); } catch (IOException &e) { mRaw->setError(e.what()); // Let's ignore it, it may have delivered somewhat useful data. } return mRaw; } else { ThrowRDE("ARW Decoder: No image data found"); } } TiffIFD* raw = data[0]; int compression = raw->getEntry(COMPRESSION)->getInt(); if (1 == compression) { // This is probably the SR2 format, let's pass it on try { DecodeSR2(raw); } catch (IOException &e) { mRaw->setError(e.what()); } return mRaw; } if (32767 != compression) ThrowRDE("ARW Decoder: Unsupported compression"); TiffEntry *offsets = raw->getEntry(STRIPOFFSETS); TiffEntry *counts = raw->getEntry(STRIPBYTECOUNTS); if (offsets->count != 1) { ThrowRDE("ARW Decoder: Multiple Strips found: %u", offsets->count); } if (counts->count != offsets->count) { ThrowRDE("ARW Decoder: Byte count number does not match strip size: count:%u, strips:%u ", counts->count, offsets->count); } uint32 width = raw->getEntry(IMAGEWIDTH)->getInt(); uint32 height = raw->getEntry(IMAGELENGTH)->getInt(); uint32 bitPerPixel = raw->getEntry(BITSPERSAMPLE)->getInt(); // Sony E-550 marks compressed 8bpp ARW with 12 bit per pixel // this makes the compression detect it as a ARW v1. // This camera has however another MAKER entry, so we MAY be able // to detect it this way in the future. data = mRootIFD->getIFDsWithTag(MAKE); if (data.size() > 1) { for (uint32 i = 0; i < data.size(); i++) { string make = data[i]->getEntry(MAKE)->getString(); /* Check for maker "SONY" without spaces */ if (!make.compare("SONY")) bitPerPixel = 8; } } bool arw1 = counts->getInt() * 8 != width * height * bitPerPixel; if (arw1) height += 8; mRaw->dim = iPoint2D(width, height); mRaw->createData(); ushort16 curve[0x4001]; const ushort16* c = raw->getEntry(SONY_CURVE)->getShortArray(); uint32 sony_curve[] = { 0, 0, 0, 0, 0, 4095 }; for (uint32 i = 0; i < 4; i++) sony_curve[i+1] = (c[i] >> 2) & 0xfff; for (uint32 i = 0; i < 0x4001; i++) curve[i] = i; for (uint32 i = 0; i < 5; i++) for (uint32 j = sony_curve[i] + 1; j <= sony_curve[i+1]; j++) curve[j] = curve[j-1] + (1 << i); if (!uncorrectedRawValues) mRaw->setTable(curve, 0x4000, true); uint32 c2 = counts->getInt(); uint32 off = offsets->getInt(); if (!mFile->isValid(off)) ThrowRDE("Sony ARW decoder: Data offset after EOF, file probably truncated"); if (!mFile->isValid(off + c2)) c2 = mFile->getSize() - off; ByteStream input(mFile->getData(off), c2); try { if (arw1) DecodeARW(input, width, height); else DecodeARW2(input, width, height, bitPerPixel); } catch (IOException &e) { mRaw->setError(e.what()); // Let's ignore it, it may have delivered somewhat useful data. } // Set the table, if it should be needed later. if (uncorrectedRawValues) { mRaw->setTable(curve, 0x4000, false); } else { mRaw->setTable(NULL); } return mRaw; } void ArwDecoder::DecodeSR2(TiffIFD* raw) { uint32 width = raw->getEntry(IMAGEWIDTH)->getInt(); uint32 height = raw->getEntry(IMAGELENGTH)->getInt(); uint32 off = raw->getEntry(STRIPOFFSETS)->getInt(); uint32 c2 = raw->getEntry(STRIPBYTECOUNTS)->getInt(); mRaw->dim = iPoint2D(width, height); mRaw->createData(); ByteStream input(mFile->getData(off), c2); Decode14BitRawBEunpacked(input, width, height); } void ArwDecoder::DecodeARW(ByteStream &input, uint32 w, uint32 h) { BitPumpMSB bits(&input); uchar8* data = mRaw->getData(); ushort16* dest = (ushort16*) & data[0]; uint32 pitch = mRaw->pitch / sizeof(ushort16); int sum = 0; for (uint32 x = w; x--;) for (uint32 y = 0; y < h + 1; y += 2) { bits.checkPos(); bits.fill(); if (y == h) y = 1; uint32 len = 4 - bits.getBitsNoFill(2); if (len == 3 && bits.getBitNoFill()) len = 0; if (len == 4) while (len < 17 && !bits.getBitNoFill()) len++; int diff = bits.getBits(len); if (len && (diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; sum += diff; _ASSERTE(!(sum >> 12)); if (y < h) dest[x+y*pitch] = sum; } } void ArwDecoder::DecodeARW2(ByteStream &input, uint32 w, uint32 h, uint32 bpp) { if (bpp == 8) { in = &input; this->startThreads(); return; } // End bpp = 8 if (bpp == 12) { uchar8* data = mRaw->getData(); uint32 pitch = mRaw->pitch; const uchar8 *in = input.getData(); if (input.getRemainSize() < (w * 3 / 2)) ThrowRDE("Sony Decoder: Image data section too small, file probably truncated"); if (input.getRemainSize() < (w*h*3 / 2)) h = input.getRemainSize() / (w * 3 / 2) - 1; for (uint32 y = 0; y < h; y++) { ushort16* dest = (ushort16*) & data[y*pitch]; for (uint32 x = 0 ; x < w; x += 2) { uint32 g1 = *in++; uint32 g2 = *in++; dest[x] = (g1 | ((g2 & 0xf) << 8)); uint32 g3 = *in++; dest[x+1] = ((g2 >> 4) | (g3 << 4)); } } // Shift scales, since black and white are the same as compressed precision mShiftDownScale = 2; return; } ThrowRDE("Unsupported bit depth"); } void ArwDecoder::checkSupportInternal(CameraMetaData *meta) { vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL); if (data.empty()) ThrowRDE("ARW Support check: Model name found"); string make = data[0]->getEntry(MAKE)->getString(); string model = data[0]->getEntry(MODEL)->getString(); this->checkCameraSupported(meta, make, model, ""); } void ArwDecoder::decodeMetaDataInternal(CameraMetaData *meta) { //Default int iso = 0; mRaw->cfa.setCFA(iPoint2D(2,2), CFA_RED, CFA_GREEN, CFA_GREEN2, CFA_BLUE); vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL); if (data.empty()) ThrowRDE("ARW Meta Decoder: Model name found"); if (!data[0]->hasEntry(MAKE)) ThrowRDE("ARW Decoder: Make name not found"); string make = data[0]->getEntry(MAKE)->getString(); string model = data[0]->getEntry(MODEL)->getString(); if (mRootIFD->hasEntryRecursive(ISOSPEEDRATINGS)) iso = mRootIFD->getEntryRecursive(ISOSPEEDRATINGS)->getInt(); setMetaData(meta, make, model, "", iso); mRaw->whitePoint >>= mShiftDownScale; mRaw->blackLevel >>= mShiftDownScale; // Set the whitebalance if (model == "DSLR-A100") { // Handle the MRW style WB of the A100 if (mRootIFD->hasEntryRecursive(DNGPRIVATEDATA)) { TiffEntry *priv = mRootIFD->getEntryRecursive(DNGPRIVATEDATA); const uchar8 *offdata = priv->getData(); uint32 off = get4LE(offdata,0); const unsigned char* data = mFile->getData(off); uint32 length = mFile->getSize()-off; uint32 currpos = 8; while (currpos < length) { uint32 tag = get4BE(data,currpos); uint32 len = get4LE(data,currpos+4); if (tag == 0x574247) { /* WBG */ ushort16 tmp[4]; for(uint32 i=0; i<4; i++) tmp[i] = get2LE(data, currpos+12+i*2); mRaw->metadata.wbCoeffs[0] = (float) tmp[0]; mRaw->metadata.wbCoeffs[1] = (float) tmp[1]; mRaw->metadata.wbCoeffs[2] = (float) tmp[3]; break; } currpos += MAX(len+8,1); // MAX(,1) to make sure we make progress } } } else { // Everything else but the A100 try { GetWB(); } catch (...) { // We caught an exception reading WB, just ignore it } } } void ArwDecoder::GetWB() { // Set the whitebalance for all the modern ARW formats (everything after A100) if (mRootIFD->hasEntryRecursive(DNGPRIVATEDATA)) { TiffEntry *priv = mRootIFD->getEntryRecursive(DNGPRIVATEDATA); const uchar8 *data = priv->getData(); uint32 off = get4LE(data, 0); TiffIFD *sony_private; if (mRootIFD->endian == getHostEndianness()) sony_private = new TiffIFD(mFile, off); else sony_private = new TiffIFDBE(mFile, off); TiffEntry *sony_offset = sony_private->getEntryRecursive(SONY_OFFSET); TiffEntry *sony_length = sony_private->getEntryRecursive(SONY_LENGTH); TiffEntry *sony_key = sony_private->getEntryRecursive(SONY_KEY); if(!sony_offset || !sony_length || !sony_key || sony_key->count != 4) ThrowRDE("ARW: couldn't find the correct metadata for WB decoding"); off = sony_offset->getInt(); uint32 len = sony_length->getInt(); data = sony_key->getData(); uint32 key = get4LE(data,0); if (sony_private) delete(sony_private); if (mFile->getSize() < off+len) ThrowRDE("ARW: Sony WB block out of range, corrupted file?"); uint32 *ifp_data = (uint32 *) mFile->getDataWrt(off); uint32 pad[128]; uint32 p; // Initialize the decryption for (p=0; p < 4; p++) pad[p] = key = key * 48828125 + 1; pad[3] = pad[3] << 1 | (pad[0]^pad[2]) >> 31; for (p=4; p < 127; p++) pad[p] = (pad[p-4]^pad[p-2]) << 1 | (pad[p-3]^pad[p-1]) >> 31; for (p=0; p < 127; p++) pad[p] = get4BE((uchar8 *) &pad[p],0); // Decrypt the buffer in place uint32 count = len/4; while (count--) *ifp_data++ ^= (pad[p++ & 127] = pad[p & 127] ^ pad[(p+64) & 127]); if (mRootIFD->endian == getHostEndianness()) sony_private = new TiffIFD(mFile, off); else sony_private = new TiffIFDBE(mFile, off); if (sony_private->hasEntry(SONYGRBGLEVELS)){ TiffEntry *wb = sony_private->getEntry(SONYGRBGLEVELS); if (wb->count != 4) ThrowRDE("ARW: WB has %d entries instead of 4", wb->count); if (wb->type == TIFF_SHORT) { // We're probably in the SR2 format const ushort16 *tmp = wb->getShortArray(); mRaw->metadata.wbCoeffs[0] = (float)tmp[1]; mRaw->metadata.wbCoeffs[1] = (float)tmp[0]; mRaw->metadata.wbCoeffs[2] = (float)tmp[2]; } else { const short16 *tmp = wb->getSignedShortArray(); mRaw->metadata.wbCoeffs[0] = (float)tmp[1]; mRaw->metadata.wbCoeffs[1] = (float)tmp[0]; mRaw->metadata.wbCoeffs[2] = (float)tmp[2]; } } else if (sony_private->hasEntry(SONYRGGBLEVELS)){ TiffEntry *wb = sony_private->getEntry(SONYRGGBLEVELS); if (wb->count != 4) ThrowRDE("ARW: WB has %d entries instead of 4", wb->count); const short16 *tmp = wb->getSignedShortArray(); mRaw->metadata.wbCoeffs[0] = (float)tmp[0]; mRaw->metadata.wbCoeffs[1] = (float)tmp[1]; mRaw->metadata.wbCoeffs[2] = (float)tmp[3]; } if (sony_private) delete(sony_private); } } /* Since ARW2 compressed images have predictable offsets, we decode them threaded */ void ArwDecoder::decodeThreaded(RawDecoderThread * t) { uchar8* data = mRaw->getData(); uint32 pitch = mRaw->pitch; uint32 w = mRaw->dim.x; BitPumpPlain bits(in); for (uint32 y = t->start_y; y < t->end_y; y++) { ushort16* dest = (ushort16*) & data[y*pitch]; // Realign bits.setAbsoluteOffset((w*8*y) >> 3); uint32 random = bits.peekBits(24); // Process 32 pixels (16x2) per loop. for (uint32 x = 0; x < w - 30;) { bits.checkPos(); int _max = bits.getBits(11); int _min = bits.getBits(11); int _imax = bits.getBits(4); int _imin = bits.getBits(4); int sh; for (sh = 0; sh < 4 && 0x80 << sh <= _max - _min; sh++); for (int i = 0; i < 16; i++) { int p; if (i == _imax) p = _max; else if (i == _imin) p = _min; else { p = (bits.getBits(7) << sh) + _min; if (p > 0x7ff) p = 0x7ff; } mRaw->setWithLookUp(p << 1, (uchar8*)&dest[x+i*2], &random); } x += x & 1 ? 31 : 1; // Skip to next 32 pixels } } } } // namespace RawSpeed
#include "StdAfx.h" #include "Rw2Decoder.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ namespace RawSpeed { Rw2Decoder::Rw2Decoder(TiffIFD *rootIFD, FileMap* file) : RawDecoder(file), mRootIFD(rootIFD), input_start(0) { decoderVersion = 1; } Rw2Decoder::~Rw2Decoder(void) { if (input_start) delete input_start; input_start = 0; if (mRootIFD) delete mRootIFD; mRootIFD = NULL; } RawImage Rw2Decoder::decodeRawInternal() { vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(PANASONIC_STRIPOFFSET); bool isOldPanasonic = FALSE; if (data.empty()) { if (!mRootIFD->hasEntryRecursive(STRIPOFFSETS)) ThrowRDE("RW2 Decoder: No image data found"); isOldPanasonic = TRUE; data = mRootIFD->getIFDsWithTag(STRIPOFFSETS); } TiffIFD* raw = data[0]; uint32 height = raw->getEntry((TiffTag)3)->getShort(); uint32 width = raw->getEntry((TiffTag)2)->getShort(); if (isOldPanasonic) { ThrowRDE("Cannot decode old-style Panasonic RAW files"); TiffEntry *offsets = raw->getEntry(STRIPOFFSETS); TiffEntry *counts = raw->getEntry(STRIPBYTECOUNTS); if (offsets->count != 1) { ThrowRDE("RW2 Decoder: Multiple Strips found: %u", offsets->count); } int off = offsets->getInt(); if (!mFile->isValid(off)) ThrowRDE("Panasonic RAW Decoder: Invalid image data offset, cannot decode."); int count = counts->getInt(); if (count != (int)(width*height*2)) ThrowRDE("Panasonic RAW Decoder: Byte count is wrong."); if (!mFile->isValid(off+count)) ThrowRDE("Panasonic RAW Decoder: Invalid image data offset, cannot decode."); mRaw->dim = iPoint2D(width, height); mRaw->createData(); ByteStream input_start(mFile->getData(off), mFile->getSize() - off); iPoint2D pos(0, 0); readUncompressedRaw(input_start, mRaw->dim,pos, width*2, 16, BitOrder_Plain); } else { mRaw->dim = iPoint2D(width, height); mRaw->createData(); TiffEntry *offsets = raw->getEntry(PANASONIC_STRIPOFFSET); if (offsets->count != 1) { ThrowRDE("RW2 Decoder: Multiple Strips found: %u", offsets->count); } load_flags = 0x2008; int off = offsets->getInt(); if (!mFile->isValid(off)) ThrowRDE("RW2 Decoder: Invalid image data offset, cannot decode."); input_start = new ByteStream(mFile->getData(off), mFile->getSize() - off); DecodeRw2(); } return mRaw; } void Rw2Decoder::DecodeRw2() { startThreads(); } void Rw2Decoder::decodeThreaded(RawDecoderThread * t) { int x, i, j, sh = 0, pred[2], nonz[2]; int w = mRaw->dim.x / 14; uint32 y; bool zero_is_bad = false; map<string,string>::iterator zero_hint = hints.find("zero_is_bad"); if (zero_hint != hints.end()) zero_is_bad = true; /* 9 + 1/7 bits per pixel */ int skip = w * 14 * t->start_y * 9; skip += w * 2 * t->start_y; skip /= 8; PanaBitpump bits(new ByteStream(input_start)); bits.load_flags = load_flags; bits.skipBytes(skip); vector<uint32> zero_pos; for (y = t->start_y; y < t->end_y; y++) { ushort16* dest = (ushort16*)mRaw->getData(0, y); for (x = 0; x < w; x++) { pred[0] = pred[1] = nonz[0] = nonz[1] = 0; int u = 0; for (i = 0; i < 14; i++) { // Even pixels if (u == 2) { sh = 4 >> (3 - bits.getBits(2)); u = -1; } if (nonz[0]) { if ((j = bits.getBits(8))) { if ((pred[0] -= 0x80 << sh) < 0 || sh == 4) pred[0] &= ~(-1 << sh); pred[0] += j << sh; } } else if ((nonz[0] = bits.getBits(8)) || i > 11) pred[0] = nonz[0] << 4 | bits.getBits(4); *dest++ = pred[0]; if (zero_is_bad && 0 == pred[0]) zero_pos.push_back((y<<16) | (x*14+i)); // Odd pixels i++; u++; if (u == 2) { sh = 4 >> (3 - bits.getBits(2)); u = -1; } if (nonz[1]) { if ((j = bits.getBits(8))) { if ((pred[1] -= 0x80 << sh) < 0 || sh == 4) pred[1] &= ~(-1 << sh); pred[1] += j << sh; } } else if ((nonz[1] = bits.getBits(8)) || i > 11) pred[1] = nonz[1] << 4 | bits.getBits(4); *dest++ = pred[1]; if (zero_is_bad && 0 == pred[1]) zero_pos.push_back((y<<16) | (x*14+i)); u++; } } } if (zero_is_bad && !zero_pos.empty()) { pthread_mutex_lock(&mRaw->mBadPixelMutex); mRaw->mBadPixelPositions.insert(mRaw->mBadPixelPositions.end(), zero_pos.begin(), zero_pos.end()); pthread_mutex_unlock(&mRaw->mBadPixelMutex); } } void Rw2Decoder::checkSupportInternal(CameraMetaData *meta) { vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL); if (data.empty()) ThrowRDE("RW2 Support check: Model name found"); string make = data[0]->getEntry(MAKE)->getString(); string model = data[0]->getEntry(MODEL)->getString(); if (!this->checkCameraSupported(meta, make, model, guessMode())) this->checkCameraSupported(meta, make, model, ""); } void Rw2Decoder::decodeMetaDataInternal(CameraMetaData *meta) { mRaw->cfa.setCFA(CFA_BLUE, CFA_GREEN, CFA_GREEN2, CFA_RED); vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL); if (data.empty()) ThrowRDE("RW2 Meta Decoder: Model name not found"); if (!data[0]->hasEntry(MAKE)) ThrowRDE("RW2 Support: Make name not found"); string make = data[0]->getEntry(MAKE)->getString(); string model = data[0]->getEntry(MODEL)->getString(); string mode = guessMode(); int iso = 0; if (mRootIFD->hasEntryRecursive(PANASONIC_ISO_SPEED)) iso = mRootIFD->getEntryRecursive(PANASONIC_ISO_SPEED)->getInt(); if (this->checkCameraSupported(meta, make, model, mode)) { setMetaData(meta, make, model, mode, iso); } else { mRaw->mode = mode; _RPT1(0, "Mode not found in DB: %s", mode.c_str()); setMetaData(meta, make, model, "", iso); } } std::string Rw2Decoder::guessMode() { float ratio = 3.0f / 2.0f; // Default if (!mRaw->isAllocated()) return ""; ratio = (float)mRaw->dim.x / (float)mRaw->dim.y; float min_diff = fabs(ratio - 16.0f / 9.0f); std::string closest_match = "16:9"; float t = fabs(ratio - 3.0f / 2.0f); if (t < min_diff) { closest_match = "3:2"; min_diff = t; } t = fabs(ratio - 4.0f / 3.0f); if (t < min_diff) { closest_match = "4:3"; min_diff = t; } t = fabs(ratio - 1.0f); if (t < min_diff) { closest_match = "1:1"; min_diff = t; } _RPT1(0, "Mode guess: '%s'\n", closest_match.c_str()); return closest_match; } PanaBitpump::PanaBitpump(ByteStream* _input) : input(_input), vbits(0) { } PanaBitpump::~PanaBitpump() { if (input) delete input; input = 0; } void PanaBitpump::skipBytes(int bytes) { int blocks = (bytes / 0x4000) * 0x4000; input->skipBytes(blocks); for (int i = blocks; i < bytes; i++) getBits(8); } uint32 PanaBitpump::getBits(int nbits) { int byte; if (!vbits) { /* On truncated files this routine will just return just for the truncated * part of the file. Since there is no chance of affecting output buffer * size we allow the decoder to decode this */ if (input->getRemainSize() < 0x4000 - load_flags) { memcpy(buf + load_flags, input->getData(), input->getRemainSize()); input->skipBytes(input->getRemainSize()); } else { memcpy(buf + load_flags, input->getData(), 0x4000 - load_flags); input->skipBytes(0x4000 - load_flags); if (input->getRemainSize() < load_flags) { memcpy(buf, input->getData(), input->getRemainSize()); input->skipBytes(input->getRemainSize()); } else { memcpy(buf, input->getData(), load_flags); input->skipBytes(load_flags); } } } vbits = (vbits - nbits) & 0x1ffff; byte = vbits >> 3 ^ 0x3ff0; return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~(-1 << nbits); } } // namespace RawSpeed Read blacklevels from Panasonic metadata. git-svn-id: 04e88ac4940b0408b73cd6f458a224a262abaaff@587 ec705bc8-faf6-4f9b-9aff-b4916e9bedc3 #include "StdAfx.h" #include "Rw2Decoder.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ namespace RawSpeed { Rw2Decoder::Rw2Decoder(TiffIFD *rootIFD, FileMap* file) : RawDecoder(file), mRootIFD(rootIFD), input_start(0) { decoderVersion = 1; } Rw2Decoder::~Rw2Decoder(void) { if (input_start) delete input_start; input_start = 0; if (mRootIFD) delete mRootIFD; mRootIFD = NULL; } RawImage Rw2Decoder::decodeRawInternal() { vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(PANASONIC_STRIPOFFSET); bool isOldPanasonic = FALSE; if (data.empty()) { if (!mRootIFD->hasEntryRecursive(STRIPOFFSETS)) ThrowRDE("RW2 Decoder: No image data found"); isOldPanasonic = TRUE; data = mRootIFD->getIFDsWithTag(STRIPOFFSETS); } TiffIFD* raw = data[0]; uint32 height = raw->getEntry((TiffTag)3)->getShort(); uint32 width = raw->getEntry((TiffTag)2)->getShort(); if (isOldPanasonic) { ThrowRDE("Cannot decode old-style Panasonic RAW files"); TiffEntry *offsets = raw->getEntry(STRIPOFFSETS); TiffEntry *counts = raw->getEntry(STRIPBYTECOUNTS); if (offsets->count != 1) { ThrowRDE("RW2 Decoder: Multiple Strips found: %u", offsets->count); } int off = offsets->getInt(); if (!mFile->isValid(off)) ThrowRDE("Panasonic RAW Decoder: Invalid image data offset, cannot decode."); int count = counts->getInt(); if (count != (int)(width*height*2)) ThrowRDE("Panasonic RAW Decoder: Byte count is wrong."); if (!mFile->isValid(off+count)) ThrowRDE("Panasonic RAW Decoder: Invalid image data offset, cannot decode."); mRaw->dim = iPoint2D(width, height); mRaw->createData(); ByteStream input_start(mFile->getData(off), mFile->getSize() - off); iPoint2D pos(0, 0); readUncompressedRaw(input_start, mRaw->dim,pos, width*2, 16, BitOrder_Plain); } else { mRaw->dim = iPoint2D(width, height); mRaw->createData(); TiffEntry *offsets = raw->getEntry(PANASONIC_STRIPOFFSET); if (offsets->count != 1) { ThrowRDE("RW2 Decoder: Multiple Strips found: %u", offsets->count); } load_flags = 0x2008; int off = offsets->getInt(); if (!mFile->isValid(off)) ThrowRDE("RW2 Decoder: Invalid image data offset, cannot decode."); input_start = new ByteStream(mFile->getData(off), mFile->getSize() - off); DecodeRw2(); } // Read blacklevels if (raw->hasEntry((TiffTag)0x1c) && raw->hasEntry((TiffTag)0x1d) && raw->hasEntry((TiffTag)0x1e)) { mRaw->blackLevelSeparate[0] = raw->getEntry((TiffTag)0x1c)->getInt() + 15; mRaw->blackLevelSeparate[1] = mRaw->blackLevelSeparate[2] = raw->getEntry((TiffTag)0x1d)->getInt() + 15; mRaw->blackLevelSeparate[3] = raw->getEntry((TiffTag)0x1e)->getInt() + 15; } return mRaw; } void Rw2Decoder::DecodeRw2() { startThreads(); } void Rw2Decoder::decodeThreaded(RawDecoderThread * t) { int x, i, j, sh = 0, pred[2], nonz[2]; int w = mRaw->dim.x / 14; uint32 y; bool zero_is_bad = false; map<string,string>::iterator zero_hint = hints.find("zero_is_bad"); if (zero_hint != hints.end()) zero_is_bad = true; /* 9 + 1/7 bits per pixel */ int skip = w * 14 * t->start_y * 9; skip += w * 2 * t->start_y; skip /= 8; PanaBitpump bits(new ByteStream(input_start)); bits.load_flags = load_flags; bits.skipBytes(skip); vector<uint32> zero_pos; for (y = t->start_y; y < t->end_y; y++) { ushort16* dest = (ushort16*)mRaw->getData(0, y); for (x = 0; x < w; x++) { pred[0] = pred[1] = nonz[0] = nonz[1] = 0; int u = 0; for (i = 0; i < 14; i++) { // Even pixels if (u == 2) { sh = 4 >> (3 - bits.getBits(2)); u = -1; } if (nonz[0]) { if ((j = bits.getBits(8))) { if ((pred[0] -= 0x80 << sh) < 0 || sh == 4) pred[0] &= ~(-1 << sh); pred[0] += j << sh; } } else if ((nonz[0] = bits.getBits(8)) || i > 11) pred[0] = nonz[0] << 4 | bits.getBits(4); *dest++ = pred[0]; if (zero_is_bad && 0 == pred[0]) zero_pos.push_back((y<<16) | (x*14+i)); // Odd pixels i++; u++; if (u == 2) { sh = 4 >> (3 - bits.getBits(2)); u = -1; } if (nonz[1]) { if ((j = bits.getBits(8))) { if ((pred[1] -= 0x80 << sh) < 0 || sh == 4) pred[1] &= ~(-1 << sh); pred[1] += j << sh; } } else if ((nonz[1] = bits.getBits(8)) || i > 11) pred[1] = nonz[1] << 4 | bits.getBits(4); *dest++ = pred[1]; if (zero_is_bad && 0 == pred[1]) zero_pos.push_back((y<<16) | (x*14+i)); u++; } } } if (zero_is_bad && !zero_pos.empty()) { pthread_mutex_lock(&mRaw->mBadPixelMutex); mRaw->mBadPixelPositions.insert(mRaw->mBadPixelPositions.end(), zero_pos.begin(), zero_pos.end()); pthread_mutex_unlock(&mRaw->mBadPixelMutex); } } void Rw2Decoder::checkSupportInternal(CameraMetaData *meta) { vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL); if (data.empty()) ThrowRDE("RW2 Support check: Model name found"); string make = data[0]->getEntry(MAKE)->getString(); string model = data[0]->getEntry(MODEL)->getString(); if (!this->checkCameraSupported(meta, make, model, guessMode())) this->checkCameraSupported(meta, make, model, ""); } void Rw2Decoder::decodeMetaDataInternal(CameraMetaData *meta) { mRaw->cfa.setCFA(CFA_BLUE, CFA_GREEN, CFA_GREEN2, CFA_RED); vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL); if (data.empty()) ThrowRDE("RW2 Meta Decoder: Model name not found"); if (!data[0]->hasEntry(MAKE)) ThrowRDE("RW2 Support: Make name not found"); string make = data[0]->getEntry(MAKE)->getString(); string model = data[0]->getEntry(MODEL)->getString(); string mode = guessMode(); int iso = 0; if (mRootIFD->hasEntryRecursive(PANASONIC_ISO_SPEED)) iso = mRootIFD->getEntryRecursive(PANASONIC_ISO_SPEED)->getInt(); if (this->checkCameraSupported(meta, make, model, mode)) { setMetaData(meta, make, model, mode, iso); } else { mRaw->mode = mode; _RPT1(0, "Mode not found in DB: %s", mode.c_str()); setMetaData(meta, make, model, "", iso); } } std::string Rw2Decoder::guessMode() { float ratio = 3.0f / 2.0f; // Default if (!mRaw->isAllocated()) return ""; ratio = (float)mRaw->dim.x / (float)mRaw->dim.y; float min_diff = fabs(ratio - 16.0f / 9.0f); std::string closest_match = "16:9"; float t = fabs(ratio - 3.0f / 2.0f); if (t < min_diff) { closest_match = "3:2"; min_diff = t; } t = fabs(ratio - 4.0f / 3.0f); if (t < min_diff) { closest_match = "4:3"; min_diff = t; } t = fabs(ratio - 1.0f); if (t < min_diff) { closest_match = "1:1"; min_diff = t; } _RPT1(0, "Mode guess: '%s'\n", closest_match.c_str()); return closest_match; } PanaBitpump::PanaBitpump(ByteStream* _input) : input(_input), vbits(0) { } PanaBitpump::~PanaBitpump() { if (input) delete input; input = 0; } void PanaBitpump::skipBytes(int bytes) { int blocks = (bytes / 0x4000) * 0x4000; input->skipBytes(blocks); for (int i = blocks; i < bytes; i++) getBits(8); } uint32 PanaBitpump::getBits(int nbits) { int byte; if (!vbits) { /* On truncated files this routine will just return just for the truncated * part of the file. Since there is no chance of affecting output buffer * size we allow the decoder to decode this */ if (input->getRemainSize() < 0x4000 - load_flags) { memcpy(buf + load_flags, input->getData(), input->getRemainSize()); input->skipBytes(input->getRemainSize()); } else { memcpy(buf + load_flags, input->getData(), 0x4000 - load_flags); input->skipBytes(0x4000 - load_flags); if (input->getRemainSize() < load_flags) { memcpy(buf, input->getData(), input->getRemainSize()); input->skipBytes(input->getRemainSize()); } else { memcpy(buf, input->getData(), load_flags); input->skipBytes(load_flags); } } } vbits = (vbits - nbits) & 0x1ffff; byte = vbits >> 3 ^ 0x3ff0; return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~(-1 << nbits); } } // namespace RawSpeed
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkDebuggerGUI.h" #include "SkPictureData.h" #include "SkPicturePlayback.h" #include "SkPictureRecord.h" #include <QListWidgetItem> #include <QtGui> #include "sk_tool_utils.h" SkDebuggerGUI::SkDebuggerGUI(QWidget *parent) : QMainWindow(parent) , fCentralSplitter(this) , fStatusBar(this) , fToolBar(this) , fActionOpen(this) , fActionBreakpoint(this) , fActionCancel(this) , fActionClearBreakpoints(this) , fActionClearDeletes(this) , fActionClose(this) , fActionCreateBreakpoint(this) , fActionDelete(this) , fActionDirectory(this) , fActionGoToLine(this) , fActionInspector(this) , fActionSettings(this) , fActionPlay(this) , fActionPause(this) , fActionRewind(this) , fActionSave(this) , fActionSaveAs(this) , fActionShowDeletes(this) , fActionStepBack(this) , fActionStepForward(this) , fActionZoomIn(this) , fActionZoomOut(this) , fMapper(this) , fListWidget(&fCentralSplitter) , fDirectoryWidget(&fCentralSplitter) , fCanvasWidget(this, &fDebugger) , fDrawCommandGeometryWidget(&fDebugger) , fMenuBar(this) , fMenuFile(this) , fMenuNavigate(this) , fMenuView(this) , fLoading(false) { setupUi(this); fListWidget.setSelectionMode(QAbstractItemView::ExtendedSelection); connect(&fListWidget, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this, SLOT(updateDrawCommandInfo())); connect(&fActionOpen, SIGNAL(triggered()), this, SLOT(openFile())); connect(&fActionDirectory, SIGNAL(triggered()), this, SLOT(toggleDirectory())); connect(&fDirectoryWidget, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this, SLOT(loadFile(QListWidgetItem *))); connect(&fActionDelete, SIGNAL(triggered()), this, SLOT(actionDelete())); connect(&fListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(toggleBreakpoint())); connect(&fActionRewind, SIGNAL(triggered()), this, SLOT(actionRewind())); connect(&fActionPlay, SIGNAL(triggered()), this, SLOT(actionPlay())); connect(&fActionStepBack, SIGNAL(triggered()), this, SLOT(actionStepBack())); connect(&fActionStepForward, SIGNAL(triggered()), this, SLOT(actionStepForward())); connect(&fActionBreakpoint, SIGNAL(triggered()), this, SLOT(actionBreakpoints())); connect(&fActionInspector, SIGNAL(triggered()), this, SLOT(actionInspector())); connect(&fActionSettings, SIGNAL(triggered()), this, SLOT(actionSettings())); connect(&fFilter, SIGNAL(activated(QString)), this, SLOT(toggleFilter(QString))); connect(&fActionCancel, SIGNAL(triggered()), this, SLOT(actionCancel())); connect(&fActionClearBreakpoints, SIGNAL(triggered()), this, SLOT(actionClearBreakpoints())); connect(&fActionClearDeletes, SIGNAL(triggered()), this, SLOT(actionClearDeletes())); connect(&fActionClose, SIGNAL(triggered()), this, SLOT(actionClose())); #if SK_SUPPORT_GPU connect(&fSettingsWidget, SIGNAL(glSettingsChanged()), this, SLOT(actionGLSettingsChanged())); #endif connect(&fSettingsWidget, SIGNAL(rasterSettingsChanged()), this, SLOT(actionRasterSettingsChanged())); connect(&fSettingsWidget, SIGNAL(visualizationsChanged()), this, SLOT(actionVisualizationsChanged())); connect(&fSettingsWidget, SIGNAL(texFilterSettingsChanged()), this, SLOT(actionTextureFilter())); connect(&fActionPause, SIGNAL(toggled(bool)), this, SLOT(pauseDrawing(bool))); connect(&fActionCreateBreakpoint, SIGNAL(activated()), this, SLOT(toggleBreakpoint())); connect(&fActionShowDeletes, SIGNAL(triggered()), this, SLOT(showDeletes())); connect(&fCanvasWidget, SIGNAL(hitChanged(int)), this, SLOT(selectCommand(int))); connect(&fCanvasWidget, SIGNAL(hitChanged(int)), this, SLOT(updateHit(int))); connect(&fCanvasWidget, SIGNAL(scaleFactorChanged(float)), this, SLOT(actionScale(float))); connect(&fActionSaveAs, SIGNAL(triggered()), this, SLOT(actionSaveAs())); connect(&fActionSave, SIGNAL(triggered()), this, SLOT(actionSave())); fMapper.setMapping(&fActionZoomIn, SkCanvasWidget::kIn_ZoomCommand); fMapper.setMapping(&fActionZoomOut, SkCanvasWidget::kOut_ZoomCommand); connect(&fActionZoomIn, SIGNAL(triggered()), &fMapper, SLOT(map())); connect(&fActionZoomOut, SIGNAL(triggered()), &fMapper, SLOT(map())); connect(&fMapper, SIGNAL(mapped(int)), &fCanvasWidget, SLOT(zoom(int))); fViewStateFrame.setDisabled(true); fInspectorWidget.setDisabled(true); fMenuEdit.setDisabled(true); fMenuNavigate.setDisabled(true); fMenuView.setDisabled(true); } void SkDebuggerGUI::actionBreakpoints() { bool breakpointsActivated = fActionBreakpoint.isChecked(); for (int row = 0; row < fListWidget.count(); row++) { QListWidgetItem *item = fListWidget.item(row); item->setHidden(item->checkState() == Qt::Unchecked && breakpointsActivated); } } void SkDebuggerGUI::showDeletes() { bool deletesActivated = fActionShowDeletes.isChecked(); for (int row = 0; row < fListWidget.count(); row++) { QListWidgetItem *item = fListWidget.item(row); item->setHidden(fDebugger.isCommandVisible(row) && deletesActivated); } } void SkDebuggerGUI::actionCancel() { for (int row = 0; row < fListWidget.count(); row++) { fListWidget.item(row)->setHidden(false); } } void SkDebuggerGUI::actionClearBreakpoints() { for (int row = 0; row < fListWidget.count(); row++) { QListWidgetItem* item = fListWidget.item(row); item->setCheckState(Qt::Unchecked); item->setData(Qt::DecorationRole, QPixmap(":/blank.png")); } } void SkDebuggerGUI::actionClearDeletes() { for (int row = 0; row < fListWidget.count(); row++) { QListWidgetItem* item = fListWidget.item(row); item->setData(Qt::UserRole + 2, QPixmap(":/blank.png")); fDebugger.setCommandVisible(row, true); fSkipCommands[row] = false; } this->updateImage(); } void SkDebuggerGUI::actionClose() { this->close(); } void SkDebuggerGUI::actionDelete() { for (int row = 0; row < fListWidget.count(); ++row) { QListWidgetItem* item = fListWidget.item(row); if (!item->isSelected()) { continue; } if (fDebugger.isCommandVisible(row)) { item->setData(Qt::UserRole + 2, QPixmap(":/delete.png")); fDebugger.setCommandVisible(row, false); fSkipCommands[row] = true; } else { item->setData(Qt::UserRole + 2, QPixmap(":/blank.png")); fDebugger.setCommandVisible(row, true); fSkipCommands[row] = false; } } this->updateImage(); } #if SK_SUPPORT_GPU void SkDebuggerGUI::actionGLSettingsChanged() { bool isToggled = fSettingsWidget.isGLActive(); if (isToggled) { fCanvasWidget.setGLSampleCount(fSettingsWidget.getGLSampleCount()); } fCanvasWidget.setWidgetVisibility(SkCanvasWidget::kGPU_WidgetType, !isToggled); } #endif void SkDebuggerGUI::actionInspector() { bool newState = !fInspectorWidget.isHidden(); fInspectorWidget.setHidden(newState); fViewStateFrame.setHidden(newState); fDrawCommandGeometryWidget.setHidden(newState); } void SkDebuggerGUI::actionPlay() { for (int row = fListWidget.currentRow() + 1; row < fListWidget.count(); row++) { QListWidgetItem *item = fListWidget.item(row); if (item->checkState() == Qt::Checked) { fListWidget.setCurrentItem(item); return; } } fListWidget.setCurrentRow(fListWidget.count() - 1); } void SkDebuggerGUI::actionRasterSettingsChanged() { fCanvasWidget.setWidgetVisibility(SkCanvasWidget::kRaster_8888_WidgetType, !fSettingsWidget.isRasterEnabled()); fDebugger.setOverdrawViz(fSettingsWidget.isOverdrawVizEnabled()); this->updateImage(); } void SkDebuggerGUI::actionVisualizationsChanged() { fDebugger.setMegaViz(fSettingsWidget.isMegaVizEnabled()); fDebugger.setPathOps(fSettingsWidget.isPathOpsEnabled()); fDebugger.highlightCurrentCommand(fSettingsWidget.isVisibilityFilterEnabled()); this->updateImage(); } void SkDebuggerGUI::actionTextureFilter() { SkFilterQuality quality; bool enabled = fSettingsWidget.getFilterOverride(&quality); fDebugger.setTexFilterOverride(enabled, quality); fCanvasWidget.update(); } void SkDebuggerGUI::actionRewind() { fListWidget.setCurrentRow(0); } void SkDebuggerGUI::actionSave() { fFileName = fPath.toAscii().data(); fFileName.append("/"); fFileName.append(fDirectoryWidget.currentItem()->text().toAscii().data()); saveToFile(fFileName); } void SkDebuggerGUI::actionSaveAs() { QString filename = QFileDialog::getSaveFileName(this, "Save File", "", "Skia Picture (*skp)"); if (!filename.endsWith(".skp", Qt::CaseInsensitive)) { filename.append(".skp"); } saveToFile(SkString(filename.toAscii().data())); } void SkDebuggerGUI::actionScale(float scaleFactor) { fZoomBox.setText(QString::number(scaleFactor * 100, 'f', 0).append("%")); } void SkDebuggerGUI::actionSettings() { if (fSettingsWidget.isHidden()) { fSettingsWidget.setHidden(false); } else { fSettingsWidget.setHidden(true); } } void SkDebuggerGUI::actionStepBack() { int currentRow = fListWidget.currentRow(); if (currentRow != 0) { fListWidget.setCurrentRow(currentRow - 1); } } void SkDebuggerGUI::actionStepForward() { int currentRow = fListWidget.currentRow(); QString curRow = QString::number(currentRow); QString curCount = QString::number(fListWidget.count()); if (currentRow < fListWidget.count() - 1) { fListWidget.setCurrentRow(currentRow + 1); } } void SkDebuggerGUI::drawComplete() { SkString clipStack; fDebugger.getClipStackText(&clipStack); fInspectorWidget.setText(clipStack.c_str(), SkInspectorWidget::kClipStack_TabType); fInspectorWidget.setMatrix(fDebugger.getCurrentMatrix()); fInspectorWidget.setClip(fDebugger.getCurrentClip()); } void SkDebuggerGUI::saveToFile(const SkString& filename) { SkFILEWStream file(filename.c_str()); SkAutoTUnref<SkPicture> copy(fDebugger.copyPicture()); sk_tool_utils::PngPixelSerializer serializer; copy->serialize(&file, &serializer); } void SkDebuggerGUI::loadFile(QListWidgetItem *item) { if (fDirectoryWidgetActive) { fFileName = fPath.toAscii().data(); // don't add a '/' to files in the local directory if (fFileName.size() > 0) { fFileName.append("/"); } fFileName.append(item->text().toAscii().data()); loadPicture(fFileName); } } void SkDebuggerGUI::openFile() { QString temp = QFileDialog::getOpenFileName(this, tr("Open File"), "", tr("Files (*.*)")); openFile(temp); } void SkDebuggerGUI::openFile(const QString &filename) { fDirectoryWidgetActive = false; if (!filename.isEmpty()) { QFileInfo pathInfo(filename); loadPicture(SkString(filename.toAscii().data())); setupDirectoryWidget(pathInfo.path()); } fDirectoryWidgetActive = true; } void SkDebuggerGUI::pauseDrawing(bool isPaused) { fPausedRow = fListWidget.currentRow(); this->updateDrawCommandInfo(); } void SkDebuggerGUI::updateDrawCommandInfo() { int currentRow = -1; if (!fLoading) { currentRow = fListWidget.currentRow(); } if (currentRow == -1) { fInspectorWidget.setText("", SkInspectorWidget::kDetail_TabType); fInspectorWidget.setText("", SkInspectorWidget::kClipStack_TabType); fCurrentCommandBox.setText(""); fDrawCommandGeometryWidget.setDrawCommandIndex(-1); } else { this->updateImage(); const SkTDArray<SkString*> *currInfo = fDebugger.getCommandInfo(currentRow); /* TODO(chudy): Add command type before parameters. Rename v * to something more informative. */ if (currInfo) { QString info; info.append("<b>Parameters: </b><br/>"); for (int i = 0; i < currInfo->count(); i++) { info.append(QString((*currInfo)[i]->c_str())); info.append("<br/>"); } fInspectorWidget.setText(info, SkInspectorWidget::kDetail_TabType); } fCurrentCommandBox.setText(QString::number(currentRow)); fDrawCommandGeometryWidget.setDrawCommandIndex(currentRow); fInspectorWidget.setDisabled(false); fViewStateFrame.setDisabled(false); } } void SkDebuggerGUI::selectCommand(int command) { if (this->isPaused()) { fListWidget.setCurrentRow(command); } } void SkDebuggerGUI::toggleBreakpoint() { QListWidgetItem* item = fListWidget.currentItem(); if (item->checkState() == Qt::Unchecked) { item->setCheckState(Qt::Checked); item->setData(Qt::DecorationRole, QPixmap(":/breakpoint_16x16.png")); } else { item->setCheckState(Qt::Unchecked); item->setData(Qt::DecorationRole, QPixmap(":/blank.png")); } } void SkDebuggerGUI::toggleDirectory() { fDirectoryWidget.setHidden(!fDirectoryWidget.isHidden()); } void SkDebuggerGUI::toggleFilter(QString string) { for (int row = 0; row < fListWidget.count(); row++) { QListWidgetItem *item = fListWidget.item(row); item->setHidden(item->text() != string); } } void SkDebuggerGUI::setupUi(QMainWindow *SkDebuggerGUI) { QIcon windowIcon; windowIcon.addFile(QString::fromUtf8(":/skia.png"), QSize(), QIcon::Normal, QIcon::Off); SkDebuggerGUI->setObjectName(QString::fromUtf8("SkDebuggerGUI")); SkDebuggerGUI->resize(1200, 1000); SkDebuggerGUI->setWindowIcon(windowIcon); SkDebuggerGUI->setWindowTitle("Skia Debugger"); fActionOpen.setShortcuts(QKeySequence::Open); fActionOpen.setText("Open"); QIcon breakpoint; breakpoint.addFile(QString::fromUtf8(":/breakpoint.png"), QSize(), QIcon::Normal, QIcon::Off); fActionBreakpoint.setShortcut(QKeySequence(tr("Ctrl+B"))); fActionBreakpoint.setIcon(breakpoint); fActionBreakpoint.setText("Breakpoints"); fActionBreakpoint.setCheckable(true); QIcon cancel; cancel.addFile(QString::fromUtf8(":/reload.png"), QSize(), QIcon::Normal, QIcon::Off); fActionCancel.setIcon(cancel); fActionCancel.setText("Clear Filter"); fActionClearBreakpoints.setShortcut(QKeySequence(tr("Alt+B"))); fActionClearBreakpoints.setText("Clear Breakpoints"); fActionClearDeletes.setShortcut(QKeySequence(tr("Alt+X"))); fActionClearDeletes.setText("Clear Deletes"); fActionClose.setShortcuts(QKeySequence::Quit); fActionClose.setText("Exit"); fActionCreateBreakpoint.setShortcut(QKeySequence(tr("B"))); fActionCreateBreakpoint.setText("Set Breakpoint"); fActionDelete.setShortcut(QKeySequence(tr("X"))); fActionDelete.setText("Delete Command"); fActionDirectory.setShortcut(QKeySequence(tr("Ctrl+D"))); fActionDirectory.setText("Directory"); QIcon inspector; inspector.addFile(QString::fromUtf8(":/inspector.png"), QSize(), QIcon::Normal, QIcon::Off); fActionInspector.setShortcut(QKeySequence(tr("Ctrl+I"))); fActionInspector.setIcon(inspector); fActionInspector.setText("Inspector"); QIcon settings; settings.addFile(QString::fromUtf8(":/inspector.png"), QSize(), QIcon::Normal, QIcon::Off); fActionSettings.setShortcut(QKeySequence(tr("Ctrl+G"))); fActionSettings.setIcon(settings); fActionSettings.setText("Settings"); QIcon play; play.addFile(QString::fromUtf8(":/play.png"), QSize(), QIcon::Normal, QIcon::Off); fActionPlay.setShortcut(QKeySequence(tr("Ctrl+P"))); fActionPlay.setIcon(play); fActionPlay.setText("Play"); QIcon pause; pause.addFile(QString::fromUtf8(":/pause.png"), QSize(), QIcon::Normal, QIcon::Off); fActionPause.setShortcut(QKeySequence(tr("Space"))); fActionPause.setCheckable(true); fActionPause.setIcon(pause); fActionPause.setText("Pause"); QIcon rewind; rewind.addFile(QString::fromUtf8(":/rewind.png"), QSize(), QIcon::Normal, QIcon::Off); fActionRewind.setShortcut(QKeySequence(tr("Ctrl+R"))); fActionRewind.setIcon(rewind); fActionRewind.setText("Rewind"); fActionSave.setShortcut(QKeySequence::Save); fActionSave.setText("Save"); fActionSave.setDisabled(true); fActionSaveAs.setShortcut(QKeySequence::SaveAs); fActionSaveAs.setText("Save As"); fActionSaveAs.setDisabled(true); fActionShowDeletes.setShortcut(QKeySequence(tr("Ctrl+X"))); fActionShowDeletes.setText("Deleted Commands"); fActionShowDeletes.setCheckable(true); QIcon stepBack; stepBack.addFile(QString::fromUtf8(":/previous.png"), QSize(), QIcon::Normal, QIcon::Off); fActionStepBack.setShortcut(QKeySequence(tr("["))); fActionStepBack.setIcon(stepBack); fActionStepBack.setText("Step Back"); QIcon stepForward; stepForward.addFile(QString::fromUtf8(":/next.png"), QSize(), QIcon::Normal, QIcon::Off); fActionStepForward.setShortcut(QKeySequence(tr("]"))); fActionStepForward.setIcon(stepForward); fActionStepForward.setText("Step Forward"); fActionZoomIn.setShortcut(QKeySequence(tr("Ctrl+="))); fActionZoomIn.setText("Zoom In"); fActionZoomOut.setShortcut(QKeySequence(tr("Ctrl+-"))); fActionZoomOut.setText("Zoom Out"); fListWidget.setItemDelegate(new SkListWidget(&fListWidget)); fListWidget.setObjectName(QString::fromUtf8("listWidget")); fListWidget.setMinimumWidth(250); fFilter.addItem("--Filter By Available Commands--"); fDirectoryWidget.setMinimumWidth(250); fDirectoryWidget.setStyleSheet("QListWidget::Item {padding: 5px;}"); fCanvasWidget.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); fDrawCommandGeometryWidget.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); fSettingsAndImageLayout.addWidget(&fSettingsWidget); // View state group, part of inspector. fViewStateFrame.setFrameStyle(QFrame::Panel); fViewStateFrame.setLayout(&fViewStateFrameLayout); fViewStateFrameLayout.addWidget(&fViewStateGroup); fViewStateGroup.setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); fViewStateGroup.setTitle("View"); fViewStateLayout.addRow("Zoom Level", &fZoomBox); fZoomBox.setText("100%"); fZoomBox.setMinimumSize(QSize(50,25)); fZoomBox.setMaximumSize(QSize(50,25)); fZoomBox.setAlignment(Qt::AlignRight); fZoomBox.setReadOnly(true); fViewStateLayout.addRow("Command HitBox", &fCommandHitBox); fCommandHitBox.setText("0"); fCommandHitBox.setMinimumSize(QSize(50,25)); fCommandHitBox.setMaximumSize(QSize(50,25)); fCommandHitBox.setAlignment(Qt::AlignRight); fCommandHitBox.setReadOnly(true); fViewStateLayout.addRow("Current Command", &fCurrentCommandBox); fCurrentCommandBox.setText("0"); fCurrentCommandBox.setMinimumSize(QSize(50,25)); fCurrentCommandBox.setMaximumSize(QSize(50,25)); fCurrentCommandBox.setAlignment(Qt::AlignRight); fCurrentCommandBox.setReadOnly(true); fViewStateGroup.setLayout(&fViewStateLayout); fSettingsAndImageLayout.addWidget(&fViewStateFrame); fDrawCommandGeometryWidget.setToolTip("Current Command Geometry"); fSettingsAndImageLayout.addWidget(&fDrawCommandGeometryWidget); fLeftColumnSplitter.addWidget(&fListWidget); fLeftColumnSplitter.addWidget(&fDirectoryWidget); fLeftColumnSplitter.setOrientation(Qt::Vertical); fCanvasSettingsAndImageLayout.setSpacing(6); fCanvasSettingsAndImageLayout.addWidget(&fCanvasWidget, 1); fCanvasSettingsAndImageLayout.addLayout(&fSettingsAndImageLayout, 0); fMainAndRightColumnLayout.setSpacing(6); fMainAndRightColumnLayout.addLayout(&fCanvasSettingsAndImageLayout, 1); fMainAndRightColumnLayout.addWidget(&fInspectorWidget, 0); fMainAndRightColumnWidget.setLayout(&fMainAndRightColumnLayout); fCentralSplitter.addWidget(&fLeftColumnSplitter); fCentralSplitter.addWidget(&fMainAndRightColumnWidget); fCentralSplitter.setStretchFactor(0, 0); fCentralSplitter.setStretchFactor(1, 1); SkDebuggerGUI->setCentralWidget(&fCentralSplitter); SkDebuggerGUI->setStatusBar(&fStatusBar); fToolBar.setIconSize(QSize(32, 32)); fToolBar.setToolButtonStyle(Qt::ToolButtonTextUnderIcon); SkDebuggerGUI->addToolBar(Qt::TopToolBarArea, &fToolBar); fSpacer.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); fToolBar.addAction(&fActionRewind); fToolBar.addAction(&fActionStepBack); fToolBar.addAction(&fActionPause); fToolBar.addAction(&fActionStepForward); fToolBar.addAction(&fActionPlay); fToolBar.addSeparator(); fToolBar.addAction(&fActionInspector); fToolBar.addAction(&fActionSettings); fToolBar.addSeparator(); fToolBar.addWidget(&fSpacer); fToolBar.addWidget(&fFilter); fToolBar.addAction(&fActionCancel); // TODO(chudy): Remove static call. fDirectoryWidgetActive = false; fFileName = ""; setupDirectoryWidget(""); fDirectoryWidgetActive = true; // Menu Bar fMenuFile.setTitle("File"); fMenuFile.addAction(&fActionOpen); fMenuFile.addAction(&fActionSave); fMenuFile.addAction(&fActionSaveAs); fMenuFile.addAction(&fActionClose); fMenuEdit.setTitle("Edit"); fMenuEdit.addAction(&fActionDelete); fMenuEdit.addAction(&fActionClearDeletes); fMenuEdit.addSeparator(); fMenuEdit.addAction(&fActionCreateBreakpoint); fMenuEdit.addAction(&fActionClearBreakpoints); fMenuNavigate.setTitle("Navigate"); fMenuNavigate.addAction(&fActionRewind); fMenuNavigate.addAction(&fActionStepBack); fMenuNavigate.addAction(&fActionStepForward); fMenuNavigate.addAction(&fActionPlay); fMenuNavigate.addAction(&fActionPause); fMenuNavigate.addAction(&fActionGoToLine); fMenuView.setTitle("View"); fMenuView.addAction(&fActionBreakpoint); fMenuView.addAction(&fActionShowDeletes); fMenuView.addAction(&fActionZoomIn); fMenuView.addAction(&fActionZoomOut); fMenuWindows.setTitle("Window"); fMenuWindows.addAction(&fActionInspector); fMenuWindows.addAction(&fActionSettings); fMenuWindows.addAction(&fActionDirectory); fActionGoToLine.setText("Go to Line..."); fActionGoToLine.setDisabled(true); fMenuBar.addAction(fMenuFile.menuAction()); fMenuBar.addAction(fMenuEdit.menuAction()); fMenuBar.addAction(fMenuView.menuAction()); fMenuBar.addAction(fMenuNavigate.menuAction()); fMenuBar.addAction(fMenuWindows.menuAction()); SkDebuggerGUI->setMenuBar(&fMenuBar); QMetaObject::connectSlotsByName(SkDebuggerGUI); } void SkDebuggerGUI::setupDirectoryWidget(const QString& path) { fPath = path; QDir dir(path); QRegExp r(".skp"); fDirectoryWidget.clear(); const QStringList files = dir.entryList(); foreach (QString f, files) { if (f.contains(r)) fDirectoryWidget.addItem(f); } } void SkDebuggerGUI::loadPicture(const SkString& fileName) { fFileName = fileName; fLoading = true; SkAutoTDelete<SkStream> stream(new SkFILEStream(fileName.c_str())); SkPicture* picture = SkPicture::CreateFromStream(stream); if (nullptr == picture) { QMessageBox::critical(this, "Error loading file", "Couldn't read file, sorry."); return; } fCanvasWidget.resetWidgetTransform(); fDebugger.loadPicture(picture); fSkipCommands.setCount(fDebugger.getSize()); for (int i = 0; i < fSkipCommands.count(); ++i) { fSkipCommands[i] = false; } SkSafeUnref(picture); /* fDebugCanvas is reinitialized every load picture. Need it to retain value * of the visibility filter. * TODO(chudy): This should be deprecated since fDebugger is not * recreated. * */ fDebugger.highlightCurrentCommand(fSettingsWidget.isVisibilityFilterEnabled()); this->setupListWidget(); this->setupComboBox(); this->setupOverviewText(nullptr, 0.0, 1); fInspectorWidget.setDisabled(false); fViewStateFrame.setDisabled(false); fSettingsWidget.setDisabled(false); fMenuEdit.setDisabled(false); fMenuNavigate.setDisabled(false); fMenuView.setDisabled(false); fActionSave.setDisabled(false); fActionSaveAs.setDisabled(false); fActionPause.setChecked(false); fDrawCommandGeometryWidget.setDrawCommandIndex(-1); fLoading = false; actionPlay(); } void SkDebuggerGUI::setupListWidget() { SkASSERT(!strcmp("Save", SkDrawCommand::GetCommandString(SkDrawCommand::kSave_OpType))); SkASSERT(!strcmp("SaveLayer", SkDrawCommand::GetCommandString(SkDrawCommand::kSaveLayer_OpType))); SkASSERT(!strcmp("Restore", SkDrawCommand::GetCommandString(SkDrawCommand::kRestore_OpType))); SkASSERT(!strcmp("BeginDrawPicture", SkDrawCommand::GetCommandString(SkDrawCommand::kBeginDrawPicture_OpType))); SkASSERT(!strcmp("EndDrawPicture", SkDrawCommand::GetCommandString(SkDrawCommand::kEndDrawPicture_OpType))); fListWidget.clear(); int counter = 0; int indent = 0; for (int i = 0; i < fDebugger.getSize(); i++) { QListWidgetItem *item = new QListWidgetItem(); SkDrawCommand* command = fDebugger.getDrawCommandAt(i); SkString commandString = command->toString(); item->setData(Qt::DisplayRole, commandString.c_str()); item->setData(Qt::UserRole + 1, counter++); if (0 == strcmp("Restore", commandString.c_str()) || 0 == strcmp("EndDrawPicture", commandString.c_str())) { indent -= 10; } item->setData(Qt::UserRole + 3, indent); if (0 == strcmp("Save", commandString.c_str()) || 0 == strcmp("SaveLayer", commandString.c_str()) || 0 == strcmp("BeginDrawPicture", commandString.c_str())) { indent += 10; } item->setData(Qt::UserRole + 4, -1); fListWidget.addItem(item); } } void SkDebuggerGUI::setupOverviewText(const SkTDArray<double>* typeTimes, double totTime, int numRuns) { SkString overview; fDebugger.getOverviewText(typeTimes, totTime, &overview, numRuns); fInspectorWidget.setText(overview.c_str(), SkInspectorWidget::kOverview_TabType); } void SkDebuggerGUI::setupComboBox() { fFilter.clear(); fFilter.addItem("--Filter By Available Commands--"); std::map<std::string, int> map; for (int i = 0; i < fDebugger.getSize(); i++) { map[fDebugger.getDrawCommandAt(i)->toString().c_str()]++; } for (std::map<std::string, int>::iterator it = map.begin(); it != map.end(); ++it) { fFilter.addItem((it->first).c_str()); } // NOTE(chudy): Makes first item unselectable. QStandardItemModel* model = qobject_cast<QStandardItemModel*>( fFilter.model()); QModelIndex firstIndex = model->index(0, fFilter.modelColumn(), fFilter.rootModelIndex()); QStandardItem* firstItem = model->itemFromIndex(firstIndex); firstItem->setSelectable(false); } void SkDebuggerGUI::updateImage() { if (this->isPaused()) { fCanvasWidget.drawTo(fPausedRow); } else { fCanvasWidget.drawTo(fListWidget.currentRow()); } } void SkDebuggerGUI::updateHit(int newHit) { fCommandHitBox.setText(QString::number(newHit)); } [SkDebugger] Remove unneeded SkDebuggerGUI includes R=robertphillips@google.com,mtklein@google.com Review URL: https://codereview.chromium.org/1411963006 /* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkDebuggerGUI.h" #include "SkPicture.h" #include <QListWidgetItem> #include <QtGui> #include "sk_tool_utils.h" SkDebuggerGUI::SkDebuggerGUI(QWidget *parent) : QMainWindow(parent) , fCentralSplitter(this) , fStatusBar(this) , fToolBar(this) , fActionOpen(this) , fActionBreakpoint(this) , fActionCancel(this) , fActionClearBreakpoints(this) , fActionClearDeletes(this) , fActionClose(this) , fActionCreateBreakpoint(this) , fActionDelete(this) , fActionDirectory(this) , fActionGoToLine(this) , fActionInspector(this) , fActionSettings(this) , fActionPlay(this) , fActionPause(this) , fActionRewind(this) , fActionSave(this) , fActionSaveAs(this) , fActionShowDeletes(this) , fActionStepBack(this) , fActionStepForward(this) , fActionZoomIn(this) , fActionZoomOut(this) , fMapper(this) , fListWidget(&fCentralSplitter) , fDirectoryWidget(&fCentralSplitter) , fCanvasWidget(this, &fDebugger) , fDrawCommandGeometryWidget(&fDebugger) , fMenuBar(this) , fMenuFile(this) , fMenuNavigate(this) , fMenuView(this) , fLoading(false) { setupUi(this); fListWidget.setSelectionMode(QAbstractItemView::ExtendedSelection); connect(&fListWidget, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this, SLOT(updateDrawCommandInfo())); connect(&fActionOpen, SIGNAL(triggered()), this, SLOT(openFile())); connect(&fActionDirectory, SIGNAL(triggered()), this, SLOT(toggleDirectory())); connect(&fDirectoryWidget, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this, SLOT(loadFile(QListWidgetItem *))); connect(&fActionDelete, SIGNAL(triggered()), this, SLOT(actionDelete())); connect(&fListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(toggleBreakpoint())); connect(&fActionRewind, SIGNAL(triggered()), this, SLOT(actionRewind())); connect(&fActionPlay, SIGNAL(triggered()), this, SLOT(actionPlay())); connect(&fActionStepBack, SIGNAL(triggered()), this, SLOT(actionStepBack())); connect(&fActionStepForward, SIGNAL(triggered()), this, SLOT(actionStepForward())); connect(&fActionBreakpoint, SIGNAL(triggered()), this, SLOT(actionBreakpoints())); connect(&fActionInspector, SIGNAL(triggered()), this, SLOT(actionInspector())); connect(&fActionSettings, SIGNAL(triggered()), this, SLOT(actionSettings())); connect(&fFilter, SIGNAL(activated(QString)), this, SLOT(toggleFilter(QString))); connect(&fActionCancel, SIGNAL(triggered()), this, SLOT(actionCancel())); connect(&fActionClearBreakpoints, SIGNAL(triggered()), this, SLOT(actionClearBreakpoints())); connect(&fActionClearDeletes, SIGNAL(triggered()), this, SLOT(actionClearDeletes())); connect(&fActionClose, SIGNAL(triggered()), this, SLOT(actionClose())); #if SK_SUPPORT_GPU connect(&fSettingsWidget, SIGNAL(glSettingsChanged()), this, SLOT(actionGLSettingsChanged())); #endif connect(&fSettingsWidget, SIGNAL(rasterSettingsChanged()), this, SLOT(actionRasterSettingsChanged())); connect(&fSettingsWidget, SIGNAL(visualizationsChanged()), this, SLOT(actionVisualizationsChanged())); connect(&fSettingsWidget, SIGNAL(texFilterSettingsChanged()), this, SLOT(actionTextureFilter())); connect(&fActionPause, SIGNAL(toggled(bool)), this, SLOT(pauseDrawing(bool))); connect(&fActionCreateBreakpoint, SIGNAL(activated()), this, SLOT(toggleBreakpoint())); connect(&fActionShowDeletes, SIGNAL(triggered()), this, SLOT(showDeletes())); connect(&fCanvasWidget, SIGNAL(hitChanged(int)), this, SLOT(selectCommand(int))); connect(&fCanvasWidget, SIGNAL(hitChanged(int)), this, SLOT(updateHit(int))); connect(&fCanvasWidget, SIGNAL(scaleFactorChanged(float)), this, SLOT(actionScale(float))); connect(&fActionSaveAs, SIGNAL(triggered()), this, SLOT(actionSaveAs())); connect(&fActionSave, SIGNAL(triggered()), this, SLOT(actionSave())); fMapper.setMapping(&fActionZoomIn, SkCanvasWidget::kIn_ZoomCommand); fMapper.setMapping(&fActionZoomOut, SkCanvasWidget::kOut_ZoomCommand); connect(&fActionZoomIn, SIGNAL(triggered()), &fMapper, SLOT(map())); connect(&fActionZoomOut, SIGNAL(triggered()), &fMapper, SLOT(map())); connect(&fMapper, SIGNAL(mapped(int)), &fCanvasWidget, SLOT(zoom(int))); fViewStateFrame.setDisabled(true); fInspectorWidget.setDisabled(true); fMenuEdit.setDisabled(true); fMenuNavigate.setDisabled(true); fMenuView.setDisabled(true); } void SkDebuggerGUI::actionBreakpoints() { bool breakpointsActivated = fActionBreakpoint.isChecked(); for (int row = 0; row < fListWidget.count(); row++) { QListWidgetItem *item = fListWidget.item(row); item->setHidden(item->checkState() == Qt::Unchecked && breakpointsActivated); } } void SkDebuggerGUI::showDeletes() { bool deletesActivated = fActionShowDeletes.isChecked(); for (int row = 0; row < fListWidget.count(); row++) { QListWidgetItem *item = fListWidget.item(row); item->setHidden(fDebugger.isCommandVisible(row) && deletesActivated); } } void SkDebuggerGUI::actionCancel() { for (int row = 0; row < fListWidget.count(); row++) { fListWidget.item(row)->setHidden(false); } } void SkDebuggerGUI::actionClearBreakpoints() { for (int row = 0; row < fListWidget.count(); row++) { QListWidgetItem* item = fListWidget.item(row); item->setCheckState(Qt::Unchecked); item->setData(Qt::DecorationRole, QPixmap(":/blank.png")); } } void SkDebuggerGUI::actionClearDeletes() { for (int row = 0; row < fListWidget.count(); row++) { QListWidgetItem* item = fListWidget.item(row); item->setData(Qt::UserRole + 2, QPixmap(":/blank.png")); fDebugger.setCommandVisible(row, true); fSkipCommands[row] = false; } this->updateImage(); } void SkDebuggerGUI::actionClose() { this->close(); } void SkDebuggerGUI::actionDelete() { for (int row = 0; row < fListWidget.count(); ++row) { QListWidgetItem* item = fListWidget.item(row); if (!item->isSelected()) { continue; } if (fDebugger.isCommandVisible(row)) { item->setData(Qt::UserRole + 2, QPixmap(":/delete.png")); fDebugger.setCommandVisible(row, false); fSkipCommands[row] = true; } else { item->setData(Qt::UserRole + 2, QPixmap(":/blank.png")); fDebugger.setCommandVisible(row, true); fSkipCommands[row] = false; } } this->updateImage(); } #if SK_SUPPORT_GPU void SkDebuggerGUI::actionGLSettingsChanged() { bool isToggled = fSettingsWidget.isGLActive(); if (isToggled) { fCanvasWidget.setGLSampleCount(fSettingsWidget.getGLSampleCount()); } fCanvasWidget.setWidgetVisibility(SkCanvasWidget::kGPU_WidgetType, !isToggled); } #endif void SkDebuggerGUI::actionInspector() { bool newState = !fInspectorWidget.isHidden(); fInspectorWidget.setHidden(newState); fViewStateFrame.setHidden(newState); fDrawCommandGeometryWidget.setHidden(newState); } void SkDebuggerGUI::actionPlay() { for (int row = fListWidget.currentRow() + 1; row < fListWidget.count(); row++) { QListWidgetItem *item = fListWidget.item(row); if (item->checkState() == Qt::Checked) { fListWidget.setCurrentItem(item); return; } } fListWidget.setCurrentRow(fListWidget.count() - 1); } void SkDebuggerGUI::actionRasterSettingsChanged() { fCanvasWidget.setWidgetVisibility(SkCanvasWidget::kRaster_8888_WidgetType, !fSettingsWidget.isRasterEnabled()); fDebugger.setOverdrawViz(fSettingsWidget.isOverdrawVizEnabled()); this->updateImage(); } void SkDebuggerGUI::actionVisualizationsChanged() { fDebugger.setMegaViz(fSettingsWidget.isMegaVizEnabled()); fDebugger.setPathOps(fSettingsWidget.isPathOpsEnabled()); fDebugger.highlightCurrentCommand(fSettingsWidget.isVisibilityFilterEnabled()); this->updateImage(); } void SkDebuggerGUI::actionTextureFilter() { SkFilterQuality quality; bool enabled = fSettingsWidget.getFilterOverride(&quality); fDebugger.setTexFilterOverride(enabled, quality); fCanvasWidget.update(); } void SkDebuggerGUI::actionRewind() { fListWidget.setCurrentRow(0); } void SkDebuggerGUI::actionSave() { fFileName = fPath.toAscii().data(); fFileName.append("/"); fFileName.append(fDirectoryWidget.currentItem()->text().toAscii().data()); saveToFile(fFileName); } void SkDebuggerGUI::actionSaveAs() { QString filename = QFileDialog::getSaveFileName(this, "Save File", "", "Skia Picture (*skp)"); if (!filename.endsWith(".skp", Qt::CaseInsensitive)) { filename.append(".skp"); } saveToFile(SkString(filename.toAscii().data())); } void SkDebuggerGUI::actionScale(float scaleFactor) { fZoomBox.setText(QString::number(scaleFactor * 100, 'f', 0).append("%")); } void SkDebuggerGUI::actionSettings() { if (fSettingsWidget.isHidden()) { fSettingsWidget.setHidden(false); } else { fSettingsWidget.setHidden(true); } } void SkDebuggerGUI::actionStepBack() { int currentRow = fListWidget.currentRow(); if (currentRow != 0) { fListWidget.setCurrentRow(currentRow - 1); } } void SkDebuggerGUI::actionStepForward() { int currentRow = fListWidget.currentRow(); QString curRow = QString::number(currentRow); QString curCount = QString::number(fListWidget.count()); if (currentRow < fListWidget.count() - 1) { fListWidget.setCurrentRow(currentRow + 1); } } void SkDebuggerGUI::drawComplete() { SkString clipStack; fDebugger.getClipStackText(&clipStack); fInspectorWidget.setText(clipStack.c_str(), SkInspectorWidget::kClipStack_TabType); fInspectorWidget.setMatrix(fDebugger.getCurrentMatrix()); fInspectorWidget.setClip(fDebugger.getCurrentClip()); } void SkDebuggerGUI::saveToFile(const SkString& filename) { SkFILEWStream file(filename.c_str()); SkAutoTUnref<SkPicture> copy(fDebugger.copyPicture()); sk_tool_utils::PngPixelSerializer serializer; copy->serialize(&file, &serializer); } void SkDebuggerGUI::loadFile(QListWidgetItem *item) { if (fDirectoryWidgetActive) { fFileName = fPath.toAscii().data(); // don't add a '/' to files in the local directory if (fFileName.size() > 0) { fFileName.append("/"); } fFileName.append(item->text().toAscii().data()); loadPicture(fFileName); } } void SkDebuggerGUI::openFile() { QString temp = QFileDialog::getOpenFileName(this, tr("Open File"), "", tr("Files (*.*)")); openFile(temp); } void SkDebuggerGUI::openFile(const QString &filename) { fDirectoryWidgetActive = false; if (!filename.isEmpty()) { QFileInfo pathInfo(filename); loadPicture(SkString(filename.toAscii().data())); setupDirectoryWidget(pathInfo.path()); } fDirectoryWidgetActive = true; } void SkDebuggerGUI::pauseDrawing(bool isPaused) { fPausedRow = fListWidget.currentRow(); this->updateDrawCommandInfo(); } void SkDebuggerGUI::updateDrawCommandInfo() { int currentRow = -1; if (!fLoading) { currentRow = fListWidget.currentRow(); } if (currentRow == -1) { fInspectorWidget.setText("", SkInspectorWidget::kDetail_TabType); fInspectorWidget.setText("", SkInspectorWidget::kClipStack_TabType); fCurrentCommandBox.setText(""); fDrawCommandGeometryWidget.setDrawCommandIndex(-1); } else { this->updateImage(); const SkTDArray<SkString*> *currInfo = fDebugger.getCommandInfo(currentRow); /* TODO(chudy): Add command type before parameters. Rename v * to something more informative. */ if (currInfo) { QString info; info.append("<b>Parameters: </b><br/>"); for (int i = 0; i < currInfo->count(); i++) { info.append(QString((*currInfo)[i]->c_str())); info.append("<br/>"); } fInspectorWidget.setText(info, SkInspectorWidget::kDetail_TabType); } fCurrentCommandBox.setText(QString::number(currentRow)); fDrawCommandGeometryWidget.setDrawCommandIndex(currentRow); fInspectorWidget.setDisabled(false); fViewStateFrame.setDisabled(false); } } void SkDebuggerGUI::selectCommand(int command) { if (this->isPaused()) { fListWidget.setCurrentRow(command); } } void SkDebuggerGUI::toggleBreakpoint() { QListWidgetItem* item = fListWidget.currentItem(); if (item->checkState() == Qt::Unchecked) { item->setCheckState(Qt::Checked); item->setData(Qt::DecorationRole, QPixmap(":/breakpoint_16x16.png")); } else { item->setCheckState(Qt::Unchecked); item->setData(Qt::DecorationRole, QPixmap(":/blank.png")); } } void SkDebuggerGUI::toggleDirectory() { fDirectoryWidget.setHidden(!fDirectoryWidget.isHidden()); } void SkDebuggerGUI::toggleFilter(QString string) { for (int row = 0; row < fListWidget.count(); row++) { QListWidgetItem *item = fListWidget.item(row); item->setHidden(item->text() != string); } } void SkDebuggerGUI::setupUi(QMainWindow *SkDebuggerGUI) { QIcon windowIcon; windowIcon.addFile(QString::fromUtf8(":/skia.png"), QSize(), QIcon::Normal, QIcon::Off); SkDebuggerGUI->setObjectName(QString::fromUtf8("SkDebuggerGUI")); SkDebuggerGUI->resize(1200, 1000); SkDebuggerGUI->setWindowIcon(windowIcon); SkDebuggerGUI->setWindowTitle("Skia Debugger"); fActionOpen.setShortcuts(QKeySequence::Open); fActionOpen.setText("Open"); QIcon breakpoint; breakpoint.addFile(QString::fromUtf8(":/breakpoint.png"), QSize(), QIcon::Normal, QIcon::Off); fActionBreakpoint.setShortcut(QKeySequence(tr("Ctrl+B"))); fActionBreakpoint.setIcon(breakpoint); fActionBreakpoint.setText("Breakpoints"); fActionBreakpoint.setCheckable(true); QIcon cancel; cancel.addFile(QString::fromUtf8(":/reload.png"), QSize(), QIcon::Normal, QIcon::Off); fActionCancel.setIcon(cancel); fActionCancel.setText("Clear Filter"); fActionClearBreakpoints.setShortcut(QKeySequence(tr("Alt+B"))); fActionClearBreakpoints.setText("Clear Breakpoints"); fActionClearDeletes.setShortcut(QKeySequence(tr("Alt+X"))); fActionClearDeletes.setText("Clear Deletes"); fActionClose.setShortcuts(QKeySequence::Quit); fActionClose.setText("Exit"); fActionCreateBreakpoint.setShortcut(QKeySequence(tr("B"))); fActionCreateBreakpoint.setText("Set Breakpoint"); fActionDelete.setShortcut(QKeySequence(tr("X"))); fActionDelete.setText("Delete Command"); fActionDirectory.setShortcut(QKeySequence(tr("Ctrl+D"))); fActionDirectory.setText("Directory"); QIcon inspector; inspector.addFile(QString::fromUtf8(":/inspector.png"), QSize(), QIcon::Normal, QIcon::Off); fActionInspector.setShortcut(QKeySequence(tr("Ctrl+I"))); fActionInspector.setIcon(inspector); fActionInspector.setText("Inspector"); QIcon settings; settings.addFile(QString::fromUtf8(":/inspector.png"), QSize(), QIcon::Normal, QIcon::Off); fActionSettings.setShortcut(QKeySequence(tr("Ctrl+G"))); fActionSettings.setIcon(settings); fActionSettings.setText("Settings"); QIcon play; play.addFile(QString::fromUtf8(":/play.png"), QSize(), QIcon::Normal, QIcon::Off); fActionPlay.setShortcut(QKeySequence(tr("Ctrl+P"))); fActionPlay.setIcon(play); fActionPlay.setText("Play"); QIcon pause; pause.addFile(QString::fromUtf8(":/pause.png"), QSize(), QIcon::Normal, QIcon::Off); fActionPause.setShortcut(QKeySequence(tr("Space"))); fActionPause.setCheckable(true); fActionPause.setIcon(pause); fActionPause.setText("Pause"); QIcon rewind; rewind.addFile(QString::fromUtf8(":/rewind.png"), QSize(), QIcon::Normal, QIcon::Off); fActionRewind.setShortcut(QKeySequence(tr("Ctrl+R"))); fActionRewind.setIcon(rewind); fActionRewind.setText("Rewind"); fActionSave.setShortcut(QKeySequence::Save); fActionSave.setText("Save"); fActionSave.setDisabled(true); fActionSaveAs.setShortcut(QKeySequence::SaveAs); fActionSaveAs.setText("Save As"); fActionSaveAs.setDisabled(true); fActionShowDeletes.setShortcut(QKeySequence(tr("Ctrl+X"))); fActionShowDeletes.setText("Deleted Commands"); fActionShowDeletes.setCheckable(true); QIcon stepBack; stepBack.addFile(QString::fromUtf8(":/previous.png"), QSize(), QIcon::Normal, QIcon::Off); fActionStepBack.setShortcut(QKeySequence(tr("["))); fActionStepBack.setIcon(stepBack); fActionStepBack.setText("Step Back"); QIcon stepForward; stepForward.addFile(QString::fromUtf8(":/next.png"), QSize(), QIcon::Normal, QIcon::Off); fActionStepForward.setShortcut(QKeySequence(tr("]"))); fActionStepForward.setIcon(stepForward); fActionStepForward.setText("Step Forward"); fActionZoomIn.setShortcut(QKeySequence(tr("Ctrl+="))); fActionZoomIn.setText("Zoom In"); fActionZoomOut.setShortcut(QKeySequence(tr("Ctrl+-"))); fActionZoomOut.setText("Zoom Out"); fListWidget.setItemDelegate(new SkListWidget(&fListWidget)); fListWidget.setObjectName(QString::fromUtf8("listWidget")); fListWidget.setMinimumWidth(250); fFilter.addItem("--Filter By Available Commands--"); fDirectoryWidget.setMinimumWidth(250); fDirectoryWidget.setStyleSheet("QListWidget::Item {padding: 5px;}"); fCanvasWidget.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); fDrawCommandGeometryWidget.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); fSettingsAndImageLayout.addWidget(&fSettingsWidget); // View state group, part of inspector. fViewStateFrame.setFrameStyle(QFrame::Panel); fViewStateFrame.setLayout(&fViewStateFrameLayout); fViewStateFrameLayout.addWidget(&fViewStateGroup); fViewStateGroup.setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); fViewStateGroup.setTitle("View"); fViewStateLayout.addRow("Zoom Level", &fZoomBox); fZoomBox.setText("100%"); fZoomBox.setMinimumSize(QSize(50,25)); fZoomBox.setMaximumSize(QSize(50,25)); fZoomBox.setAlignment(Qt::AlignRight); fZoomBox.setReadOnly(true); fViewStateLayout.addRow("Command HitBox", &fCommandHitBox); fCommandHitBox.setText("0"); fCommandHitBox.setMinimumSize(QSize(50,25)); fCommandHitBox.setMaximumSize(QSize(50,25)); fCommandHitBox.setAlignment(Qt::AlignRight); fCommandHitBox.setReadOnly(true); fViewStateLayout.addRow("Current Command", &fCurrentCommandBox); fCurrentCommandBox.setText("0"); fCurrentCommandBox.setMinimumSize(QSize(50,25)); fCurrentCommandBox.setMaximumSize(QSize(50,25)); fCurrentCommandBox.setAlignment(Qt::AlignRight); fCurrentCommandBox.setReadOnly(true); fViewStateGroup.setLayout(&fViewStateLayout); fSettingsAndImageLayout.addWidget(&fViewStateFrame); fDrawCommandGeometryWidget.setToolTip("Current Command Geometry"); fSettingsAndImageLayout.addWidget(&fDrawCommandGeometryWidget); fLeftColumnSplitter.addWidget(&fListWidget); fLeftColumnSplitter.addWidget(&fDirectoryWidget); fLeftColumnSplitter.setOrientation(Qt::Vertical); fCanvasSettingsAndImageLayout.setSpacing(6); fCanvasSettingsAndImageLayout.addWidget(&fCanvasWidget, 1); fCanvasSettingsAndImageLayout.addLayout(&fSettingsAndImageLayout, 0); fMainAndRightColumnLayout.setSpacing(6); fMainAndRightColumnLayout.addLayout(&fCanvasSettingsAndImageLayout, 1); fMainAndRightColumnLayout.addWidget(&fInspectorWidget, 0); fMainAndRightColumnWidget.setLayout(&fMainAndRightColumnLayout); fCentralSplitter.addWidget(&fLeftColumnSplitter); fCentralSplitter.addWidget(&fMainAndRightColumnWidget); fCentralSplitter.setStretchFactor(0, 0); fCentralSplitter.setStretchFactor(1, 1); SkDebuggerGUI->setCentralWidget(&fCentralSplitter); SkDebuggerGUI->setStatusBar(&fStatusBar); fToolBar.setIconSize(QSize(32, 32)); fToolBar.setToolButtonStyle(Qt::ToolButtonTextUnderIcon); SkDebuggerGUI->addToolBar(Qt::TopToolBarArea, &fToolBar); fSpacer.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); fToolBar.addAction(&fActionRewind); fToolBar.addAction(&fActionStepBack); fToolBar.addAction(&fActionPause); fToolBar.addAction(&fActionStepForward); fToolBar.addAction(&fActionPlay); fToolBar.addSeparator(); fToolBar.addAction(&fActionInspector); fToolBar.addAction(&fActionSettings); fToolBar.addSeparator(); fToolBar.addWidget(&fSpacer); fToolBar.addWidget(&fFilter); fToolBar.addAction(&fActionCancel); // TODO(chudy): Remove static call. fDirectoryWidgetActive = false; fFileName = ""; setupDirectoryWidget(""); fDirectoryWidgetActive = true; // Menu Bar fMenuFile.setTitle("File"); fMenuFile.addAction(&fActionOpen); fMenuFile.addAction(&fActionSave); fMenuFile.addAction(&fActionSaveAs); fMenuFile.addAction(&fActionClose); fMenuEdit.setTitle("Edit"); fMenuEdit.addAction(&fActionDelete); fMenuEdit.addAction(&fActionClearDeletes); fMenuEdit.addSeparator(); fMenuEdit.addAction(&fActionCreateBreakpoint); fMenuEdit.addAction(&fActionClearBreakpoints); fMenuNavigate.setTitle("Navigate"); fMenuNavigate.addAction(&fActionRewind); fMenuNavigate.addAction(&fActionStepBack); fMenuNavigate.addAction(&fActionStepForward); fMenuNavigate.addAction(&fActionPlay); fMenuNavigate.addAction(&fActionPause); fMenuNavigate.addAction(&fActionGoToLine); fMenuView.setTitle("View"); fMenuView.addAction(&fActionBreakpoint); fMenuView.addAction(&fActionShowDeletes); fMenuView.addAction(&fActionZoomIn); fMenuView.addAction(&fActionZoomOut); fMenuWindows.setTitle("Window"); fMenuWindows.addAction(&fActionInspector); fMenuWindows.addAction(&fActionSettings); fMenuWindows.addAction(&fActionDirectory); fActionGoToLine.setText("Go to Line..."); fActionGoToLine.setDisabled(true); fMenuBar.addAction(fMenuFile.menuAction()); fMenuBar.addAction(fMenuEdit.menuAction()); fMenuBar.addAction(fMenuView.menuAction()); fMenuBar.addAction(fMenuNavigate.menuAction()); fMenuBar.addAction(fMenuWindows.menuAction()); SkDebuggerGUI->setMenuBar(&fMenuBar); QMetaObject::connectSlotsByName(SkDebuggerGUI); } void SkDebuggerGUI::setupDirectoryWidget(const QString& path) { fPath = path; QDir dir(path); QRegExp r(".skp"); fDirectoryWidget.clear(); const QStringList files = dir.entryList(); foreach (QString f, files) { if (f.contains(r)) fDirectoryWidget.addItem(f); } } void SkDebuggerGUI::loadPicture(const SkString& fileName) { fFileName = fileName; fLoading = true; SkAutoTDelete<SkStream> stream(new SkFILEStream(fileName.c_str())); SkPicture* picture = SkPicture::CreateFromStream(stream); if (nullptr == picture) { QMessageBox::critical(this, "Error loading file", "Couldn't read file, sorry."); return; } fCanvasWidget.resetWidgetTransform(); fDebugger.loadPicture(picture); fSkipCommands.setCount(fDebugger.getSize()); for (int i = 0; i < fSkipCommands.count(); ++i) { fSkipCommands[i] = false; } SkSafeUnref(picture); /* fDebugCanvas is reinitialized every load picture. Need it to retain value * of the visibility filter. * TODO(chudy): This should be deprecated since fDebugger is not * recreated. * */ fDebugger.highlightCurrentCommand(fSettingsWidget.isVisibilityFilterEnabled()); this->setupListWidget(); this->setupComboBox(); this->setupOverviewText(nullptr, 0.0, 1); fInspectorWidget.setDisabled(false); fViewStateFrame.setDisabled(false); fSettingsWidget.setDisabled(false); fMenuEdit.setDisabled(false); fMenuNavigate.setDisabled(false); fMenuView.setDisabled(false); fActionSave.setDisabled(false); fActionSaveAs.setDisabled(false); fActionPause.setChecked(false); fDrawCommandGeometryWidget.setDrawCommandIndex(-1); fLoading = false; actionPlay(); } void SkDebuggerGUI::setupListWidget() { SkASSERT(!strcmp("Save", SkDrawCommand::GetCommandString(SkDrawCommand::kSave_OpType))); SkASSERT(!strcmp("SaveLayer", SkDrawCommand::GetCommandString(SkDrawCommand::kSaveLayer_OpType))); SkASSERT(!strcmp("Restore", SkDrawCommand::GetCommandString(SkDrawCommand::kRestore_OpType))); SkASSERT(!strcmp("BeginDrawPicture", SkDrawCommand::GetCommandString(SkDrawCommand::kBeginDrawPicture_OpType))); SkASSERT(!strcmp("EndDrawPicture", SkDrawCommand::GetCommandString(SkDrawCommand::kEndDrawPicture_OpType))); fListWidget.clear(); int counter = 0; int indent = 0; for (int i = 0; i < fDebugger.getSize(); i++) { QListWidgetItem *item = new QListWidgetItem(); SkDrawCommand* command = fDebugger.getDrawCommandAt(i); SkString commandString = command->toString(); item->setData(Qt::DisplayRole, commandString.c_str()); item->setData(Qt::UserRole + 1, counter++); if (0 == strcmp("Restore", commandString.c_str()) || 0 == strcmp("EndDrawPicture", commandString.c_str())) { indent -= 10; } item->setData(Qt::UserRole + 3, indent); if (0 == strcmp("Save", commandString.c_str()) || 0 == strcmp("SaveLayer", commandString.c_str()) || 0 == strcmp("BeginDrawPicture", commandString.c_str())) { indent += 10; } item->setData(Qt::UserRole + 4, -1); fListWidget.addItem(item); } } void SkDebuggerGUI::setupOverviewText(const SkTDArray<double>* typeTimes, double totTime, int numRuns) { SkString overview; fDebugger.getOverviewText(typeTimes, totTime, &overview, numRuns); fInspectorWidget.setText(overview.c_str(), SkInspectorWidget::kOverview_TabType); } void SkDebuggerGUI::setupComboBox() { fFilter.clear(); fFilter.addItem("--Filter By Available Commands--"); std::map<std::string, int> map; for (int i = 0; i < fDebugger.getSize(); i++) { map[fDebugger.getDrawCommandAt(i)->toString().c_str()]++; } for (std::map<std::string, int>::iterator it = map.begin(); it != map.end(); ++it) { fFilter.addItem((it->first).c_str()); } // NOTE(chudy): Makes first item unselectable. QStandardItemModel* model = qobject_cast<QStandardItemModel*>( fFilter.model()); QModelIndex firstIndex = model->index(0, fFilter.modelColumn(), fFilter.rootModelIndex()); QStandardItem* firstItem = model->itemFromIndex(firstIndex); firstItem->setSelectable(false); } void SkDebuggerGUI::updateImage() { if (this->isPaused()) { fCanvasWidget.drawTo(fPausedRow); } else { fCanvasWidget.drawTo(fListWidget.currentRow()); } } void SkDebuggerGUI::updateHit(int newHit) { fCommandHitBox.setText(QString::number(newHit)); }
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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. * ***************************************************************/ #include "condor_common.h" #include "condor_config.h" #include "util_lib_proto.h" #include "basename.h" #include "my_hostname.h" #include "condor_version.h" #include "limit.h" #include "condor_email.h" #include "sig_install.h" #include "daemon.h" #include "condor_debug.h" #include "condor_distribution.h" #include "condor_environ.h" #include "setenv.h" #include "time_offset.h" #include "subsystem_info.h" #include "file_lock.h" #include "directory.h" #include "exit.h" #if HAVE_EXT_GCB #include "GCB.h" #endif #include "file_sql.h" #include "file_xml.h" #define _NO_EXTERN_DAEMON_CORE 1 #include "condor_daemon_core.h" #ifdef WIN32 #include "exception_handling.WINDOWS.h" #endif #if HAVE_EXT_COREDUMPER #include "google/coredumper.h" #endif // Externs to Globals extern DLL_IMPORT_MAGIC char **environ; // External protos extern int main_init(int argc, char *argv[]); // old main() extern int main_config(bool is_full); extern int main_shutdown_fast(); extern int main_shutdown_graceful(); extern void main_pre_dc_init(int argc, char *argv[]); extern void main_pre_command_sock_init(); // Internal protos void dc_reconfig( bool is_full ); void dc_config_auth(); // Configuring GSI (and maybe other) authentication related stuff int handle_fetch_log_history(ReliSock *s, char *name); int handle_fetch_log_history_dir(ReliSock *s, char *name); int handle_fetch_log_history_purge(ReliSock *s); // Globals int Foreground = 0; // run in background by default static const char* myName; // set to basename(argv[0]) char *_condor_myServiceName; // name of service on Win32 (argv[0] from SCM) static char* myFullName; // set to the full path to ourselves DaemonCore* daemonCore; char* logDir = NULL; char* pidFile = NULL; char* addrFile = NULL; static char* logAppend = NULL; int condor_main_argc; char **condor_main_argv; time_t daemon_stop_time; /* ODBC object */ //extern ODBC *DBObj; /* FILESQL object */ extern FILESQL *FILEObj; /* FILEXML object */ extern FILEXML *XMLObj; #ifdef WIN32 int line_where_service_stopped = 0; #endif bool DynamicDirs = false; // runfor is non-zero if the -r command-line option is specified. // It is specified to tell a daemon to kill itself after runfor minutes. // Currently, it is only used for the master, and it is specified for // glide-in jobs that know that they can only run for a certain amount // of time. Glide-in will tell the master to kill itself a minute before // it needs to quit, and it will kill the other daemons. // // The master will check this global variable and set an environment // variable to inform the children how much time they have left to run. // This will mainly be used by the startd, which will advertise how much // time it has left before it exits. This can be used by a job's requirements // so that it can decide if it should run at a particular machine or not. int runfor = 0; //allow cmd line option to exit after *runfor* minutes // This flag tells daemoncore whether to do the authorization initialization. // It can be set to false by calling the DC_Skip_Auth_Init() function. static bool doAuthInit = true; #ifndef WIN32 // This function polls our parent process; if it is gone, shutdown. void check_parent( ) { if ( daemonCore->Is_Pid_Alive( daemonCore->getppid() ) == FALSE ) { // our parent is gone! dprintf(D_ALWAYS, "Our parent process (pid %d) went away; shutting down\n", daemonCore->getppid()); daemonCore->Send_Signal( daemonCore->getpid(), SIGTERM ); } } #endif // This function clears expired sessions from the cache void check_session_cache( ) { daemonCore->getSecMan()->invalidateExpiredCache(); } bool global_dc_set_cookie(int len, unsigned char* data) { if (daemonCore) { return daemonCore->set_cookie(len, data); } else { return false; } } bool global_dc_get_cookie(int &len, unsigned char* &data) { if (daemonCore) { return daemonCore->get_cookie(len, data); } else { return false; } } void handle_cookie_refresh( ) { unsigned char randomjunk[256]; char symbols[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; for (int i = 0; i < 128; i++) { randomjunk[i] = symbols[rand() % 16]; } // good ol null terminator randomjunk[127] = 0; global_dc_set_cookie (128, randomjunk); } char const* global_dc_sinful() { if (daemonCore) { return daemonCore->InfoCommandSinfulString(); } else { return NULL; } } void clean_files() { // If we created a pid file, remove it. if( pidFile ) { if( unlink(pidFile) < 0 ) { dprintf( D_ALWAYS, "DaemonCore: ERROR: Can't delete pid file %s\n", pidFile ); } else { if( DebugFlags & (D_FULLDEBUG | D_DAEMONCORE) ) { dprintf( D_DAEMONCORE, "Removed pid file %s\n", pidFile ); } } } if( addrFile ) { if( unlink(addrFile) < 0 ) { dprintf( D_ALWAYS, "DaemonCore: ERROR: Can't delete address file %s\n", addrFile ); } else { if( DebugFlags & (D_FULLDEBUG | D_DAEMONCORE) ) { dprintf( D_DAEMONCORE, "Removed address file %s\n", addrFile ); } } // Since we param()'ed for this, we need to free it now. free( addrFile ); } if(daemonCore) { if( daemonCore->localAdFile ) { if( unlink(daemonCore->localAdFile) < 0 ) { dprintf( D_ALWAYS, "DaemonCore: ERROR: Can't delete classad file %s\n", daemonCore->localAdFile ); } else { if( DebugFlags & (D_FULLDEBUG | D_DAEMONCORE) ) { dprintf( D_DAEMONCORE, "Removed local classad file %s\n", daemonCore->localAdFile ); } } free( daemonCore->localAdFile ); daemonCore->localAdFile = NULL; } } } // All daemons call this function when they want daemonCore to really // exit. Put any daemon-wide shutdown code in here. void DC_Exit( int status, const char *shutdown_program ) { // First, delete any files we might have created, like the // address file or the pid file. clean_files(); if(FILEObj) { delete FILEObj; FILEObj = NULL; } if(XMLObj) { delete XMLObj; XMLObj = NULL; } // See if this daemon wants to be restarted (true by // default). If so, use the given status. Otherwise, use the // special code to tell our parent not to restart us. int exit_status; if (daemonCore == NULL || daemonCore->wantsRestart()) { exit_status = status; } else { exit_status = DAEMON_NO_RESTART; } // Now, delete the daemonCore object, since we allocated it. unsigned long pid = daemonCore->getpid( ); delete daemonCore; daemonCore = NULL; // Free up the memory from the config hash table, too. clear_config(); // and deallocate the memory from the passwd_cache (uids.C) delete_passwd_cache(); /* Log a message. We want to do this *AFTER* we delete the daemonCore object and free up other memory, just to make sure we don't hit an EXCEPT() or anything in there and end up exiting with something else after we print this. all the dprintf() code has already initialized everything it needs to know from the config file, so it's ok that we already cleared out our config hashtable, too. Derek 2004-11-23 */ if ( shutdown_program ) { # if (HAVE_EXECL) dprintf( D_ALWAYS, "**** %s (%s_%s) pid %lu EXITING BY EXECING %s\n", myName, myDistro->Get(), get_mySubSystem()->getName(), pid, shutdown_program ); int exec_status = execl( shutdown_program, shutdown_program, NULL ); dprintf( D_ALWAYS, "**** execl() FAILED %d %d %s\n", exec_status, errno, strerror(errno) ); # elif defined(WIN32) dprintf( D_ALWAYS, "**** %s (%s_%s) pid %lu EXECING SHUTDOWN PROGRAM %s\n", myName, myDistro->Get(), get_mySubSystem()->getName(), pid, shutdown_program ); int exec_status = execl( shutdown_program, shutdown_program, NULL ); if ( exec_status ) { dprintf( D_ALWAYS, "**** _execl() FAILED %d %d %s\n", exec_status, errno, strerror(errno) ); } # else dprintf( D_ALWAYS, "**** execl() not available on this system\n" ); # endif } dprintf( D_ALWAYS, "**** %s (%s_%s) pid %lu EXITING WITH STATUS %d\n", myName, myDistro->Get(), get_mySubSystem()->getName(), pid, exit_status ); // Finally, exit with the appropriate status. exit( exit_status ); } void DC_Skip_Auth_Init() { doAuthInit = false; } static void kill_daemon_ad_file() { MyString param_name; param_name.sprintf( "%s_DAEMON_AD_FILE", get_mySubSystem()->getName() ); char *ad_file = param(param_name.Value()); if( !ad_file ) { return; } unlink(ad_file); free(ad_file); } void drop_addr_file() { FILE *ADDR_FILE; char addr_file[100]; sprintf( addr_file, "%s_ADDRESS_FILE", get_mySubSystem()->getName() ); if( addrFile ) { free( addrFile ); } addrFile = param( addr_file ); if( addrFile ) { MyString newAddrFile; newAddrFile.sprintf("%s.new",addrFile); if( (ADDR_FILE = safe_fopen_wrapper(newAddrFile.Value(), "w")) ) { // Always prefer the local, private address if possible. const char* addr = daemonCore->privateNetworkIpAddr(); if (!addr) { // And if not, fall back to the public. addr = daemonCore->publicNetworkIpAddr(); } fprintf( ADDR_FILE, "%s\n", addr ); fprintf( ADDR_FILE, "%s\n", CondorVersion() ); fprintf( ADDR_FILE, "%s\n", CondorPlatform() ); fclose( ADDR_FILE ); if( rotate_file(newAddrFile.Value(),addrFile)!=0 ) { dprintf( D_ALWAYS, "DaemonCore: ERROR: failed to rotate %s to %s\n", newAddrFile.Value(), addrFile); } } else { dprintf( D_ALWAYS, "DaemonCore: ERROR: Can't open address file %s\n", newAddrFile.Value() ); } } } void drop_pid_file() { FILE *PID_FILE; if( !pidFile ) { // There's no file, just return return; } if( (PID_FILE = safe_fopen_wrapper(pidFile, "w")) ) { fprintf( PID_FILE, "%lu\n", (unsigned long)daemonCore->getpid() ); fclose( PID_FILE ); } else { dprintf( D_ALWAYS, "DaemonCore: ERROR: Can't open pid file %s\n", pidFile ); } } void do_kill() { #ifndef WIN32 FILE *PID_FILE; pid_t pid = 0; unsigned long tmp_ul_int = 0; char *log, *tmp; if( !pidFile ) { fprintf( stderr, "DaemonCore: ERROR: no pidfile specified for -kill\n" ); exit( 1 ); } if( pidFile[0] != '/' ) { // There's no absolute path, append the LOG directory if( (log = param("LOG")) ) { tmp = (char*)malloc( (strlen(log) + strlen(pidFile) + 2) * sizeof(char) ); sprintf( tmp, "%s/%s", log, pidFile ); free( log ); pidFile = tmp; } } if( (PID_FILE = safe_fopen_wrapper(pidFile, "r")) ) { fscanf( PID_FILE, "%lu", &tmp_ul_int ); pid = (pid_t)tmp_ul_int; fclose( PID_FILE ); } else { fprintf( stderr, "DaemonCore: ERROR: Can't open pid file %s for reading\n", pidFile ); exit( 1 ); } if( pid > 0 ) { // We have a valid pid, try to kill it. if( kill(pid, SIGTERM) < 0 ) { fprintf( stderr, "DaemonCore: ERROR: can't send SIGTERM to pid (%lu)\n", (unsigned long)pid ); fprintf( stderr, "\terrno: %d (%s)\n", errno, strerror(errno) ); exit( 1 ); } // kill worked, now, make sure the thing is gone. Keep // trying to send signal 0 (test signal) to the process // until that fails. while( kill(pid, 0) == 0 ) { sleep( 3 ); } // Everything's cool, exit normally. exit( 0 ); } else { // Invalid pid fprintf( stderr, "DaemonCore: ERROR: pid (%lu) in pid file (%s) is invalid.\n", (unsigned long)pid, pidFile ); exit( 1 ); } #endif // of ifndef WIN32 } // Create the directory we were given, with extra error checking. void make_dir( const char* logdir ) { mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO; struct stat stats; if( stat(logdir, &stats) >= 0 ) { if( ! S_ISDIR(stats.st_mode) ) { fprintf( stderr, "DaemonCore: ERROR: %s exists and is not a directory.\n", logdir ); exit( 1 ); } } else { if( mkdir(logdir, mode) < 0 ) { fprintf( stderr, "DaemonCore: ERROR: can't create directory %s\n", logdir ); fprintf( stderr, "\terrno: %d (%s)\n", errno, strerror(errno) ); exit( 1 ); } } } // Set our log directory in our config hash table, and create it. void set_log_dir() { if( !logDir ) { return; } config_insert( "LOG", logDir ); make_dir( logDir ); } void handle_log_append( char* append_str ) { if( ! append_str ) { return; } char *tmp1, *tmp2; char buf[100]; sprintf( buf, "%s_LOG", get_mySubSystem()->getName() ); if( !(tmp1 = param(buf)) ) { EXCEPT( "%s not defined!", buf ); } tmp2 = (char*)malloc( (strlen(tmp1) + strlen(append_str) + 2) * sizeof(char) ); if( !tmp2 ) { EXCEPT( "Out of memory!" ); } sprintf( tmp2, "%s.%s", tmp1, append_str ); config_insert( buf, tmp2 ); free( tmp1 ); free( tmp2 ); } void dc_touch_log_file( ) { dprintf_touch_log(); daemonCore->Register_Timer( param_integer( "TOUCH_LOG_INTERVAL", 60 ), dc_touch_log_file, "dc_touch_log_file" ); } void dc_touch_lock_files( ) { priv_state p; // For any outstanding lock objects that are associated with the real lock // file, update their timestamps. Do it as Condor, and ignore files that we // don't have permissions to alter. This allows things like the Instance // lock to be updated, but doesn't update things like the job event log. // do this here to make the priv switching operations fast in the // FileLock Object. p = set_condor_priv(); FileLock::updateAllLockTimestamps(); set_priv(p); // reset the timer for next incarnation of the update. daemonCore->Register_Timer( param_integer("LOCK_FILE_UPDATE_INTERVAL", 3600 * 8, 60, INT_MAX), dc_touch_lock_files, "dc_touch_lock_files" ); } void set_dynamic_dir( char* param_name, const char* append_str ) { char* val; MyString newdir; val = param( (char *)param_name ); if( ! val ) { // nothing to do return; } // First, create the new name. newdir.sprintf( "%s.%s", val, append_str ); // Next, try to create the given directory, if it doesn't // already exist. make_dir( newdir.Value() ); // Now, set our own config hashtable entry so we start using // this new directory. config_insert( (char *) param_name, newdir.Value() ); // Finally, insert the _condor_<param_name> environment // variable, so our children get the right configuration. MyString env_str( "_" ); env_str += myDistro->Get(); env_str += "_"; env_str += param_name; env_str += "="; env_str += newdir; char *env_cstr = strdup( env_str.Value() ); if( SetEnv(env_cstr) != TRUE ) { fprintf( stderr, "ERROR: Can't add %s to the environment!\n", env_cstr ); exit( 4 ); } } void handle_dynamic_dirs() { // We want the log, spool and execute directory of ourselves // and our children to have our pid appended to them. If the // directories aren't there, we should create them, as Condor, // if possible. if( ! DynamicDirs ) { return; } int mypid = daemonCore->getpid(); char buf[256]; sprintf( buf, "%s-%d", inet_ntoa(*(my_sin_addr())), mypid ); set_dynamic_dir( "LOG", buf ); set_dynamic_dir( "SPOOL", buf ); set_dynamic_dir( "EXECUTE", buf ); // Final, evil hack. Set the _condor_STARTD_NAME environment // variable, so that the startd will have a unique name. sprintf( buf, "_%s_STARTD_NAME=%d", myDistro->Get(), mypid ); char* env_str = strdup( buf ); if( SetEnv(env_str) != TRUE ) { fprintf( stderr, "ERROR: Can't add %s to the environment!\n", env_str ); exit( 4 ); } } static char *core_dir = NULL; #if HAVE_EXT_COREDUMPER void linux_sig_coredump(int signum) { struct sigaction sa; static bool down = false; /* It turns out that the abort() call will unblock the sig abort signal and allow the handler to be called again. So, in a real world case, which led me to write this test, glibc decided something was wrong and called abort(), then, in this signal handler, we tickled the exact thing glibc didn't like in the first place and so it called abort() again, leading back to this handler. A segmentation fault happened finally when the stack was exhausted. This guard is here to prevent that type of scenario from happening again with this handler. This fixes ticket number #183 in the condor-wiki. NOTE: We never set down to false again, because this handler is meant to exit() and not return. */ if (down == true) { return; } down = true; dprintf_dump_stack(); // Just in case we're running as condor or a user. setuid(0); setgid(0); if (core_dir != NULL) { chdir(core_dir); } WriteCoreDump("core"); // It would be a good idea to actually terminate for the same reason. sa.sa_handler = SIG_DFL; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(signum, &sa, NULL); sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL); raise(signum); // If for whatever reason the second raise doesn't kill us properly, // we shall exit with a non-zero code so if anything depends on us, // at least they know there was a problem. exit(1); } #endif void install_core_dump_handler() { #if HAVE_EXT_COREDUMPER // We only need to do this if we're root. if( getuid() == 0) { dprintf(D_FULLDEBUG, "Running as root. Enabling specialized core dump routines\n"); sigset_t fullset; sigfillset( &fullset ); install_sig_handler_with_mask(SIGSEGV, &fullset, linux_sig_coredump); install_sig_handler_with_mask(SIGABRT, &fullset, linux_sig_coredump); install_sig_handler_with_mask(SIGILL, &fullset, linux_sig_coredump); install_sig_handler_with_mask(SIGFPE, &fullset, linux_sig_coredump); install_sig_handler_with_mask(SIGBUS, &fullset, linux_sig_coredump); } # endif // of ifdef HAVE_EXT_COREDUMPER } void drop_core_in_log( void ) { // chdir to the LOG directory so that if we dump a core // it will go there. // and on Win32, tell our ExceptionHandler class to drop // its pseudo-core file to the LOG directory as well. char* ptmp = param("LOG"); if ( ptmp ) { if ( chdir(ptmp) < 0 ) { EXCEPT("cannot chdir to dir <%s>",ptmp); } } else { dprintf( D_FULLDEBUG, "No LOG directory specified in config file(s), " "not calling chdir()\n" ); return; } core_dir = strdup(ptmp); // in some case we need to hook up our own handler to generate // core files. install_core_dump_handler(); #ifdef WIN32 { // give our Win32 exception handler a filename for the core file char pseudoCoreFileName[MAX_PATH]; sprintf(pseudoCoreFileName,"%s\\core.%s.WIN32",ptmp, get_mySubSystem()->getName() ); g_ExceptionHandler.SetLogFileName(pseudoCoreFileName); // set the path where our Win32 exception handler can find // debug symbols char *binpath = param("BIN"); if ( binpath ) { SetEnv( "_NT_SYMBOL_PATH", binpath ); free(binpath); } // give the handler our pid g_ExceptionHandler.SetPID ( daemonCore->getpid () ); } #endif free(ptmp); } // See if we should set the limits on core files. If the parameter is // defined, do what it says. Otherwise, do nothing. // On NT, if CREATE_CORE_FILES is False, then we will use the // default NT exception handler which brings up the "Abort or Debug" // dialog box, etc. Otherwise, we will just write out a core file // "summary" in the log directory and not display the dialog. void check_core_files() { char* tmp; int want_set_error_mode = TRUE; if( (tmp = param("CREATE_CORE_FILES")) ) { #ifndef WIN32 if( *tmp == 't' || *tmp == 'T' ) { limit( RLIMIT_CORE, RLIM_INFINITY, CONDOR_SOFT_LIMIT,"max core size" ); } else { limit( RLIMIT_CORE, 0, CONDOR_SOFT_LIMIT,"max core size" ); } #endif if( *tmp == 'f' || *tmp == 'F' ) { want_set_error_mode = FALSE; } free( tmp ); } #ifdef WIN32 // Call SetErrorMode so that Win32 "critical errors" and such // do not open up a dialog window! if ( want_set_error_mode ) { ::SetErrorMode( SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX ); g_ExceptionHandler.TurnOn(); } else { ::SetErrorMode( 0 ); g_ExceptionHandler.TurnOff(); } #endif } static int handle_off_fast( Service*, int, Stream* stream) { if( !stream->end_of_message() ) { dprintf( D_ALWAYS, "handle_off_fast: failed to read end of message\n"); return FALSE; } daemonCore->Send_Signal( daemonCore->getpid(), SIGQUIT ); return TRUE; } static int handle_off_graceful( Service*, int, Stream* stream) { if( !stream->end_of_message() ) { dprintf( D_ALWAYS, "handle_off_graceful: failed to read end of message\n"); return FALSE; } daemonCore->Send_Signal( daemonCore->getpid(), SIGTERM ); return TRUE; } static int handle_off_peaceful( Service*, int, Stream* stream) { // Peaceful shutdown is the same as graceful, except // there is no timeout waiting for things to finish. if( !stream->end_of_message() ) { dprintf( D_ALWAYS, "handle_off_peaceful: failed to read end of message\n"); return FALSE; } daemonCore->SetPeacefulShutdown(true); daemonCore->Send_Signal( daemonCore->getpid(), SIGTERM ); return TRUE; } static int handle_set_peaceful_shutdown( Service*, int, Stream* stream) { // If the master could send peaceful shutdown signals, it would // not be necessary to have a message for turning on the peaceful // shutdown toggle. Since the master only sends fast and graceful // shutdown signals, condor_off is responsible for first turning // on peaceful shutdown in appropriate daemons. if( !stream->end_of_message() ) { dprintf( D_ALWAYS, "handle_set_peaceful_shutdown: failed to read end of message\n"); return FALSE; } daemonCore->SetPeacefulShutdown(true); return TRUE; } static int handle_reconfig( Service*, int cmd, Stream* stream ) { if( !stream->end_of_message() ) { dprintf( D_ALWAYS, "handle_reconfig: failed to read end of message\n"); return FALSE; } if( cmd == DC_RECONFIG_FULL ) { dc_reconfig( true ); } else { dc_reconfig( false ); } return TRUE; } int handle_fetch_log( Service *, int, ReliSock *stream ) { char *name = NULL; int total_bytes = 0; int result; int type = -1; if( ! stream->code(type) || ! stream->code(name) || ! stream->end_of_message()) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log: can't read log request\n" ); free( name ); return FALSE; } stream->encode(); switch (type) { case DC_FETCH_LOG_TYPE_PLAIN: break; // handled below case DC_FETCH_LOG_TYPE_HISTORY: return handle_fetch_log_history(stream, name); case DC_FETCH_LOG_TYPE_HISTORY_DIR: return handle_fetch_log_history_dir(stream, name); case DC_FETCH_LOG_TYPE_HISTORY_PURGE: free(name); return handle_fetch_log_history_purge(stream); default: dprintf(D_ALWAYS,"DaemonCore: handle_fetch_log: I don't know about log type %d!\n",type); result = DC_FETCH_LOG_RESULT_BAD_TYPE; stream->code(result); stream->end_of_message(); free(name); return FALSE; } char *pname = (char*)malloc (strlen(name) + 5); char *ext = strchr(name,'.'); //If there is a dot in the name, it is of the form "<SUBSYS>.<ext>" //Otherwise, it is "<SUBSYS>". The file extension is used to //handle such things as "StarterLog.slot1" and "StarterLog.cod" if(ext) { strncpy(pname, name, ext-name); pname[ext-name] = '\0'; } else { strcpy(pname, name); } strcat (pname, "_LOG"); char *filename = param(pname); if(!filename) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log: no parameter named %s\n",pname); result = DC_FETCH_LOG_RESULT_NO_NAME; stream->code(result); stream->end_of_message(); free(pname); free(name); return FALSE; } MyString full_filename = filename; if(ext) { full_filename += ext; } int fd = safe_open_wrapper(full_filename.Value(),O_RDONLY); if(fd<0) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log: can't open file %s\n",full_filename.Value()); result = DC_FETCH_LOG_RESULT_CANT_OPEN; stream->code(result); stream->end_of_message(); free(filename); free(pname); free(name); return FALSE; } result = DC_FETCH_LOG_RESULT_SUCCESS; stream->code(result); filesize_t size; stream->put_file(&size, fd); total_bytes += size; stream->end_of_message(); if(total_bytes<0) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log: couldn't send all data!\n"); } close(fd); free(filename); free(pname); free(name); return total_bytes>=0; } int handle_fetch_log_history(ReliSock *stream, char *name) { int result = DC_FETCH_LOG_RESULT_BAD_TYPE; char *history_file_param = "HISTORY"; if (strcmp(name, "STARTD_HISTORY") == 0) { history_file_param = "STARTD_HISTORY"; } free(name); char *history_file = param(history_file_param); if (!history_file) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log_history: no parameter named %s\n", history_file_param); stream->code(result); stream->end_of_message(); return FALSE; } int fd = safe_open_wrapper(history_file,O_RDONLY); free(history_file); if(fd<0) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log_history: can't open history file\n"); result = DC_FETCH_LOG_RESULT_CANT_OPEN; stream->code(result); stream->end_of_message(); return FALSE; } result = DC_FETCH_LOG_RESULT_SUCCESS; stream->code(result); filesize_t size; stream->put_file(&size, fd); stream->end_of_message(); if(size<0) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log_history: couldn't send all data!\n"); } close(fd); return TRUE; } int handle_fetch_log_history_dir(ReliSock *stream, char *paramName) { int result = DC_FETCH_LOG_RESULT_BAD_TYPE; free(paramName); char *dirName = param("STARTD.PER_JOB_HISTORY_DIR"); if (!dirName) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log_history_dir: no parameter named PER_JOB\n"); stream->code(result); stream->end_of_message(); return FALSE; } Directory d(dirName); const char *filename; int one=1; int zero=0; while ((filename = d.Next())) { stream->code(one); // more data stream->put(filename); MyString fullPath(dirName); fullPath += "/"; fullPath += filename; int fd = safe_open_wrapper(fullPath.Value(),O_RDONLY); if (fd > 0) { filesize_t size; stream->put_file(&size, fd); } } free(dirName); stream->code(zero); // no more data stream->end_of_message(); return 0; } int handle_fetch_log_history_purge(ReliSock *s) { int result = 0; time_t cutoff = 0; s->code(cutoff); s->end_of_message(); s->encode(); char *dirName = param("STARTD.PER_JOB_HISTORY_DIR"); if (!dirName) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log_history_dir: no parameter named PER_JOB\n"); s->code(result); s->end_of_message(); return FALSE; } Directory d(dirName); result = 1; while (d.Next()) { time_t last = d.GetModifyTime(); if (last < cutoff) { d.Remove_Current_File(); } } free(dirName); s->code(result); // no more data s->end_of_message(); return 0; } int handle_nop( Service*, int, Stream* stream) { if( !stream->end_of_message() ) { dprintf( D_ALWAYS, "handle_nop: failed to read end of message\n"); return FALSE; } return TRUE; } int handle_invalidate_key( Service*, int, Stream* stream) { int result = 0; char *key_id = NULL; stream->decode(); if ( ! stream->code(key_id) ) { dprintf ( D_ALWAYS, "DC_INVALIDATE_KEY: unable to receive key id!.\n"); return FALSE; } if ( ! stream->end_of_message() ) { dprintf ( D_ALWAYS, "DC_INVALIDATE_KEY: unable to receive EOM on key %s.\n", key_id); return FALSE; } result = daemonCore->getSecMan()->invalidateKey(key_id); free(key_id); return result; } int handle_config_val( Service*, int, Stream* stream ) { char *param_name = NULL, *tmp; stream->decode(); if( ! stream->code(param_name) ) { dprintf( D_ALWAYS, "Can't read parameter name\n" ); free( param_name ); return FALSE; } if( ! stream->end_of_message() ) { dprintf( D_ALWAYS, "Can't read end_of_message\n" ); free( param_name ); return FALSE; } stream->encode(); tmp = param( param_name ); if( ! tmp ) { dprintf( D_FULLDEBUG, "Got DC_CONFIG_VAL request for unknown parameter (%s)\n", param_name ); free( param_name ); if( ! stream->put("Not defined") ) { dprintf( D_ALWAYS, "Can't send reply for DC_CONFIG_VAL\n" ); return FALSE; } if( ! stream->end_of_message() ) { dprintf( D_ALWAYS, "Can't send end of message for DC_CONFIG_VAL\n" ); return FALSE; } return FALSE; } else { free( param_name ); if( ! stream->code(tmp) ) { dprintf( D_ALWAYS, "Can't send reply for DC_CONFIG_VAL\n" ); free( tmp ); return FALSE; } free( tmp ); if( ! stream->end_of_message() ) { dprintf( D_ALWAYS, "Can't send end of message for DC_CONFIG_VAL\n" ); return FALSE; } } return TRUE; } int handle_config( Service *, int cmd, Stream *stream ) { char *admin = NULL, *config = NULL; char *to_check = NULL; int rval = 0; bool failed = false; stream->decode(); if ( ! stream->code(admin) ) { dprintf( D_ALWAYS, "Can't read admin string\n" ); free( admin ); return FALSE; } if ( ! stream->code(config) ) { dprintf( D_ALWAYS, "Can't read configuration string\n" ); free( admin ); free( config ); return FALSE; } if( !stream->end_of_message() ) { dprintf( D_ALWAYS, "handle_config: failed to read end of message\n"); return FALSE; } if( config && config[0] ) { to_check = config; } else { to_check = admin; } if( ! daemonCore->CheckConfigSecurity(to_check, (Sock*)stream) ) { // This request is insecure, so don't try to do anything // with it. We can't return yet, since we want to send // back an rval indicating the error. free( admin ); free( config ); rval = -1; failed = true; } // If we haven't hit an error yet, try to process the command if( ! failed ) { switch(cmd) { case DC_CONFIG_PERSIST: rval = set_persistent_config(admin, config); // set_persistent_config will free admin and config // when appropriate break; case DC_CONFIG_RUNTIME: rval = set_runtime_config(admin, config); // set_runtime_config will free admin and config when // appropriate break; default: dprintf( D_ALWAYS, "unknown DC_CONFIG command!\n" ); free( admin ); free( config ); return FALSE; } } stream->encode(); if ( ! stream->code(rval) ) { dprintf (D_ALWAYS, "Failed to send rval for DC_CONFIG.\n" ); return FALSE; } if( ! stream->end_of_message() ) { dprintf( D_ALWAYS, "Can't send end of message for DC_CONFIG.\n" ); return FALSE; } return (failed ? FALSE : TRUE); } #ifndef WIN32 void unix_sighup(int) { daemonCore->Send_Signal( daemonCore->getpid(), SIGHUP ); } void unix_sigterm(int) { daemonCore->Send_Signal( daemonCore->getpid(), SIGTERM ); } void unix_sigquit(int) { daemonCore->Send_Signal( daemonCore->getpid(), SIGQUIT ); } void unix_sigchld(int) { daemonCore->Send_Signal( daemonCore->getpid(), SIGCHLD ); } void unix_sigusr1(int) { daemonCore->Send_Signal( daemonCore->getpid(), SIGUSR1 ); } void unix_sigusr2(int) { daemonCore->Send_Signal( daemonCore->getpid(), SIGUSR2 ); } #endif /* ! WIN32 */ void dc_reconfig( bool is_full ) { // do this first in case anything else depends on DNS daemonCore->refreshDNS(); // Actually re-read the files... Added by Derek Wright on // 12/8/97 (long after this function was first written... // nice goin', Todd). *grin* /* purify flags this as a stack bounds array read violation when we're expecting to use the default argument. However, due to _craziness_ in the header file that declares this function as an extern "C" linkage with a default argument(WTF!?) while being called in a C++ context, something goes wrong. So, we'll just supply the errant argument. */ config(0); // See if we're supposed to be allowing core files or not check_core_files(); if( DynamicDirs ) { handle_dynamic_dirs(); } // If we're supposed to be using our own log file, reset that here. if( logDir ) { set_log_dir(); } if( logAppend ) { handle_log_append( logAppend ); } // Reinitialize logging system; after all, LOG may have been changed. dprintf_config(get_mySubSystem()->getName() ); // again, chdir to the LOG directory so that if we dump a core // it will go there. the location of LOG may have changed, so redo it here. drop_core_in_log(); // Re-read everything from the config file DaemonCore itself cares about. // This also cleares the DNS cache. daemonCore->reconfig(); // Clear out the passwd cache. if( is_full ) { clear_passwd_cache(); } // Re-drop the address file, if it's defined, just to be safe. drop_addr_file(); // Re-drop the pid file, if it's requested, just to be safe. if( pidFile ) { drop_pid_file(); } // If requested to do so in the config file, do a segv now. // This is to test our handling/writing of a core file. char* ptmp; if ( (ptmp=param("DROP_CORE_ON_RECONFIG")) && (*ptmp=='T' || *ptmp=='t') ) { // on purpose, derefernce a null pointer. ptmp = NULL; char segfault; segfault = *ptmp; // should blow up here ptmp[0] = 'a'; // should never make it to here! EXCEPT("FAILED TO DROP CORE"); } // call this daemon's specific main_config() main_config( is_full ); } int handle_dc_sighup( Service*, int ) { dprintf( D_ALWAYS, "Got SIGHUP. Re-reading config files.\n" ); dc_reconfig( true ); return TRUE; } int handle_dc_sigterm( Service*, int ) { static int been_here = FALSE; if( been_here ) { dprintf( D_FULLDEBUG, "Got SIGTERM, but we've already done graceful shutdown. Ignoring.\n" ); return TRUE; } been_here = TRUE; dprintf(D_ALWAYS, "Got SIGTERM. Performing graceful shutdown.\n"); #if defined(WIN32) && 0 if ( line_where_service_stopped != 0 ) { dprintf(D_ALWAYS,"Line where service stopped = %d\n", line_where_service_stopped); } #endif if( daemonCore->GetPeacefulShutdown() ) { dprintf( D_FULLDEBUG, "Peaceful shutdown in effect. No timeout enforced.\n"); } else { int timeout = 30 * MINUTE; char* tmp = param( "SHUTDOWN_GRACEFUL_TIMEOUT" ); if( tmp ) { timeout = atoi( tmp ); free( tmp ); } daemonCore->Register_Timer( timeout, 0, (TimerHandler)main_shutdown_fast, "main_shutdown_fast" ); dprintf( D_FULLDEBUG, "Started timer to call main_shutdown_fast in %d seconds\n", timeout ); } main_shutdown_graceful(); return TRUE; } int handle_dc_sigquit( Service*, int ) { static int been_here = FALSE; if( been_here ) { dprintf( D_FULLDEBUG, "Got SIGQUIT, but we've already done fast shutdown. Ignoring.\n" ); return TRUE; } been_here = TRUE; dprintf(D_ALWAYS, "Got SIGQUIT. Performing fast shutdown.\n"); main_shutdown_fast(); return TRUE; } void handle_gcb_recovery_failed( ) { dprintf( D_ALWAYS, "GCB failed to recover from a failure with the " "Broker. Performing fast shutdown.\n" ); main_shutdown_fast(); } static void gcb_recovery_failed_callback() { // BEWARE! This function is called by GCB. Most likely, either // DaemonCore is blocked on a select() or CEDAR is blocked on a // network operation. So we register a daemoncore timer to do // the real work. daemonCore->Register_Timer( 0, handle_gcb_recovery_failed, "handle_gcb_recovery_failed" ); } // This is the main entry point for daemon core. On WinNT, however, we // have a different, smaller main which checks if "-f" is ommitted from // the command line args of the condor_master, in which case it registers as // an NT service. #ifdef WIN32 int dc_main( int argc, char** argv ) #else int main( int argc, char** argv ) #endif { char** ptr; int command_port = -1; int http_port = -1; int dcargs = 0; // number of daemon core command-line args found char *ptmp, *ptmp1; int i; int wantsKill = FALSE, wantsQuiet = FALSE; condor_main_argc = argc; condor_main_argv = (char **)malloc((argc+1)*sizeof(char *)); for(i=0;i<argc;i++) { condor_main_argv[i] = strdup(argv[i]); } condor_main_argv[i] = NULL; #ifdef WIN32 /** Enable support of the %n format in the printf family of functions. */ _set_printf_count_output(TRUE); #endif #ifndef WIN32 // Set a umask value so we get reasonable permissions on the // files we create. Derek Wright <wright@cs.wisc.edu> 3/3/98 umask( 022 ); // Handle Unix signals // Block all signals now. We'll unblock them right before we // do the select. sigset_t fullset; sigfillset( &fullset ); // We do not want to block the following signals ---- sigdelset(&fullset, SIGSEGV); // so we get a core right away sigdelset(&fullset, SIGABRT); // so assert() failures drop core right away sigdelset(&fullset, SIGILL); // so we get a core right away sigdelset(&fullset, SIGBUS); // so we get a core right away sigdelset(&fullset, SIGFPE); // so we get a core right away sigdelset(&fullset, SIGTRAP); // so gdb works when it uses SIGTRAP sigprocmask( SIG_SETMASK, &fullset, NULL ); // Install these signal handlers with a default mask // of all signals blocked when we're in the handlers. install_sig_handler_with_mask(SIGQUIT, &fullset, unix_sigquit); install_sig_handler_with_mask(SIGHUP, &fullset, unix_sighup); install_sig_handler_with_mask(SIGTERM, &fullset, unix_sigterm); install_sig_handler_with_mask(SIGCHLD, &fullset, unix_sigchld); install_sig_handler_with_mask(SIGUSR1, &fullset, unix_sigusr1); install_sig_handler_with_mask(SIGUSR2, &fullset, unix_sigusr2); install_sig_handler(SIGPIPE, SIG_IGN ); #endif // of ifndef WIN32 _condor_myServiceName = argv[0]; // set myName to be argv[0] with the path stripped off myName = condor_basename(argv[0]); myFullName = getExecPath(); if( ! myFullName ) { // if getExecPath() didn't work, the best we can do is try // saving argv[0] and hope for the best... if( argv[0][0] == '/' ) { // great, it's already a full path myFullName = strdup(argv[0]); } else { // we don't have anything reliable, so forget it. myFullName = NULL; } } myDistro->Init( argc, argv ); if ( EnvInit() < 0 ) { exit( 1 ); } // call out to the handler for pre daemonCore initialization // stuff so that our client side can do stuff before we start // messing with argv[] main_pre_dc_init( argc, argv ); // Make sure this is set, since DaemonCore needs it for all // sorts of things, and it's better to clearly EXCEPT here // than to seg fault down the road... if( ! get_mySubSystem() ) { EXCEPT( "Programmer error: get_mySubSystem() is NULL!" ); } if( !get_mySubSystem()->isValid() ) { get_mySubSystem()->printf( ); EXCEPT( "Programmer error: get_mySubSystem() info is invalid(%s,%d,%s)!", get_mySubSystem()->getName(), get_mySubSystem()->getType(), get_mySubSystem()->getTypeName() ); } // strip off any daemon-core specific command line arguments // from the front of the command line. i = 0; bool done = false; for(ptr = argv + 1; *ptr && (i < argc - 1); ptr++,i++) { if(ptr[0][0] != '-') { break; } /* NOTE! If you're adding a new command line argument to this switch statement, YOU HAVE TO ADD IT TO THE #ifdef WIN32 VERSION OF "main()" NEAR THE END OF THIS FILE, TOO. You should actually deal with the argument here, but you need to add it there to be skipped over because of NT weirdness with starting as a service, etc. Also, please add your argument in alphabetical order, so we can maintain some semblance of order in here, and make it easier to keep the two switch statements in sync. Derek Wright <wright@cs.wisc.edu> 11/11/99 */ switch(ptr[0][1]) { case 'a': // Append to the log file name. ptr++; if( ptr && *ptr ) { logAppend = *ptr; dcargs += 2; } else { fprintf( stderr, "DaemonCore: ERROR: -append needs another argument.\n" ); fprintf( stderr, " Please specify a string to append to our log's filename.\n" ); exit( 1 ); } break; case 'b': // run in Background (default) Foreground = 0; dcargs++; break; case 'c': // specify directory where Config file lives ptr++; if( ptr && *ptr ) { ptmp = *ptr; dcargs += 2; ptmp1 = (char *)malloc( strlen(ptmp) + myDistro->GetLen() + 10 ); if ( ptmp1 ) { sprintf(ptmp1,"%s_CONFIG=%s", myDistro->GetUc(), ptmp); SetEnv(ptmp1); } } else { fprintf( stderr, "DaemonCore: ERROR: -config needs another argument.\n" ); fprintf( stderr, " Please specify the filename of the config file.\n" ); exit( 1 ); } break; case 'd': // Dynamic local directories DynamicDirs = true; dcargs++; break; case 'f': // run in Foreground Foreground = 1; dcargs++; break; #ifndef WIN32 case 'k': // Kill the pid in the given pid file ptr++; if( ptr && *ptr ) { pidFile = *ptr; wantsKill = TRUE; dcargs += 2; } else { fprintf( stderr, "DaemonCore: ERROR: -kill needs another argument.\n" ); fprintf( stderr, " Please specify a file that holds the pid you want to kill.\n" ); exit( 1 ); } break; #endif case 'l': // -local-name or -log // specify local name if ( strcmp( &ptr[0][1], "local-name" ) == 0 ) { ptr++; if( ptr && *ptr ) { get_mySubSystem()->setLocalName( *ptr ); dcargs += 2; } else { fprintf( stderr, "DaemonCore: ERROR: " "-local-name needs another argument.\n" ); fprintf( stderr, " Please specify the local config to use.\n" ); exit( 1 ); } } // specify Log directory else { ptr++; if( ptr && *ptr ) { logDir = *ptr; dcargs += 2; } else { fprintf( stderr, "DaemonCore: ERROR: -log needs another " "argument\n" ); exit( 1 ); } } break; case 'h': // -http <port> : specify port for HTTP and SOAP requests if ( ptr[0][2] && ptr[0][2] == 't' ) { // specify an HTTP port ptr++; if( ptr && *ptr ) { http_port = atoi( *ptr ); dcargs += 2; } else { fprintf( stderr, "DaemonCore: ERROR: -http needs another argument.\n" ); fprintf( stderr, " Please specify the port to use for the HTTP socket.\n" ); exit( 1 ); } } else { // it's not -http, so do NOT consume this arg!! // in fact, we're done w/ DC args, since it's the // first option we didn't recognize. done = true; } break; case 'p': // use well-known Port for command socket, or // specify a Pidfile to drop your pid into if( ptr[0][2] && ptr[0][2] == 'i' ) { // Specify a Pidfile ptr++; if( ptr && *ptr ) { pidFile = *ptr; dcargs += 2; } else { fprintf( stderr, "DaemonCore: ERROR: -pidfile needs another argument.\n" ); fprintf( stderr, " Please specify a filename to store the pid.\n" ); exit( 1 ); } } else { // use well-known Port for command socket // note: "-p 0" means _no_ command socket ptr++; if( ptr && *ptr ) { command_port = atoi( *ptr ); dcargs += 2; } else { fprintf( stderr, "DaemonCore: ERROR: -port needs another argument.\n" ); fprintf( stderr, " Please specify the port to use for the command socket.\n" ); exit( 1 ); } } break; case 'q': // Quiet output wantsQuiet = TRUE; dcargs++; break; case 'r': // Run for <arg> minutes, then gracefully exit ptr++; if( ptr && *ptr ) { runfor = atoi( *ptr ); dcargs += 2; } else { fprintf( stderr, "DaemonCore: ERROR: -runfor needs another argument.\n" ); fprintf( stderr, " Please specify the number of minutes to run for.\n" ); exit( 1 ); } //call Register_Timer below after intialized... break; case 't': // log to Terminal (stderr) Termlog = 1; dcargs++; break; case 'v': // display Version info and exit printf( "%s\n%s\n", CondorVersion(), CondorPlatform() ); exit(0); break; default: done = true; break; } if ( done ) { break; // break out of for loop } } // using "-t" also implicitly sets "-f"; i.e. only to stderr in the foreground if ( Termlog ) { Foreground = 1; } // call config so we can call param. if ( get_mySubSystem()->isType(SUBSYSTEM_TYPE_SHADOW) ) { // Try to minimize shadow footprint by not loading // the "extra" info from the config file config( wantsQuiet, false, false ); } else { config( wantsQuiet, false, true ); } // call dc_config_GSI to set GSI related parameters so that all // the daemons will know what to do. if ( doAuthInit ) { condor_auth_config( true ); } // See if we're supposed to be allowing core files or not check_core_files(); // If we want to kill something, do that now. if( wantsKill ) { do_kill(); } if( ! DynamicDirs ) { // We need to setup logging. Normally, we want to do this // before the fork(), so that if there are problems and we // fprintf() to stderr, we'll still see them. However, if // we want DynamicDirs, we can't do this yet, since we // need our pid to specify the log directory... // If want to override what's set in our config file, we've // got to do that here, between where we config and where we // setup logging. Note: we also have to do this in reconfig. if( logDir ) { set_log_dir(); } // If we're told on the command-line to append something to // the name of our log file, we do that here, so that when we // setup logging, we get the right filename. -Derek Wright // 11/20/98 if( logAppend ) { handle_log_append( logAppend ); } // Actually set up logging. dprintf_config(get_mySubSystem()->getName() ); } // run as condor 99.9% of the time, so studies tell us. set_condor_priv(); // we want argv[] stripped of daemoncore options ptmp = argv[0]; // save a temp pointer to argv[0] argv = --ptr; // make space for argv[0] argv[0] = ptmp; // set argv[0] argc -= dcargs; if ( argc < 1 ) argc = 1; // Arrange to run in the background. // SPECIAL CASE: if this is the MASTER, and we are to run in the background, // then register ourselves as an NT Service. if (!Foreground) { #ifdef WIN32 // Disconnect from the console FreeConsole(); #else // UNIX // on unix, background means just fork ourselves if ( fork() ) { // parent exit(0); } // And close stdin, out, err if we are the MASTER. // NRL 2006-08-10: Here's what and why we're doing this..... // // In days of yore, we'd simply close FDs 0,1,2 and be done // with it. Unfortunately, some 3rd party tools were writing // directly to these FDs. Now, you might not that that this // would be a problem, right? Unfortunately, once you close // an FD (say, 1 or 2), then next safe_open_wrapper() or socket() // call can / will now return 1 (or 2). So, when libfoo.a thinks // it fprintf()ing an error message to fd 2 (the FD behind // stderr), it's actually sending that message over a socket // to a process that has no idea how to handle it. // // So, here's what we do. We open /dev/null, and then use // dup2() to copy this "safe" fd to these decriptors. Note // that if you don't open it with O_RDWR, you can cause writes // to the FD to return errors. // // Finally, we only do this in the master. Why? Because // Create_Process() has similar logic, so when the master // starts, say, condor_startd, the Create_Process() logic // takes over and does The Right Thing(tm). // // Regarding the std in/out/err streams (the FILE *s, not the // FDs), we leave those open. Otherwise, if libfoo.a tries to // fwrite to stderr, it would get back an error from fprintf() // (or fwrite(), etc.). If it checks this, it might Do // Something Bad(tm) like abort() -- who knows. In any case, // it seems safest to just leave them open but attached to // /dev/null. if ( get_mySubSystem()->isType( SUBSYSTEM_TYPE_MASTER ) ) { int fd_null = safe_open_wrapper( NULL_FILE, O_RDWR ); if ( fd_null < 0 ) { fprintf( stderr, "Unable to open %s: %s\n", NULL_FILE, strerror(errno) ); dprintf( D_ALWAYS, "Unable to open %s: %s\n", NULL_FILE, strerror(errno) ); } int fd; for( fd=0; fd<=2; fd++ ) { close( fd ); if ( ( fd_null >= 0 ) && ( fd_null != fd ) && ( dup2( fd_null, fd ) < 0 ) ) { dprintf( D_ALWAYS, "Error dup2()ing %s -> %d: %s\n", NULL_FILE, fd, strerror(errno) ); } } // Close the /dev/null descriptor _IF_ it's not stdin/out/err if ( fd_null > 2 ) { close( fd_null ); } } // and detach from the controlling tty detach(); #endif // of else of ifdef WIN32 } // if if !Foreground // See if the config tells us to wait on startup for a debugger to attach. MyString debug_wait_param; debug_wait_param.sprintf("%s_DEBUG_WAIT", get_mySubSystem()->getName() ); if (param_boolean(debug_wait_param.Value(), false, false)) { int debug_wait = 1; dprintf(D_ALWAYS, "%s is TRUE, waiting for debugger to attach to pid %d.\n", debug_wait_param.Value(), (int)::getpid()); while (debug_wait) { sleep(1); } } // Now that we've potentially forked, we have our real pid, so // we can instantiate a daemon core and it'll have the right // pid. Have lots of pid table hash buckets if we're the // SCHEDD, since the SCHEDD could have lots of children... if ( get_mySubSystem()->isType( SUBSYSTEM_TYPE_SCHEDD ) ) { daemonCore = new DaemonCore(503); } else { daemonCore = new DaemonCore(); } if( DynamicDirs ) { // If we want to use dynamic dirs for log, spool and // execute, we now have our real pid, so we can actually // give it the correct name. handle_dynamic_dirs(); if( logAppend ) { handle_log_append( logAppend ); } // Actually set up logging. dprintf_config(get_mySubSystem()->getName() ); } // Now that we have the daemonCore object, we can finally // know what our pid is, so we can print out our opening // banner. Plus, if we're using dynamic dirs, we have dprintf // configured now, so the dprintf()s will work. dprintf(D_ALWAYS,"******************************************************\n"); dprintf(D_ALWAYS,"** %s (%s_%s) STARTING UP\n", myName,myDistro->GetUc(), get_mySubSystem()->getName() ); if( myFullName ) { dprintf( D_ALWAYS, "** %s\n", myFullName ); free( myFullName ); myFullName = NULL; } dprintf(D_ALWAYS,"** %s\n", get_mySubSystem()->getString() ); dprintf(D_ALWAYS,"** Configuration: subsystem:%s local:%s class:%s\n", get_mySubSystem()->getName(), get_mySubSystem()->getLocalName("<NONE>"), get_mySubSystem()->getClassName( ) ); dprintf(D_ALWAYS,"** %s\n", CondorVersion()); dprintf(D_ALWAYS,"** %s\n", CondorPlatform()); dprintf(D_ALWAYS,"** PID = %lu\n", (unsigned long) daemonCore->getpid()); time_t log_last_mod_time = dprintf_last_modification(); if ( log_last_mod_time <= 0 ) { dprintf(D_ALWAYS,"** Log last touched time unavailable (%s)\n", strerror(-log_last_mod_time)); } else { struct tm *tm = localtime( &log_last_mod_time ); dprintf(D_ALWAYS,"** Log last touched %d/%d %02d:%02d:%02d\n", tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); } #ifndef WIN32 // Want to do this dprintf() here, since we can't do it w/n // the priv code itself or we get major problems. // -Derek Wright 12/21/98 if( getuid() ) { dprintf(D_PRIV, "** Running as non-root: No privilege switching\n"); } else { dprintf(D_PRIV, "** Running as root: Privilege switching in effect\n"); } #endif dprintf(D_ALWAYS,"******************************************************\n"); if (global_config_source != "") { dprintf(D_ALWAYS, "Using config source: %s\n", global_config_source.Value()); } else { const char* env_name = EnvGetName( ENV_CONFIG ); char* env = getenv( env_name ); if( env ) { dprintf(D_ALWAYS, "%s is set to '%s', not reading a config file\n", env_name, env ); } } if (!local_config_sources.isEmpty()) { dprintf(D_ALWAYS, "Using local config sources: \n"); local_config_sources.rewind(); char *source; while( (source = local_config_sources.next()) != NULL ) { dprintf(D_ALWAYS, " %s\n", source ); } } // chdir() into our log directory so if we drop core, that's // where it goes. We also do some NT-specific stuff in here. drop_core_in_log(); #ifdef WIN32 // On NT, we need to make certain we have a console allocated, // since many standard mechanisms do not work without a console // attached [like popen(), stdin/out/err, GenerateConsoleEvent]. // There are several reasons why we may not have a console // right now: a) we are running as a service, and services are // born without a console, or b) the user did not specify "-f" // or "-t", and thus we called FreeConsole() above. // for now, don't create a console for the kbdd, as that daemon // is now a win32 app and not a console app. BOOL is_kbdd = (0 == strcmp(get_mySubSystem()->getName(), "KBDD")); if(!is_kbdd) AllocConsole(); #endif // Avoid possibility of stale info sticking around from previous run. // For example, we had problems in 7.0.4 and earlier with reconnect // shadows in parallel universe reading the old schedd ad file. kill_daemon_ad_file(); // Now that we have our pid, we could dump our pidfile, if we // want it. if( pidFile ) { drop_pid_file(); } #ifndef WIN32 // Now that logging is setup, create a pipe to deal with unix // async signals. We do this after logging is setup so that // we can EXCEPT (and really log something) on failure... if ( pipe(daemonCore->async_pipe) == -1 || fcntl(daemonCore->async_pipe[0],F_SETFL,O_NONBLOCK) == -1 || fcntl(daemonCore->async_pipe[1],F_SETFL,O_NONBLOCK) == -1 ) { EXCEPT("Failed to create async pipe"); } #else if ( daemonCore->async_pipe[1].connect_socketpair(daemonCore->async_pipe[0])==false ) { EXCEPT("Failed to create async pipe socket pair"); } #endif #if HAVE_EXT_GCB // Set up our GCB failure callback GCB_Recovery_failed_callback_set( gcb_recovery_failed_callback ); #endif main_pre_command_sock_init(); // SETUP COMMAND SOCKET daemonCore->InitDCCommandSocket( command_port ); // Install DaemonCore signal handlers common to all daemons. daemonCore->Register_Signal( SIGHUP, "SIGHUP", (SignalHandler)handle_dc_sighup, "handle_dc_sighup()" ); daemonCore->Register_Signal( SIGQUIT, "SIGQUIT", (SignalHandler)handle_dc_sigquit, "handle_dc_sigquit()" ); daemonCore->Register_Signal( SIGTERM, "SIGTERM", (SignalHandler)handle_dc_sigterm, "handle_dc_sigterm()" ); daemonCore->Register_Signal( DC_SERVICEWAITPIDS, "DC_SERVICEWAITPIDS", (SignalHandlercpp)&DaemonCore::HandleDC_SERVICEWAITPIDS, "HandleDC_SERVICEWAITPIDS()",daemonCore); #ifndef WIN32 daemonCore->Register_Signal( SIGCHLD, "SIGCHLD", (SignalHandlercpp)&DaemonCore::HandleDC_SIGCHLD, "HandleDC_SIGCHLD()",daemonCore); #endif // Install DaemonCore timers common to all daemons. //if specified on command line, set timer to gracefully exit if ( runfor ) { daemon_stop_time = time(NULL)+runfor*60; daemonCore->Register_Timer( runfor * 60, 0, (TimerHandler)handle_dc_sigterm, "handle_dc_sigterm" ); dprintf(D_ALWAYS,"Registered Timer for graceful shutdown in %d minutes\n", runfor ); } else { daemon_stop_time = 0; } #ifndef WIN32 // This timer checks if our parent is dead; if so, we shutdown. // We only do this on Unix; on NT we watch our parent via a different mechanism. // Also note: we do not want the master to exibit this behavior! if ( ! get_mySubSystem()->isType(SUBSYSTEM_TYPE_MASTER) ) { daemonCore->Register_Timer( 15, 120, check_parent, "check_parent" ); } #endif daemonCore->Register_Timer( 0, dc_touch_log_file, "dc_touch_log_file" ); daemonCore->Register_Timer( 0, dc_touch_lock_files, "dc_touch_lock_files" ); daemonCore->Register_Timer( 0, 5 * 60, check_session_cache, "check_session_cache" ); // set the timer for half the session duration, // since we retain the old cookie. Also make sure // the value is atleast 1. int cookie_refresh = (param_integer("SEC_DEFAULT_SESSION_DURATION", 3600)/2)+1; daemonCore->Register_Timer( 0, cookie_refresh, handle_cookie_refresh, "handle_cookie_refresh"); if( get_mySubSystem()->isType( SUBSYSTEM_TYPE_MASTER ) || get_mySubSystem()->isType( SUBSYSTEM_TYPE_SCHEDD ) || get_mySubSystem()->isType( SUBSYSTEM_TYPE_STARTD ) ) { daemonCore->monitor_data.EnableMonitoring(); } // Install DaemonCore command handlers common to all daemons. daemonCore->Register_Command( DC_RECONFIG, "DC_RECONFIG", (CommandHandler)handle_reconfig, "handle_reconfig()", 0, WRITE ); daemonCore->Register_Command( DC_RECONFIG_FULL, "DC_RECONFIG_FULL", (CommandHandler)handle_reconfig, "handle_reconfig()", 0, ADMINISTRATOR ); daemonCore->Register_Command( DC_CONFIG_VAL, "DC_CONFIG_VAL", (CommandHandler)handle_config_val, "handle_config_val()", 0, READ ); // Deprecated name for it. daemonCore->Register_Command( CONFIG_VAL, "CONFIG_VAL", (CommandHandler)handle_config_val, "handle_config_val()", 0, READ ); // The handler for setting config variables does its own // authorization, so these two commands should be registered // as "ALLOW" and the handler will do further checks. daemonCore->Register_Command( DC_CONFIG_PERSIST, "DC_CONFIG_PERSIST", (CommandHandler)handle_config, "handle_config()", 0, ALLOW ); daemonCore->Register_Command( DC_CONFIG_RUNTIME, "DC_CONFIG_RUNTIME", (CommandHandler)handle_config, "handle_config()", 0, ALLOW ); daemonCore->Register_Command( DC_OFF_FAST, "DC_OFF_FAST", (CommandHandler)handle_off_fast, "handle_off_fast()", 0, ADMINISTRATOR ); daemonCore->Register_Command( DC_OFF_GRACEFUL, "DC_OFF_GRACEFUL", (CommandHandler)handle_off_graceful, "handle_off_graceful()", 0, ADMINISTRATOR ); daemonCore->Register_Command( DC_OFF_PEACEFUL, "DC_OFF_PEACEFUL", (CommandHandler)handle_off_peaceful, "handle_off_peaceful()", 0, ADMINISTRATOR ); daemonCore->Register_Command( DC_SET_PEACEFUL_SHUTDOWN, "DC_SET_PEACEFUL_SHUTDOWN", (CommandHandler)handle_set_peaceful_shutdown, "handle_set_peaceful_shutdown()", 0, ADMINISTRATOR ); daemonCore->Register_Command( DC_NOP, "DC_NOP", (CommandHandler)handle_nop, "handle_nop()", 0, READ ); daemonCore->Register_Command( DC_FETCH_LOG, "DC_FETCH_LOG", (CommandHandler)handle_fetch_log, "handle_fetch_log()", 0, ADMINISTRATOR ); daemonCore->Register_Command( DC_PURGE_LOG, "DC_PURGE_LOG", (CommandHandler)handle_fetch_log_history_purge, "handle_fetch_log_history_purge()", 0, ADMINISTRATOR ); daemonCore->Register_Command( DC_INVALIDATE_KEY, "DC_INVALIDATE_KEY", (CommandHandler)handle_invalidate_key, "handle_invalidate_key()", 0, ALLOW ); // // The time offset command is used to figure out what // the range of the clock skew is between the daemon code and another // entity calling into us // daemonCore->Register_Command( DC_TIME_OFFSET, "DC_TIME_OFFSET", (CommandHandler)time_offset_receive_cedar_stub, "time_offset_cedar_stub", 0, DAEMON ); // Call daemonCore's reconfig(), which reads everything from // the config file that daemonCore cares about and initializes // private data members, etc. daemonCore->reconfig(); // zmiller // look in the env for ENV_PARENT_ID const char* envName = EnvGetName ( ENV_PARENT_ID ); MyString parent_id; GetEnv( envName, parent_id ); // send it to the SecMan object so it can include it in any // classads it sends. if this is NULL, it will not include // the attribute. daemonCore->sec_man->set_parent_unique_id(parent_id.Value()); // now re-set the identity so that any children we spawn will have it // in their environment SetEnv( envName, daemonCore->sec_man->my_unique_id() ); // create a database connection object //DBObj = createConnection(); // create a sql log object. We always have one defined, but // if quill is not enabled we never write data to the logfile bool use_sql_log = param_boolean( "QUILL_USE_SQL_LOG", false ); FILEObj = FILESQL::createInstance(use_sql_log); // create an xml log object XMLObj = FILEXML::createInstanceXML(); // call the daemon's main_init() main_init( argc, argv ); // now call the driver. we never return from the driver (infinite loop). daemonCore->Driver(); // should never get here EXCEPT("returned from Driver()"); return FALSE; } #ifdef WIN32 int main( int argc, char** argv) { char **ptr; int i; // Scan our command line arguments for a "-f". If we don't find a "-f", // or a "-v", then we want to register as an NT Service. i = 0; bool done = false; for( ptr = argv + 1; *ptr && (i < argc - 1); ptr++,i++) { if( ptr[0][0] != '-' ) { break; } switch( ptr[0][1] ) { case 'a': // Append to the log file name. ptr++; break; case 'b': // run in Background (default) break; case 'c': // specify directory where Config file lives ptr++; break; case 'd': // Dynamic local directories break; case 'f': // run in Foreground Foreground = 1; break; case 'l': // specify Log directory ptr++; break; case 'p': // Use well-known Port for command socket. ptr++; // Also used to specify a Pid file, but both break; // versions require a 2nd arg, so we're safe. case 'q': // Quiet output break; case 'r': // Run for <arg> minutes, then gracefully exit ptr++; break; case 't': // log to Terminal (stderr) break; case 'v': // display Version info and exit printf( "%s\n%s\n", CondorVersion(), CondorPlatform() ); exit(0); break; default: done = true; break; } if( done ) { break; // break out of for loop } } if ( (Foreground != 1) && get_mySubSystem()->isType(SUBSYSTEM_TYPE_MASTER) ) { main_init(-1,NULL); // passing the master main_init a -1 will register as an NT service return 1; } else { return(dc_main(argc,argv)); } } #endif // of ifdef WIN32 Introduced TimerHandler_dc_sigterm to call handle_dc_sigterm from a timer, instead of casting function pointer and changing signature, #946 /*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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. * ***************************************************************/ #include "condor_common.h" #include "condor_config.h" #include "util_lib_proto.h" #include "basename.h" #include "my_hostname.h" #include "condor_version.h" #include "limit.h" #include "condor_email.h" #include "sig_install.h" #include "daemon.h" #include "condor_debug.h" #include "condor_distribution.h" #include "condor_environ.h" #include "setenv.h" #include "time_offset.h" #include "subsystem_info.h" #include "file_lock.h" #include "directory.h" #include "exit.h" #if HAVE_EXT_GCB #include "GCB.h" #endif #include "file_sql.h" #include "file_xml.h" #define _NO_EXTERN_DAEMON_CORE 1 #include "condor_daemon_core.h" #ifdef WIN32 #include "exception_handling.WINDOWS.h" #endif #if HAVE_EXT_COREDUMPER #include "google/coredumper.h" #endif // Externs to Globals extern DLL_IMPORT_MAGIC char **environ; // External protos extern int main_init(int argc, char *argv[]); // old main() extern int main_config(bool is_full); extern int main_shutdown_fast(); extern int main_shutdown_graceful(); extern void main_pre_dc_init(int argc, char *argv[]); extern void main_pre_command_sock_init(); // Internal protos void dc_reconfig( bool is_full ); void dc_config_auth(); // Configuring GSI (and maybe other) authentication related stuff int handle_fetch_log_history(ReliSock *s, char *name); int handle_fetch_log_history_dir(ReliSock *s, char *name); int handle_fetch_log_history_purge(ReliSock *s); // Globals int Foreground = 0; // run in background by default static const char* myName; // set to basename(argv[0]) char *_condor_myServiceName; // name of service on Win32 (argv[0] from SCM) static char* myFullName; // set to the full path to ourselves DaemonCore* daemonCore; char* logDir = NULL; char* pidFile = NULL; char* addrFile = NULL; static char* logAppend = NULL; int condor_main_argc; char **condor_main_argv; time_t daemon_stop_time; /* ODBC object */ //extern ODBC *DBObj; /* FILESQL object */ extern FILESQL *FILEObj; /* FILEXML object */ extern FILEXML *XMLObj; #ifdef WIN32 int line_where_service_stopped = 0; #endif bool DynamicDirs = false; // runfor is non-zero if the -r command-line option is specified. // It is specified to tell a daemon to kill itself after runfor minutes. // Currently, it is only used for the master, and it is specified for // glide-in jobs that know that they can only run for a certain amount // of time. Glide-in will tell the master to kill itself a minute before // it needs to quit, and it will kill the other daemons. // // The master will check this global variable and set an environment // variable to inform the children how much time they have left to run. // This will mainly be used by the startd, which will advertise how much // time it has left before it exits. This can be used by a job's requirements // so that it can decide if it should run at a particular machine or not. int runfor = 0; //allow cmd line option to exit after *runfor* minutes // This flag tells daemoncore whether to do the authorization initialization. // It can be set to false by calling the DC_Skip_Auth_Init() function. static bool doAuthInit = true; #ifndef WIN32 // This function polls our parent process; if it is gone, shutdown. void check_parent( ) { if ( daemonCore->Is_Pid_Alive( daemonCore->getppid() ) == FALSE ) { // our parent is gone! dprintf(D_ALWAYS, "Our parent process (pid %d) went away; shutting down\n", daemonCore->getppid()); daemonCore->Send_Signal( daemonCore->getpid(), SIGTERM ); } } #endif // This function clears expired sessions from the cache void check_session_cache( ) { daemonCore->getSecMan()->invalidateExpiredCache(); } bool global_dc_set_cookie(int len, unsigned char* data) { if (daemonCore) { return daemonCore->set_cookie(len, data); } else { return false; } } bool global_dc_get_cookie(int &len, unsigned char* &data) { if (daemonCore) { return daemonCore->get_cookie(len, data); } else { return false; } } void handle_cookie_refresh( ) { unsigned char randomjunk[256]; char symbols[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; for (int i = 0; i < 128; i++) { randomjunk[i] = symbols[rand() % 16]; } // good ol null terminator randomjunk[127] = 0; global_dc_set_cookie (128, randomjunk); } char const* global_dc_sinful() { if (daemonCore) { return daemonCore->InfoCommandSinfulString(); } else { return NULL; } } void clean_files() { // If we created a pid file, remove it. if( pidFile ) { if( unlink(pidFile) < 0 ) { dprintf( D_ALWAYS, "DaemonCore: ERROR: Can't delete pid file %s\n", pidFile ); } else { if( DebugFlags & (D_FULLDEBUG | D_DAEMONCORE) ) { dprintf( D_DAEMONCORE, "Removed pid file %s\n", pidFile ); } } } if( addrFile ) { if( unlink(addrFile) < 0 ) { dprintf( D_ALWAYS, "DaemonCore: ERROR: Can't delete address file %s\n", addrFile ); } else { if( DebugFlags & (D_FULLDEBUG | D_DAEMONCORE) ) { dprintf( D_DAEMONCORE, "Removed address file %s\n", addrFile ); } } // Since we param()'ed for this, we need to free it now. free( addrFile ); } if(daemonCore) { if( daemonCore->localAdFile ) { if( unlink(daemonCore->localAdFile) < 0 ) { dprintf( D_ALWAYS, "DaemonCore: ERROR: Can't delete classad file %s\n", daemonCore->localAdFile ); } else { if( DebugFlags & (D_FULLDEBUG | D_DAEMONCORE) ) { dprintf( D_DAEMONCORE, "Removed local classad file %s\n", daemonCore->localAdFile ); } } free( daemonCore->localAdFile ); daemonCore->localAdFile = NULL; } } } // All daemons call this function when they want daemonCore to really // exit. Put any daemon-wide shutdown code in here. void DC_Exit( int status, const char *shutdown_program ) { // First, delete any files we might have created, like the // address file or the pid file. clean_files(); if(FILEObj) { delete FILEObj; FILEObj = NULL; } if(XMLObj) { delete XMLObj; XMLObj = NULL; } // See if this daemon wants to be restarted (true by // default). If so, use the given status. Otherwise, use the // special code to tell our parent not to restart us. int exit_status; if (daemonCore == NULL || daemonCore->wantsRestart()) { exit_status = status; } else { exit_status = DAEMON_NO_RESTART; } // Now, delete the daemonCore object, since we allocated it. unsigned long pid = daemonCore->getpid( ); delete daemonCore; daemonCore = NULL; // Free up the memory from the config hash table, too. clear_config(); // and deallocate the memory from the passwd_cache (uids.C) delete_passwd_cache(); /* Log a message. We want to do this *AFTER* we delete the daemonCore object and free up other memory, just to make sure we don't hit an EXCEPT() or anything in there and end up exiting with something else after we print this. all the dprintf() code has already initialized everything it needs to know from the config file, so it's ok that we already cleared out our config hashtable, too. Derek 2004-11-23 */ if ( shutdown_program ) { # if (HAVE_EXECL) dprintf( D_ALWAYS, "**** %s (%s_%s) pid %lu EXITING BY EXECING %s\n", myName, myDistro->Get(), get_mySubSystem()->getName(), pid, shutdown_program ); int exec_status = execl( shutdown_program, shutdown_program, NULL ); dprintf( D_ALWAYS, "**** execl() FAILED %d %d %s\n", exec_status, errno, strerror(errno) ); # elif defined(WIN32) dprintf( D_ALWAYS, "**** %s (%s_%s) pid %lu EXECING SHUTDOWN PROGRAM %s\n", myName, myDistro->Get(), get_mySubSystem()->getName(), pid, shutdown_program ); int exec_status = execl( shutdown_program, shutdown_program, NULL ); if ( exec_status ) { dprintf( D_ALWAYS, "**** _execl() FAILED %d %d %s\n", exec_status, errno, strerror(errno) ); } # else dprintf( D_ALWAYS, "**** execl() not available on this system\n" ); # endif } dprintf( D_ALWAYS, "**** %s (%s_%s) pid %lu EXITING WITH STATUS %d\n", myName, myDistro->Get(), get_mySubSystem()->getName(), pid, exit_status ); // Finally, exit with the appropriate status. exit( exit_status ); } void DC_Skip_Auth_Init() { doAuthInit = false; } static void kill_daemon_ad_file() { MyString param_name; param_name.sprintf( "%s_DAEMON_AD_FILE", get_mySubSystem()->getName() ); char *ad_file = param(param_name.Value()); if( !ad_file ) { return; } unlink(ad_file); free(ad_file); } void drop_addr_file() { FILE *ADDR_FILE; char addr_file[100]; sprintf( addr_file, "%s_ADDRESS_FILE", get_mySubSystem()->getName() ); if( addrFile ) { free( addrFile ); } addrFile = param( addr_file ); if( addrFile ) { MyString newAddrFile; newAddrFile.sprintf("%s.new",addrFile); if( (ADDR_FILE = safe_fopen_wrapper(newAddrFile.Value(), "w")) ) { // Always prefer the local, private address if possible. const char* addr = daemonCore->privateNetworkIpAddr(); if (!addr) { // And if not, fall back to the public. addr = daemonCore->publicNetworkIpAddr(); } fprintf( ADDR_FILE, "%s\n", addr ); fprintf( ADDR_FILE, "%s\n", CondorVersion() ); fprintf( ADDR_FILE, "%s\n", CondorPlatform() ); fclose( ADDR_FILE ); if( rotate_file(newAddrFile.Value(),addrFile)!=0 ) { dprintf( D_ALWAYS, "DaemonCore: ERROR: failed to rotate %s to %s\n", newAddrFile.Value(), addrFile); } } else { dprintf( D_ALWAYS, "DaemonCore: ERROR: Can't open address file %s\n", newAddrFile.Value() ); } } } void drop_pid_file() { FILE *PID_FILE; if( !pidFile ) { // There's no file, just return return; } if( (PID_FILE = safe_fopen_wrapper(pidFile, "w")) ) { fprintf( PID_FILE, "%lu\n", (unsigned long)daemonCore->getpid() ); fclose( PID_FILE ); } else { dprintf( D_ALWAYS, "DaemonCore: ERROR: Can't open pid file %s\n", pidFile ); } } void do_kill() { #ifndef WIN32 FILE *PID_FILE; pid_t pid = 0; unsigned long tmp_ul_int = 0; char *log, *tmp; if( !pidFile ) { fprintf( stderr, "DaemonCore: ERROR: no pidfile specified for -kill\n" ); exit( 1 ); } if( pidFile[0] != '/' ) { // There's no absolute path, append the LOG directory if( (log = param("LOG")) ) { tmp = (char*)malloc( (strlen(log) + strlen(pidFile) + 2) * sizeof(char) ); sprintf( tmp, "%s/%s", log, pidFile ); free( log ); pidFile = tmp; } } if( (PID_FILE = safe_fopen_wrapper(pidFile, "r")) ) { fscanf( PID_FILE, "%lu", &tmp_ul_int ); pid = (pid_t)tmp_ul_int; fclose( PID_FILE ); } else { fprintf( stderr, "DaemonCore: ERROR: Can't open pid file %s for reading\n", pidFile ); exit( 1 ); } if( pid > 0 ) { // We have a valid pid, try to kill it. if( kill(pid, SIGTERM) < 0 ) { fprintf( stderr, "DaemonCore: ERROR: can't send SIGTERM to pid (%lu)\n", (unsigned long)pid ); fprintf( stderr, "\terrno: %d (%s)\n", errno, strerror(errno) ); exit( 1 ); } // kill worked, now, make sure the thing is gone. Keep // trying to send signal 0 (test signal) to the process // until that fails. while( kill(pid, 0) == 0 ) { sleep( 3 ); } // Everything's cool, exit normally. exit( 0 ); } else { // Invalid pid fprintf( stderr, "DaemonCore: ERROR: pid (%lu) in pid file (%s) is invalid.\n", (unsigned long)pid, pidFile ); exit( 1 ); } #endif // of ifndef WIN32 } // Create the directory we were given, with extra error checking. void make_dir( const char* logdir ) { mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO; struct stat stats; if( stat(logdir, &stats) >= 0 ) { if( ! S_ISDIR(stats.st_mode) ) { fprintf( stderr, "DaemonCore: ERROR: %s exists and is not a directory.\n", logdir ); exit( 1 ); } } else { if( mkdir(logdir, mode) < 0 ) { fprintf( stderr, "DaemonCore: ERROR: can't create directory %s\n", logdir ); fprintf( stderr, "\terrno: %d (%s)\n", errno, strerror(errno) ); exit( 1 ); } } } // Set our log directory in our config hash table, and create it. void set_log_dir() { if( !logDir ) { return; } config_insert( "LOG", logDir ); make_dir( logDir ); } void handle_log_append( char* append_str ) { if( ! append_str ) { return; } char *tmp1, *tmp2; char buf[100]; sprintf( buf, "%s_LOG", get_mySubSystem()->getName() ); if( !(tmp1 = param(buf)) ) { EXCEPT( "%s not defined!", buf ); } tmp2 = (char*)malloc( (strlen(tmp1) + strlen(append_str) + 2) * sizeof(char) ); if( !tmp2 ) { EXCEPT( "Out of memory!" ); } sprintf( tmp2, "%s.%s", tmp1, append_str ); config_insert( buf, tmp2 ); free( tmp1 ); free( tmp2 ); } void dc_touch_log_file( ) { dprintf_touch_log(); daemonCore->Register_Timer( param_integer( "TOUCH_LOG_INTERVAL", 60 ), dc_touch_log_file, "dc_touch_log_file" ); } void dc_touch_lock_files( ) { priv_state p; // For any outstanding lock objects that are associated with the real lock // file, update their timestamps. Do it as Condor, and ignore files that we // don't have permissions to alter. This allows things like the Instance // lock to be updated, but doesn't update things like the job event log. // do this here to make the priv switching operations fast in the // FileLock Object. p = set_condor_priv(); FileLock::updateAllLockTimestamps(); set_priv(p); // reset the timer for next incarnation of the update. daemonCore->Register_Timer( param_integer("LOCK_FILE_UPDATE_INTERVAL", 3600 * 8, 60, INT_MAX), dc_touch_lock_files, "dc_touch_lock_files" ); } void set_dynamic_dir( char* param_name, const char* append_str ) { char* val; MyString newdir; val = param( (char *)param_name ); if( ! val ) { // nothing to do return; } // First, create the new name. newdir.sprintf( "%s.%s", val, append_str ); // Next, try to create the given directory, if it doesn't // already exist. make_dir( newdir.Value() ); // Now, set our own config hashtable entry so we start using // this new directory. config_insert( (char *) param_name, newdir.Value() ); // Finally, insert the _condor_<param_name> environment // variable, so our children get the right configuration. MyString env_str( "_" ); env_str += myDistro->Get(); env_str += "_"; env_str += param_name; env_str += "="; env_str += newdir; char *env_cstr = strdup( env_str.Value() ); if( SetEnv(env_cstr) != TRUE ) { fprintf( stderr, "ERROR: Can't add %s to the environment!\n", env_cstr ); exit( 4 ); } } void handle_dynamic_dirs() { // We want the log, spool and execute directory of ourselves // and our children to have our pid appended to them. If the // directories aren't there, we should create them, as Condor, // if possible. if( ! DynamicDirs ) { return; } int mypid = daemonCore->getpid(); char buf[256]; sprintf( buf, "%s-%d", inet_ntoa(*(my_sin_addr())), mypid ); set_dynamic_dir( "LOG", buf ); set_dynamic_dir( "SPOOL", buf ); set_dynamic_dir( "EXECUTE", buf ); // Final, evil hack. Set the _condor_STARTD_NAME environment // variable, so that the startd will have a unique name. sprintf( buf, "_%s_STARTD_NAME=%d", myDistro->Get(), mypid ); char* env_str = strdup( buf ); if( SetEnv(env_str) != TRUE ) { fprintf( stderr, "ERROR: Can't add %s to the environment!\n", env_str ); exit( 4 ); } } static char *core_dir = NULL; #if HAVE_EXT_COREDUMPER void linux_sig_coredump(int signum) { struct sigaction sa; static bool down = false; /* It turns out that the abort() call will unblock the sig abort signal and allow the handler to be called again. So, in a real world case, which led me to write this test, glibc decided something was wrong and called abort(), then, in this signal handler, we tickled the exact thing glibc didn't like in the first place and so it called abort() again, leading back to this handler. A segmentation fault happened finally when the stack was exhausted. This guard is here to prevent that type of scenario from happening again with this handler. This fixes ticket number #183 in the condor-wiki. NOTE: We never set down to false again, because this handler is meant to exit() and not return. */ if (down == true) { return; } down = true; dprintf_dump_stack(); // Just in case we're running as condor or a user. setuid(0); setgid(0); if (core_dir != NULL) { chdir(core_dir); } WriteCoreDump("core"); // It would be a good idea to actually terminate for the same reason. sa.sa_handler = SIG_DFL; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(signum, &sa, NULL); sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL); raise(signum); // If for whatever reason the second raise doesn't kill us properly, // we shall exit with a non-zero code so if anything depends on us, // at least they know there was a problem. exit(1); } #endif void install_core_dump_handler() { #if HAVE_EXT_COREDUMPER // We only need to do this if we're root. if( getuid() == 0) { dprintf(D_FULLDEBUG, "Running as root. Enabling specialized core dump routines\n"); sigset_t fullset; sigfillset( &fullset ); install_sig_handler_with_mask(SIGSEGV, &fullset, linux_sig_coredump); install_sig_handler_with_mask(SIGABRT, &fullset, linux_sig_coredump); install_sig_handler_with_mask(SIGILL, &fullset, linux_sig_coredump); install_sig_handler_with_mask(SIGFPE, &fullset, linux_sig_coredump); install_sig_handler_with_mask(SIGBUS, &fullset, linux_sig_coredump); } # endif // of ifdef HAVE_EXT_COREDUMPER } void drop_core_in_log( void ) { // chdir to the LOG directory so that if we dump a core // it will go there. // and on Win32, tell our ExceptionHandler class to drop // its pseudo-core file to the LOG directory as well. char* ptmp = param("LOG"); if ( ptmp ) { if ( chdir(ptmp) < 0 ) { EXCEPT("cannot chdir to dir <%s>",ptmp); } } else { dprintf( D_FULLDEBUG, "No LOG directory specified in config file(s), " "not calling chdir()\n" ); return; } core_dir = strdup(ptmp); // in some case we need to hook up our own handler to generate // core files. install_core_dump_handler(); #ifdef WIN32 { // give our Win32 exception handler a filename for the core file char pseudoCoreFileName[MAX_PATH]; sprintf(pseudoCoreFileName,"%s\\core.%s.WIN32",ptmp, get_mySubSystem()->getName() ); g_ExceptionHandler.SetLogFileName(pseudoCoreFileName); // set the path where our Win32 exception handler can find // debug symbols char *binpath = param("BIN"); if ( binpath ) { SetEnv( "_NT_SYMBOL_PATH", binpath ); free(binpath); } // give the handler our pid g_ExceptionHandler.SetPID ( daemonCore->getpid () ); } #endif free(ptmp); } // See if we should set the limits on core files. If the parameter is // defined, do what it says. Otherwise, do nothing. // On NT, if CREATE_CORE_FILES is False, then we will use the // default NT exception handler which brings up the "Abort or Debug" // dialog box, etc. Otherwise, we will just write out a core file // "summary" in the log directory and not display the dialog. void check_core_files() { char* tmp; int want_set_error_mode = TRUE; if( (tmp = param("CREATE_CORE_FILES")) ) { #ifndef WIN32 if( *tmp == 't' || *tmp == 'T' ) { limit( RLIMIT_CORE, RLIM_INFINITY, CONDOR_SOFT_LIMIT,"max core size" ); } else { limit( RLIMIT_CORE, 0, CONDOR_SOFT_LIMIT,"max core size" ); } #endif if( *tmp == 'f' || *tmp == 'F' ) { want_set_error_mode = FALSE; } free( tmp ); } #ifdef WIN32 // Call SetErrorMode so that Win32 "critical errors" and such // do not open up a dialog window! if ( want_set_error_mode ) { ::SetErrorMode( SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX ); g_ExceptionHandler.TurnOn(); } else { ::SetErrorMode( 0 ); g_ExceptionHandler.TurnOff(); } #endif } static int handle_off_fast( Service*, int, Stream* stream) { if( !stream->end_of_message() ) { dprintf( D_ALWAYS, "handle_off_fast: failed to read end of message\n"); return FALSE; } daemonCore->Send_Signal( daemonCore->getpid(), SIGQUIT ); return TRUE; } static int handle_off_graceful( Service*, int, Stream* stream) { if( !stream->end_of_message() ) { dprintf( D_ALWAYS, "handle_off_graceful: failed to read end of message\n"); return FALSE; } daemonCore->Send_Signal( daemonCore->getpid(), SIGTERM ); return TRUE; } static int handle_off_peaceful( Service*, int, Stream* stream) { // Peaceful shutdown is the same as graceful, except // there is no timeout waiting for things to finish. if( !stream->end_of_message() ) { dprintf( D_ALWAYS, "handle_off_peaceful: failed to read end of message\n"); return FALSE; } daemonCore->SetPeacefulShutdown(true); daemonCore->Send_Signal( daemonCore->getpid(), SIGTERM ); return TRUE; } static int handle_set_peaceful_shutdown( Service*, int, Stream* stream) { // If the master could send peaceful shutdown signals, it would // not be necessary to have a message for turning on the peaceful // shutdown toggle. Since the master only sends fast and graceful // shutdown signals, condor_off is responsible for first turning // on peaceful shutdown in appropriate daemons. if( !stream->end_of_message() ) { dprintf( D_ALWAYS, "handle_set_peaceful_shutdown: failed to read end of message\n"); return FALSE; } daemonCore->SetPeacefulShutdown(true); return TRUE; } static int handle_reconfig( Service*, int cmd, Stream* stream ) { if( !stream->end_of_message() ) { dprintf( D_ALWAYS, "handle_reconfig: failed to read end of message\n"); return FALSE; } if( cmd == DC_RECONFIG_FULL ) { dc_reconfig( true ); } else { dc_reconfig( false ); } return TRUE; } int handle_fetch_log( Service *, int, ReliSock *stream ) { char *name = NULL; int total_bytes = 0; int result; int type = -1; if( ! stream->code(type) || ! stream->code(name) || ! stream->end_of_message()) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log: can't read log request\n" ); free( name ); return FALSE; } stream->encode(); switch (type) { case DC_FETCH_LOG_TYPE_PLAIN: break; // handled below case DC_FETCH_LOG_TYPE_HISTORY: return handle_fetch_log_history(stream, name); case DC_FETCH_LOG_TYPE_HISTORY_DIR: return handle_fetch_log_history_dir(stream, name); case DC_FETCH_LOG_TYPE_HISTORY_PURGE: free(name); return handle_fetch_log_history_purge(stream); default: dprintf(D_ALWAYS,"DaemonCore: handle_fetch_log: I don't know about log type %d!\n",type); result = DC_FETCH_LOG_RESULT_BAD_TYPE; stream->code(result); stream->end_of_message(); free(name); return FALSE; } char *pname = (char*)malloc (strlen(name) + 5); char *ext = strchr(name,'.'); //If there is a dot in the name, it is of the form "<SUBSYS>.<ext>" //Otherwise, it is "<SUBSYS>". The file extension is used to //handle such things as "StarterLog.slot1" and "StarterLog.cod" if(ext) { strncpy(pname, name, ext-name); pname[ext-name] = '\0'; } else { strcpy(pname, name); } strcat (pname, "_LOG"); char *filename = param(pname); if(!filename) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log: no parameter named %s\n",pname); result = DC_FETCH_LOG_RESULT_NO_NAME; stream->code(result); stream->end_of_message(); free(pname); free(name); return FALSE; } MyString full_filename = filename; if(ext) { full_filename += ext; } int fd = safe_open_wrapper(full_filename.Value(),O_RDONLY); if(fd<0) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log: can't open file %s\n",full_filename.Value()); result = DC_FETCH_LOG_RESULT_CANT_OPEN; stream->code(result); stream->end_of_message(); free(filename); free(pname); free(name); return FALSE; } result = DC_FETCH_LOG_RESULT_SUCCESS; stream->code(result); filesize_t size; stream->put_file(&size, fd); total_bytes += size; stream->end_of_message(); if(total_bytes<0) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log: couldn't send all data!\n"); } close(fd); free(filename); free(pname); free(name); return total_bytes>=0; } int handle_fetch_log_history(ReliSock *stream, char *name) { int result = DC_FETCH_LOG_RESULT_BAD_TYPE; char *history_file_param = "HISTORY"; if (strcmp(name, "STARTD_HISTORY") == 0) { history_file_param = "STARTD_HISTORY"; } free(name); char *history_file = param(history_file_param); if (!history_file) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log_history: no parameter named %s\n", history_file_param); stream->code(result); stream->end_of_message(); return FALSE; } int fd = safe_open_wrapper(history_file,O_RDONLY); free(history_file); if(fd<0) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log_history: can't open history file\n"); result = DC_FETCH_LOG_RESULT_CANT_OPEN; stream->code(result); stream->end_of_message(); return FALSE; } result = DC_FETCH_LOG_RESULT_SUCCESS; stream->code(result); filesize_t size; stream->put_file(&size, fd); stream->end_of_message(); if(size<0) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log_history: couldn't send all data!\n"); } close(fd); return TRUE; } int handle_fetch_log_history_dir(ReliSock *stream, char *paramName) { int result = DC_FETCH_LOG_RESULT_BAD_TYPE; free(paramName); char *dirName = param("STARTD.PER_JOB_HISTORY_DIR"); if (!dirName) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log_history_dir: no parameter named PER_JOB\n"); stream->code(result); stream->end_of_message(); return FALSE; } Directory d(dirName); const char *filename; int one=1; int zero=0; while ((filename = d.Next())) { stream->code(one); // more data stream->put(filename); MyString fullPath(dirName); fullPath += "/"; fullPath += filename; int fd = safe_open_wrapper(fullPath.Value(),O_RDONLY); if (fd > 0) { filesize_t size; stream->put_file(&size, fd); } } free(dirName); stream->code(zero); // no more data stream->end_of_message(); return 0; } int handle_fetch_log_history_purge(ReliSock *s) { int result = 0; time_t cutoff = 0; s->code(cutoff); s->end_of_message(); s->encode(); char *dirName = param("STARTD.PER_JOB_HISTORY_DIR"); if (!dirName) { dprintf( D_ALWAYS, "DaemonCore: handle_fetch_log_history_dir: no parameter named PER_JOB\n"); s->code(result); s->end_of_message(); return FALSE; } Directory d(dirName); result = 1; while (d.Next()) { time_t last = d.GetModifyTime(); if (last < cutoff) { d.Remove_Current_File(); } } free(dirName); s->code(result); // no more data s->end_of_message(); return 0; } int handle_nop( Service*, int, Stream* stream) { if( !stream->end_of_message() ) { dprintf( D_ALWAYS, "handle_nop: failed to read end of message\n"); return FALSE; } return TRUE; } int handle_invalidate_key( Service*, int, Stream* stream) { int result = 0; char *key_id = NULL; stream->decode(); if ( ! stream->code(key_id) ) { dprintf ( D_ALWAYS, "DC_INVALIDATE_KEY: unable to receive key id!.\n"); return FALSE; } if ( ! stream->end_of_message() ) { dprintf ( D_ALWAYS, "DC_INVALIDATE_KEY: unable to receive EOM on key %s.\n", key_id); return FALSE; } result = daemonCore->getSecMan()->invalidateKey(key_id); free(key_id); return result; } int handle_config_val( Service*, int, Stream* stream ) { char *param_name = NULL, *tmp; stream->decode(); if( ! stream->code(param_name) ) { dprintf( D_ALWAYS, "Can't read parameter name\n" ); free( param_name ); return FALSE; } if( ! stream->end_of_message() ) { dprintf( D_ALWAYS, "Can't read end_of_message\n" ); free( param_name ); return FALSE; } stream->encode(); tmp = param( param_name ); if( ! tmp ) { dprintf( D_FULLDEBUG, "Got DC_CONFIG_VAL request for unknown parameter (%s)\n", param_name ); free( param_name ); if( ! stream->put("Not defined") ) { dprintf( D_ALWAYS, "Can't send reply for DC_CONFIG_VAL\n" ); return FALSE; } if( ! stream->end_of_message() ) { dprintf( D_ALWAYS, "Can't send end of message for DC_CONFIG_VAL\n" ); return FALSE; } return FALSE; } else { free( param_name ); if( ! stream->code(tmp) ) { dprintf( D_ALWAYS, "Can't send reply for DC_CONFIG_VAL\n" ); free( tmp ); return FALSE; } free( tmp ); if( ! stream->end_of_message() ) { dprintf( D_ALWAYS, "Can't send end of message for DC_CONFIG_VAL\n" ); return FALSE; } } return TRUE; } int handle_config( Service *, int cmd, Stream *stream ) { char *admin = NULL, *config = NULL; char *to_check = NULL; int rval = 0; bool failed = false; stream->decode(); if ( ! stream->code(admin) ) { dprintf( D_ALWAYS, "Can't read admin string\n" ); free( admin ); return FALSE; } if ( ! stream->code(config) ) { dprintf( D_ALWAYS, "Can't read configuration string\n" ); free( admin ); free( config ); return FALSE; } if( !stream->end_of_message() ) { dprintf( D_ALWAYS, "handle_config: failed to read end of message\n"); return FALSE; } if( config && config[0] ) { to_check = config; } else { to_check = admin; } if( ! daemonCore->CheckConfigSecurity(to_check, (Sock*)stream) ) { // This request is insecure, so don't try to do anything // with it. We can't return yet, since we want to send // back an rval indicating the error. free( admin ); free( config ); rval = -1; failed = true; } // If we haven't hit an error yet, try to process the command if( ! failed ) { switch(cmd) { case DC_CONFIG_PERSIST: rval = set_persistent_config(admin, config); // set_persistent_config will free admin and config // when appropriate break; case DC_CONFIG_RUNTIME: rval = set_runtime_config(admin, config); // set_runtime_config will free admin and config when // appropriate break; default: dprintf( D_ALWAYS, "unknown DC_CONFIG command!\n" ); free( admin ); free( config ); return FALSE; } } stream->encode(); if ( ! stream->code(rval) ) { dprintf (D_ALWAYS, "Failed to send rval for DC_CONFIG.\n" ); return FALSE; } if( ! stream->end_of_message() ) { dprintf( D_ALWAYS, "Can't send end of message for DC_CONFIG.\n" ); return FALSE; } return (failed ? FALSE : TRUE); } #ifndef WIN32 void unix_sighup(int) { daemonCore->Send_Signal( daemonCore->getpid(), SIGHUP ); } void unix_sigterm(int) { daemonCore->Send_Signal( daemonCore->getpid(), SIGTERM ); } void unix_sigquit(int) { daemonCore->Send_Signal( daemonCore->getpid(), SIGQUIT ); } void unix_sigchld(int) { daemonCore->Send_Signal( daemonCore->getpid(), SIGCHLD ); } void unix_sigusr1(int) { daemonCore->Send_Signal( daemonCore->getpid(), SIGUSR1 ); } void unix_sigusr2(int) { daemonCore->Send_Signal( daemonCore->getpid(), SIGUSR2 ); } #endif /* ! WIN32 */ void dc_reconfig( bool is_full ) { // do this first in case anything else depends on DNS daemonCore->refreshDNS(); // Actually re-read the files... Added by Derek Wright on // 12/8/97 (long after this function was first written... // nice goin', Todd). *grin* /* purify flags this as a stack bounds array read violation when we're expecting to use the default argument. However, due to _craziness_ in the header file that declares this function as an extern "C" linkage with a default argument(WTF!?) while being called in a C++ context, something goes wrong. So, we'll just supply the errant argument. */ config(0); // See if we're supposed to be allowing core files or not check_core_files(); if( DynamicDirs ) { handle_dynamic_dirs(); } // If we're supposed to be using our own log file, reset that here. if( logDir ) { set_log_dir(); } if( logAppend ) { handle_log_append( logAppend ); } // Reinitialize logging system; after all, LOG may have been changed. dprintf_config(get_mySubSystem()->getName() ); // again, chdir to the LOG directory so that if we dump a core // it will go there. the location of LOG may have changed, so redo it here. drop_core_in_log(); // Re-read everything from the config file DaemonCore itself cares about. // This also cleares the DNS cache. daemonCore->reconfig(); // Clear out the passwd cache. if( is_full ) { clear_passwd_cache(); } // Re-drop the address file, if it's defined, just to be safe. drop_addr_file(); // Re-drop the pid file, if it's requested, just to be safe. if( pidFile ) { drop_pid_file(); } // If requested to do so in the config file, do a segv now. // This is to test our handling/writing of a core file. char* ptmp; if ( (ptmp=param("DROP_CORE_ON_RECONFIG")) && (*ptmp=='T' || *ptmp=='t') ) { // on purpose, derefernce a null pointer. ptmp = NULL; char segfault; segfault = *ptmp; // should blow up here ptmp[0] = 'a'; // should never make it to here! EXCEPT("FAILED TO DROP CORE"); } // call this daemon's specific main_config() main_config( is_full ); } int handle_dc_sighup( Service*, int ) { dprintf( D_ALWAYS, "Got SIGHUP. Re-reading config files.\n" ); dc_reconfig( true ); return TRUE; } int handle_dc_sigterm( Service*, int ) { static int been_here = FALSE; if( been_here ) { dprintf( D_FULLDEBUG, "Got SIGTERM, but we've already done graceful shutdown. Ignoring.\n" ); return TRUE; } been_here = TRUE; dprintf(D_ALWAYS, "Got SIGTERM. Performing graceful shutdown.\n"); #if defined(WIN32) && 0 if ( line_where_service_stopped != 0 ) { dprintf(D_ALWAYS,"Line where service stopped = %d\n", line_where_service_stopped); } #endif if( daemonCore->GetPeacefulShutdown() ) { dprintf( D_FULLDEBUG, "Peaceful shutdown in effect. No timeout enforced.\n"); } else { int timeout = 30 * MINUTE; char* tmp = param( "SHUTDOWN_GRACEFUL_TIMEOUT" ); if( tmp ) { timeout = atoi( tmp ); free( tmp ); } daemonCore->Register_Timer( timeout, 0, (TimerHandler)main_shutdown_fast, "main_shutdown_fast" ); dprintf( D_FULLDEBUG, "Started timer to call main_shutdown_fast in %d seconds\n", timeout ); } main_shutdown_graceful(); return TRUE; } void TimerHandler_dc_sigterm() { handle_dc_sigterm(NULL, SIGTERM); } int handle_dc_sigquit( Service*, int ) { static int been_here = FALSE; if( been_here ) { dprintf( D_FULLDEBUG, "Got SIGQUIT, but we've already done fast shutdown. Ignoring.\n" ); return TRUE; } been_here = TRUE; dprintf(D_ALWAYS, "Got SIGQUIT. Performing fast shutdown.\n"); main_shutdown_fast(); return TRUE; } void handle_gcb_recovery_failed( ) { dprintf( D_ALWAYS, "GCB failed to recover from a failure with the " "Broker. Performing fast shutdown.\n" ); main_shutdown_fast(); } static void gcb_recovery_failed_callback() { // BEWARE! This function is called by GCB. Most likely, either // DaemonCore is blocked on a select() or CEDAR is blocked on a // network operation. So we register a daemoncore timer to do // the real work. daemonCore->Register_Timer( 0, handle_gcb_recovery_failed, "handle_gcb_recovery_failed" ); } // This is the main entry point for daemon core. On WinNT, however, we // have a different, smaller main which checks if "-f" is ommitted from // the command line args of the condor_master, in which case it registers as // an NT service. #ifdef WIN32 int dc_main( int argc, char** argv ) #else int main( int argc, char** argv ) #endif { char** ptr; int command_port = -1; int http_port = -1; int dcargs = 0; // number of daemon core command-line args found char *ptmp, *ptmp1; int i; int wantsKill = FALSE, wantsQuiet = FALSE; condor_main_argc = argc; condor_main_argv = (char **)malloc((argc+1)*sizeof(char *)); for(i=0;i<argc;i++) { condor_main_argv[i] = strdup(argv[i]); } condor_main_argv[i] = NULL; #ifdef WIN32 /** Enable support of the %n format in the printf family of functions. */ _set_printf_count_output(TRUE); #endif #ifndef WIN32 // Set a umask value so we get reasonable permissions on the // files we create. Derek Wright <wright@cs.wisc.edu> 3/3/98 umask( 022 ); // Handle Unix signals // Block all signals now. We'll unblock them right before we // do the select. sigset_t fullset; sigfillset( &fullset ); // We do not want to block the following signals ---- sigdelset(&fullset, SIGSEGV); // so we get a core right away sigdelset(&fullset, SIGABRT); // so assert() failures drop core right away sigdelset(&fullset, SIGILL); // so we get a core right away sigdelset(&fullset, SIGBUS); // so we get a core right away sigdelset(&fullset, SIGFPE); // so we get a core right away sigdelset(&fullset, SIGTRAP); // so gdb works when it uses SIGTRAP sigprocmask( SIG_SETMASK, &fullset, NULL ); // Install these signal handlers with a default mask // of all signals blocked when we're in the handlers. install_sig_handler_with_mask(SIGQUIT, &fullset, unix_sigquit); install_sig_handler_with_mask(SIGHUP, &fullset, unix_sighup); install_sig_handler_with_mask(SIGTERM, &fullset, unix_sigterm); install_sig_handler_with_mask(SIGCHLD, &fullset, unix_sigchld); install_sig_handler_with_mask(SIGUSR1, &fullset, unix_sigusr1); install_sig_handler_with_mask(SIGUSR2, &fullset, unix_sigusr2); install_sig_handler(SIGPIPE, SIG_IGN ); #endif // of ifndef WIN32 _condor_myServiceName = argv[0]; // set myName to be argv[0] with the path stripped off myName = condor_basename(argv[0]); myFullName = getExecPath(); if( ! myFullName ) { // if getExecPath() didn't work, the best we can do is try // saving argv[0] and hope for the best... if( argv[0][0] == '/' ) { // great, it's already a full path myFullName = strdup(argv[0]); } else { // we don't have anything reliable, so forget it. myFullName = NULL; } } myDistro->Init( argc, argv ); if ( EnvInit() < 0 ) { exit( 1 ); } // call out to the handler for pre daemonCore initialization // stuff so that our client side can do stuff before we start // messing with argv[] main_pre_dc_init( argc, argv ); // Make sure this is set, since DaemonCore needs it for all // sorts of things, and it's better to clearly EXCEPT here // than to seg fault down the road... if( ! get_mySubSystem() ) { EXCEPT( "Programmer error: get_mySubSystem() is NULL!" ); } if( !get_mySubSystem()->isValid() ) { get_mySubSystem()->printf( ); EXCEPT( "Programmer error: get_mySubSystem() info is invalid(%s,%d,%s)!", get_mySubSystem()->getName(), get_mySubSystem()->getType(), get_mySubSystem()->getTypeName() ); } // strip off any daemon-core specific command line arguments // from the front of the command line. i = 0; bool done = false; for(ptr = argv + 1; *ptr && (i < argc - 1); ptr++,i++) { if(ptr[0][0] != '-') { break; } /* NOTE! If you're adding a new command line argument to this switch statement, YOU HAVE TO ADD IT TO THE #ifdef WIN32 VERSION OF "main()" NEAR THE END OF THIS FILE, TOO. You should actually deal with the argument here, but you need to add it there to be skipped over because of NT weirdness with starting as a service, etc. Also, please add your argument in alphabetical order, so we can maintain some semblance of order in here, and make it easier to keep the two switch statements in sync. Derek Wright <wright@cs.wisc.edu> 11/11/99 */ switch(ptr[0][1]) { case 'a': // Append to the log file name. ptr++; if( ptr && *ptr ) { logAppend = *ptr; dcargs += 2; } else { fprintf( stderr, "DaemonCore: ERROR: -append needs another argument.\n" ); fprintf( stderr, " Please specify a string to append to our log's filename.\n" ); exit( 1 ); } break; case 'b': // run in Background (default) Foreground = 0; dcargs++; break; case 'c': // specify directory where Config file lives ptr++; if( ptr && *ptr ) { ptmp = *ptr; dcargs += 2; ptmp1 = (char *)malloc( strlen(ptmp) + myDistro->GetLen() + 10 ); if ( ptmp1 ) { sprintf(ptmp1,"%s_CONFIG=%s", myDistro->GetUc(), ptmp); SetEnv(ptmp1); } } else { fprintf( stderr, "DaemonCore: ERROR: -config needs another argument.\n" ); fprintf( stderr, " Please specify the filename of the config file.\n" ); exit( 1 ); } break; case 'd': // Dynamic local directories DynamicDirs = true; dcargs++; break; case 'f': // run in Foreground Foreground = 1; dcargs++; break; #ifndef WIN32 case 'k': // Kill the pid in the given pid file ptr++; if( ptr && *ptr ) { pidFile = *ptr; wantsKill = TRUE; dcargs += 2; } else { fprintf( stderr, "DaemonCore: ERROR: -kill needs another argument.\n" ); fprintf( stderr, " Please specify a file that holds the pid you want to kill.\n" ); exit( 1 ); } break; #endif case 'l': // -local-name or -log // specify local name if ( strcmp( &ptr[0][1], "local-name" ) == 0 ) { ptr++; if( ptr && *ptr ) { get_mySubSystem()->setLocalName( *ptr ); dcargs += 2; } else { fprintf( stderr, "DaemonCore: ERROR: " "-local-name needs another argument.\n" ); fprintf( stderr, " Please specify the local config to use.\n" ); exit( 1 ); } } // specify Log directory else { ptr++; if( ptr && *ptr ) { logDir = *ptr; dcargs += 2; } else { fprintf( stderr, "DaemonCore: ERROR: -log needs another " "argument\n" ); exit( 1 ); } } break; case 'h': // -http <port> : specify port for HTTP and SOAP requests if ( ptr[0][2] && ptr[0][2] == 't' ) { // specify an HTTP port ptr++; if( ptr && *ptr ) { http_port = atoi( *ptr ); dcargs += 2; } else { fprintf( stderr, "DaemonCore: ERROR: -http needs another argument.\n" ); fprintf( stderr, " Please specify the port to use for the HTTP socket.\n" ); exit( 1 ); } } else { // it's not -http, so do NOT consume this arg!! // in fact, we're done w/ DC args, since it's the // first option we didn't recognize. done = true; } break; case 'p': // use well-known Port for command socket, or // specify a Pidfile to drop your pid into if( ptr[0][2] && ptr[0][2] == 'i' ) { // Specify a Pidfile ptr++; if( ptr && *ptr ) { pidFile = *ptr; dcargs += 2; } else { fprintf( stderr, "DaemonCore: ERROR: -pidfile needs another argument.\n" ); fprintf( stderr, " Please specify a filename to store the pid.\n" ); exit( 1 ); } } else { // use well-known Port for command socket // note: "-p 0" means _no_ command socket ptr++; if( ptr && *ptr ) { command_port = atoi( *ptr ); dcargs += 2; } else { fprintf( stderr, "DaemonCore: ERROR: -port needs another argument.\n" ); fprintf( stderr, " Please specify the port to use for the command socket.\n" ); exit( 1 ); } } break; case 'q': // Quiet output wantsQuiet = TRUE; dcargs++; break; case 'r': // Run for <arg> minutes, then gracefully exit ptr++; if( ptr && *ptr ) { runfor = atoi( *ptr ); dcargs += 2; } else { fprintf( stderr, "DaemonCore: ERROR: -runfor needs another argument.\n" ); fprintf( stderr, " Please specify the number of minutes to run for.\n" ); exit( 1 ); } //call Register_Timer below after intialized... break; case 't': // log to Terminal (stderr) Termlog = 1; dcargs++; break; case 'v': // display Version info and exit printf( "%s\n%s\n", CondorVersion(), CondorPlatform() ); exit(0); break; default: done = true; break; } if ( done ) { break; // break out of for loop } } // using "-t" also implicitly sets "-f"; i.e. only to stderr in the foreground if ( Termlog ) { Foreground = 1; } // call config so we can call param. if ( get_mySubSystem()->isType(SUBSYSTEM_TYPE_SHADOW) ) { // Try to minimize shadow footprint by not loading // the "extra" info from the config file config( wantsQuiet, false, false ); } else { config( wantsQuiet, false, true ); } // call dc_config_GSI to set GSI related parameters so that all // the daemons will know what to do. if ( doAuthInit ) { condor_auth_config( true ); } // See if we're supposed to be allowing core files or not check_core_files(); // If we want to kill something, do that now. if( wantsKill ) { do_kill(); } if( ! DynamicDirs ) { // We need to setup logging. Normally, we want to do this // before the fork(), so that if there are problems and we // fprintf() to stderr, we'll still see them. However, if // we want DynamicDirs, we can't do this yet, since we // need our pid to specify the log directory... // If want to override what's set in our config file, we've // got to do that here, between where we config and where we // setup logging. Note: we also have to do this in reconfig. if( logDir ) { set_log_dir(); } // If we're told on the command-line to append something to // the name of our log file, we do that here, so that when we // setup logging, we get the right filename. -Derek Wright // 11/20/98 if( logAppend ) { handle_log_append( logAppend ); } // Actually set up logging. dprintf_config(get_mySubSystem()->getName() ); } // run as condor 99.9% of the time, so studies tell us. set_condor_priv(); // we want argv[] stripped of daemoncore options ptmp = argv[0]; // save a temp pointer to argv[0] argv = --ptr; // make space for argv[0] argv[0] = ptmp; // set argv[0] argc -= dcargs; if ( argc < 1 ) argc = 1; // Arrange to run in the background. // SPECIAL CASE: if this is the MASTER, and we are to run in the background, // then register ourselves as an NT Service. if (!Foreground) { #ifdef WIN32 // Disconnect from the console FreeConsole(); #else // UNIX // on unix, background means just fork ourselves if ( fork() ) { // parent exit(0); } // And close stdin, out, err if we are the MASTER. // NRL 2006-08-10: Here's what and why we're doing this..... // // In days of yore, we'd simply close FDs 0,1,2 and be done // with it. Unfortunately, some 3rd party tools were writing // directly to these FDs. Now, you might not that that this // would be a problem, right? Unfortunately, once you close // an FD (say, 1 or 2), then next safe_open_wrapper() or socket() // call can / will now return 1 (or 2). So, when libfoo.a thinks // it fprintf()ing an error message to fd 2 (the FD behind // stderr), it's actually sending that message over a socket // to a process that has no idea how to handle it. // // So, here's what we do. We open /dev/null, and then use // dup2() to copy this "safe" fd to these decriptors. Note // that if you don't open it with O_RDWR, you can cause writes // to the FD to return errors. // // Finally, we only do this in the master. Why? Because // Create_Process() has similar logic, so when the master // starts, say, condor_startd, the Create_Process() logic // takes over and does The Right Thing(tm). // // Regarding the std in/out/err streams (the FILE *s, not the // FDs), we leave those open. Otherwise, if libfoo.a tries to // fwrite to stderr, it would get back an error from fprintf() // (or fwrite(), etc.). If it checks this, it might Do // Something Bad(tm) like abort() -- who knows. In any case, // it seems safest to just leave them open but attached to // /dev/null. if ( get_mySubSystem()->isType( SUBSYSTEM_TYPE_MASTER ) ) { int fd_null = safe_open_wrapper( NULL_FILE, O_RDWR ); if ( fd_null < 0 ) { fprintf( stderr, "Unable to open %s: %s\n", NULL_FILE, strerror(errno) ); dprintf( D_ALWAYS, "Unable to open %s: %s\n", NULL_FILE, strerror(errno) ); } int fd; for( fd=0; fd<=2; fd++ ) { close( fd ); if ( ( fd_null >= 0 ) && ( fd_null != fd ) && ( dup2( fd_null, fd ) < 0 ) ) { dprintf( D_ALWAYS, "Error dup2()ing %s -> %d: %s\n", NULL_FILE, fd, strerror(errno) ); } } // Close the /dev/null descriptor _IF_ it's not stdin/out/err if ( fd_null > 2 ) { close( fd_null ); } } // and detach from the controlling tty detach(); #endif // of else of ifdef WIN32 } // if if !Foreground // See if the config tells us to wait on startup for a debugger to attach. MyString debug_wait_param; debug_wait_param.sprintf("%s_DEBUG_WAIT", get_mySubSystem()->getName() ); if (param_boolean(debug_wait_param.Value(), false, false)) { int debug_wait = 1; dprintf(D_ALWAYS, "%s is TRUE, waiting for debugger to attach to pid %d.\n", debug_wait_param.Value(), (int)::getpid()); while (debug_wait) { sleep(1); } } // Now that we've potentially forked, we have our real pid, so // we can instantiate a daemon core and it'll have the right // pid. Have lots of pid table hash buckets if we're the // SCHEDD, since the SCHEDD could have lots of children... if ( get_mySubSystem()->isType( SUBSYSTEM_TYPE_SCHEDD ) ) { daemonCore = new DaemonCore(503); } else { daemonCore = new DaemonCore(); } if( DynamicDirs ) { // If we want to use dynamic dirs for log, spool and // execute, we now have our real pid, so we can actually // give it the correct name. handle_dynamic_dirs(); if( logAppend ) { handle_log_append( logAppend ); } // Actually set up logging. dprintf_config(get_mySubSystem()->getName() ); } // Now that we have the daemonCore object, we can finally // know what our pid is, so we can print out our opening // banner. Plus, if we're using dynamic dirs, we have dprintf // configured now, so the dprintf()s will work. dprintf(D_ALWAYS,"******************************************************\n"); dprintf(D_ALWAYS,"** %s (%s_%s) STARTING UP\n", myName,myDistro->GetUc(), get_mySubSystem()->getName() ); if( myFullName ) { dprintf( D_ALWAYS, "** %s\n", myFullName ); free( myFullName ); myFullName = NULL; } dprintf(D_ALWAYS,"** %s\n", get_mySubSystem()->getString() ); dprintf(D_ALWAYS,"** Configuration: subsystem:%s local:%s class:%s\n", get_mySubSystem()->getName(), get_mySubSystem()->getLocalName("<NONE>"), get_mySubSystem()->getClassName( ) ); dprintf(D_ALWAYS,"** %s\n", CondorVersion()); dprintf(D_ALWAYS,"** %s\n", CondorPlatform()); dprintf(D_ALWAYS,"** PID = %lu\n", (unsigned long) daemonCore->getpid()); time_t log_last_mod_time = dprintf_last_modification(); if ( log_last_mod_time <= 0 ) { dprintf(D_ALWAYS,"** Log last touched time unavailable (%s)\n", strerror(-log_last_mod_time)); } else { struct tm *tm = localtime( &log_last_mod_time ); dprintf(D_ALWAYS,"** Log last touched %d/%d %02d:%02d:%02d\n", tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); } #ifndef WIN32 // Want to do this dprintf() here, since we can't do it w/n // the priv code itself or we get major problems. // -Derek Wright 12/21/98 if( getuid() ) { dprintf(D_PRIV, "** Running as non-root: No privilege switching\n"); } else { dprintf(D_PRIV, "** Running as root: Privilege switching in effect\n"); } #endif dprintf(D_ALWAYS,"******************************************************\n"); if (global_config_source != "") { dprintf(D_ALWAYS, "Using config source: %s\n", global_config_source.Value()); } else { const char* env_name = EnvGetName( ENV_CONFIG ); char* env = getenv( env_name ); if( env ) { dprintf(D_ALWAYS, "%s is set to '%s', not reading a config file\n", env_name, env ); } } if (!local_config_sources.isEmpty()) { dprintf(D_ALWAYS, "Using local config sources: \n"); local_config_sources.rewind(); char *source; while( (source = local_config_sources.next()) != NULL ) { dprintf(D_ALWAYS, " %s\n", source ); } } // chdir() into our log directory so if we drop core, that's // where it goes. We also do some NT-specific stuff in here. drop_core_in_log(); #ifdef WIN32 // On NT, we need to make certain we have a console allocated, // since many standard mechanisms do not work without a console // attached [like popen(), stdin/out/err, GenerateConsoleEvent]. // There are several reasons why we may not have a console // right now: a) we are running as a service, and services are // born without a console, or b) the user did not specify "-f" // or "-t", and thus we called FreeConsole() above. // for now, don't create a console for the kbdd, as that daemon // is now a win32 app and not a console app. BOOL is_kbdd = (0 == strcmp(get_mySubSystem()->getName(), "KBDD")); if(!is_kbdd) AllocConsole(); #endif // Avoid possibility of stale info sticking around from previous run. // For example, we had problems in 7.0.4 and earlier with reconnect // shadows in parallel universe reading the old schedd ad file. kill_daemon_ad_file(); // Now that we have our pid, we could dump our pidfile, if we // want it. if( pidFile ) { drop_pid_file(); } #ifndef WIN32 // Now that logging is setup, create a pipe to deal with unix // async signals. We do this after logging is setup so that // we can EXCEPT (and really log something) on failure... if ( pipe(daemonCore->async_pipe) == -1 || fcntl(daemonCore->async_pipe[0],F_SETFL,O_NONBLOCK) == -1 || fcntl(daemonCore->async_pipe[1],F_SETFL,O_NONBLOCK) == -1 ) { EXCEPT("Failed to create async pipe"); } #else if ( daemonCore->async_pipe[1].connect_socketpair(daemonCore->async_pipe[0])==false ) { EXCEPT("Failed to create async pipe socket pair"); } #endif #if HAVE_EXT_GCB // Set up our GCB failure callback GCB_Recovery_failed_callback_set( gcb_recovery_failed_callback ); #endif main_pre_command_sock_init(); // SETUP COMMAND SOCKET daemonCore->InitDCCommandSocket( command_port ); // Install DaemonCore signal handlers common to all daemons. daemonCore->Register_Signal( SIGHUP, "SIGHUP", (SignalHandler)handle_dc_sighup, "handle_dc_sighup()" ); daemonCore->Register_Signal( SIGQUIT, "SIGQUIT", (SignalHandler)handle_dc_sigquit, "handle_dc_sigquit()" ); daemonCore->Register_Signal( SIGTERM, "SIGTERM", (SignalHandler)handle_dc_sigterm, "handle_dc_sigterm()" ); daemonCore->Register_Signal( DC_SERVICEWAITPIDS, "DC_SERVICEWAITPIDS", (SignalHandlercpp)&DaemonCore::HandleDC_SERVICEWAITPIDS, "HandleDC_SERVICEWAITPIDS()",daemonCore); #ifndef WIN32 daemonCore->Register_Signal( SIGCHLD, "SIGCHLD", (SignalHandlercpp)&DaemonCore::HandleDC_SIGCHLD, "HandleDC_SIGCHLD()",daemonCore); #endif // Install DaemonCore timers common to all daemons. //if specified on command line, set timer to gracefully exit if ( runfor ) { daemon_stop_time = time(NULL)+runfor*60; daemonCore->Register_Timer( runfor * 60, 0, TimerHandler_dc_sigterm, "handle_dc_sigterm" ); dprintf(D_ALWAYS,"Registered Timer for graceful shutdown in %d minutes\n", runfor ); } else { daemon_stop_time = 0; } #ifndef WIN32 // This timer checks if our parent is dead; if so, we shutdown. // We only do this on Unix; on NT we watch our parent via a different mechanism. // Also note: we do not want the master to exibit this behavior! if ( ! get_mySubSystem()->isType(SUBSYSTEM_TYPE_MASTER) ) { daemonCore->Register_Timer( 15, 120, check_parent, "check_parent" ); } #endif daemonCore->Register_Timer( 0, dc_touch_log_file, "dc_touch_log_file" ); daemonCore->Register_Timer( 0, dc_touch_lock_files, "dc_touch_lock_files" ); daemonCore->Register_Timer( 0, 5 * 60, check_session_cache, "check_session_cache" ); // set the timer for half the session duration, // since we retain the old cookie. Also make sure // the value is atleast 1. int cookie_refresh = (param_integer("SEC_DEFAULT_SESSION_DURATION", 3600)/2)+1; daemonCore->Register_Timer( 0, cookie_refresh, handle_cookie_refresh, "handle_cookie_refresh"); if( get_mySubSystem()->isType( SUBSYSTEM_TYPE_MASTER ) || get_mySubSystem()->isType( SUBSYSTEM_TYPE_SCHEDD ) || get_mySubSystem()->isType( SUBSYSTEM_TYPE_STARTD ) ) { daemonCore->monitor_data.EnableMonitoring(); } // Install DaemonCore command handlers common to all daemons. daemonCore->Register_Command( DC_RECONFIG, "DC_RECONFIG", (CommandHandler)handle_reconfig, "handle_reconfig()", 0, WRITE ); daemonCore->Register_Command( DC_RECONFIG_FULL, "DC_RECONFIG_FULL", (CommandHandler)handle_reconfig, "handle_reconfig()", 0, ADMINISTRATOR ); daemonCore->Register_Command( DC_CONFIG_VAL, "DC_CONFIG_VAL", (CommandHandler)handle_config_val, "handle_config_val()", 0, READ ); // Deprecated name for it. daemonCore->Register_Command( CONFIG_VAL, "CONFIG_VAL", (CommandHandler)handle_config_val, "handle_config_val()", 0, READ ); // The handler for setting config variables does its own // authorization, so these two commands should be registered // as "ALLOW" and the handler will do further checks. daemonCore->Register_Command( DC_CONFIG_PERSIST, "DC_CONFIG_PERSIST", (CommandHandler)handle_config, "handle_config()", 0, ALLOW ); daemonCore->Register_Command( DC_CONFIG_RUNTIME, "DC_CONFIG_RUNTIME", (CommandHandler)handle_config, "handle_config()", 0, ALLOW ); daemonCore->Register_Command( DC_OFF_FAST, "DC_OFF_FAST", (CommandHandler)handle_off_fast, "handle_off_fast()", 0, ADMINISTRATOR ); daemonCore->Register_Command( DC_OFF_GRACEFUL, "DC_OFF_GRACEFUL", (CommandHandler)handle_off_graceful, "handle_off_graceful()", 0, ADMINISTRATOR ); daemonCore->Register_Command( DC_OFF_PEACEFUL, "DC_OFF_PEACEFUL", (CommandHandler)handle_off_peaceful, "handle_off_peaceful()", 0, ADMINISTRATOR ); daemonCore->Register_Command( DC_SET_PEACEFUL_SHUTDOWN, "DC_SET_PEACEFUL_SHUTDOWN", (CommandHandler)handle_set_peaceful_shutdown, "handle_set_peaceful_shutdown()", 0, ADMINISTRATOR ); daemonCore->Register_Command( DC_NOP, "DC_NOP", (CommandHandler)handle_nop, "handle_nop()", 0, READ ); daemonCore->Register_Command( DC_FETCH_LOG, "DC_FETCH_LOG", (CommandHandler)handle_fetch_log, "handle_fetch_log()", 0, ADMINISTRATOR ); daemonCore->Register_Command( DC_PURGE_LOG, "DC_PURGE_LOG", (CommandHandler)handle_fetch_log_history_purge, "handle_fetch_log_history_purge()", 0, ADMINISTRATOR ); daemonCore->Register_Command( DC_INVALIDATE_KEY, "DC_INVALIDATE_KEY", (CommandHandler)handle_invalidate_key, "handle_invalidate_key()", 0, ALLOW ); // // The time offset command is used to figure out what // the range of the clock skew is between the daemon code and another // entity calling into us // daemonCore->Register_Command( DC_TIME_OFFSET, "DC_TIME_OFFSET", (CommandHandler)time_offset_receive_cedar_stub, "time_offset_cedar_stub", 0, DAEMON ); // Call daemonCore's reconfig(), which reads everything from // the config file that daemonCore cares about and initializes // private data members, etc. daemonCore->reconfig(); // zmiller // look in the env for ENV_PARENT_ID const char* envName = EnvGetName ( ENV_PARENT_ID ); MyString parent_id; GetEnv( envName, parent_id ); // send it to the SecMan object so it can include it in any // classads it sends. if this is NULL, it will not include // the attribute. daemonCore->sec_man->set_parent_unique_id(parent_id.Value()); // now re-set the identity so that any children we spawn will have it // in their environment SetEnv( envName, daemonCore->sec_man->my_unique_id() ); // create a database connection object //DBObj = createConnection(); // create a sql log object. We always have one defined, but // if quill is not enabled we never write data to the logfile bool use_sql_log = param_boolean( "QUILL_USE_SQL_LOG", false ); FILEObj = FILESQL::createInstance(use_sql_log); // create an xml log object XMLObj = FILEXML::createInstanceXML(); // call the daemon's main_init() main_init( argc, argv ); // now call the driver. we never return from the driver (infinite loop). daemonCore->Driver(); // should never get here EXCEPT("returned from Driver()"); return FALSE; } #ifdef WIN32 int main( int argc, char** argv) { char **ptr; int i; // Scan our command line arguments for a "-f". If we don't find a "-f", // or a "-v", then we want to register as an NT Service. i = 0; bool done = false; for( ptr = argv + 1; *ptr && (i < argc - 1); ptr++,i++) { if( ptr[0][0] != '-' ) { break; } switch( ptr[0][1] ) { case 'a': // Append to the log file name. ptr++; break; case 'b': // run in Background (default) break; case 'c': // specify directory where Config file lives ptr++; break; case 'd': // Dynamic local directories break; case 'f': // run in Foreground Foreground = 1; break; case 'l': // specify Log directory ptr++; break; case 'p': // Use well-known Port for command socket. ptr++; // Also used to specify a Pid file, but both break; // versions require a 2nd arg, so we're safe. case 'q': // Quiet output break; case 'r': // Run for <arg> minutes, then gracefully exit ptr++; break; case 't': // log to Terminal (stderr) break; case 'v': // display Version info and exit printf( "%s\n%s\n", CondorVersion(), CondorPlatform() ); exit(0); break; default: done = true; break; } if( done ) { break; // break out of for loop } } if ( (Foreground != 1) && get_mySubSystem()->isType(SUBSYSTEM_TYPE_MASTER) ) { main_init(-1,NULL); // passing the master main_init a -1 will register as an NT service return 1; } else { return(dc_main(argc,argv)); } } #endif // of ifdef WIN32
#include "convertpopup.h" // Tnz6 includes #include "menubarcommandids.h" #include "tapp.h" #include "formatsettingspopups.h" #include "filebrowser.h" // TnzQt includes #include "toonzqt/gutil.h" #include "toonzqt/imageutils.h" #include "toonzqt/menubarcommand.h" #include "toonzqt/filefield.h" #include "toonzqt/intfield.h" #include "toonzqt/colorfield.h" #include "toonzqt/checkbox.h" #include "toonzqt/icongenerator.h" // TnzLib includes #include "toonz/tscenehandle.h" #include "toonz/toonzscene.h" #include "toonz/sceneproperties.h" #include "toonz/tproject.h" #include "toutputproperties.h" #include "convert2tlv.h" #include "toonz/preferences.h" // TnzCore includes #include "tsystem.h" #include "tfiletype.h" #include "tlevel_io.h" #include "tiio.h" #include "tenv.h" // Qt includes #include <QPushButton> #include <QComboBox> #include <QLabel> #include <QApplication> #include <QMainWindow> #include <QCheckBox> /*-- Format --*/ TEnv::StringVar ConvertPopupFileFormat("ConvertPopupFileFormat", "tga"); /*-- 背景色 --*/ TEnv::IntVar ConvertPopupBgColorR("ConvertPopupBgColorR", 255); TEnv::IntVar ConvertPopupBgColorG("ConvertPopupBgColorG", 255); TEnv::IntVar ConvertPopupBgColorB("ConvertPopupBgColorB", 255); TEnv::IntVar ConvertPopupBgColorA("ConvertPopupBgColorA", 255); TEnv::IntVar ConvertPopupSkipExisting("ConvertPopupSkipExisting", 0); /*-- フレーム番号の前のドットを取る --*/ TEnv::IntVar ConvertPopupRemoveDot("ConvertPopupRemoveDot", 1); TEnv::IntVar ConvertPopupSaveToNopaint("ConvertPopupSaveToNopaint", 1); TEnv::IntVar ConvertPopupAppendDefaultPalette( "ConvertPopupAppendDefaultPalette", 0); TEnv::IntVar ConvertPopupRemoveUnusedStyles("ConvertPopupRemoveUnusedStyles", 0); //============================================================================= // convertPopup //----------------------------------------------------------------------------- QMap<std::string, TPropertyGroup *> ConvertPopup::m_formatProperties; /* TRANSLATOR namespace::ConvertPopup */ // const QString CreateNewPalette(QObject::tr("Create new palette")); const QString TlvExtension("tlv"); /* const QString TlvMode_Unpainted(QObject::tr("Unpainted tlv")); const QString TlvMode_PaintedFromTwoImages(QObject::tr("Painted tlv from two images")); const QString TlvMode_PaintedFromNonAA(QObject::tr("Painted tlv from non AA source")); const QString SameAsPainted(QObject::tr("Same as Painted")); */ //============================================================================= // // Converter // //----------------------------------------------------------------------------- class ConvertPopup::Converter final : public QThread { int m_skippedCount; ConvertPopup *m_parent; bool m_saveToNopaintOnlyFlag; public: Converter(ConvertPopup *parent) : m_parent(parent), m_skippedCount(0) {} void run() override; void convertLevel(const TFilePath &fp); void convertLevelWithConvert2Tlv(const TFilePath &fp); int getSkippedCount() const { return m_skippedCount; } }; void ConvertPopup::Converter::run() { ToonzScene *sc = TApp::instance()->getCurrentScene()->getScene(); DVGui::ProgressDialog *progressDialog = m_parent->m_progressDialog; int levelCount = m_parent->m_srcFilePaths.size(); TFilePath dstFolder(m_parent->m_saveInFileFld->getPath()); for (int i = 0; !m_parent->m_notifier->abortTask() && i < levelCount; i++) { TFilePath sourceLevelPath = sc->decodeFilePath(m_parent->m_srcFilePaths[i]); QString levelName = QString::fromStdString(sourceLevelPath.getLevelName()); // check already exsistent levels TFilePath dstFilePath = m_parent->getDestinationFilePath(m_parent->m_srcFilePaths[i]); // perche' ?? TFilePath // path=dstFilePath.getParentDir()+(dstFilePath.getName()+"."+dstFilePath.getDottedType()); // if(TSystem::doesExistFileOrLevel(dstFilePath)||TSystem::doesExistFileOrLevel(path)) m_saveToNopaintOnlyFlag = false; if (TSystem::doesExistFileOrLevel(dstFilePath)) { if (m_parent->m_skip->isChecked()) { DVGui::info(tr("Level %1 already exists; skipped.").arg(levelName)); m_skippedCount++; continue; } else { /*--- ここで、tlv形式に変換、かつ、UnpaintedTlvが選択され、かつ、    nopaintにバックアップを保存するオプションがONのとき、 出力先をnopaintに変更する。既にあるnopaint内のtlvを消す ---*/ if (m_parent->isSaveTlvBackupToNopaintActive()) { TFilePath unpaintedLevelPath = dstFilePath.getParentDir() + "nopaint\\" + TFilePath(dstFilePath.getName() + "_np." + dstFilePath.getType()); if (TSystem::doesExistFileOrLevel(unpaintedLevelPath)) { TSystem::removeFileOrLevel(unpaintedLevelPath); TSystem::deleteFile((unpaintedLevelPath.getParentDir() + unpaintedLevelPath.getName()) .withType("tpl")); } m_saveToNopaintOnlyFlag = true; } else // todo: handle errors!! TSystem::removeFileOrLevel(dstFilePath); } } if (m_parent->m_srcFilePaths.size() == 1) { progressDialog->setLabelText(QString(tr("Converting %1").arg(levelName))); } else { progressDialog->setLabelText(QString(tr("Converting level %1 of %2: %3") .arg(i + 1) .arg(levelCount) .arg(levelName))); } m_parent->m_notifier->notifyFrameCompleted(0); convertLevel(sourceLevelPath); } } void ConvertPopup::Converter::convertLevel( const TFilePath &sourceFileFullPath) { ToonzScene *sc = TApp::instance()->getCurrentScene()->getScene(); ConvertPopup *popup = m_parent; QString levelName = QString::fromStdString(sourceFileFullPath.getLevelName()); std::string ext = popup->m_fileFormat->currentText().toStdString(); TPropertyGroup *prop = popup->getFormatProperties(ext); TFilePath dstFileFullPath = popup->getDestinationFilePath(sourceFileFullPath); // bool isTlvNonAA = isTlv && popup->getTlvMode() == TlvMode_PaintedFromNonAA; bool isTlvNonAA = !(m_parent->getTlvMode().compare(m_parent->TlvMode_PaintedFromNonAA)); TFrameId from, to; if (TFileType::isLevelFilePath(sourceFileFullPath)) { popup->getFrameRange(sourceFileFullPath, from, to); if (from == TFrameId() || to == TFrameId()) { DVGui::warning(tr("Level %1 has no frame; skipped.").arg(levelName)); popup->m_notifier->notifyError(); return; } } TOutputProperties *oprop = TApp::instance() ->getCurrentScene() ->getScene() ->getProperties() ->getOutputProperties(); double framerate = oprop->getFrameRate(); if (popup->m_fileFormat->currentText() == TlvExtension) { // convert to TLV if (!(m_parent->getTlvMode().compare(m_parent->TlvMode_PaintedFromNonAA))) { // no AA source (retas) TPaletteP palette = popup->readUserProvidedPalette(); ImageUtils::convertNaa2Tlv(sourceFileFullPath, dstFileFullPath, from, to, m_parent->m_notifier, palette.getPointer(), m_parent->m_removeUnusedStyles->isChecked()); } else { convertLevelWithConvert2Tlv(sourceFileFullPath); } } else { // convert to full-color TPixel32 bgColor = m_parent->m_bgColorField->getColor(); ImageUtils::convert(sourceFileFullPath, dstFileFullPath, from, to, framerate, prop, m_parent->m_notifier, bgColor, m_parent->m_removeDotBeforeFrameNumber->isChecked()); } popup->m_notifier->notifyLevelCompleted(dstFileFullPath); } // to use legacy code void ConvertPopup::Converter::convertLevelWithConvert2Tlv( const TFilePath &sourceFileFullPath) { ConvertPopup *popup = m_parent; Convert2Tlv *tlvConverter = popup->makeTlvConverter(sourceFileFullPath); TFilePath levelOut = tlvConverter->m_levelOut; if (m_saveToNopaintOnlyFlag) { TFilePath unpaintedLevelPath = tlvConverter->m_levelOut.getParentDir() + "nopaint\\" + TFilePath(tlvConverter->m_levelOut.getName() + "_np." + tlvConverter->m_levelOut.getType()); tlvConverter->m_levelOut = unpaintedLevelPath; } std::string errorMessage; if (!tlvConverter->init(errorMessage)) { DVGui::warning(QString::fromStdString(errorMessage)); tlvConverter->abort(); } else { int count = tlvConverter->getFramesToConvertCount(); bool stop = false; for (int j = 0; j < count && !stop; j++) { if (!tlvConverter->convertNext(errorMessage)) { stop = true; DVGui::warning(QString::fromStdString(errorMessage)); } if (popup->m_progressDialog->wasCanceled()) stop = true; } if (stop) tlvConverter->abort(); delete tlvConverter; } /*--- nopaintファイルを複製する ---*/ if (m_parent->isSaveTlvBackupToNopaintActive() && !m_saveToNopaintOnlyFlag) { /*--- nopaintフォルダの作成 ---*/ TFilePath nopaintDir = levelOut.getParentDir() + "nopaint"; if (!TFileStatus(nopaintDir).doesExist()) { try { TSystem::mkDir(nopaintDir); } catch (...) { return; } } TFilePath unpaintedLevelPath = levelOut.getParentDir() + "nopaint\\" + TFilePath(levelOut.getName() + "_np." + levelOut.getType()); /*--- もしnopaintのファイルがあった場合は消去する ---*/ if (TSystem::doesExistFileOrLevel(unpaintedLevelPath)) { TSystem::removeFileOrLevel(unpaintedLevelPath); TSystem::deleteFile( (unpaintedLevelPath.getParentDir() + unpaintedLevelPath.getName()) .withType("tpl")); } TSystem::copyFile(unpaintedLevelPath, levelOut); /*--- Paletteのコピー ---*/ TFilePath levelPalettePath = levelOut.getParentDir() + TFilePath(levelOut.getName() + ".tpl"); TFilePath unpaintedLevelPalettePath = levelPalettePath.getParentDir() + "nopaint\\" + TFilePath(levelPalettePath.getName() + "_np." + levelPalettePath.getType()); TSystem::copyFile(unpaintedLevelPalettePath, levelPalettePath); } /* QApplication::restoreOverrideCursor(); FileBrowser::refreshFolder(m_srcFilePaths[0].getParentDir()); TFilePath::setUnderscoreFormatAllowed(false); TFilePath levelOut(converters[i]->m_levelOut); delete converters[i]; IconGenerator::instance()->invalidate(levelOut); */ } //============================================================================= ConvertPopup::ConvertPopup(bool specifyInput) : Dialog(TApp::instance()->getMainWindow(), true, false, "Convert") , m_converter(0) , m_isConverting(false) { // Su MAC i dialog modali non hanno bottoni di chiusura nella titleBar setModal(false); TlvMode_Unpainted = tr("Unpainted tlv"); TlvMode_UnpaintedFromNonAA = tr("Unpainted tlv from non AA source"); TlvMode_PaintedFromTwoImages = tr("Painted tlv from two images"); TlvMode_PaintedFromNonAA = tr("Painted tlv from non AA source"); SameAsPainted = tr("Same as Painted"); CreateNewPalette = tr("Create new palette"); m_fromFld = new DVGui::IntLineEdit(this); m_toFld = new DVGui::IntLineEdit(this); m_saveInFileFld = new DVGui::FileField(0, QString("")); m_fileNameFld = new DVGui::LineEdit(QString("")); m_fileFormat = new QComboBox(); m_formatOptions = new QPushButton(tr("Options"), this); m_bgColorField = new DVGui::ColorField(this, true, TPixel32::Transparent, 35, false); m_okBtn = new QPushButton(tr("Convert"), this); m_cancelBtn = new QPushButton(tr("Cancel"), this); m_bgColorLabel = new QLabel(tr("Bg Color:")); m_tlvFrame = createTlvSettings(); m_notifier = new ImageUtils::FrameTaskNotifier(); m_progressDialog = new DVGui::ProgressDialog("", tr("Cancel"), 0, 0); m_skip = new DVGui::CheckBox(tr("Skip Existing Files"), this); m_removeDotBeforeFrameNumber = new QCheckBox(tr("Remove dot before frame number"), this); if (specifyInput) m_convertFileFld = new DVGui::FileField(0, QString(""), true); else m_convertFileFld = 0; //----------------------- // File Format QStringList formats; TImageWriter::getSupportedFormats(formats, true); TLevelWriter::getSupportedFormats(formats, true); Tiio::Writer::getSupportedFormats(formats, true); m_fileFormat->addItems(formats); m_fileFormat->setMaxVisibleItems(15); m_skip->setChecked(true); m_okBtn->setDefault(true); if (specifyInput) { m_convertFileFld->setFileMode(QFileDialog::ExistingFile); QStringList filter; filter << "tif" << "tiff" << "png" << "tga" << "tlv" << "gif" << "bmp" << "avi" << "mov" << "jpg" << "pic" << "pict" << "rgb" << "sgi" << "png"; m_convertFileFld->setFilters(filter); m_okBtn->setEnabled(false); } m_removeDotBeforeFrameNumber->setChecked(false); m_progressDialog->setWindowTitle(tr("Convert... ")); m_progressDialog->setWindowFlags( Qt::Dialog | Qt::WindowTitleHint); // Don't show ? and X buttons m_progressDialog->setWindowModality(Qt::WindowModal); //----layout m_topLayout->setMargin(5); m_topLayout->setSpacing(5); { QGridLayout *upperLay = new QGridLayout(); upperLay->setMargin(0); upperLay->setSpacing(5); { upperLay->addWidget(new QLabel(tr("Start:"), this), 0, 0); upperLay->addWidget(m_fromFld, 0, 1); upperLay->addWidget(new QLabel(tr(" End:"), this), 0, 2); upperLay->addWidget(m_toFld, 0, 3); upperLay->addWidget(new QLabel(tr("Save in:"), this), 1, 0); upperLay->addWidget(m_saveInFileFld, 1, 1, 1, 4); upperLay->addWidget(new QLabel(tr("File Name:"), this), 2, 0); upperLay->addWidget(m_fileNameFld, 2, 1, 1, 4); upperLay->addWidget(new QLabel(tr("File Format:"), this), 3, 0); upperLay->addWidget(m_fileFormat, 3, 1, 1, 2); upperLay->addWidget(m_formatOptions, 3, 3); upperLay->addWidget(m_bgColorLabel, 4, 0); upperLay->addWidget(m_bgColorField, 4, 1, 1, 4); upperLay->addWidget(m_skip, 5, 1, 1, 4); upperLay->addWidget(m_removeDotBeforeFrameNumber, 6, 1, 1, 4); } upperLay->setColumnStretch(0, 0); upperLay->setColumnStretch(1, 1); upperLay->setColumnStretch(2, 0); upperLay->setColumnStretch(3, 1); upperLay->setColumnStretch(4, 1); m_topLayout->addLayout(upperLay); m_topLayout->addWidget(m_tlvFrame); } m_buttonLayout->setMargin(0); m_buttonLayout->setSpacing(20); { m_buttonLayout->addWidget(m_okBtn); m_buttonLayout->addWidget(m_cancelBtn); } int formatIndex = m_fileFormat->findText( QString::fromStdString(ConvertPopupFileFormat.getValue())); if (formatIndex) m_fileFormat->setCurrentIndex(formatIndex); else m_fileFormat->setCurrentIndex(m_fileFormat->findText("tif")); m_bgColorField->setColor(TPixel32(ConvertPopupBgColorR, ConvertPopupBgColorG, ConvertPopupBgColorB, ConvertPopupBgColorA)); m_skip->setChecked(ConvertPopupSkipExisting != 0); m_removeDotBeforeFrameNumber->setChecked(ConvertPopupRemoveDot != 0); m_saveBackupToNopaint->setChecked(ConvertPopupSaveToNopaint != 0); m_appendDefaultPalette->setChecked(ConvertPopupAppendDefaultPalette != 0); m_removeUnusedStyles->setChecked(ConvertPopupRemoveUnusedStyles != 0); //--- signal-slot connections qRegisterMetaType<TFilePath>("TFilePath"); bool ret = true; ret = ret && connect(m_tlvMode, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(onTlvModeSelected(const QString &))); ret = ret && connect(m_fromFld, SIGNAL(editingFinished()), this, SLOT(onRangeChanged())); ret = ret && connect(m_toFld, SIGNAL(editingFinished()), this, SLOT(onRangeChanged())); ret = ret && connect(m_fileFormat, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(onFormatSelected(const QString &))); ret = ret && connect(m_formatOptions, SIGNAL(clicked()), this, SLOT(onOptionsClicked())); ret = ret && connect(m_okBtn, SIGNAL(clicked()), this, SLOT(apply())); ret = ret && connect(m_cancelBtn, SIGNAL(clicked()), this, SLOT(reject())); ret = ret && connect(m_notifier, SIGNAL(frameCompleted(int)), m_progressDialog, SLOT(setValue(int))); ret = ret && connect(m_notifier, SIGNAL(levelCompleted(const TFilePath &)), this, SLOT(onLevelConverted(const TFilePath &))); ret = ret && connect(m_progressDialog, SIGNAL(canceled()), m_notifier, SLOT(onCancelTask())); if (specifyInput) ret = ret && connect(m_convertFileFld, SIGNAL(pathChanged()), this, SLOT(onFileInChanged())); // update unable/enable of checkboxes onTlvModeSelected(m_tlvMode->currentText()); assert(ret); } //------------------------------------------------------------------ ConvertPopup::~ConvertPopup() { delete m_notifier; delete m_progressDialog; delete m_converter; } //----------------------------------------------------------------------------- QString ConvertPopup::getDestinationType() const { return m_fileFormat->currentText(); } //----------------------------------------------------------------------------- QString ConvertPopup::getTlvMode() const { return m_tlvMode->currentText(); } //----------------------------------------------------------------------------- QFrame *ConvertPopup::createSvgSettings() { bool ret = true; QHBoxLayout *hLayout; QFrame *frame = new QFrame(); QVBoxLayout *vLayout = new QVBoxLayout(); frame->setLayout(vLayout); hLayout = new QHBoxLayout(); hLayout->addWidget(new QLabel(tr("Stroke Mode:"))); hLayout->addWidget(m_tlvMode = new QComboBox()); QStringList items; items << tr("Centerline") << tr("Outline"); m_tlvMode->addItems(items); hLayout->addStretch(); vLayout->addLayout(hLayout); frame->setVisible(false); return frame; } QFrame *ConvertPopup::createTlvSettings() { QFrame *frame = new QFrame(); frame->setObjectName("SolidLineFrame"); m_tlvMode = new QComboBox(); m_unpaintedFolderLabel = new QLabel(tr("Unpainted File Folder:")); m_unpaintedFolder = new DVGui::FileField(0, QString(tr("Same as Painted")), true, true); m_suffixLabel = new QLabel(tr(" Unpainted File Suffix:")); m_unpaintedSuffix = new DVGui::LineEdit("_np"); m_applyAutoclose = new QCheckBox(tr("Apply Autoclose")); m_saveBackupToNopaint = new QCheckBox(tr("Save Backup to \"nopaint\" Folder")); m_appendDefaultPalette = new QCheckBox(tr("Append Default Palette")); m_antialias = new QComboBox(); m_antialiasIntensity = new DVGui::IntLineEdit(0, 50, 0, 100); m_palettePath = new DVGui::FileField(0, QString(CreateNewPalette), true, true); m_tolerance = new DVGui::IntLineEdit(0, 0, 0, 255); m_removeUnusedStyles = new QCheckBox(tr("Remove Unused Styles from Input Palette")); m_unpaintedFolder->setFileMode(QFileDialog::DirectoryOnly); m_unpaintedSuffix->setMaximumWidth(40); QStringList items1; items1 << tr("Keep Original Antialiasing") << tr("Add Antialiasing with Intensity:") << tr("Remove Antialiasing using Threshold:"); m_antialias->addItems(items1); QStringList items; items << TlvMode_Unpainted << TlvMode_UnpaintedFromNonAA << TlvMode_PaintedFromTwoImages << TlvMode_PaintedFromNonAA; m_tlvMode->addItems(items); m_antialiasIntensity->setEnabled(false); m_appendDefaultPalette->setToolTip( tr("When activated, styles of the default " "palette\n($TOONZSTUDIOPALETTE\\cleanup_default.tpl) will \nbe " "appended to the palette after conversion in \norder to save the " "effort of creating styles \nbefore color designing.")); m_palettePath->setMinimumWidth(300); m_palettePath->setFileMode(QFileDialog::ExistingFile); m_palettePath->setFilters(QStringList("tpl")); // m_tolerance->setMaximumWidth(10); QGridLayout *gridLay = new QGridLayout(); { gridLay->addWidget(new QLabel(tr("Mode:")), 0, 0, Qt::AlignRight | Qt::AlignVCenter); gridLay->addWidget(m_tlvMode, 0, 1); gridLay->addWidget(m_unpaintedFolderLabel, 1, 0, Qt::AlignRight | Qt::AlignVCenter); gridLay->addWidget(m_unpaintedFolder, 1, 1); gridLay->addWidget(m_suffixLabel, 1, 2, Qt::AlignRight | Qt::AlignVCenter); gridLay->addWidget(m_unpaintedSuffix, 1, 3); gridLay->addWidget(m_applyAutoclose, 2, 1, 1, 3); gridLay->addWidget(new QLabel(tr("Antialias:")), 3, 0, Qt::AlignRight | Qt::AlignVCenter); gridLay->addWidget(m_antialias, 3, 1); gridLay->addWidget(m_antialiasIntensity, 3, 2); gridLay->addWidget(new QLabel(tr("Palette:")), 4, 0, Qt::AlignRight | Qt::AlignVCenter); gridLay->addWidget(m_palettePath, 4, 1); gridLay->addWidget(new QLabel(tr("Tolerance:")), 4, 2, Qt::AlignRight | Qt::AlignVCenter); gridLay->addWidget(m_tolerance, 4, 3); gridLay->addWidget(m_removeUnusedStyles, 5, 1, 1, 3); gridLay->addWidget(m_appendDefaultPalette, 6, 1, 1, 3); gridLay->addWidget(m_saveBackupToNopaint, 7, 1, 1, 3); } gridLay->setColumnStretch(0, 0); gridLay->setColumnStretch(1, 1); gridLay->setColumnStretch(2, 0); gridLay->setColumnStretch(3, 0); frame->setLayout(gridLay); bool ret = true; ret = ret && connect(m_antialias, SIGNAL(currentIndexChanged(int)), this, SLOT(onAntialiasSelected(int))); ret = ret && connect(m_palettePath, SIGNAL(pathChanged()), this, SLOT(onPalettePathChanged())); assert(ret); frame->setVisible(false); return frame; } //-------------------------------------------------------------------------- void ConvertPopup::onRangeChanged() { if (m_srcFilePaths.empty()) return; TLevelReaderP lr = TLevelReaderP(m_srcFilePaths[0]); if (lr) { TLevelP l = lr->loadInfo(); TLevel::Table *t = l->getTable(); if (t->empty()) return; TFrameId start = t->begin()->first; TFrameId end = t->rbegin()->first; if (m_toFld->getValue() > end.getNumber()) m_toFld->setValue(end.getNumber() != -2 ? end.getNumber() : 1); if (m_fromFld->getValue() < start.getNumber()) m_fromFld->setValue(start.getNumber()); } } //------------------------------------------------------------------- void ConvertPopup::onAntialiasSelected(int index) { m_antialiasIntensity->setEnabled(index != 0); } //----------------------------------------------------------------- void ConvertPopup::onFileInChanged() { assert(m_convertFileFld); std::vector<TFilePath> fps; TProject *project = TProjectManager::instance()->getCurrentProject().getPointer(); ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene(); fps.push_back(scene->decodeFilePath( TFilePath(m_convertFileFld->getPath().toStdString()))); setFiles(fps); } //------------------------------------------------- void ConvertPopup::onTlvModeSelected(const QString &tlvMode) { bool usesTwoImages = TlvMode_PaintedFromTwoImages == tlvMode; m_unpaintedFolderLabel->setEnabled(usesTwoImages); m_unpaintedFolder->setEnabled(usesTwoImages); m_suffixLabel->setEnabled(usesTwoImages); m_unpaintedSuffix->setEnabled(usesTwoImages); m_antialias->setEnabled(TlvMode_PaintedFromNonAA != tlvMode); // m_palettePath->setEnabled(TlvMode_PaintedFromNonAA != tlvMode); m_tolerance->setEnabled(TlvMode_PaintedFromNonAA != tlvMode); m_appendDefaultPalette->setEnabled(TlvMode_PaintedFromNonAA != tlvMode); m_removeUnusedStyles->setEnabled(TlvMode_PaintedFromNonAA == tlvMode && m_palettePath->getPath() != CreateNewPalette); m_saveBackupToNopaint->setEnabled(TlvMode_Unpainted == tlvMode); } //------------------------------------------------- void ConvertPopup::onFormatSelected(const QString &format) { onFormatChanged(format); bool isTlv = format == TlvExtension; bool isPli = format == "svg"; m_formatOptions->setVisible(!isTlv); m_bgColorField->setVisible(!isTlv && !isPli); m_bgColorLabel->setVisible(!isTlv && !isPli); m_tlvFrame->setVisible(isTlv); // m_svgFrame->setVisible(isPli); if (isTlv) { bool isPainted = m_tlvMode->currentText() == TlvMode_PaintedFromTwoImages; m_unpaintedFolderLabel->setEnabled(isPainted); m_unpaintedFolder->setEnabled(isPainted); m_suffixLabel->setEnabled(isPainted); m_unpaintedSuffix->setEnabled(isPainted); m_saveBackupToNopaint->setEnabled(m_tlvMode->currentText() == TlvMode_Unpainted); } } //------------------------------------------------------------------ void ConvertPopup::setFiles(const std::vector<TFilePath> &fps) { m_okBtn->setEnabled(true); m_fileFormat->setEnabled(true); m_fileFormat->removeItem(m_fileFormat->findText("svg")); bool areFullcolor = true; bool areVector = false; for (int i = 0; i < (int)fps.size(); i++) { TFileType::Type type = TFileType::getInfo(fps[i]); if (!TFileType::isFullColor(type)) { areFullcolor = false; if (TFileType::isVector(type)) areVector = true; break; } } int currIndex = m_fileFormat->currentIndex(); int tlvIndex = m_fileFormat->findText(TlvExtension); if (areFullcolor) { if (tlvIndex < 0) m_fileFormat->addItem(TlvExtension); } else if (areVector) { int svgIndex = m_fileFormat->findText("svg"); if (svgIndex < 0) m_fileFormat->addItem("svg"); m_fileFormat->setCurrentIndex(m_fileFormat->findText("svg")); m_fileFormat->setEnabled(false); onFormatSelected("svg"); } else { if (tlvIndex >= 0) { int index = m_fileFormat->currentIndex(); m_fileFormat->removeItem(tlvIndex); } } m_srcFilePaths = fps; if (m_srcFilePaths.size() == 1) { setWindowTitle(tr("Convert 1 Level")); m_fromFld->setEnabled(true); m_toFld->setEnabled(true); m_fileNameFld->setEnabled(true); m_fromFld->setText(""); m_toFld->setText(""); TLevelP levelTmp; TLevelReaderP lrTmp = TLevelReaderP(fps[0]); if (lrTmp) { levelTmp = lrTmp->loadInfo(); TLevel::Table *t = levelTmp->getTable(); if (!t->empty()) { TFrameId start = t->begin()->first; TFrameId end = t->rbegin()->first; if (start.getNumber() > 0) m_fromFld->setText(QString::number(start.getNumber())); if (end.getNumber() > 0) m_toFld->setText(QString::number(end.getNumber())); } } // m_fromFld->setText("1"); // m_toFld->setText(QString::number(levelTmp->getFrameCount()==-2?1:levelTmp->getFrameCount())); m_fileNameFld->setText(QString::fromStdString(fps[0].getName())); } else { setWindowTitle(tr("Convert %1 Levels").arg(m_srcFilePaths.size())); m_fromFld->setText(""); m_toFld->setText(""); m_fileNameFld->setText(""); m_fromFld->setEnabled(false); m_toFld->setEnabled(false); m_fileNameFld->setEnabled(false); } m_saveInFileFld->setPath(toQString(fps[0].getParentDir())); // if (m_unpaintedFolder->getPath()==SameAsPainted) // m_unpaintedFolder->setPath(toQString(fps[0].getParentDir())); m_palettePath->setPath(CreateNewPalette); m_removeUnusedStyles->setEnabled(false); // m_fileFormat->setCurrentIndex(areFullcolor?0:m_fileFormat->findText("tif")); } //------------------------------------------------------------------- Convert2Tlv *ConvertPopup::makeTlvConverter(const TFilePath &sourceFilePath) { ToonzScene *sc = TApp::instance()->getCurrentScene()->getScene(); TFilePath unpaintedfilePath; if (m_tlvMode->currentText() == TlvMode_PaintedFromTwoImages) { QString suffixString = m_unpaintedSuffix->text(); TFilePath unpaintedFolder; if (m_unpaintedFolder->getPath() == SameAsPainted) unpaintedFolder = sourceFilePath.getParentDir(); else unpaintedFolder = TFilePath(m_unpaintedFolder->getPath().toStdString()); std::string basename = sourceFilePath.getName() + suffixString.toStdString(); unpaintedfilePath = sc->decodeFilePath( sourceFilePath.withParentDir(unpaintedFolder).withName(basename)); } int from = -1, to = -1; if (m_srcFilePaths.size() > 1) { from = m_fromFld->getValue(); to = m_toFld->getValue(); } TFilePath palettePath; if (m_palettePath->getPath() != CreateNewPalette) palettePath = sc->decodeFilePath(TFilePath(m_palettePath->getPath().toStdString())); TFilePath fn = sc->decodeFilePath(sourceFilePath); TFilePath out = sc->decodeFilePath(TFilePath(m_saveInFileFld->getPath().toStdWString())); Convert2Tlv *converter = new Convert2Tlv( fn, unpaintedfilePath, out, m_fileNameFld->text(), from, to, m_applyAutoclose->isChecked(), palettePath, m_tolerance->getValue(), m_antialias->currentIndex(), m_antialiasIntensity->getValue(), getTlvMode() == TlvMode_UnpaintedFromNonAA, m_appendDefaultPalette->isChecked()); return converter; } //------------------------------------------------------------------- void ConvertPopup::convertToTlv(bool toPainted) { #ifdef CICCIO ToonzScene *sc = TApp::instance()->getCurrentScene()->getScene(); bool doAutoclose = false; QApplication::setOverrideCursor(Qt::WaitCursor); int i, totFrames = 0, skipped = 0; TFilePath::setUnderscoreFormatAllowed( !m_unpaintedSuffix->text().contains('_')); std::vector<Convert2Tlv *> converters; for (i = 0; i < m_srcFilePaths.size(); i++) { Convert2Tlv *converter = makeTlvConverter(m_srcFilePaths[i]); if (TSystem::doesExistFileOrLevel(converter->m_levelOut)) { if (m_skip->isChecked()) { DVGui::info( QString(tr("Level ")) + QString::fromStdWString( converter->m_levelOut.withoutParentDir().getWideString()) + QString(tr(" already exists; skipped"))); delete converter; skipped++; continue; } else TSystem::removeFileOrLevel(converter->m_levelOut); } totFrames += converter->getFramesToConvertCount(); converters.push_back(converter); } if (converters.empty()) { QApplication::restoreOverrideCursor(); TFilePath::setUnderscoreFormatAllowed(false); return; } ProgressDialog pb("", tr("Cancel"), 0, totFrames); int j, l, k = 0; for (i = 0; i < converters.size(); i++) { std::string errorMessage; if (!converters[i]->init(errorMessage)) { converters[i]->abort(); DVGui::error(QString::fromStdString(errorMessage)); delete converters[i]; converters[i] = 0; skipped++; continue; } int count = converters[i]->getFramesToConvertCount(); pb.setLabelText(tr("Generating level ") + toQString(converters[i]->m_levelOut)); pb.show(); for (j = 0; j < count; j++) { std::string errorMessage = ""; if (!converters[i]->convertNext(errorMessage) || pb.wasCanceled()) { for (l = i; l < converters.size(); l++) { converters[l]->abort(); delete converters[i]; converters[i] = 0; } if (errorMessage != "") DVGui::error(QString::fromStdString(errorMessage)); QApplication::restoreOverrideCursor(); FileBrowser::refreshFolder(m_srcFilePaths[0].getParentDir()); TFilePath::setUnderscoreFormatAllowed(false); return; } pb.setValue(++k); DVGui::info(QString(tr("Level ")) + QString::fromStdWString( m_srcFilePaths[i].withoutParentDir().getWideString()) + QString(tr(" converted to tlv."))); } TFilePath levelOut(converters[i]->m_levelOut); delete converters[i]; IconGenerator::instance()->invalidate(levelOut); converters[i] = 0; } QApplication::restoreOverrideCursor(); pb.hide(); if (m_srcFilePaths.size() == 1) { if (skipped == 0) DVGui::info( tr("Level %1 converted to TLV Format") .arg(QString::fromStdWString( m_srcFilePaths[0].withoutParentDir().getWideString()))); else DVGui::warning( tr("Warning: Level %1 NOT converted to TLV Format") .arg(QString::fromStdWString( m_srcFilePaths[0].withoutParentDir().getWideString()))); } else DVGui::MsgBox(skipped == 0 ? DVGui::INFORMATION : DVGui::WARNING, tr("Converted %1 out of %2 Levels to TLV Format") .arg(QString::number(m_srcFilePaths.size() - skipped)) .arg(QString::number(m_srcFilePaths.size()))); FileBrowser::refreshFolder(m_srcFilePaths[0].getParentDir()); TFilePath::setUnderscoreFormatAllowed(false); #endif } //----------------------------------------------------------------------------- TFilePath ConvertPopup::getDestinationFilePath( const TFilePath &sourceFilePath) { // Build the DECODED output folder path TFilePath destFolder = sourceFilePath.getParentDir(); if (!m_saveInFileFld->getPath().isEmpty()) { TFilePath dir(m_saveInFileFld->getPath().toStdWString()); ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene(); destFolder = scene->decodeFilePath(dir); } // Build the output level name const QString &fldName = m_fileNameFld->text(); const std::string &ext = m_fileFormat->currentText().toStdString(); const std::wstring &name = fldName.isEmpty() ? sourceFilePath.getWideName() : fldName.toStdWString(); TFilePath destName = TFilePath(name).withType(ext); if (TFileType::isLevelFilePath(sourceFilePath) && !TFileType::isLevelExtension(ext)) destName = destName.withFrame(TFrameId::EMPTY_FRAME); // use the '..' // format to denote // an output level // Merge the two return destFolder + destName; } //----------------------------------------------------------------------------- TPalette *ConvertPopup::readUserProvidedPalette() const { if (m_palettePath->getPath() == CreateNewPalette || m_fileFormat->currentText() != TlvExtension) return 0; ToonzScene *sc = TApp::instance()->getCurrentScene()->getScene(); TFilePath palettePath = sc->decodeFilePath(TFilePath(m_palettePath->getPath().toStdString())); TPalette *palette = 0; try { TIStream is(palettePath); is >> palette; // note! refCount==0 } catch (...) { DVGui::warning( tr("Warning: Can't read palette '%1' ").arg(m_palettePath->getPath())); if (palette) { delete palette; palette = 0; } } return palette; } //----------------------------------------------------------------------------- void ConvertPopup::getFrameRange(const TFilePath &sourceFilePath, TFrameId &from, TFrameId &to) { from = to = TFrameId(); if (!TFileType::isLevelFilePath(sourceFilePath)) return; TLevelReaderP lr(sourceFilePath); if (!lr) return; TLevelP level = lr->loadInfo(); if (level->begin() == level->end()) return; TFrameId firstFrame = from = level->begin()->first, lastFrame = to = (--level->end())->first; if (m_srcFilePaths.size() == 1) { // Just one level - consider from/to input fields, too TFrameId fid; bool ok; fid = TFrameId(m_fromFld->text().toInt(&ok)); if (ok && fid > from) from = tcrop(fid, firstFrame, lastFrame); fid = TFrameId(m_toFld->text().toInt(&ok)); if (ok && fid < to) to = tcrop(fid, firstFrame, lastFrame); } } //----------------------------------------------------------------------------- bool ConvertPopup::checkParameters() const { if (m_srcFilePaths.size() == 1 && m_fileNameFld->text().isEmpty()) { DVGui::warning( tr("No output filename specified: please choose a valid level name.")); return false; } if (m_fileFormat->currentText() == TlvExtension) { if (m_tlvMode->currentText() == TlvMode_PaintedFromTwoImages) { if (m_unpaintedSuffix->text() == "") { DVGui::warning(tr("No unpainted suffix specified: cannot convert.")); return false; } } } if (m_palettePath->getPath() == CreateNewPalette || m_fileFormat->currentText() != TlvExtension) { TPalette *palette = readUserProvidedPalette(); delete palette; // note: don't keep a reference to the palette because that can not be used // by the Convert2Tlv class (that requires a TFilePath instead) } return true; } //-------------------------------------------------- void ConvertPopup::apply() { // if parameters are not ok do nothing and don't close the dialog if (!checkParameters()) return; /*--- envにパラメータを記憶 ---*/ ConvertPopupFileFormat = m_fileFormat->currentText().toStdString(); TPixel32 bgCol = m_bgColorField->getColor(); ConvertPopupBgColorR = (int)bgCol.r; ConvertPopupBgColorG = (int)bgCol.g; ConvertPopupBgColorB = (int)bgCol.b; ConvertPopupBgColorA = (int)bgCol.m; ConvertPopupSkipExisting = m_skip->isChecked() ? 1 : 0; ConvertPopupRemoveDot = m_removeDotBeforeFrameNumber->isChecked() ? 1 : 0; ConvertPopupSaveToNopaint = m_saveBackupToNopaint->isChecked() ? 1 : 0; ConvertPopupAppendDefaultPalette = m_appendDefaultPalette->isChecked() ? 1 : 0; ConvertPopupRemoveUnusedStyles = m_removeUnusedStyles->isChecked() ? 1 : 0; // parameters are ok: close the dialog first close(); m_isConverting = true; m_progressDialog->show(); m_notifier->reset(); QApplication::setOverrideCursor(Qt::WaitCursor); m_converter = new Converter(this); #if QT_VERSION >= 0x050000 bool ret = connect(m_converter, SIGNAL(finished()), this, SLOT(onConvertFinished())); #else int ret = connect(m_converter, SIGNAL(finished()), this, SLOT(onConvertFinished())); #endif Q_ASSERT(ret); // TODO: salvare il vecchio stato if (m_fileFormat->currentText() == TlvExtension && m_tlvMode->currentText() == TlvMode_PaintedFromTwoImages) { if (!m_unpaintedSuffix->text().contains('_')) TFilePath::setUnderscoreFormatAllowed(true); } // start converting. Conversion end is handled by onConvertFinished() slot m_converter->start(); } //------------------------------------------------------------------ void ConvertPopup::onConvertFinished() { m_isConverting = false; TFilePath dstFilePath(m_saveInFileFld->getPath().toStdWString()); if (dstFilePath == m_srcFilePaths[0].getParentDir()) FileBrowser::refreshFolder(dstFilePath); m_progressDialog->close(); QApplication::restoreOverrideCursor(); int errorCount = m_notifier->getErrorCount(); int skippedCount = m_converter->getSkippedCount(); if (errorCount > 0) { if (skippedCount > 0) DVGui::error( tr("Convert completed with %1 error(s) and %2 level(s) skipped") .arg(errorCount) .arg(skippedCount)); else DVGui::error(tr("Convert completed with %1 error(s) ").arg(errorCount)); } else if (skippedCount > 0) { DVGui::warning(tr("%1 level(s) skipped").arg(skippedCount)); } /* if (m_srcFilePaths.size()==1) { if (skipped==0) DVGui::info(tr("Level %1 converted to TLV Format").arg(QString::fromStdWString(m_srcFilePaths[0].withoutParentDir().getWideString()))); else DVGui::warning(tr("Warning: Level %1 NOT converted to TLV Format").arg(QString::fromStdWString(m_srcFilePaths[0].withoutParentDir().getWideString()))); } else DVGui::MsgBox(skipped==0?DVGui::INFORMATION:DVGui::WARNING, tr("Converted %1 out of %2 Levels to TLV Format").arg( QString::number(m_srcFilePaths.size()-skipped)).arg(QString::number(m_srcFilePaths.size()))); */ // TFilePath parentDir = m_srcFilePaths[0].getParentDir(); // FileBrowser::refreshFolder(parentDir); delete m_converter; m_converter = 0; } //------------------------------------------------------------------- void ConvertPopup::onLevelConverted(const TFilePath &fullPath) { IconGenerator::instance()->invalidate(fullPath); } //------------------------------------------------------------------- TPropertyGroup *ConvertPopup::getFormatProperties(const std::string &ext) { if (m_formatProperties.contains(ext)) return m_formatProperties[ext]; TPropertyGroup *props = Tiio::makeWriterProperties(ext); m_formatProperties[ext] = props; return props; } //------------------------------------------------------------------- void ConvertPopup::onOptionsClicked() { std::string ext = m_fileFormat->currentText().toStdString(); TPropertyGroup *props = getFormatProperties(ext); openFormatSettingsPopup(this, ext, props, m_srcFilePaths.size() == 1 ? m_srcFilePaths[0] : TFilePath()); } //------------------------------------------------------------------- void ConvertPopup::onFormatChanged(const QString &ext) { if (ext == QString("avi") || ext == QString("tzp") || ext == TlvExtension) { m_removeDotBeforeFrameNumber->setChecked(false); m_removeDotBeforeFrameNumber->setEnabled(false); } else { m_removeDotBeforeFrameNumber->setEnabled(true); if (ext == QString("tga")) m_removeDotBeforeFrameNumber->setChecked(true); } } //------------------------------------------------------------------- void ConvertPopup::onPalettePathChanged() { m_removeUnusedStyles->setEnabled( m_tlvMode->currentText() == TlvMode_PaintedFromNonAA && m_palettePath->getPath() != CreateNewPalette); } //------------------------------------------------------------------- bool ConvertPopup::isSaveTlvBackupToNopaintActive() { return m_fileFormat->currentText() == TlvExtension /*-- tlvが選択されている --*/ && m_tlvMode->currentText() == TlvMode_Unpainted /*-- Unpainted Tlvが選択されている --*/ && m_saveBackupToNopaint->isChecked(); /*-- Save Backup to "nopaint" Folder オプションが有効 --*/ } //============================================================================= // ConvertPopupCommand //----------------------------------------------------------------------------- OpenPopupCommandHandler<ConvertPopup> openConvertPopup(MI_ConvertFiles); fix convert popup #include "convertpopup.h" // Tnz6 includes #include "menubarcommandids.h" #include "tapp.h" #include "formatsettingspopups.h" #include "filebrowser.h" // TnzQt includes #include "toonzqt/gutil.h" #include "toonzqt/imageutils.h" #include "toonzqt/menubarcommand.h" #include "toonzqt/filefield.h" #include "toonzqt/intfield.h" #include "toonzqt/colorfield.h" #include "toonzqt/checkbox.h" #include "toonzqt/icongenerator.h" // TnzLib includes #include "toonz/tscenehandle.h" #include "toonz/toonzscene.h" #include "toonz/sceneproperties.h" #include "toonz/tproject.h" #include "toutputproperties.h" #include "convert2tlv.h" #include "toonz/preferences.h" // TnzCore includes #include "tsystem.h" #include "tfiletype.h" #include "tlevel_io.h" #include "tiio.h" #include "tenv.h" // Qt includes #include <QPushButton> #include <QComboBox> #include <QLabel> #include <QApplication> #include <QMainWindow> #include <QCheckBox> /*-- Format --*/ TEnv::StringVar ConvertPopupFileFormat("ConvertPopupFileFormat", "tga"); /*-- 背景色 --*/ TEnv::IntVar ConvertPopupBgColorR("ConvertPopupBgColorR", 255); TEnv::IntVar ConvertPopupBgColorG("ConvertPopupBgColorG", 255); TEnv::IntVar ConvertPopupBgColorB("ConvertPopupBgColorB", 255); TEnv::IntVar ConvertPopupBgColorA("ConvertPopupBgColorA", 255); TEnv::IntVar ConvertPopupSkipExisting("ConvertPopupSkipExisting", 0); /*-- フレーム番号の前のドットを取る --*/ TEnv::IntVar ConvertPopupRemoveDot("ConvertPopupRemoveDot", 1); TEnv::IntVar ConvertPopupSaveToNopaint("ConvertPopupSaveToNopaint", 1); TEnv::IntVar ConvertPopupAppendDefaultPalette( "ConvertPopupAppendDefaultPalette", 0); TEnv::IntVar ConvertPopupRemoveUnusedStyles("ConvertPopupRemoveUnusedStyles", 0); //============================================================================= // convertPopup //----------------------------------------------------------------------------- QMap<std::string, TPropertyGroup *> ConvertPopup::m_formatProperties; /* TRANSLATOR namespace::ConvertPopup */ // const QString CreateNewPalette(QObject::tr("Create new palette")); const QString TlvExtension("tlv"); /* const QString TlvMode_Unpainted(QObject::tr("Unpainted tlv")); const QString TlvMode_PaintedFromTwoImages(QObject::tr("Painted tlv from two images")); const QString TlvMode_PaintedFromNonAA(QObject::tr("Painted tlv from non AA source")); const QString SameAsPainted(QObject::tr("Same as Painted")); */ //============================================================================= // // Converter // //----------------------------------------------------------------------------- class ConvertPopup::Converter final : public QThread { int m_skippedCount; ConvertPopup *m_parent; bool m_saveToNopaintOnlyFlag; public: Converter(ConvertPopup *parent) : m_parent(parent), m_skippedCount(0) {} void run() override; void convertLevel(const TFilePath &fp); void convertLevelWithConvert2Tlv(const TFilePath &fp); int getSkippedCount() const { return m_skippedCount; } }; void ConvertPopup::Converter::run() { ToonzScene *sc = TApp::instance()->getCurrentScene()->getScene(); DVGui::ProgressDialog *progressDialog = m_parent->m_progressDialog; int levelCount = m_parent->m_srcFilePaths.size(); TFilePath dstFolder(m_parent->m_saveInFileFld->getPath()); for (int i = 0; !m_parent->m_notifier->abortTask() && i < levelCount; i++) { TFilePath sourceLevelPath = sc->decodeFilePath(m_parent->m_srcFilePaths[i]); QString levelName = QString::fromStdString(sourceLevelPath.getLevelName()); // check already exsistent levels TFilePath dstFilePath = m_parent->getDestinationFilePath(m_parent->m_srcFilePaths[i]); // perche' ?? TFilePath // path=dstFilePath.getParentDir()+(dstFilePath.getName()+"."+dstFilePath.getDottedType()); // if(TSystem::doesExistFileOrLevel(dstFilePath)||TSystem::doesExistFileOrLevel(path)) m_saveToNopaintOnlyFlag = false; if (TSystem::doesExistFileOrLevel(dstFilePath)) { if (m_parent->m_skip->isChecked()) { DVGui::info(tr("Level %1 already exists; skipped.").arg(levelName)); m_skippedCount++; continue; } else { /*--- ここで、tlv形式に変換、かつ、UnpaintedTlvが選択され、かつ、    nopaintにバックアップを保存するオプションがONのとき、 出力先をnopaintに変更する。既にあるnopaint内のtlvを消す ---*/ if (m_parent->isSaveTlvBackupToNopaintActive()) { TFilePath unpaintedLevelPath = dstFilePath.getParentDir() + "nopaint\\" + TFilePath(dstFilePath.getName() + "_np." + dstFilePath.getType()); if (TSystem::doesExistFileOrLevel(unpaintedLevelPath)) { TSystem::removeFileOrLevel(unpaintedLevelPath); TSystem::deleteFile((unpaintedLevelPath.getParentDir() + unpaintedLevelPath.getName()) .withType("tpl")); } m_saveToNopaintOnlyFlag = true; } else // todo: handle errors!! TSystem::removeFileOrLevel(dstFilePath); } } if (m_parent->m_srcFilePaths.size() == 1) { progressDialog->setLabelText(QString(tr("Converting %1").arg(levelName))); } else { progressDialog->setLabelText(QString(tr("Converting level %1 of %2: %3") .arg(i + 1) .arg(levelCount) .arg(levelName))); } m_parent->m_notifier->notifyFrameCompleted(0); convertLevel(sourceLevelPath); } } void ConvertPopup::Converter::convertLevel( const TFilePath &sourceFileFullPath) { ToonzScene *sc = TApp::instance()->getCurrentScene()->getScene(); ConvertPopup *popup = m_parent; QString levelName = QString::fromStdString(sourceFileFullPath.getLevelName()); std::string ext = popup->m_fileFormat->currentText().toStdString(); TPropertyGroup *prop = popup->getFormatProperties(ext); TFilePath dstFileFullPath = popup->getDestinationFilePath(sourceFileFullPath); // bool isTlvNonAA = isTlv && popup->getTlvMode() == TlvMode_PaintedFromNonAA; bool isTlvNonAA = !(m_parent->getTlvMode().compare(m_parent->TlvMode_PaintedFromNonAA)); TFrameId from, to; if (TFileType::isLevelFilePath(sourceFileFullPath)) { popup->getFrameRange(sourceFileFullPath, from, to); if (from == TFrameId() || to == TFrameId()) { DVGui::warning(tr("Level %1 has no frame; skipped.").arg(levelName)); popup->m_notifier->notifyError(); return; } } TOutputProperties *oprop = TApp::instance() ->getCurrentScene() ->getScene() ->getProperties() ->getOutputProperties(); double framerate = oprop->getFrameRate(); if (popup->m_fileFormat->currentText() == TlvExtension) { // convert to TLV if (!(m_parent->getTlvMode().compare(m_parent->TlvMode_PaintedFromNonAA))) { // no AA source (retas) TPaletteP palette = popup->readUserProvidedPalette(); ImageUtils::convertNaa2Tlv(sourceFileFullPath, dstFileFullPath, from, to, m_parent->m_notifier, palette.getPointer(), m_parent->m_removeUnusedStyles->isChecked()); } else { convertLevelWithConvert2Tlv(sourceFileFullPath); } } else { // convert to full-color TPixel32 bgColor = m_parent->m_bgColorField->getColor(); ImageUtils::convert(sourceFileFullPath, dstFileFullPath, from, to, framerate, prop, m_parent->m_notifier, bgColor, m_parent->m_removeDotBeforeFrameNumber->isChecked()); } popup->m_notifier->notifyLevelCompleted(dstFileFullPath); } // to use legacy code void ConvertPopup::Converter::convertLevelWithConvert2Tlv( const TFilePath &sourceFileFullPath) { ConvertPopup *popup = m_parent; Convert2Tlv *tlvConverter = popup->makeTlvConverter(sourceFileFullPath); TFilePath levelOut = tlvConverter->m_levelOut; if (m_saveToNopaintOnlyFlag) { TFilePath unpaintedLevelPath = tlvConverter->m_levelOut.getParentDir() + "nopaint\\" + TFilePath(tlvConverter->m_levelOut.getName() + "_np." + tlvConverter->m_levelOut.getType()); tlvConverter->m_levelOut = unpaintedLevelPath; } std::string errorMessage; if (!tlvConverter->init(errorMessage)) { DVGui::warning(QString::fromStdString(errorMessage)); tlvConverter->abort(); } else { int count = tlvConverter->getFramesToConvertCount(); bool stop = false; for (int j = 0; j < count && !stop; j++) { if (!tlvConverter->convertNext(errorMessage)) { stop = true; DVGui::warning(QString::fromStdString(errorMessage)); } if (popup->m_progressDialog->wasCanceled()) stop = true; } if (stop) tlvConverter->abort(); delete tlvConverter; } /*--- nopaintファイルを複製する ---*/ if (m_parent->isSaveTlvBackupToNopaintActive() && !m_saveToNopaintOnlyFlag) { /*--- nopaintフォルダの作成 ---*/ TFilePath nopaintDir = levelOut.getParentDir() + "nopaint"; if (!TFileStatus(nopaintDir).doesExist()) { try { TSystem::mkDir(nopaintDir); } catch (...) { return; } } TFilePath unpaintedLevelPath = levelOut.getParentDir() + "nopaint\\" + TFilePath(levelOut.getName() + "_np." + levelOut.getType()); /*--- もしnopaintのファイルがあった場合は消去する ---*/ if (TSystem::doesExistFileOrLevel(unpaintedLevelPath)) { TSystem::removeFileOrLevel(unpaintedLevelPath); TSystem::deleteFile( (unpaintedLevelPath.getParentDir() + unpaintedLevelPath.getName()) .withType("tpl")); } TSystem::copyFile(unpaintedLevelPath, levelOut); /*--- Paletteのコピー ---*/ TFilePath levelPalettePath = levelOut.getParentDir() + TFilePath(levelOut.getName() + ".tpl"); TFilePath unpaintedLevelPalettePath = levelPalettePath.getParentDir() + "nopaint\\" + TFilePath(levelPalettePath.getName() + "_np." + levelPalettePath.getType()); TSystem::copyFile(unpaintedLevelPalettePath, levelPalettePath); } /* QApplication::restoreOverrideCursor(); FileBrowser::refreshFolder(m_srcFilePaths[0].getParentDir()); TFilePath::setUnderscoreFormatAllowed(false); TFilePath levelOut(converters[i]->m_levelOut); delete converters[i]; IconGenerator::instance()->invalidate(levelOut); */ } //============================================================================= ConvertPopup::ConvertPopup(bool specifyInput) : Dialog(TApp::instance()->getMainWindow(), true, false, "Convert") , m_converter(0) , m_isConverting(false) { // Su MAC i dialog modali non hanno bottoni di chiusura nella titleBar setModal(false); TlvMode_Unpainted = tr("Unpainted tlv"); TlvMode_UnpaintedFromNonAA = tr("Unpainted tlv from non AA source"); TlvMode_PaintedFromTwoImages = tr("Painted tlv from two images"); TlvMode_PaintedFromNonAA = tr("Painted tlv from non AA source"); SameAsPainted = tr("Same as Painted"); CreateNewPalette = tr("Create new palette"); m_fromFld = new DVGui::IntLineEdit(this); m_toFld = new DVGui::IntLineEdit(this); m_saveInFileFld = new DVGui::FileField(0, QString("")); m_fileNameFld = new DVGui::LineEdit(QString("")); m_fileFormat = new QComboBox(); m_formatOptions = new QPushButton(tr("Options"), this); m_bgColorField = new DVGui::ColorField(this, true, TPixel32::Transparent, 35, false); m_okBtn = new QPushButton(tr("Convert"), this); m_cancelBtn = new QPushButton(tr("Cancel"), this); m_bgColorLabel = new QLabel(tr("Bg Color:")); m_tlvFrame = createTlvSettings(); m_notifier = new ImageUtils::FrameTaskNotifier(); m_progressDialog = new DVGui::ProgressDialog("", tr("Cancel"), 0, 0); m_skip = new DVGui::CheckBox(tr("Skip Existing Files"), this); m_removeDotBeforeFrameNumber = new QCheckBox(tr("Remove dot before frame number"), this); if (specifyInput) m_convertFileFld = new DVGui::FileField(0, QString(""), true); else m_convertFileFld = 0; //----------------------- // File Format QStringList formats; TImageWriter::getSupportedFormats(formats, true); TLevelWriter::getSupportedFormats(formats, true); Tiio::Writer::getSupportedFormats(formats, true); m_fileFormat->addItems(formats); m_fileFormat->setMaxVisibleItems(15); m_skip->setChecked(true); m_okBtn->setDefault(true); if (specifyInput) { m_convertFileFld->setFileMode(QFileDialog::ExistingFile); QStringList filter; filter << "tif" << "tiff" << "png" << "tga" << "tlv" << "gif" << "bmp" << "avi" << "mov" << "jpg" << "pic" << "pict" << "rgb" << "sgi" << "png"; m_convertFileFld->setFilters(filter); m_okBtn->setEnabled(false); } m_removeDotBeforeFrameNumber->setChecked(false); m_progressDialog->setWindowTitle(tr("Convert... ")); m_progressDialog->setWindowFlags( Qt::Dialog | Qt::WindowTitleHint); // Don't show ? and X buttons m_progressDialog->setWindowModality(Qt::WindowModal); //----layout m_topLayout->setMargin(5); m_topLayout->setSpacing(5); { QGridLayout *upperLay = new QGridLayout(); upperLay->setMargin(0); upperLay->setSpacing(5); { int row = 0; if (specifyInput) { upperLay->addWidget(new QLabel(tr("File to convert:"), this), row, 0); upperLay->addWidget(m_convertFileFld, row, 1, 1, 4); row++; } upperLay->addWidget(new QLabel(tr("Start:"), this), row, 0); upperLay->addWidget(m_fromFld, row, 1); upperLay->addWidget(new QLabel(tr(" End:"), this), row, 2); upperLay->addWidget(m_toFld, row, 3); row++; upperLay->addWidget(new QLabel(tr("Save in:"), this), row, 0); upperLay->addWidget(m_saveInFileFld, row, 1, 1, 4); row++; upperLay->addWidget(new QLabel(tr("File Name:"), this), row, 0); upperLay->addWidget(m_fileNameFld, row, 1, 1, 4); ; row++; upperLay->addWidget(new QLabel(tr("File Format:"), this), row, 0); upperLay->addWidget(m_fileFormat, row, 1, 1, 2); upperLay->addWidget(m_formatOptions, row, 3); ; row++; upperLay->addWidget(m_bgColorLabel, row, 0); upperLay->addWidget(m_bgColorField, row, 1, 1, 4); ; row++; upperLay->addWidget(m_skip, row, 1, 1, 4); ; row++; upperLay->addWidget(m_removeDotBeforeFrameNumber, row, 1, 1, 4); } upperLay->setColumnStretch(0, 0); upperLay->setColumnStretch(1, 1); upperLay->setColumnStretch(2, 0); upperLay->setColumnStretch(3, 1); upperLay->setColumnStretch(4, 1); m_topLayout->addLayout(upperLay); m_topLayout->addWidget(m_tlvFrame); } m_buttonLayout->setMargin(0); m_buttonLayout->setSpacing(20); { m_buttonLayout->addWidget(m_okBtn); m_buttonLayout->addWidget(m_cancelBtn); } int formatIndex = m_fileFormat->findText( QString::fromStdString(ConvertPopupFileFormat.getValue())); if (formatIndex) m_fileFormat->setCurrentIndex(formatIndex); else m_fileFormat->setCurrentIndex(m_fileFormat->findText("tif")); m_bgColorField->setColor(TPixel32(ConvertPopupBgColorR, ConvertPopupBgColorG, ConvertPopupBgColorB, ConvertPopupBgColorA)); m_skip->setChecked(ConvertPopupSkipExisting != 0); m_removeDotBeforeFrameNumber->setChecked(ConvertPopupRemoveDot != 0); m_saveBackupToNopaint->setChecked(ConvertPopupSaveToNopaint != 0); m_appendDefaultPalette->setChecked(ConvertPopupAppendDefaultPalette != 0); m_removeUnusedStyles->setChecked(ConvertPopupRemoveUnusedStyles != 0); //--- signal-slot connections qRegisterMetaType<TFilePath>("TFilePath"); bool ret = true; ret = ret && connect(m_tlvMode, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(onTlvModeSelected(const QString &))); ret = ret && connect(m_fromFld, SIGNAL(editingFinished()), this, SLOT(onRangeChanged())); ret = ret && connect(m_toFld, SIGNAL(editingFinished()), this, SLOT(onRangeChanged())); ret = ret && connect(m_fileFormat, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(onFormatSelected(const QString &))); ret = ret && connect(m_formatOptions, SIGNAL(clicked()), this, SLOT(onOptionsClicked())); ret = ret && connect(m_okBtn, SIGNAL(clicked()), this, SLOT(apply())); ret = ret && connect(m_cancelBtn, SIGNAL(clicked()), this, SLOT(reject())); ret = ret && connect(m_notifier, SIGNAL(frameCompleted(int)), m_progressDialog, SLOT(setValue(int))); ret = ret && connect(m_notifier, SIGNAL(levelCompleted(const TFilePath &)), this, SLOT(onLevelConverted(const TFilePath &))); ret = ret && connect(m_progressDialog, SIGNAL(canceled()), m_notifier, SLOT(onCancelTask())); if (specifyInput) ret = ret && connect(m_convertFileFld, SIGNAL(pathChanged()), this, SLOT(onFileInChanged())); // update unable/enable of checkboxes onTlvModeSelected(m_tlvMode->currentText()); assert(ret); } //------------------------------------------------------------------ ConvertPopup::~ConvertPopup() { delete m_notifier; delete m_progressDialog; delete m_converter; } //----------------------------------------------------------------------------- QString ConvertPopup::getDestinationType() const { return m_fileFormat->currentText(); } //----------------------------------------------------------------------------- QString ConvertPopup::getTlvMode() const { return m_tlvMode->currentText(); } //----------------------------------------------------------------------------- QFrame *ConvertPopup::createSvgSettings() { bool ret = true; QHBoxLayout *hLayout; QFrame *frame = new QFrame(); QVBoxLayout *vLayout = new QVBoxLayout(); frame->setLayout(vLayout); hLayout = new QHBoxLayout(); hLayout->addWidget(new QLabel(tr("Stroke Mode:"))); hLayout->addWidget(m_tlvMode = new QComboBox()); QStringList items; items << tr("Centerline") << tr("Outline"); m_tlvMode->addItems(items); hLayout->addStretch(); vLayout->addLayout(hLayout); frame->setVisible(false); return frame; } QFrame *ConvertPopup::createTlvSettings() { QFrame *frame = new QFrame(); frame->setObjectName("SolidLineFrame"); m_tlvMode = new QComboBox(); m_unpaintedFolderLabel = new QLabel(tr("Unpainted File Folder:")); m_unpaintedFolder = new DVGui::FileField(0, QString(tr("Same as Painted")), true, true); m_suffixLabel = new QLabel(tr(" Unpainted File Suffix:")); m_unpaintedSuffix = new DVGui::LineEdit("_np"); m_applyAutoclose = new QCheckBox(tr("Apply Autoclose")); m_saveBackupToNopaint = new QCheckBox(tr("Save Backup to \"nopaint\" Folder")); m_appendDefaultPalette = new QCheckBox(tr("Append Default Palette")); m_antialias = new QComboBox(); m_antialiasIntensity = new DVGui::IntLineEdit(0, 50, 0, 100); m_palettePath = new DVGui::FileField(0, QString(CreateNewPalette), true, true); m_tolerance = new DVGui::IntLineEdit(0, 0, 0, 255); m_removeUnusedStyles = new QCheckBox(tr("Remove Unused Styles from Input Palette")); m_unpaintedFolder->setFileMode(QFileDialog::DirectoryOnly); m_unpaintedSuffix->setMaximumWidth(40); QStringList items1; items1 << tr("Keep Original Antialiasing") << tr("Add Antialiasing with Intensity:") << tr("Remove Antialiasing using Threshold:"); m_antialias->addItems(items1); QStringList items; items << TlvMode_Unpainted << TlvMode_UnpaintedFromNonAA << TlvMode_PaintedFromTwoImages << TlvMode_PaintedFromNonAA; m_tlvMode->addItems(items); m_antialiasIntensity->setEnabled(false); m_appendDefaultPalette->setToolTip( tr("When activated, styles of the default " "palette\n($TOONZSTUDIOPALETTE\\cleanup_default.tpl) will \nbe " "appended to the palette after conversion in \norder to save the " "effort of creating styles \nbefore color designing.")); m_palettePath->setMinimumWidth(300); m_palettePath->setFileMode(QFileDialog::ExistingFile); m_palettePath->setFilters(QStringList("tpl")); // m_tolerance->setMaximumWidth(10); QGridLayout *gridLay = new QGridLayout(); { gridLay->addWidget(new QLabel(tr("Mode:")), 0, 0, Qt::AlignRight | Qt::AlignVCenter); gridLay->addWidget(m_tlvMode, 0, 1); gridLay->addWidget(m_unpaintedFolderLabel, 1, 0, Qt::AlignRight | Qt::AlignVCenter); gridLay->addWidget(m_unpaintedFolder, 1, 1); gridLay->addWidget(m_suffixLabel, 1, 2, Qt::AlignRight | Qt::AlignVCenter); gridLay->addWidget(m_unpaintedSuffix, 1, 3); gridLay->addWidget(m_applyAutoclose, 2, 1, 1, 3); gridLay->addWidget(new QLabel(tr("Antialias:")), 3, 0, Qt::AlignRight | Qt::AlignVCenter); gridLay->addWidget(m_antialias, 3, 1); gridLay->addWidget(m_antialiasIntensity, 3, 2); gridLay->addWidget(new QLabel(tr("Palette:")), 4, 0, Qt::AlignRight | Qt::AlignVCenter); gridLay->addWidget(m_palettePath, 4, 1); gridLay->addWidget(new QLabel(tr("Tolerance:")), 4, 2, Qt::AlignRight | Qt::AlignVCenter); gridLay->addWidget(m_tolerance, 4, 3); gridLay->addWidget(m_removeUnusedStyles, 5, 1, 1, 3); gridLay->addWidget(m_appendDefaultPalette, 6, 1, 1, 3); gridLay->addWidget(m_saveBackupToNopaint, 7, 1, 1, 3); } gridLay->setColumnStretch(0, 0); gridLay->setColumnStretch(1, 1); gridLay->setColumnStretch(2, 0); gridLay->setColumnStretch(3, 0); frame->setLayout(gridLay); bool ret = true; ret = ret && connect(m_antialias, SIGNAL(currentIndexChanged(int)), this, SLOT(onAntialiasSelected(int))); ret = ret && connect(m_palettePath, SIGNAL(pathChanged()), this, SLOT(onPalettePathChanged())); assert(ret); frame->setVisible(false); return frame; } //-------------------------------------------------------------------------- void ConvertPopup::onRangeChanged() { if (m_srcFilePaths.empty()) return; TLevelReaderP lr = TLevelReaderP(m_srcFilePaths[0]); if (lr) { TLevelP l = lr->loadInfo(); TLevel::Table *t = l->getTable(); if (t->empty()) return; TFrameId start = t->begin()->first; TFrameId end = t->rbegin()->first; if (m_toFld->getValue() > end.getNumber()) m_toFld->setValue(end.getNumber() != -2 ? end.getNumber() : 1); if (m_fromFld->getValue() < start.getNumber()) m_fromFld->setValue(start.getNumber()); } } //------------------------------------------------------------------- void ConvertPopup::onAntialiasSelected(int index) { m_antialiasIntensity->setEnabled(index != 0); } //----------------------------------------------------------------- void ConvertPopup::onFileInChanged() { assert(m_convertFileFld); std::vector<TFilePath> fps; TProject *project = TProjectManager::instance()->getCurrentProject().getPointer(); ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene(); fps.push_back(scene->decodeFilePath( TFilePath(m_convertFileFld->getPath().toStdString()))); setFiles(fps); } //------------------------------------------------- void ConvertPopup::onTlvModeSelected(const QString &tlvMode) { bool usesTwoImages = TlvMode_PaintedFromTwoImages == tlvMode; m_unpaintedFolderLabel->setEnabled(usesTwoImages); m_unpaintedFolder->setEnabled(usesTwoImages); m_suffixLabel->setEnabled(usesTwoImages); m_unpaintedSuffix->setEnabled(usesTwoImages); m_antialias->setEnabled(TlvMode_PaintedFromNonAA != tlvMode); // m_palettePath->setEnabled(TlvMode_PaintedFromNonAA != tlvMode); m_tolerance->setEnabled(TlvMode_PaintedFromNonAA != tlvMode); m_appendDefaultPalette->setEnabled(TlvMode_PaintedFromNonAA != tlvMode); m_removeUnusedStyles->setEnabled(TlvMode_PaintedFromNonAA == tlvMode && m_palettePath->getPath() != CreateNewPalette); m_saveBackupToNopaint->setEnabled(TlvMode_Unpainted == tlvMode); } //------------------------------------------------- void ConvertPopup::onFormatSelected(const QString &format) { onFormatChanged(format); bool isTlv = format == TlvExtension; bool isPli = format == "svg"; m_formatOptions->setVisible(!isTlv); m_bgColorField->setVisible(!isTlv && !isPli); m_bgColorLabel->setVisible(!isTlv && !isPli); m_tlvFrame->setVisible(isTlv); // m_svgFrame->setVisible(isPli); if (isTlv) { bool isPainted = m_tlvMode->currentText() == TlvMode_PaintedFromTwoImages; m_unpaintedFolderLabel->setEnabled(isPainted); m_unpaintedFolder->setEnabled(isPainted); m_suffixLabel->setEnabled(isPainted); m_unpaintedSuffix->setEnabled(isPainted); m_saveBackupToNopaint->setEnabled(m_tlvMode->currentText() == TlvMode_Unpainted); } } //------------------------------------------------------------------ void ConvertPopup::setFiles(const std::vector<TFilePath> &fps) { m_okBtn->setEnabled(true); m_fileFormat->setEnabled(true); m_fileFormat->removeItem(m_fileFormat->findText("svg")); bool areFullcolor = true; bool areVector = false; for (int i = 0; i < (int)fps.size(); i++) { TFileType::Type type = TFileType::getInfo(fps[i]); if (!TFileType::isFullColor(type)) { areFullcolor = false; if (TFileType::isVector(type)) areVector = true; break; } } int currIndex = m_fileFormat->currentIndex(); int tlvIndex = m_fileFormat->findText(TlvExtension); if (areFullcolor) { if (tlvIndex < 0) m_fileFormat->addItem(TlvExtension); } else if (areVector) { int svgIndex = m_fileFormat->findText("svg"); if (svgIndex < 0) m_fileFormat->addItem("svg"); m_fileFormat->setCurrentIndex(m_fileFormat->findText("svg")); m_fileFormat->setEnabled(false); onFormatSelected("svg"); } else { if (tlvIndex >= 0) { int index = m_fileFormat->currentIndex(); m_fileFormat->removeItem(tlvIndex); } } m_srcFilePaths = fps; if (m_srcFilePaths.size() == 1) { setWindowTitle(tr("Convert 1 Level")); m_fromFld->setEnabled(true); m_toFld->setEnabled(true); m_fileNameFld->setEnabled(true); m_fromFld->setText(""); m_toFld->setText(""); TLevelP levelTmp; TLevelReaderP lrTmp = TLevelReaderP(fps[0]); if (lrTmp) { levelTmp = lrTmp->loadInfo(); TLevel::Table *t = levelTmp->getTable(); if (!t->empty()) { TFrameId start = t->begin()->first; TFrameId end = t->rbegin()->first; if (start.getNumber() > 0) m_fromFld->setText(QString::number(start.getNumber())); if (end.getNumber() > 0) m_toFld->setText(QString::number(end.getNumber())); } } // m_fromFld->setText("1"); // m_toFld->setText(QString::number(levelTmp->getFrameCount()==-2?1:levelTmp->getFrameCount())); m_fileNameFld->setText(QString::fromStdString(fps[0].getName())); } else { setWindowTitle(tr("Convert %1 Levels").arg(m_srcFilePaths.size())); m_fromFld->setText(""); m_toFld->setText(""); m_fileNameFld->setText(""); m_fromFld->setEnabled(false); m_toFld->setEnabled(false); m_fileNameFld->setEnabled(false); } m_saveInFileFld->setPath(toQString(fps[0].getParentDir())); // if (m_unpaintedFolder->getPath()==SameAsPainted) // m_unpaintedFolder->setPath(toQString(fps[0].getParentDir())); m_palettePath->setPath(CreateNewPalette); m_removeUnusedStyles->setEnabled(false); // m_fileFormat->setCurrentIndex(areFullcolor?0:m_fileFormat->findText("tif")); } //------------------------------------------------------------------- Convert2Tlv *ConvertPopup::makeTlvConverter(const TFilePath &sourceFilePath) { ToonzScene *sc = TApp::instance()->getCurrentScene()->getScene(); TFilePath unpaintedfilePath; if (m_tlvMode->currentText() == TlvMode_PaintedFromTwoImages) { QString suffixString = m_unpaintedSuffix->text(); TFilePath unpaintedFolder; if (m_unpaintedFolder->getPath() == SameAsPainted) unpaintedFolder = sourceFilePath.getParentDir(); else unpaintedFolder = TFilePath(m_unpaintedFolder->getPath().toStdString()); std::string basename = sourceFilePath.getName() + suffixString.toStdString(); unpaintedfilePath = sc->decodeFilePath( sourceFilePath.withParentDir(unpaintedFolder).withName(basename)); } int from = -1, to = -1; if (m_srcFilePaths.size() > 1) { from = m_fromFld->getValue(); to = m_toFld->getValue(); } TFilePath palettePath; if (m_palettePath->getPath() != CreateNewPalette) palettePath = sc->decodeFilePath(TFilePath(m_palettePath->getPath().toStdString())); TFilePath fn = sc->decodeFilePath(sourceFilePath); TFilePath out = sc->decodeFilePath(TFilePath(m_saveInFileFld->getPath().toStdWString())); Convert2Tlv *converter = new Convert2Tlv( fn, unpaintedfilePath, out, m_fileNameFld->text(), from, to, m_applyAutoclose->isChecked(), palettePath, m_tolerance->getValue(), m_antialias->currentIndex(), m_antialiasIntensity->getValue(), getTlvMode() == TlvMode_UnpaintedFromNonAA, m_appendDefaultPalette->isChecked()); return converter; } //------------------------------------------------------------------- void ConvertPopup::convertToTlv(bool toPainted) { #ifdef CICCIO ToonzScene *sc = TApp::instance()->getCurrentScene()->getScene(); bool doAutoclose = false; QApplication::setOverrideCursor(Qt::WaitCursor); int i, totFrames = 0, skipped = 0; TFilePath::setUnderscoreFormatAllowed( !m_unpaintedSuffix->text().contains('_')); std::vector<Convert2Tlv *> converters; for (i = 0; i < m_srcFilePaths.size(); i++) { Convert2Tlv *converter = makeTlvConverter(m_srcFilePaths[i]); if (TSystem::doesExistFileOrLevel(converter->m_levelOut)) { if (m_skip->isChecked()) { DVGui::info( QString(tr("Level ")) + QString::fromStdWString( converter->m_levelOut.withoutParentDir().getWideString()) + QString(tr(" already exists; skipped"))); delete converter; skipped++; continue; } else TSystem::removeFileOrLevel(converter->m_levelOut); } totFrames += converter->getFramesToConvertCount(); converters.push_back(converter); } if (converters.empty()) { QApplication::restoreOverrideCursor(); TFilePath::setUnderscoreFormatAllowed(false); return; } ProgressDialog pb("", tr("Cancel"), 0, totFrames); int j, l, k = 0; for (i = 0; i < converters.size(); i++) { std::string errorMessage; if (!converters[i]->init(errorMessage)) { converters[i]->abort(); DVGui::error(QString::fromStdString(errorMessage)); delete converters[i]; converters[i] = 0; skipped++; continue; } int count = converters[i]->getFramesToConvertCount(); pb.setLabelText(tr("Generating level ") + toQString(converters[i]->m_levelOut)); pb.show(); for (j = 0; j < count; j++) { std::string errorMessage = ""; if (!converters[i]->convertNext(errorMessage) || pb.wasCanceled()) { for (l = i; l < converters.size(); l++) { converters[l]->abort(); delete converters[i]; converters[i] = 0; } if (errorMessage != "") DVGui::error(QString::fromStdString(errorMessage)); QApplication::restoreOverrideCursor(); FileBrowser::refreshFolder(m_srcFilePaths[0].getParentDir()); TFilePath::setUnderscoreFormatAllowed(false); return; } pb.setValue(++k); DVGui::info(QString(tr("Level ")) + QString::fromStdWString( m_srcFilePaths[i].withoutParentDir().getWideString()) + QString(tr(" converted to tlv."))); } TFilePath levelOut(converters[i]->m_levelOut); delete converters[i]; IconGenerator::instance()->invalidate(levelOut); converters[i] = 0; } QApplication::restoreOverrideCursor(); pb.hide(); if (m_srcFilePaths.size() == 1) { if (skipped == 0) DVGui::info( tr("Level %1 converted to TLV Format") .arg(QString::fromStdWString( m_srcFilePaths[0].withoutParentDir().getWideString()))); else DVGui::warning( tr("Warning: Level %1 NOT converted to TLV Format") .arg(QString::fromStdWString( m_srcFilePaths[0].withoutParentDir().getWideString()))); } else DVGui::MsgBox(skipped == 0 ? DVGui::INFORMATION : DVGui::WARNING, tr("Converted %1 out of %2 Levels to TLV Format") .arg(QString::number(m_srcFilePaths.size() - skipped)) .arg(QString::number(m_srcFilePaths.size()))); FileBrowser::refreshFolder(m_srcFilePaths[0].getParentDir()); TFilePath::setUnderscoreFormatAllowed(false); #endif } //----------------------------------------------------------------------------- TFilePath ConvertPopup::getDestinationFilePath( const TFilePath &sourceFilePath) { // Build the DECODED output folder path TFilePath destFolder = sourceFilePath.getParentDir(); if (!m_saveInFileFld->getPath().isEmpty()) { TFilePath dir(m_saveInFileFld->getPath().toStdWString()); ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene(); destFolder = scene->decodeFilePath(dir); } // Build the output level name const QString &fldName = m_fileNameFld->text(); const std::string &ext = m_fileFormat->currentText().toStdString(); const std::wstring &name = fldName.isEmpty() ? sourceFilePath.getWideName() : fldName.toStdWString(); TFilePath destName = TFilePath(name).withType(ext); if (TFileType::isLevelFilePath(sourceFilePath) && !TFileType::isLevelExtension(ext)) destName = destName.withFrame(TFrameId::EMPTY_FRAME); // use the '..' // format to denote // an output level // Merge the two return destFolder + destName; } //----------------------------------------------------------------------------- TPalette *ConvertPopup::readUserProvidedPalette() const { if (m_palettePath->getPath() == CreateNewPalette || m_fileFormat->currentText() != TlvExtension) return 0; ToonzScene *sc = TApp::instance()->getCurrentScene()->getScene(); TFilePath palettePath = sc->decodeFilePath(TFilePath(m_palettePath->getPath().toStdString())); TPalette *palette = 0; try { TIStream is(palettePath); is >> palette; // note! refCount==0 } catch (...) { DVGui::warning( tr("Warning: Can't read palette '%1' ").arg(m_palettePath->getPath())); if (palette) { delete palette; palette = 0; } } return palette; } //----------------------------------------------------------------------------- void ConvertPopup::getFrameRange(const TFilePath &sourceFilePath, TFrameId &from, TFrameId &to) { from = to = TFrameId(); if (!TFileType::isLevelFilePath(sourceFilePath)) return; TLevelReaderP lr(sourceFilePath); if (!lr) return; TLevelP level = lr->loadInfo(); if (level->begin() == level->end()) return; TFrameId firstFrame = from = level->begin()->first, lastFrame = to = (--level->end())->first; if (m_srcFilePaths.size() == 1) { // Just one level - consider from/to input fields, too TFrameId fid; bool ok; fid = TFrameId(m_fromFld->text().toInt(&ok)); if (ok && fid > from) from = tcrop(fid, firstFrame, lastFrame); fid = TFrameId(m_toFld->text().toInt(&ok)); if (ok && fid < to) to = tcrop(fid, firstFrame, lastFrame); } } //----------------------------------------------------------------------------- bool ConvertPopup::checkParameters() const { if (m_srcFilePaths.size() == 1 && m_fileNameFld->text().isEmpty()) { DVGui::warning( tr("No output filename specified: please choose a valid level name.")); return false; } if (m_fileFormat->currentText() == TlvExtension) { if (m_tlvMode->currentText() == TlvMode_PaintedFromTwoImages) { if (m_unpaintedSuffix->text() == "") { DVGui::warning(tr("No unpainted suffix specified: cannot convert.")); return false; } } } if (m_palettePath->getPath() == CreateNewPalette || m_fileFormat->currentText() != TlvExtension) { TPalette *palette = readUserProvidedPalette(); delete palette; // note: don't keep a reference to the palette because that can not be used // by the Convert2Tlv class (that requires a TFilePath instead) } return true; } //-------------------------------------------------- void ConvertPopup::apply() { // if parameters are not ok do nothing and don't close the dialog if (!checkParameters()) return; /*--- envにパラメータを記憶 ---*/ ConvertPopupFileFormat = m_fileFormat->currentText().toStdString(); TPixel32 bgCol = m_bgColorField->getColor(); ConvertPopupBgColorR = (int)bgCol.r; ConvertPopupBgColorG = (int)bgCol.g; ConvertPopupBgColorB = (int)bgCol.b; ConvertPopupBgColorA = (int)bgCol.m; ConvertPopupSkipExisting = m_skip->isChecked() ? 1 : 0; ConvertPopupRemoveDot = m_removeDotBeforeFrameNumber->isChecked() ? 1 : 0; ConvertPopupSaveToNopaint = m_saveBackupToNopaint->isChecked() ? 1 : 0; ConvertPopupAppendDefaultPalette = m_appendDefaultPalette->isChecked() ? 1 : 0; ConvertPopupRemoveUnusedStyles = m_removeUnusedStyles->isChecked() ? 1 : 0; // parameters are ok: close the dialog first close(); m_isConverting = true; m_progressDialog->show(); m_notifier->reset(); QApplication::setOverrideCursor(Qt::WaitCursor); m_converter = new Converter(this); #if QT_VERSION >= 0x050000 bool ret = connect(m_converter, SIGNAL(finished()), this, SLOT(onConvertFinished())); #else int ret = connect(m_converter, SIGNAL(finished()), this, SLOT(onConvertFinished())); #endif Q_ASSERT(ret); // TODO: salvare il vecchio stato if (m_fileFormat->currentText() == TlvExtension && m_tlvMode->currentText() == TlvMode_PaintedFromTwoImages) { if (!m_unpaintedSuffix->text().contains('_')) TFilePath::setUnderscoreFormatAllowed(true); } // start converting. Conversion end is handled by onConvertFinished() slot m_converter->start(); } //------------------------------------------------------------------ void ConvertPopup::onConvertFinished() { m_isConverting = false; TFilePath dstFilePath(m_saveInFileFld->getPath().toStdWString()); if (dstFilePath == m_srcFilePaths[0].getParentDir()) FileBrowser::refreshFolder(dstFilePath); m_progressDialog->close(); QApplication::restoreOverrideCursor(); int errorCount = m_notifier->getErrorCount(); int skippedCount = m_converter->getSkippedCount(); if (errorCount > 0) { if (skippedCount > 0) DVGui::error( tr("Convert completed with %1 error(s) and %2 level(s) skipped") .arg(errorCount) .arg(skippedCount)); else DVGui::error(tr("Convert completed with %1 error(s) ").arg(errorCount)); } else if (skippedCount > 0) { DVGui::warning(tr("%1 level(s) skipped").arg(skippedCount)); } /* if (m_srcFilePaths.size()==1) { if (skipped==0) DVGui::info(tr("Level %1 converted to TLV Format").arg(QString::fromStdWString(m_srcFilePaths[0].withoutParentDir().getWideString()))); else DVGui::warning(tr("Warning: Level %1 NOT converted to TLV Format").arg(QString::fromStdWString(m_srcFilePaths[0].withoutParentDir().getWideString()))); } else DVGui::MsgBox(skipped==0?DVGui::INFORMATION:DVGui::WARNING, tr("Converted %1 out of %2 Levels to TLV Format").arg( QString::number(m_srcFilePaths.size()-skipped)).arg(QString::number(m_srcFilePaths.size()))); */ // TFilePath parentDir = m_srcFilePaths[0].getParentDir(); // FileBrowser::refreshFolder(parentDir); delete m_converter; m_converter = 0; } //------------------------------------------------------------------- void ConvertPopup::onLevelConverted(const TFilePath &fullPath) { IconGenerator::instance()->invalidate(fullPath); } //------------------------------------------------------------------- TPropertyGroup *ConvertPopup::getFormatProperties(const std::string &ext) { if (m_formatProperties.contains(ext)) return m_formatProperties[ext]; TPropertyGroup *props = Tiio::makeWriterProperties(ext); m_formatProperties[ext] = props; return props; } //------------------------------------------------------------------- void ConvertPopup::onOptionsClicked() { std::string ext = m_fileFormat->currentText().toStdString(); TPropertyGroup *props = getFormatProperties(ext); openFormatSettingsPopup(this, ext, props, m_srcFilePaths.size() == 1 ? m_srcFilePaths[0] : TFilePath()); } //------------------------------------------------------------------- void ConvertPopup::onFormatChanged(const QString &ext) { if (ext == QString("avi") || ext == QString("tzp") || ext == TlvExtension) { m_removeDotBeforeFrameNumber->setChecked(false); m_removeDotBeforeFrameNumber->setEnabled(false); } else { m_removeDotBeforeFrameNumber->setEnabled(true); if (ext == QString("tga")) m_removeDotBeforeFrameNumber->setChecked(true); } } //------------------------------------------------------------------- void ConvertPopup::onPalettePathChanged() { m_removeUnusedStyles->setEnabled( m_tlvMode->currentText() == TlvMode_PaintedFromNonAA && m_palettePath->getPath() != CreateNewPalette); } //------------------------------------------------------------------- bool ConvertPopup::isSaveTlvBackupToNopaintActive() { return m_fileFormat->currentText() == TlvExtension /*-- tlvが選択されている --*/ && m_tlvMode->currentText() == TlvMode_Unpainted /*-- Unpainted Tlvが選択されている --*/ && m_saveBackupToNopaint->isChecked(); /*-- Save Backup to "nopaint" Folder オプションが有効 --*/ } //============================================================================= // ConvertPopupCommand //----------------------------------------------------------------------------- OpenPopupCommandHandler<ConvertPopup> openConvertPopup(MI_ConvertFiles);
/* test_minimizer.cpp - Test Adept minimizer with N-dimensional Rosenbrock function Copyright (C) 2020 ECMWF Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without any warranty. */ //#include <string> // for std::stoi in C++11 #include <cstdio> // for std::sscanf in C++98 #include <iostream> #include <adept_optimize.h> // Set this to a large or small number to test if the minimization // algorithms are immune to the absolute scaling of the cost function #define COST_SCALING 1.0 using namespace adept; class RosenbrockN : public Optimizable { public: RosenbrockN() : ls_iteration_(0) {} int ls_iteration_; // Line search iteration // N-dimensional Rosenbrock function can be expressed as the sum of // the squared elements of vector y(x) defined as follows. This // form facilitates the calculation of the Hessian from the Jacobian // dy/dx. It is templated so that can be called either with a // passive "Vector" or active "aVector" argument. template <bool IsActive> Array<1,Real,IsActive> calc_y(const Array<1,Real,IsActive>& x) { int nx = x.size(); Array<1,Real,IsActive> y((nx-1)*2); for (int ix = 0; ix < nx-1; ++ix) { y(ix*2) = 10.0 * (x(ix+1)-x(ix)*x(ix)); y(ix*2+1) = 1.0 - x(ix); } y *= sqrt(2.0 * COST_SCALING); return y; } virtual void report_progress(int niter, const adept::Vector& x, Real cost, Real gnorm) { ls_iteration_ = 0; std::cout << "Iteration " << niter << ": cost=" << cost << ", gnorm=" << gnorm << "\n"; } void state_to_stderr(const adept::Vector& x, Real cost) { // For plotting progress, direct standard error to a text file std::cerr << ls_iteration_ << " "; for (int ix = 0; ix < x.size(); ++ix) { std::cerr << x(ix) << " "; } std::cerr << cost << "\n"; ++ls_iteration_; } void final_state_to_stderr(const adept::Vector& x, Real cost) { ls_iteration_ = -1; state_to_stderr(x, cost); } virtual bool provides_derivative(int order) { if (order >= 0 && order <= 2) { return true; } else { return false; } } virtual Real calc_cost_function(const Vector& x) { //std::cout << " test x: " << x << "\n"; Vector y = calc_y(x); Real cost = 0.5*sum(y*y); state_to_stderr(x,cost); return cost; } virtual Real calc_cost_function_gradient(const Vector& x, Vector gradient) { Stack stack; aVector xactive = x; stack.new_recording(); aVector y = calc_y(xactive); aReal cost = 0.5*sum(y*y); cost.set_gradient(1.0); stack.reverse(); gradient = xactive.get_gradient(); state_to_stderr(x,value(cost)); return value(cost); } virtual Real calc_cost_function_gradient_hessian(const Vector& x, Vector gradient, SymmMatrix& hessian) { Stack stack; aVector xactive = x; stack.new_recording(); aVector y = calc_y(xactive); aReal cost = 0.5*sum(y*y); stack.independent(xactive); stack.dependent(y); Matrix jac = stack.jacobian(); hessian = jac.T() ** jac; gradient = jac.T() ** value(y); state_to_stderr(x,value(cost)); return value(cost); } }; int main(int argc, const char* argv[]) { if (!adept::have_linear_algebra()) { std::cout << "Adept compiled without linear-algebra support: minimizer not available\n"; return 0; } RosenbrockN rosenbrock; Minimizer minimizer(MINIMIZER_ALGORITHM_LEVENBERG_MARQUARDT); // The convergence criterion should be changed in accordance with // the cost function scaling minimizer.set_converged_gradient_norm(0.1*COST_SCALING); int nx = 2; if (argc > 1) { // nx = std::stoi(argv[1]); std::sscanf(argv[1], "%d", &nx); if (argc > 2) { minimizer.set_algorithm(argv[2]); if (argc > 3) { int max_it; // max_it = std::stof(argv[3]); std::sscanf(argv[3], "%d", &max_it); minimizer.set_max_iterations(max_it); if (argc > 4) { double converged_grad_norm; //converged_grad_norm = std::stof(argv[4]); std::sscanf(argv[4], "%lf", &converged_grad_norm); minimizer.set_converged_gradient_norm(converged_grad_norm); } } } } else { std::cout << "Usage: " << argv[0] << " [nx] [Levenberg|Levenberg-Marquardt|L-BFGS|Conjugate-Gradient] [max_iterations] [converged_gradient_norm]\n"; } //minimizer.set_levenberg_damping_start(0.0); //minimizer.set_max_step_size(1.0); // minimizer.set_levenberg_damping_multiplier(3.0, 5.0); minimizer.ensure_updated_state(2); std::cout << "Minimizing " << nx << "-dimensional Rosenbrock function\n"; std::cout << "Algorithm: " << minimizer.algorithm_name() << "\n"; std::cout << "Maximum iterations: " << minimizer.max_iterations() << "\n"; std::cout << "Converged gradient norm: " << minimizer.converged_gradient_norm() << "\n"; // Initial state vector Vector x(nx); // Standard start x = -3.0; // Trickier start (other end of the banana) //x = -3.0; x(1) = 3.0; // Near other minima in higher dimensions //x = 1.0; x(0) = -1.0; bool is_bounded = false; MinimizerStatus status; if (is_bounded) { x = -3.0; x(1) = 3.0; Vector x_lower, x_upper; adept::minimizer_initialize_bounds(nx, x_lower, x_upper); x_upper(1) = 2.0; x_lower(1) = 0.2; status = minimizer.minimize(rosenbrock, x, x_lower, x_upper); } else { status = minimizer.minimize(rosenbrock, x); } //rosenbrock.final_state_to_stderr(x, minimizer.cost_function()); std::cout << "Status: " << minimizer_status_string(status) << "\n"; std::cout << "Solution: x=" << x << "\n"; std::cout << "Number of samples: " << minimizer.n_samples() << "\n"; return static_cast<int>(status); } Updated test_minimizer settings so that bounded reproduces video on web site /* test_minimizer.cpp - Test Adept minimizer with N-dimensional Rosenbrock function Copyright (C) 2020 ECMWF Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without any warranty. */ //#include <string> // for std::stoi in C++11 #include <cstdio> // for std::sscanf in C++98 #include <iostream> #include <adept_optimize.h> // Set this to a large or small number to test if the minimization // algorithms are immune to the absolute scaling of the cost function #define COST_SCALING 1.0 using namespace adept; class RosenbrockN : public Optimizable { public: RosenbrockN() : ls_iteration_(0) {} int ls_iteration_; // Line search iteration // N-dimensional Rosenbrock function can be expressed as the sum of // the squared elements of vector y(x) defined as follows. This // form facilitates the calculation of the Hessian from the Jacobian // dy/dx. It is templated so that can be called either with a // passive "Vector" or active "aVector" argument. template <bool IsActive> Array<1,Real,IsActive> calc_y(const Array<1,Real,IsActive>& x) { int nx = x.size(); Array<1,Real,IsActive> y((nx-1)*2); for (int ix = 0; ix < nx-1; ++ix) { y(ix*2) = 10.0 * (x(ix+1)-x(ix)*x(ix)); y(ix*2+1) = 1.0 - x(ix); } y *= sqrt(2.0 * COST_SCALING); return y; } virtual void report_progress(int niter, const adept::Vector& x, Real cost, Real gnorm) { ls_iteration_ = 0; std::cout << "Iteration " << niter << ": cost=" << cost << ", gnorm=" << gnorm << "\n"; } void state_to_stderr(const adept::Vector& x, Real cost) { // For plotting progress, direct standard error to a text file std::cerr << ls_iteration_ << " "; for (int ix = 0; ix < x.size(); ++ix) { std::cerr << x(ix) << " "; } std::cerr << cost << "\n"; ++ls_iteration_; } void final_state_to_stderr(const adept::Vector& x, Real cost) { ls_iteration_ = -1; state_to_stderr(x, cost); } virtual bool provides_derivative(int order) { if (order >= 0 && order <= 2) { return true; } else { return false; } } virtual Real calc_cost_function(const Vector& x) { //std::cout << " test x: " << x << "\n"; Vector y = calc_y(x); Real cost = 0.5*sum(y*y); state_to_stderr(x,cost); return cost; } virtual Real calc_cost_function_gradient(const Vector& x, Vector gradient) { Stack stack; aVector xactive = x; stack.new_recording(); aVector y = calc_y(xactive); aReal cost = 0.5*sum(y*y); cost.set_gradient(1.0); stack.reverse(); gradient = xactive.get_gradient(); state_to_stderr(x,value(cost)); return value(cost); } virtual Real calc_cost_function_gradient_hessian(const Vector& x, Vector gradient, SymmMatrix& hessian) { Stack stack; aVector xactive = x; stack.new_recording(); aVector y = calc_y(xactive); aReal cost = 0.5*sum(y*y); stack.independent(xactive); stack.dependent(y); Matrix jac = stack.jacobian(); hessian = jac.T() ** jac; gradient = jac.T() ** value(y); state_to_stderr(x,value(cost)); return value(cost); } }; int main(int argc, const char* argv[]) { if (!adept::have_linear_algebra()) { std::cout << "Adept compiled without linear-algebra support: minimizer not available\n"; return 0; } RosenbrockN rosenbrock; Minimizer minimizer(MINIMIZER_ALGORITHM_LEVENBERG_MARQUARDT); // The convergence criterion should be changed in accordance with // the cost function scaling minimizer.set_converged_gradient_norm(0.1*COST_SCALING); int nx = 2; if (argc > 1) { // nx = std::stoi(argv[1]); std::sscanf(argv[1], "%d", &nx); if (argc > 2) { minimizer.set_algorithm(argv[2]); if (argc > 3) { int max_it; // max_it = std::stof(argv[3]); std::sscanf(argv[3], "%d", &max_it); minimizer.set_max_iterations(max_it); if (argc > 4) { double converged_grad_norm; //converged_grad_norm = std::stof(argv[4]); std::sscanf(argv[4], "%lf", &converged_grad_norm); minimizer.set_converged_gradient_norm(converged_grad_norm); } } } } else { std::cout << "Usage: " << argv[0] << " [nx] [Levenberg|Levenberg-Marquardt|L-BFGS|Conjugate-Gradient] [max_iterations] [converged_gradient_norm]\n"; } minimizer.set_levenberg_damping_start(0.25); //minimizer.set_max_step_size(1.0); // minimizer.set_levenberg_damping_multiplier(3.0, 5.0); minimizer.ensure_updated_state(2); std::cout << "Minimizing " << nx << "-dimensional Rosenbrock function\n"; std::cout << "Algorithm: " << minimizer.algorithm_name() << "\n"; std::cout << "Maximum iterations: " << minimizer.max_iterations() << "\n"; std::cout << "Converged gradient norm: " << minimizer.converged_gradient_norm() << "\n"; // Initial state vector Vector x(nx); // Standard start x = -3.0; // Trickier start (other end of the banana) //x = -3.0; x(1) = 3.0; // Near other minima in higher dimensions //x = 1.0; x(0) = -1.0; bool is_bounded = false; MinimizerStatus status; if (is_bounded) { // x = -3.0; x(1) = 3.0; x = -0.75; x(1) = 3.0; Vector x_lower, x_upper; adept::minimizer_initialize_bounds(nx, x_lower, x_upper); // x_upper(1) = 2.0; x_lower(1) = 0.2; x_lower(0) = -1; status = minimizer.minimize(rosenbrock, x, x_lower, x_upper); } else { status = minimizer.minimize(rosenbrock, x); } //rosenbrock.final_state_to_stderr(x, minimizer.cost_function()); std::cout << "Status: " << minimizer_status_string(status) << "\n"; std::cout << "Solution: x=" << x << "\n"; std::cout << "Number of samples: " << minimizer.n_samples() << "\n"; return static_cast<int>(status); }
/****************************************************************************** * Copyright 2017 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. *****************************************************************************/ #include "modules/dreamview/backend/simulation_world/simulation_world_service.h" #include <iostream> #include "gtest/gtest.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/quaternion.h" #include "modules/dreamview/backend/common/dreamview_gflags.h" using apollo::canbus::Chassis; using apollo::common::TrajectoryPoint; using apollo::common::monitor::MonitorMessage; using apollo::localization::LocalizationEstimate; using apollo::perception::PerceptionObstacle; using apollo::perception::PerceptionObstacles; using apollo::planning::ADCTrajectory; using apollo::planning::DecisionResult; using apollo::prediction::PredictionObstacle; using apollo::prediction::PredictionObstacles; using apollo::common::adapter::AdapterConfig; using apollo::common::adapter::AdapterManager; using apollo::common::adapter::AdapterManagerConfig; using apollo::common::util::StrCat; namespace apollo { namespace dreamview { const float kEpsilon = 0.01; class SimulationWorldServiceTest : public ::testing::Test { public: virtual void SetUp() { // Setup AdapterManager. AdapterManagerConfig config; config.set_is_ros(false); { auto* sub_config = config.add_config(); sub_config->set_mode(AdapterConfig::PUBLISH_ONLY); sub_config->set_type(AdapterConfig::MONITOR); } { auto* sub_config = config.add_config(); sub_config->set_mode(AdapterConfig::PUBLISH_ONLY); sub_config->set_type(AdapterConfig::ROUTING_RESPONSE); } AdapterManager::Reset(); AdapterManager::Init(config); FLAGS_routing_response_file = "modules/dreamview/backend/testdata/routing.pb.txt"; apollo::common::VehicleConfigHelper::Init(); sim_world_service_.reset(new SimulationWorldService(map_service_.get())); } protected: SimulationWorldServiceTest() { FLAGS_map_dir = "modules/dreamview/backend/testdata"; FLAGS_base_map_filename = "garage.bin"; FLAGS_sim_world_with_routing_path = true; map_service_.reset(new MapService(false)); } std::unique_ptr<SimulationWorldService> sim_world_service_; std::unique_ptr<MapService> map_service_; }; TEST_F(SimulationWorldServiceTest, UpdateMonitorSuccess) { MonitorMessage monitor; monitor.add_item()->set_msg("I am the latest message."); monitor.mutable_header()->set_timestamp_sec(2000); auto* world_monitor = sim_world_service_->world_.mutable_monitor(); world_monitor->mutable_header()->set_timestamp_sec(1990); world_monitor->add_item()->set_msg("I am the previous message."); sim_world_service_->UpdateSimulationWorld(monitor); EXPECT_EQ(2, world_monitor->item_size()); EXPECT_EQ("I am the latest message.", world_monitor->item(0).msg()); EXPECT_EQ("I am the previous message.", world_monitor->item(1).msg()); } TEST_F(SimulationWorldServiceTest, UpdateMonitorRemove) { MonitorMessage monitor; monitor.add_item()->set_msg("I am message -2"); monitor.add_item()->set_msg("I am message -1"); monitor.mutable_header()->set_timestamp_sec(2000); auto* world_monitor = sim_world_service_->world_.mutable_monitor(); world_monitor->mutable_header()->set_timestamp_sec(1990); for (int i = 0; i < SimulationWorldService::kMaxMonitorItems; ++i) { world_monitor->add_item()->set_msg(StrCat("I am message ", i)); } int last = SimulationWorldService::kMaxMonitorItems - 1; EXPECT_EQ(StrCat("I am message ", last), world_monitor->item(last).msg()); sim_world_service_->UpdateSimulationWorld(monitor); EXPECT_EQ(SimulationWorldService::kMaxMonitorItems, world_monitor->item_size()); EXPECT_EQ("I am message -2", world_monitor->item(0).msg()); EXPECT_EQ("I am message -1", world_monitor->item(1).msg()); EXPECT_EQ(StrCat("I am message ", last - monitor.item_size()), world_monitor->item(last).msg()); } TEST_F(SimulationWorldServiceTest, UpdateMonitorTruncate) { MonitorMessage monitor; int large_size = SimulationWorldService::kMaxMonitorItems + 10; for (int i = 0; i < large_size; ++i) { monitor.add_item()->set_msg(StrCat("I am message ", i)); } monitor.mutable_header()->set_timestamp_sec(2000); EXPECT_EQ(large_size, monitor.item_size()); EXPECT_EQ(StrCat("I am message ", large_size - 1), monitor.item(large_size - 1).msg()); auto* world_monitor = sim_world_service_->world_.mutable_monitor(); world_monitor->mutable_header()->set_timestamp_sec(1990); sim_world_service_->UpdateSimulationWorld(monitor); int last = SimulationWorldService::kMaxMonitorItems - 1; EXPECT_EQ(SimulationWorldService::kMaxMonitorItems, world_monitor->item_size()); EXPECT_EQ("I am message 0", world_monitor->item(0).msg()); EXPECT_EQ(StrCat("I am message ", last), world_monitor->item(last).msg()); } TEST_F(SimulationWorldServiceTest, UpdateChassisInfo) { // Prepare the chassis message that will be used to update the // SimulationWorld object. Chassis chassis; chassis.set_speed_mps(25); chassis.set_throttle_percentage(50); chassis.set_brake_percentage(10); chassis.set_steering_percentage(25); chassis.mutable_signal()->set_turn_signal( apollo::common::VehicleSignal::TURN_RIGHT); // Commit the update. sim_world_service_->UpdateSimulationWorld(chassis); // Check the update reuslt. const Object& car = sim_world_service_->world_.auto_driving_car(); EXPECT_DOUBLE_EQ(4.933, car.length()); EXPECT_DOUBLE_EQ(2.11, car.width()); EXPECT_DOUBLE_EQ(1.48, car.height()); EXPECT_DOUBLE_EQ(25.0, car.speed()); EXPECT_DOUBLE_EQ(50.0, car.throttle_percentage()); EXPECT_DOUBLE_EQ(10.0, car.brake_percentage()); EXPECT_DOUBLE_EQ(25.0, car.steering_percentage()); EXPECT_EQ("RIGHT", car.current_signal()); } TEST_F(SimulationWorldServiceTest, UpdateLocalization) { // Prepare the localization message that will be used to update the // SimulationWorld object. LocalizationEstimate localization; localization.mutable_pose()->mutable_position()->set_x(1.0); localization.mutable_pose()->mutable_position()->set_y(1.5); localization.mutable_pose()->mutable_orientation()->set_qx(0.0); localization.mutable_pose()->mutable_orientation()->set_qy(0.0); localization.mutable_pose()->mutable_orientation()->set_qz(0.0); localization.mutable_pose()->mutable_orientation()->set_qw(0.0); auto pose = localization.pose(); auto heading = apollo::common::math::QuaternionToHeading( pose.orientation().qw(), pose.orientation().qx(), pose.orientation().qy(), pose.orientation().qz()); localization.mutable_pose()->set_heading(heading); // Commit the update. sim_world_service_->UpdateSimulationWorld(localization); // Check the update result. const Object& car = sim_world_service_->world_.auto_driving_car(); EXPECT_DOUBLE_EQ(1.0, car.position_x()); EXPECT_DOUBLE_EQ(1.5, car.position_y()); EXPECT_DOUBLE_EQ( apollo::common::math::QuaternionToHeading(0.0, 0.0, 0.0, 0.0), car.heading()); } TEST_F(SimulationWorldServiceTest, UpdatePerceptionObstacles) { PerceptionObstacles obstacles; PerceptionObstacle* obstacle1 = obstacles.add_perception_obstacle(); obstacle1->set_id(1); apollo::perception::Point* point1 = obstacle1->add_polygon_point(); point1->set_x(0.0); point1->set_y(0.0); apollo::perception::Point* point2 = obstacle1->add_polygon_point(); point2->set_x(0.0); point2->set_y(1.0); apollo::perception::Point* point3 = obstacle1->add_polygon_point(); point3->set_x(-1.0); point3->set_y(0.0); apollo::perception::Point* point4 = obstacle1->add_polygon_point(); point4->set_x(-1.0); point4->set_y(0.0); obstacle1->set_timestamp(1489794020.123); obstacle1->set_type(apollo::perception::PerceptionObstacle_Type_UNKNOWN); PerceptionObstacle* obstacle2 = obstacles.add_perception_obstacle(); obstacle2->set_id(2); apollo::perception::Point* point = obstacle2->mutable_position(); point->set_x(1.0); point->set_y(2.0); obstacle2->set_theta(3.0); obstacle2->set_length(4.0); obstacle2->set_width(5.0); obstacle2->set_height(6.0); obstacle2->mutable_velocity()->set_x(3.0); obstacle2->mutable_velocity()->set_y(4.0); obstacle2->set_type(apollo::perception::PerceptionObstacle_Type_VEHICLE); sim_world_service_->UpdateSimulationWorld(obstacles); sim_world_service_->world_.clear_object(); for (auto& kv : sim_world_service_->obj_map_) { *sim_world_service_->world_.add_object() = kv.second; } EXPECT_EQ(2, sim_world_service_->world_.object_size()); for (const auto& object : sim_world_service_->world_.object()) { if (object.id() == "1") { EXPECT_DOUBLE_EQ(1489794020.123, object.timestamp_sec()); EXPECT_EQ(3, object.polygon_point_size()); EXPECT_EQ(Object_Type_UNKNOWN, object.type()); } else if (object.id() == "2") { EXPECT_DOUBLE_EQ(1.0, object.position_x()); EXPECT_DOUBLE_EQ(2.0, object.position_y()); EXPECT_DOUBLE_EQ(3.0, object.heading()); EXPECT_DOUBLE_EQ(4.0, object.length()); EXPECT_DOUBLE_EQ(5.0, object.width()); EXPECT_DOUBLE_EQ(6.0, object.height()); EXPECT_DOUBLE_EQ(5.0, object.speed()); EXPECT_NEAR(0.927295, object.speed_heading(), kEpsilon); EXPECT_EQ(0, object.polygon_point_size()); EXPECT_EQ(Object_Type_VEHICLE, object.type()); } else { EXPECT_TRUE(false) << "Unexpected object id " << object.id(); } } } TEST_F(SimulationWorldServiceTest, UpdatePlanningTrajectory) { // Prepare the trajectory message that will be used to update the // SimulationWorld object. ADCTrajectory planning_trajectory; for (int i = 0; i < 30; ++i) { TrajectoryPoint* point = planning_trajectory.add_trajectory_point(); point->mutable_path_point()->set_x(i * 10); point->mutable_path_point()->set_y(i * 10 + 10); } // Commit the update. sim_world_service_->UpdatePlanningTrajectory(planning_trajectory); // Check the update result. const SimulationWorld& world = sim_world_service_->world(); EXPECT_EQ(29, world.planning_trajectory_size()); // Check first point. { const Object point = world.planning_trajectory(0); EXPECT_DOUBLE_EQ(0.0, point.position_x()); EXPECT_DOUBLE_EQ(10.0, point.position_y()); EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading()); } // Check last point. { const Object point = world.planning_trajectory(world.planning_trajectory_size() - 1); EXPECT_DOUBLE_EQ(280.0, point.position_x()); EXPECT_DOUBLE_EQ(290.0, point.position_y()); EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading()); } } TEST_F(SimulationWorldServiceTest, UpdateDecision) { DecisionResult decision_res; decision_res.mutable_vehicle_signal()->set_turn_signal( apollo::common::VehicleSignal::TURN_RIGHT); apollo::planning::MainDecision* main_decision = decision_res.mutable_main_decision(); main_decision->add_target_lane()->set_speed_limit(35); apollo::planning::MainStop* main_stop = main_decision->mutable_stop(); main_stop->mutable_stop_point()->set_x(45678.9); main_stop->mutable_stop_point()->set_y(1234567.8); main_stop->set_stop_heading(1.234); main_stop->set_reason_code( apollo::planning::StopReasonCode::STOP_REASON_CROSSWALK); apollo::planning::ObjectDecisions* obj_decisions = decision_res.mutable_object_decision(); // The 1st obstacle is from perception and has 2 decisions: nudge or sidepass. apollo::planning::ObjectDecision* obj_decision1 = obj_decisions->add_decision(); obj_decision1->set_perception_id(1); Object& perception1 = sim_world_service_->obj_map_["1"]; perception1.set_type(Object_Type_UNKNOWN_UNMOVABLE); perception1.set_id("1"); perception1.set_position_x(1.0); perception1.set_position_y(2.0); perception1.set_heading(3.0); perception1.set_length(4.0); perception1.set_width(5.0); perception1.set_height(6.0); for (int i = 0; i < 3; ++i) { PolygonPoint* perception_pt = perception1.add_polygon_point(); if (i < 2) { perception_pt->set_x(10.0 * (i + 1)); perception_pt->set_y(20.0 * (i + 1)); } else { perception_pt->set_y(10.0 * (i + 1)); perception_pt->set_x(20.0 * (i + 1)); } } obj_decision1->add_object_decision()->mutable_nudge()->set_distance_l(1.8); obj_decision1->add_object_decision()->mutable_sidepass(); // The 2nd obstacle is virtual and has only 1 decision: yield. apollo::planning::ObjectDecision* obj_decision2 = obj_decisions->add_decision(); obj_decision2->set_perception_id(2); apollo::planning::ObjectYield* yield = obj_decision2->add_object_decision()->mutable_yield(); apollo::common::PointENU* fence_point = yield->mutable_fence_point(); fence_point->set_x(-1859.98); fence_point->set_y(-3000.03); yield->set_fence_heading(1.3); sim_world_service_->UpdateDecision(decision_res, 1501095053); const SimulationWorld& world = sim_world_service_->world(); EXPECT_EQ("RIGHT", world.auto_driving_car().current_signal()); EXPECT_EQ(35, world.speed_limit()); const Object& world_main_stop = world.main_decision(); EXPECT_EQ(1, world_main_stop.decision_size()); EXPECT_EQ(Decision::STOP_REASON_CROSSWALK, world_main_stop.decision(0).stopreason()); EXPECT_DOUBLE_EQ(45678.9, world_main_stop.position_x()); EXPECT_DOUBLE_EQ(1234567.8, world_main_stop.position_y()); EXPECT_DOUBLE_EQ(1.234, world_main_stop.heading()); sim_world_service_->world_.clear_object(); for (auto& kv : sim_world_service_->obj_map_) { *sim_world_service_->world_.add_object() = kv.second; } EXPECT_EQ(2, world.object_size()); for (int i = 0; i < 2; ++i) { const Object& obj_dec = world.object(i); if (obj_dec.id() == "1") { EXPECT_EQ(Object_Type_UNKNOWN_UNMOVABLE, obj_dec.type()); EXPECT_DOUBLE_EQ(1.0, obj_dec.position_x()); EXPECT_DOUBLE_EQ(2.0, obj_dec.position_y()); EXPECT_DOUBLE_EQ(3.0, obj_dec.heading()); EXPECT_DOUBLE_EQ(4.0, obj_dec.length()); EXPECT_DOUBLE_EQ(5.0, obj_dec.width()); EXPECT_DOUBLE_EQ(6.0, obj_dec.height()); EXPECT_EQ(obj_dec.decision_size(), 2); for (int j = 0; j < obj_dec.decision_size(); ++j) { const Decision& decision = obj_dec.decision(j); if (j == 0) { EXPECT_EQ(decision.type(), Decision_Type_NUDGE); EXPECT_EQ(decision.polygon_point_size(), 67); } else { EXPECT_EQ(decision.type(), Decision_Type_SIDEPASS); } } } else { EXPECT_EQ(Object_Type_VIRTUAL, obj_dec.type()); EXPECT_EQ(1, obj_dec.decision_size()); const Decision& decision = obj_dec.decision(0); EXPECT_EQ(Decision_Type_YIELD, decision.type()); EXPECT_DOUBLE_EQ(-1859.98, decision.position_x()); EXPECT_DOUBLE_EQ(-3000.03, decision.position_y()); EXPECT_DOUBLE_EQ(1.3, decision.heading()); } } } TEST_F(SimulationWorldServiceTest, UpdatePrediction) { // Update with prediction obstacles PredictionObstacles prediction_obstacles; for (int i = 0; i < 3; ++i) { auto* obstacle = prediction_obstacles.add_prediction_obstacle(); auto* perception_obstacle = obstacle->mutable_perception_obstacle(); perception_obstacle->set_id(i); for (int j = 0; j < 5; ++j) { auto* traj = obstacle->add_trajectory(); traj->set_probability(i * 0.1 + j); for (int k = 0; k < 8; ++k) { auto* traj_pt = traj->add_trajectory_point()->mutable_path_point(); int pt = j * 10 + k; traj_pt->set_x(pt); traj_pt->set_y(pt); traj_pt->set_z(pt); } } obstacle->set_timestamp(123.456); } sim_world_service_->UpdateSimulationWorld(prediction_obstacles); sim_world_service_->world_.clear_object(); for (auto& kv : sim_world_service_->obj_map_) { *sim_world_service_->world_.add_object() = kv.second; } // Verify const auto& sim_world = sim_world_service_->world(); EXPECT_EQ(3, sim_world.object_size()); for (int i = 0; i < sim_world.object_size(); ++i) { const Object& obj = sim_world.object(i); EXPECT_EQ(5, obj.prediction_size()); for (int j = 0; j < obj.prediction_size(); ++j) { const Prediction& prediction = obj.prediction(j); EXPECT_NEAR((sim_world.object_size() - i - 1) * 0.1 + j, prediction.probability(), kEpsilon); EXPECT_EQ(prediction.predicted_trajectory_size(), 2); // Downsampled } EXPECT_NEAR(123.456, obj.timestamp_sec(), kEpsilon); } } TEST_F(SimulationWorldServiceTest, UpdateRouting) { // Load routing from file sim_world_service_.reset( new SimulationWorldService(map_service_.get(), true)); sim_world_service_->UpdateSimulationWorld( *AdapterManager::GetRoutingResponse()->GetLatestPublished()); auto& world = sim_world_service_->world_; EXPECT_EQ(world.routing_time(), 1234.5); EXPECT_EQ(1, world.route_path_size()); double points[23][2] = { {-1826.41, -3027.52}, {-1839.88, -3023.9}, {-1851.95, -3020.71}, {-1857.06, -3018.62}, {-1858.04, -3017.94}, {-1859.56, -3016.51}, {-1860.48, -3014.95}, {-1861.12, -3013.2}, {-1861.62, -3010.06}, {-1861.29, -3005.88}, {-1859.8, -2999.36}, {-1855.8, -2984.56}, {-1851.39, -2968.23}, {-1844.32, -2943.14}, {-1842.9, -2939.22}, {-1841.74, -2937.09}, {-1839.35, -2934.03}, {-1837.76, -2932.88}, {-1835.53, -2931.86}, {-1833.36, -2931.52}, {-1831.33, -2931.67}, {-1827.05, -2932.6}, {-1809.64, -2937.85}}; const auto& path = world.route_path(0); EXPECT_EQ(23, path.point_size()); for (int i = 0; i < path.point_size(); ++i) { EXPECT_NEAR(path.point(i).x(), points[i][0], kEpsilon); EXPECT_NEAR(path.point(i).y(), points[i][1], kEpsilon); } } } // namespace dreamview } // namespace apollo Update simulation_world_service_test.cc (#4561) /****************************************************************************** * Copyright 2017 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. *****************************************************************************/ #include "modules/dreamview/backend/simulation_world/simulation_world_service.h" #include <iostream> #include "gtest/gtest.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/quaternion.h" #include "modules/dreamview/backend/common/dreamview_gflags.h" using apollo::canbus::Chassis; using apollo::common::TrajectoryPoint; using apollo::common::monitor::MonitorMessage; using apollo::localization::LocalizationEstimate; using apollo::perception::PerceptionObstacle; using apollo::perception::PerceptionObstacles; using apollo::planning::ADCTrajectory; using apollo::planning::DecisionResult; using apollo::prediction::PredictionObstacle; using apollo::prediction::PredictionObstacles; using apollo::common::adapter::AdapterConfig; using apollo::common::adapter::AdapterManager; using apollo::common::adapter::AdapterManagerConfig; using apollo::common::util::StrCat; namespace apollo { namespace dreamview { const float kEpsilon = 0.01; class SimulationWorldServiceTest : public ::testing::Test { public: virtual void SetUp() { // Setup AdapterManager. AdapterManagerConfig config; config.set_is_ros(false); { auto* sub_config = config.add_config(); sub_config->set_mode(AdapterConfig::PUBLISH_ONLY); sub_config->set_type(AdapterConfig::MONITOR); } { auto* sub_config = config.add_config(); sub_config->set_mode(AdapterConfig::PUBLISH_ONLY); sub_config->set_type(AdapterConfig::ROUTING_RESPONSE); } AdapterManager::Reset(); AdapterManager::Init(config); FLAGS_routing_response_file = "modules/dreamview/backend/testdata/routing.pb.txt"; apollo::common::VehicleConfigHelper::Init(); sim_world_service_.reset(new SimulationWorldService(map_service_.get())); } protected: SimulationWorldServiceTest() { FLAGS_map_dir = "modules/dreamview/backend/testdata"; FLAGS_base_map_filename = "garage.bin"; FLAGS_sim_world_with_routing_path = true; map_service_.reset(new MapService(false)); } std::unique_ptr<SimulationWorldService> sim_world_service_; std::unique_ptr<MapService> map_service_; }; TEST_F(SimulationWorldServiceTest, UpdateMonitorSuccess) { MonitorMessage monitor; monitor.add_item()->set_msg("I am the latest message."); monitor.mutable_header()->set_timestamp_sec(2000); auto* world_monitor = sim_world_service_->world_.mutable_monitor(); world_monitor->mutable_header()->set_timestamp_sec(1990); world_monitor->add_item()->set_msg("I am the previous message."); sim_world_service_->UpdateSimulationWorld(monitor); EXPECT_EQ(2, world_monitor->item_size()); EXPECT_EQ("I am the latest message.", world_monitor->item(0).msg()); EXPECT_EQ("I am the previous message.", world_monitor->item(1).msg()); } TEST_F(SimulationWorldServiceTest, UpdateMonitorRemove) { MonitorMessage monitor; monitor.add_item()->set_msg("I am message -2"); monitor.add_item()->set_msg("I am message -1"); monitor.mutable_header()->set_timestamp_sec(2000); auto* world_monitor = sim_world_service_->world_.mutable_monitor(); world_monitor->mutable_header()->set_timestamp_sec(1990); for (int i = 0; i < SimulationWorldService::kMaxMonitorItems; ++i) { world_monitor->add_item()->set_msg(StrCat("I am message ", i)); } int last = SimulationWorldService::kMaxMonitorItems - 1; EXPECT_EQ(StrCat("I am message ", last), world_monitor->item(last).msg()); sim_world_service_->UpdateSimulationWorld(monitor); EXPECT_EQ(SimulationWorldService::kMaxMonitorItems, world_monitor->item_size()); EXPECT_EQ("I am message -2", world_monitor->item(0).msg()); EXPECT_EQ("I am message -1", world_monitor->item(1).msg()); EXPECT_EQ(StrCat("I am message ", last - monitor.item_size()), world_monitor->item(last).msg()); } TEST_F(SimulationWorldServiceTest, UpdateMonitorTruncate) { MonitorMessage monitor; int large_size = SimulationWorldService::kMaxMonitorItems + 10; for (int i = 0; i < large_size; ++i) { monitor.add_item()->set_msg(StrCat("I am message ", i)); } monitor.mutable_header()->set_timestamp_sec(2000); EXPECT_EQ(large_size, monitor.item_size()); EXPECT_EQ(StrCat("I am message ", large_size - 1), monitor.item(large_size - 1).msg()); auto* world_monitor = sim_world_service_->world_.mutable_monitor(); world_monitor->mutable_header()->set_timestamp_sec(1990); sim_world_service_->UpdateSimulationWorld(monitor); int last = SimulationWorldService::kMaxMonitorItems - 1; EXPECT_EQ(SimulationWorldService::kMaxMonitorItems, world_monitor->item_size()); EXPECT_EQ("I am message 0", world_monitor->item(0).msg()); EXPECT_EQ(StrCat("I am message ", last), world_monitor->item(last).msg()); } TEST_F(SimulationWorldServiceTest, UpdateChassisInfo) { // Prepare the chassis message that will be used to update the // SimulationWorld object. Chassis chassis; chassis.set_speed_mps(25); chassis.set_throttle_percentage(50); chassis.set_brake_percentage(10); chassis.set_steering_percentage(25); chassis.mutable_signal()->set_turn_signal( apollo::common::VehicleSignal::TURN_RIGHT); // Commit the update. sim_world_service_->UpdateSimulationWorld(chassis); // Check the update result. const Object& car = sim_world_service_->world_.auto_driving_car(); EXPECT_DOUBLE_EQ(4.933, car.length()); EXPECT_DOUBLE_EQ(2.11, car.width()); EXPECT_DOUBLE_EQ(1.48, car.height()); EXPECT_DOUBLE_EQ(25.0, car.speed()); EXPECT_DOUBLE_EQ(50.0, car.throttle_percentage()); EXPECT_DOUBLE_EQ(10.0, car.brake_percentage()); EXPECT_DOUBLE_EQ(25.0, car.steering_percentage()); EXPECT_EQ("RIGHT", car.current_signal()); } TEST_F(SimulationWorldServiceTest, UpdateLocalization) { // Prepare the localization message that will be used to update the // SimulationWorld object. LocalizationEstimate localization; localization.mutable_pose()->mutable_position()->set_x(1.0); localization.mutable_pose()->mutable_position()->set_y(1.5); localization.mutable_pose()->mutable_orientation()->set_qx(0.0); localization.mutable_pose()->mutable_orientation()->set_qy(0.0); localization.mutable_pose()->mutable_orientation()->set_qz(0.0); localization.mutable_pose()->mutable_orientation()->set_qw(0.0); auto pose = localization.pose(); auto heading = apollo::common::math::QuaternionToHeading( pose.orientation().qw(), pose.orientation().qx(), pose.orientation().qy(), pose.orientation().qz()); localization.mutable_pose()->set_heading(heading); // Commit the update. sim_world_service_->UpdateSimulationWorld(localization); // Check the update result. const Object& car = sim_world_service_->world_.auto_driving_car(); EXPECT_DOUBLE_EQ(1.0, car.position_x()); EXPECT_DOUBLE_EQ(1.5, car.position_y()); EXPECT_DOUBLE_EQ( apollo::common::math::QuaternionToHeading(0.0, 0.0, 0.0, 0.0), car.heading()); } TEST_F(SimulationWorldServiceTest, UpdatePerceptionObstacles) { PerceptionObstacles obstacles; PerceptionObstacle* obstacle1 = obstacles.add_perception_obstacle(); obstacle1->set_id(1); apollo::perception::Point* point1 = obstacle1->add_polygon_point(); point1->set_x(0.0); point1->set_y(0.0); apollo::perception::Point* point2 = obstacle1->add_polygon_point(); point2->set_x(0.0); point2->set_y(1.0); apollo::perception::Point* point3 = obstacle1->add_polygon_point(); point3->set_x(-1.0); point3->set_y(0.0); apollo::perception::Point* point4 = obstacle1->add_polygon_point(); point4->set_x(-1.0); point4->set_y(0.0); obstacle1->set_timestamp(1489794020.123); obstacle1->set_type(apollo::perception::PerceptionObstacle_Type_UNKNOWN); PerceptionObstacle* obstacle2 = obstacles.add_perception_obstacle(); obstacle2->set_id(2); apollo::perception::Point* point = obstacle2->mutable_position(); point->set_x(1.0); point->set_y(2.0); obstacle2->set_theta(3.0); obstacle2->set_length(4.0); obstacle2->set_width(5.0); obstacle2->set_height(6.0); obstacle2->mutable_velocity()->set_x(3.0); obstacle2->mutable_velocity()->set_y(4.0); obstacle2->set_type(apollo::perception::PerceptionObstacle_Type_VEHICLE); sim_world_service_->UpdateSimulationWorld(obstacles); sim_world_service_->world_.clear_object(); for (auto& kv : sim_world_service_->obj_map_) { *sim_world_service_->world_.add_object() = kv.second; } EXPECT_EQ(2, sim_world_service_->world_.object_size()); for (const auto& object : sim_world_service_->world_.object()) { if (object.id() == "1") { EXPECT_DOUBLE_EQ(1489794020.123, object.timestamp_sec()); EXPECT_EQ(3, object.polygon_point_size()); EXPECT_EQ(Object_Type_UNKNOWN, object.type()); } else if (object.id() == "2") { EXPECT_DOUBLE_EQ(1.0, object.position_x()); EXPECT_DOUBLE_EQ(2.0, object.position_y()); EXPECT_DOUBLE_EQ(3.0, object.heading()); EXPECT_DOUBLE_EQ(4.0, object.length()); EXPECT_DOUBLE_EQ(5.0, object.width()); EXPECT_DOUBLE_EQ(6.0, object.height()); EXPECT_DOUBLE_EQ(5.0, object.speed()); EXPECT_NEAR(0.927295, object.speed_heading(), kEpsilon); EXPECT_EQ(0, object.polygon_point_size()); EXPECT_EQ(Object_Type_VEHICLE, object.type()); } else { EXPECT_TRUE(false) << "Unexpected object id " << object.id(); } } } TEST_F(SimulationWorldServiceTest, UpdatePlanningTrajectory) { // Prepare the trajectory message that will be used to update the // SimulationWorld object. ADCTrajectory planning_trajectory; for (int i = 0; i < 30; ++i) { TrajectoryPoint* point = planning_trajectory.add_trajectory_point(); point->mutable_path_point()->set_x(i * 10); point->mutable_path_point()->set_y(i * 10 + 10); } // Commit the update. sim_world_service_->UpdatePlanningTrajectory(planning_trajectory); // Check the update result. const SimulationWorld& world = sim_world_service_->world(); EXPECT_EQ(29, world.planning_trajectory_size()); // Check first point. { const Object point = world.planning_trajectory(0); EXPECT_DOUBLE_EQ(0.0, point.position_x()); EXPECT_DOUBLE_EQ(10.0, point.position_y()); EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading()); } // Check last point. { const Object point = world.planning_trajectory(world.planning_trajectory_size() - 1); EXPECT_DOUBLE_EQ(280.0, point.position_x()); EXPECT_DOUBLE_EQ(290.0, point.position_y()); EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading()); } } TEST_F(SimulationWorldServiceTest, UpdateDecision) { DecisionResult decision_res; decision_res.mutable_vehicle_signal()->set_turn_signal( apollo::common::VehicleSignal::TURN_RIGHT); apollo::planning::MainDecision* main_decision = decision_res.mutable_main_decision(); main_decision->add_target_lane()->set_speed_limit(35); apollo::planning::MainStop* main_stop = main_decision->mutable_stop(); main_stop->mutable_stop_point()->set_x(45678.9); main_stop->mutable_stop_point()->set_y(1234567.8); main_stop->set_stop_heading(1.234); main_stop->set_reason_code( apollo::planning::StopReasonCode::STOP_REASON_CROSSWALK); apollo::planning::ObjectDecisions* obj_decisions = decision_res.mutable_object_decision(); // The 1st obstacle is from perception and has 2 decisions: nudge or sidepass. apollo::planning::ObjectDecision* obj_decision1 = obj_decisions->add_decision(); obj_decision1->set_perception_id(1); Object& perception1 = sim_world_service_->obj_map_["1"]; perception1.set_type(Object_Type_UNKNOWN_UNMOVABLE); perception1.set_id("1"); perception1.set_position_x(1.0); perception1.set_position_y(2.0); perception1.set_heading(3.0); perception1.set_length(4.0); perception1.set_width(5.0); perception1.set_height(6.0); for (int i = 0; i < 3; ++i) { PolygonPoint* perception_pt = perception1.add_polygon_point(); if (i < 2) { perception_pt->set_x(10.0 * (i + 1)); perception_pt->set_y(20.0 * (i + 1)); } else { perception_pt->set_y(10.0 * (i + 1)); perception_pt->set_x(20.0 * (i + 1)); } } obj_decision1->add_object_decision()->mutable_nudge()->set_distance_l(1.8); obj_decision1->add_object_decision()->mutable_sidepass(); // The 2nd obstacle is virtual and has only 1 decision: yield. apollo::planning::ObjectDecision* obj_decision2 = obj_decisions->add_decision(); obj_decision2->set_perception_id(2); apollo::planning::ObjectYield* yield = obj_decision2->add_object_decision()->mutable_yield(); apollo::common::PointENU* fence_point = yield->mutable_fence_point(); fence_point->set_x(-1859.98); fence_point->set_y(-3000.03); yield->set_fence_heading(1.3); sim_world_service_->UpdateDecision(decision_res, 1501095053); const SimulationWorld& world = sim_world_service_->world(); EXPECT_EQ("RIGHT", world.auto_driving_car().current_signal()); EXPECT_EQ(35, world.speed_limit()); const Object& world_main_stop = world.main_decision(); EXPECT_EQ(1, world_main_stop.decision_size()); EXPECT_EQ(Decision::STOP_REASON_CROSSWALK, world_main_stop.decision(0).stopreason()); EXPECT_DOUBLE_EQ(45678.9, world_main_stop.position_x()); EXPECT_DOUBLE_EQ(1234567.8, world_main_stop.position_y()); EXPECT_DOUBLE_EQ(1.234, world_main_stop.heading()); sim_world_service_->world_.clear_object(); for (auto& kv : sim_world_service_->obj_map_) { *sim_world_service_->world_.add_object() = kv.second; } EXPECT_EQ(2, world.object_size()); for (int i = 0; i < 2; ++i) { const Object& obj_dec = world.object(i); if (obj_dec.id() == "1") { EXPECT_EQ(Object_Type_UNKNOWN_UNMOVABLE, obj_dec.type()); EXPECT_DOUBLE_EQ(1.0, obj_dec.position_x()); EXPECT_DOUBLE_EQ(2.0, obj_dec.position_y()); EXPECT_DOUBLE_EQ(3.0, obj_dec.heading()); EXPECT_DOUBLE_EQ(4.0, obj_dec.length()); EXPECT_DOUBLE_EQ(5.0, obj_dec.width()); EXPECT_DOUBLE_EQ(6.0, obj_dec.height()); EXPECT_EQ(obj_dec.decision_size(), 2); for (int j = 0; j < obj_dec.decision_size(); ++j) { const Decision& decision = obj_dec.decision(j); if (j == 0) { EXPECT_EQ(decision.type(), Decision_Type_NUDGE); EXPECT_EQ(decision.polygon_point_size(), 67); } else { EXPECT_EQ(decision.type(), Decision_Type_SIDEPASS); } } } else { EXPECT_EQ(Object_Type_VIRTUAL, obj_dec.type()); EXPECT_EQ(1, obj_dec.decision_size()); const Decision& decision = obj_dec.decision(0); EXPECT_EQ(Decision_Type_YIELD, decision.type()); EXPECT_DOUBLE_EQ(-1859.98, decision.position_x()); EXPECT_DOUBLE_EQ(-3000.03, decision.position_y()); EXPECT_DOUBLE_EQ(1.3, decision.heading()); } } } TEST_F(SimulationWorldServiceTest, UpdatePrediction) { // Update with prediction obstacles PredictionObstacles prediction_obstacles; for (int i = 0; i < 3; ++i) { auto* obstacle = prediction_obstacles.add_prediction_obstacle(); auto* perception_obstacle = obstacle->mutable_perception_obstacle(); perception_obstacle->set_id(i); for (int j = 0; j < 5; ++j) { auto* traj = obstacle->add_trajectory(); traj->set_probability(i * 0.1 + j); for (int k = 0; k < 8; ++k) { auto* traj_pt = traj->add_trajectory_point()->mutable_path_point(); int pt = j * 10 + k; traj_pt->set_x(pt); traj_pt->set_y(pt); traj_pt->set_z(pt); } } obstacle->set_timestamp(123.456); } sim_world_service_->UpdateSimulationWorld(prediction_obstacles); sim_world_service_->world_.clear_object(); for (auto& kv : sim_world_service_->obj_map_) { *sim_world_service_->world_.add_object() = kv.second; } // Verify const auto& sim_world = sim_world_service_->world(); EXPECT_EQ(3, sim_world.object_size()); for (int i = 0; i < sim_world.object_size(); ++i) { const Object& obj = sim_world.object(i); EXPECT_EQ(5, obj.prediction_size()); for (int j = 0; j < obj.prediction_size(); ++j) { const Prediction& prediction = obj.prediction(j); EXPECT_NEAR((sim_world.object_size() - i - 1) * 0.1 + j, prediction.probability(), kEpsilon); EXPECT_EQ(prediction.predicted_trajectory_size(), 2); // Downsampled } EXPECT_NEAR(123.456, obj.timestamp_sec(), kEpsilon); } } TEST_F(SimulationWorldServiceTest, UpdateRouting) { // Load routing from file sim_world_service_.reset( new SimulationWorldService(map_service_.get(), true)); sim_world_service_->UpdateSimulationWorld( *AdapterManager::GetRoutingResponse()->GetLatestPublished()); auto& world = sim_world_service_->world_; EXPECT_EQ(world.routing_time(), 1234.5); EXPECT_EQ(1, world.route_path_size()); double points[23][2] = { {-1826.41, -3027.52}, {-1839.88, -3023.9}, {-1851.95, -3020.71}, {-1857.06, -3018.62}, {-1858.04, -3017.94}, {-1859.56, -3016.51}, {-1860.48, -3014.95}, {-1861.12, -3013.2}, {-1861.62, -3010.06}, {-1861.29, -3005.88}, {-1859.8, -2999.36}, {-1855.8, -2984.56}, {-1851.39, -2968.23}, {-1844.32, -2943.14}, {-1842.9, -2939.22}, {-1841.74, -2937.09}, {-1839.35, -2934.03}, {-1837.76, -2932.88}, {-1835.53, -2931.86}, {-1833.36, -2931.52}, {-1831.33, -2931.67}, {-1827.05, -2932.6}, {-1809.64, -2937.85}}; const auto& path = world.route_path(0); EXPECT_EQ(23, path.point_size()); for (int i = 0; i < path.point_size(); ++i) { EXPECT_NEAR(path.point(i).x(), points[i][0], kEpsilon); EXPECT_NEAR(path.point(i).y(), points[i][1], kEpsilon); } } } // namespace dreamview } // namespace apollo
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ /////////////////////////////////////////////////////////////////////////////// // // // TRD MCM (Multi Chip Module) simulator // // which simulates the TRAP processing after the AD-conversion. // // The relevant parameters (i.e. configuration settings of the TRAP) // // are taken from AliTRDtrapConfig. // // // /////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <iomanip> #include "TCanvas.h" #include "TH1F.h" #include "TH2F.h" #include "TGraph.h" #include "TLine.h" #include "TRandom.h" #include "TClonesArray.h" #include "TMath.h" #include "AliLog.h" #include "AliRunLoader.h" #include "AliLoader.h" #include "AliTRDfeeParam.h" #include "AliTRDtrapConfig.h" #include "AliTRDdigitsManager.h" #include "AliTRDarrayADC.h" #include "AliTRDarrayDictionary.h" #include "AliTRDtrackletMCM.h" #include "AliTRDmcmSim.h" ClassImp(AliTRDmcmSim) Bool_t AliTRDmcmSim::fgApplyCut = kTRUE; Int_t AliTRDmcmSim::fgAddBaseline = 0; const Int_t AliTRDmcmSim::fgkFormatIndex = std::ios_base::xalloc(); const Int_t AliTRDmcmSim::fgkNADC = AliTRDfeeParam::GetNadcMcm(); const UShort_t AliTRDmcmSim::fgkFPshifts[4] = {11, 14, 17, 21}; AliTRDmcmSim::AliTRDmcmSim() : TObject(), fInitialized(kFALSE), fDetector(-1), fRobPos(-1), fMcmPos(-1), fRow (-1), fNTimeBin(-1), fADCR(NULL), fADCF(NULL), fMCMT(NULL), fTrackletArray(NULL), fZSMap(NULL), fTrklBranchName("mcmtrklbranch"), fFeeParam(NULL), fTrapConfig(NULL), fDigitsManager(NULL), fPedAcc(NULL), fGainCounterA(NULL), fGainCounterB(NULL), fTailAmplLong(NULL), fTailAmplShort(NULL), fNHits(0), fFitReg(NULL) { // // AliTRDmcmSim default constructor // By default, nothing is initialized. // It is necessary to issue Init before use. for (Int_t iDict = 0; iDict < 3; iDict++) fDict[iDict] = 0x0; fFitPtr[0] = 0; fFitPtr[1] = 0; fFitPtr[2] = 0; fFitPtr[3] = 0; } AliTRDmcmSim::~AliTRDmcmSim() { // // AliTRDmcmSim destructor // if(fInitialized) { for( Int_t iAdc = 0 ; iAdc < fgkNADC; iAdc++ ) { delete [] fADCR[iAdc]; delete [] fADCF[iAdc]; } delete [] fADCR; delete [] fADCF; delete [] fZSMap; delete [] fMCMT; delete [] fPedAcc; delete [] fGainCounterA; delete [] fGainCounterB; delete [] fTailAmplLong; delete [] fTailAmplShort; delete [] fFitReg; fTrackletArray->Delete(); delete fTrackletArray; } } void AliTRDmcmSim::Init( Int_t det, Int_t robPos, Int_t mcmPos, Bool_t /* newEvent */ ) { // // Initialize the class with new MCM position information // memory is allocated in the first initialization // if (!fInitialized) { fFeeParam = AliTRDfeeParam::Instance(); fTrapConfig = AliTRDtrapConfig::Instance(); } fDetector = det; fRobPos = robPos; fMcmPos = mcmPos; fNTimeBin = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kC13CPUA); fRow = fFeeParam->GetPadRowFromMCM( fRobPos, fMcmPos ); if (!fInitialized) { fADCR = new Int_t *[fgkNADC]; fADCF = new Int_t *[fgkNADC]; fZSMap = new Int_t [fgkNADC]; fGainCounterA = new UInt_t[fgkNADC]; fGainCounterB = new UInt_t[fgkNADC]; for( Int_t iAdc = 0 ; iAdc < fgkNADC; iAdc++ ) { fADCR[iAdc] = new Int_t[fNTimeBin]; fADCF[iAdc] = new Int_t[fNTimeBin]; } // filter registers fPedAcc = new UInt_t[fgkNADC]; // accumulator for pedestal filter fTailAmplLong = new UShort_t[fgkNADC]; fTailAmplShort = new UShort_t[fgkNADC]; // tracklet calculation fFitReg = new FitReg_t[fgkNADC]; fTrackletArray = new TClonesArray("AliTRDtrackletMCM", fgkMaxTracklets); fMCMT = new UInt_t[fgkMaxTracklets]; } fInitialized = kTRUE; Reset(); } void AliTRDmcmSim::Reset() { // Resets the data values and internal filter registers // by re-initialising them if( !CheckInitialized() ) return; for( Int_t iAdc = 0 ; iAdc < fgkNADC; iAdc++ ) { for( Int_t it = 0 ; it < fNTimeBin ; it++ ) { fADCR[iAdc][it] = 0; fADCF[iAdc][it] = 0; } fZSMap[iAdc] = -1; // Default unread, low active bit mask fGainCounterA[iAdc] = 0; fGainCounterB[iAdc] = 0; } for(Int_t i = 0; i < fgkMaxTracklets; i++) { fMCMT[i] = 0; } for (Int_t iDict = 0; iDict < 3; iDict++) fDict[iDict] = 0x0; FilterPedestalInit(); FilterGainInit(); FilterTailInit(); } void AliTRDmcmSim::SetNTimebins(Int_t ntimebins) { // Reallocate memory if a change in the number of timebins // is needed (should not be the case for real data) if( !CheckInitialized() ) return; fNTimeBin = ntimebins; for( Int_t iAdc = 0 ; iAdc < fgkNADC; iAdc++ ) { delete fADCR[iAdc]; delete fADCF[iAdc]; fADCR[iAdc] = new Int_t[fNTimeBin]; fADCF[iAdc] = new Int_t[fNTimeBin]; } } Bool_t AliTRDmcmSim::LoadMCM(AliRunLoader* const runloader, Int_t det, Int_t rob, Int_t mcm) { // loads the ADC data as obtained from the digitsManager for the specified MCM. // This method is meant for rare execution, e.g. in the visualization. When called // frequently use SetData(...) instead. Init(det, rob, mcm); if (!runloader) { AliError("No Runloader given"); return kFALSE; } AliLoader *trdLoader = runloader->GetLoader("TRDLoader"); if (!trdLoader) { AliError("Could not get TRDLoader"); return kFALSE; } Bool_t retval = kTRUE; trdLoader->LoadDigits(); fDigitsManager = 0x0; AliTRDdigitsManager *digMgr = new AliTRDdigitsManager(); digMgr->SetSDigits(0); digMgr->CreateArrays(); digMgr->ReadDigits(trdLoader->TreeD()); AliTRDarrayADC *digits = (AliTRDarrayADC*) digMgr->GetDigits(det); if (digits->HasData()) { digits->Expand(); if (fNTimeBin != digits->GetNtime()) { AliWarning(Form("Changing no. of timebins from %i to %i", fNTimeBin, digits->GetNtime())); SetNTimebins(digits->GetNtime()); } SetData(digits); } else retval = kFALSE; delete digMgr; return retval; } void AliTRDmcmSim::NoiseTest(Int_t nsamples, Int_t mean, Int_t sigma, Int_t inputGain, Int_t inputTail) { // This function can be used to test the filters. // It feeds nsamples of ADC values with a gaussian distribution specified by mean and sigma. // The filter chain implemented here consists of: // Pedestal -> Gain -> Tail // With inputGain and inputTail the input to the gain and tail filter, respectively, // can be chosen where // 0: noise input // 1: pedestal output // 2: gain output // The input has to be chosen from a stage before. // The filter behaviour is controlled by the TRAP parameters from AliTRDtrapConfig in the // same way as in normal simulation. // The functions produces four histograms with the values at the different stages. if( !CheckInitialized() ) return; TString nameInputGain; TString nameInputTail; switch (inputGain) { case 0: nameInputGain = "Noise"; break; case 1: nameInputGain = "Pedestal"; break; default: AliError("Undefined input to tail cancellation filter"); return; } switch (inputTail) { case 0: nameInputTail = "Noise"; break; case 1: nameInputTail = "Pedestal"; break; case 2: nameInputTail = "Gain"; break; default: AliError("Undefined input to tail cancellation filter"); return; } TH1F *h = new TH1F("noise", "Gaussian Noise;sample;ADC count", nsamples, 0, nsamples); TH1F *hfp = new TH1F("ped", "Noise #rightarrow Pedestal filter;sample;ADC count", nsamples, 0, nsamples); TH1F *hfg = new TH1F("gain", (nameInputGain + "#rightarrow Gain;sample;ADC count").Data(), nsamples, 0, nsamples); TH1F *hft = new TH1F("tail", (nameInputTail + "#rightarrow Tail;sample;ADC count").Data(), nsamples, 0, nsamples); h->SetStats(kFALSE); hfp->SetStats(kFALSE); hfg->SetStats(kFALSE); hft->SetStats(kFALSE); Int_t value; // ADC count with noise (10 bit) Int_t valuep; // pedestal filter output (12 bit) Int_t valueg; // gain filter output (12 bit) Int_t valuet; // tail filter value (12 bit) for (Int_t i = 0; i < nsamples; i++) { value = (Int_t) gRandom->Gaus(mean, sigma); // generate noise with gaussian distribution h->SetBinContent(i, value); valuep = FilterPedestalNextSample(1, 0, ((Int_t) value) << 2); if (inputGain == 0) valueg = FilterGainNextSample(1, ((Int_t) value) << 2); else valueg = FilterGainNextSample(1, valuep); if (inputTail == 0) valuet = FilterTailNextSample(1, ((Int_t) value) << 2); else if (inputTail == 1) valuet = FilterTailNextSample(1, valuep); else valuet = FilterTailNextSample(1, valueg); hfp->SetBinContent(i, valuep >> 2); hfg->SetBinContent(i, valueg >> 2); hft->SetBinContent(i, valuet >> 2); } TCanvas *c = new TCanvas; c->Divide(2,2); c->cd(1); h->Draw(); c->cd(2); hfp->Draw(); c->cd(3); hfg->Draw(); c->cd(4); hft->Draw(); } Bool_t AliTRDmcmSim::CheckInitialized() const { // // Check whether object is initialized // if( ! fInitialized ) AliError(Form ("AliTRDmcmSim is not initialized but function other than Init() is called.")); return fInitialized; } void AliTRDmcmSim::Print(Option_t* const option) const { // Prints the data stored and/or calculated for this MCM. // The output is controlled by option which can be a sequence of any of // the following characters: // R - prints raw ADC data // F - prints filtered data // H - prints detected hits // T - prints found tracklets // The later stages are only meaningful after the corresponding calculations // have been performed. if ( !CheckInitialized() ) return; printf("MCM %i on ROB %i in detector %i\n", fMcmPos, fRobPos, fDetector); TString opt = option; if (opt.Contains("R") || opt.Contains("F")) { std::cout << *this; } if (opt.Contains("H")) { printf("Found %i hits:\n", fNHits); for (Int_t iHit = 0; iHit < fNHits; iHit++) { printf("Hit %3i in timebin %2i, ADC %2i has charge %3i and position %3i\n", iHit, fHits[iHit].fTimebin, fHits[iHit].fChannel, fHits[iHit].fQtot, fHits[iHit].fYpos); } } if (opt.Contains("T")) { printf("Tracklets:\n"); for (Int_t iTrkl = 0; iTrkl < fTrackletArray->GetEntriesFast(); iTrkl++) { printf("tracklet %i: 0x%08x\n", iTrkl, ((AliTRDtrackletMCM*) (*fTrackletArray)[iTrkl])->GetTrackletWord()); } } } void AliTRDmcmSim::Draw(Option_t* const option) { // Plots the data stored in a 2-dim. timebin vs. ADC channel plot. // The option selects what data is plotted and can be a sequence of // the following characters: // R - plot raw data (default) // F - plot filtered data (meaningless if R is specified) // In addition to the ADC values: // H - plot hits // T - plot tracklets if( !CheckInitialized() ) return; TString opt = option; TH2F *hist = new TH2F("mcmdata", Form("Data of MCM %i on ROB %i in detector %i", \ fMcmPos, fRobPos, fDetector), \ fgkNADC, -0.5, fgkNADC-.5, fNTimeBin, -.5, fNTimeBin-.5); hist->GetXaxis()->SetTitle("ADC Channel"); hist->GetYaxis()->SetTitle("Timebin"); hist->SetStats(kFALSE); if (opt.Contains("R")) { for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { hist->SetBinContent(iAdc+1, iTimeBin+1, fADCR[iAdc][iTimeBin] >> fgkAddDigits); } } } else { for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { hist->SetBinContent(iAdc+1, iTimeBin+1, fADCF[iAdc][iTimeBin] >> fgkAddDigits); } } } hist->Draw("colz"); if (opt.Contains("H")) { TGraph *grHits = new TGraph(); for (Int_t iHit = 0; iHit < fNHits; iHit++) { grHits->SetPoint(iHit, fHits[iHit].fChannel + 1 + fHits[iHit].fYpos/256., fHits[iHit].fTimebin); } grHits->Draw("*"); } if (opt.Contains("T")) { TLine *trklLines = new TLine[4]; for (Int_t iTrkl = 0; iTrkl < fTrackletArray->GetEntries(); iTrkl++) { AliTRDtrackletMCM *trkl = (AliTRDtrackletMCM*) (*fTrackletArray)[iTrkl]; Float_t padWidth = 0.635 + 0.03 * (fDetector % 6); Float_t offset = padWidth/256. * ((((((fRobPos & 0x1) << 2) + (fMcmPos & 0x3)) * 18) << 8) - ((18*4*2 - 18*2 - 3) << 7)); // revert adding offset in FitTracklet Int_t ndrift = fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrNdrift, fDetector, fRobPos, fMcmPos) >> 5; Float_t slope = trkl->GetdY() * 140e-4 / ndrift; Int_t t0 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFS); Int_t t1 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFE); trklLines[iTrkl].SetX1((offset - (trkl->GetY() - slope * t0)) / padWidth); // ??? sign? trklLines[iTrkl].SetY1(t0); trklLines[iTrkl].SetX2((offset - (trkl->GetY() - slope * t1)) / padWidth); // ??? sign? trklLines[iTrkl].SetY2(t1); trklLines[iTrkl].SetLineColor(2); trklLines[iTrkl].SetLineWidth(2); printf("Tracklet %i: y = %f, dy = %f, offset = %f\n", iTrkl, trkl->GetY(), (trkl->GetdY() * 140e-4), offset); trklLines[iTrkl].Draw(); } } } void AliTRDmcmSim::SetData( Int_t adc, Int_t* const data ) { // // Store ADC data into array of raw data // if( !CheckInitialized() ) return; if( adc < 0 || adc >= fgkNADC ) { AliError(Form ("Error: ADC %i is out of range (0 .. %d).", adc, fgkNADC-1)); return; } for( Int_t it = 0 ; it < fNTimeBin ; it++ ) { fADCR[adc][it] = (Int_t) (data[it]) << fgkAddDigits; fADCF[adc][it] = (Int_t) (data[it]) << fgkAddDigits; } } void AliTRDmcmSim::SetData( Int_t adc, Int_t it, Int_t data ) { // // Store ADC data into array of raw data // if( !CheckInitialized() ) return; if( adc < 0 || adc >= fgkNADC ) { AliError(Form ("Error: ADC %i is out of range (0 .. %d).", adc, fgkNADC-1)); return; } fADCR[adc][it] = data << fgkAddDigits; fADCF[adc][it] = data << fgkAddDigits; } void AliTRDmcmSim::SetData(AliTRDarrayADC* const adcArray, AliTRDdigitsManager * const digitsManager) { // Set the ADC data from an AliTRDarrayADC if( !CheckInitialized() ) return; fDigitsManager = digitsManager; if (fDigitsManager) { for (Int_t iDict = 0; iDict < 3; iDict++) { AliTRDarrayDictionary *newDict = (AliTRDarrayDictionary*) fDigitsManager->GetDictionary(fDetector, iDict); if (fDict[iDict] != 0x0 && newDict != 0x0) { if (fDict[iDict] == newDict) continue; fDict[iDict] = newDict; if (fDict[iDict]->GetDim() == 0) { AliError(Form("Dictionary %i of det. %i has dim. 0", fDetector, iDict)); continue; } fDict[iDict]->Expand(); } else { fDict[iDict] = newDict; if (fDict[iDict]) fDict[iDict]->Expand(); } } } if (fNTimeBin != adcArray->GetNtime()) SetNTimebins(adcArray->GetNtime()); Int_t offset = (fMcmPos % 4 + 1) * 21 + (fRobPos % 2) * 84 - 1; for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { Int_t value = adcArray->GetDataByAdcCol(GetRow(), offset - iAdc, iTimeBin); if (value < 0 || (offset - iAdc < 1) || (offset - iAdc > 165)) { fADCR[iAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP) + (fgAddBaseline << fgkAddDigits); fADCF[iAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits); } else { fZSMap[iAdc] = 0; fADCR[iAdc][iTimeBin] = (value << fgkAddDigits) + (fgAddBaseline << fgkAddDigits); fADCF[iAdc][iTimeBin] = (value << fgkAddDigits) + (fgAddBaseline << fgkAddDigits); } } } } void AliTRDmcmSim::SetDataByPad(AliTRDarrayADC* const adcArray, AliTRDdigitsManager * const digitsManager) { // Set the ADC data from an AliTRDarrayADC // (by pad, to be used during initial reading in simulation) if( !CheckInitialized() ) return; fDigitsManager = digitsManager; if (fDigitsManager) { for (Int_t iDict = 0; iDict < 3; iDict++) { AliTRDarrayDictionary *newDict = (AliTRDarrayDictionary*) fDigitsManager->GetDictionary(fDetector, iDict); if (fDict[iDict] != 0x0 && newDict != 0x0) { if (fDict[iDict] == newDict) continue; fDict[iDict] = newDict; if (fDict[iDict]->GetDim() == 0) { AliError(Form("Dictionary %i of det. %i has dim. 0", fDetector, iDict)); continue; } fDict[iDict]->Expand(); } else { fDict[iDict] = newDict; if (fDict[iDict]) fDict[iDict]->Expand(); } } } if (fNTimeBin != adcArray->GetNtime()) SetNTimebins(adcArray->GetNtime()); Int_t offset = (fMcmPos % 4 + 1) * 18 + (fRobPos % 2) * 72 + 1; for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { Int_t value = -1; Int_t pad = offset - iAdc; if (pad > -1 && pad < 144) value = adcArray->GetData(GetRow(), offset - iAdc, iTimeBin); // Int_t value = adcArray->GetDataByAdcCol(GetRow(), offset - iAdc, iTimeBin); if (value < 0 || (offset - iAdc < 1) || (offset - iAdc > 165)) { fADCR[iAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP) + (fgAddBaseline << fgkAddDigits); fADCF[iAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits); } else { fZSMap[iAdc] = 0; fADCR[iAdc][iTimeBin] = (value << fgkAddDigits) + (fgAddBaseline << fgkAddDigits); fADCF[iAdc][iTimeBin] = (value << fgkAddDigits) + (fgAddBaseline << fgkAddDigits); } } } } void AliTRDmcmSim::SetDataPedestal( Int_t adc ) { // // Store ADC data into array of raw data // if( !CheckInitialized() ) return; if( adc < 0 || adc >= fgkNADC ) { return; } for( Int_t it = 0 ; it < fNTimeBin ; it++ ) { fADCR[adc][it] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP) + (fgAddBaseline << fgkAddDigits); fADCF[adc][it] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits); } } Bool_t AliTRDmcmSim::GetHit(Int_t index, Int_t &channel, Int_t &timebin, Int_t &qtot, Int_t &ypos, Float_t &y, Int_t &label) const { // retrieve the MC hit information (not available in TRAP hardware) if (index < 0 || index >= fNHits) return kFALSE; channel = fHits[index].fChannel; timebin = fHits[index].fTimebin; qtot = fHits[index].fQtot; ypos = fHits[index].fYpos; y = (Float_t) ((((((fRobPos & 0x1) << 2) + (fMcmPos & 0x3)) * 18) << 8) - ((18*4*2 - 18*2 - 1) << 7) - (channel << 8) - ypos) * (0.635 + 0.03 * (fDetector % 6)) / 256.0; label = fHits[index].fLabel[0]; return kTRUE; } Int_t AliTRDmcmSim::GetCol( Int_t adc ) { // // Return column id of the pad for the given ADC channel // if( !CheckInitialized() ) return -1; Int_t col = fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, adc); if (col < 0 || col >= fFeeParam->GetNcol()) return -1; else return col; } Int_t AliTRDmcmSim::ProduceRawStream( UInt_t *buf, Int_t bufSize, UInt_t iEv) const { // // Produce raw data stream from this MCM and put in buf // Returns number of words filled, or negative value // with -1 * number of overflowed words // if( !CheckInitialized() ) return 0; UInt_t x; UInt_t mcmHeader = 0; UInt_t adcMask = 0; Int_t nw = 0; // Number of written words Int_t of = 0; // Number of overflowed words Int_t rawVer = fFeeParam->GetRAWversion(); Int_t **adc; Int_t nActiveADC = 0; // number of activated ADC bits in a word if( !CheckInitialized() ) return 0; if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBSF) != 0) // store unfiltered data adc = fADCR; else adc = fADCF; // Produce ADC mask : nncc cccm mmmm mmmm mmmm mmmm mmmm 1100 // n : unused , c : ADC count, m : selected ADCs if( rawVer >= 3 && (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kC15CPUA) & (1 << 13))) { // check for zs flag in TRAP configuration for( Int_t iAdc = 0 ; iAdc < fgkNADC ; iAdc++ ) { if( ~fZSMap[iAdc] != 0 ) { // 0 means not suppressed adcMask |= (1 << (iAdc+4) ); // last 4 digit reserved for 1100=0xc nActiveADC++; // number of 1 in mmm....m } } if ((nActiveADC == 0) && (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kC15CPUA) & (1 << 8))) // check for DEH flag in TRAP configuration return 0; // assemble adc mask word adcMask |= (1 << 30) | ( ( 0x3FFFFFFC ) & (~(nActiveADC) << 25) ) | 0xC; // nn = 01, ccccc are inverted, 0xc=1100 } // MCM header mcmHeader = (1<<31) | (fRobPos << 28) | (fMcmPos << 24) | ((iEv % 0x100000) << 4) | 0xC; if (nw < bufSize) buf[nw++] = mcmHeader; else of++; // ADC mask if( adcMask != 0 ) { if (nw < bufSize) buf[nw++] = adcMask; else of++; } // Produce ADC data. 3 timebins are packed into one 32 bits word // In this version, different ADC channel will NOT share the same word UInt_t aa=0, a1=0, a2=0, a3=0; for (Int_t iAdc = 0; iAdc < 21; iAdc++ ) { if( rawVer>= 3 && ~fZSMap[iAdc] == 0 ) continue; // Zero Suppression, 0 means not suppressed aa = !(iAdc & 1) + 2; for (Int_t iT = 0; iT < fNTimeBin; iT+=3 ) { a1 = ((iT ) < fNTimeBin ) ? adc[iAdc][iT ] >> fgkAddDigits : 0; a2 = ((iT + 1) < fNTimeBin ) ? adc[iAdc][iT+1] >> fgkAddDigits : 0; a3 = ((iT + 2) < fNTimeBin ) ? adc[iAdc][iT+2] >> fgkAddDigits : 0; x = (a3 << 22) | (a2 << 12) | (a1 << 2) | aa; if (nw < bufSize) { buf[nw++] = x; } else { of++; } } } if( of != 0 ) return -of; else return nw; } Int_t AliTRDmcmSim::ProduceTrackletStream( UInt_t *buf, Int_t bufSize ) { // // Produce tracklet data stream from this MCM and put in buf // Returns number of words filled, or negative value // with -1 * number of overflowed words // if( !CheckInitialized() ) return 0; Int_t nw = 0; // Number of written words Int_t of = 0; // Number of overflowed words // Produce tracklet data. A maximum of four 32 Bit words will be written per MCM // fMCMT is filled continuously until no more tracklet words available for (Int_t iTracklet = 0; iTracklet < fTrackletArray->GetEntriesFast(); iTracklet++) { if (nw < bufSize) buf[nw++] = ((AliTRDtrackletMCM*) (*fTrackletArray)[iTracklet])->GetTrackletWord(); else of++; } if( of != 0 ) return -of; else return nw; } void AliTRDmcmSim::Filter() { // // Filter the raw ADC values. The active filter stages and their // parameters are taken from AliTRDtrapConfig. // The raw data is stored separate from the filtered data. Thus, // it is possible to run the filters on a set of raw values // sequentially for parameter tuning. // if( !CheckInitialized() ) return; // Apply filters sequentially. Bypass is handled by filters // since counters and internal registers may be updated even // if the filter is bypassed. // The first filter takes the data from fADCR and // outputs to fADCF. // Non-linearity filter not implemented. FilterPedestal(); FilterGain(); FilterTail(); // Crosstalk filter not implemented. } void AliTRDmcmSim::FilterPedestalInit(Int_t baseline) { // Initializes the pedestal filter assuming that the input has // been constant for a long time (compared to the time constant). UShort_t fptc = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPTC); // 0..3, 0 - fastest, 3 - slowest for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) fPedAcc[iAdc] = (baseline << 2) * (1 << fgkFPshifts[fptc]); } UShort_t AliTRDmcmSim::FilterPedestalNextSample(Int_t adc, Int_t timebin, UShort_t value) { // Returns the output of the pedestal filter given the input value. // The output depends on the internal registers and, thus, the // history of the filter. UShort_t fpnp = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP); // 0..511 -> 0..127.75, pedestal at the output UShort_t fptc = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPTC); // 0..3, 0 - fastest, 3 - slowest UShort_t fpby = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPBY); // 0..1 bypass, active low UShort_t accumulatorShifted; Int_t correction; UShort_t inpAdd; inpAdd = value + fpnp; accumulatorShifted = (fPedAcc[adc] >> fgkFPshifts[fptc]) & 0x3FF; // 10 bits if (timebin == 0) // the accumulator is disabled in the drift time { correction = (value & 0x3FF) - accumulatorShifted; fPedAcc[adc] = (fPedAcc[adc] + correction) & 0x7FFFFFFF; // 31 bits } if (fpby == 0) return value; if (inpAdd <= accumulatorShifted) return 0; else { inpAdd = inpAdd - accumulatorShifted; if (inpAdd > 0xFFF) return 0xFFF; else return inpAdd; } } void AliTRDmcmSim::FilterPedestal() { // // Apply pedestal filter // // As the first filter in the chain it reads data from fADCR // and outputs to fADCF. // It has only an effect if previous samples have been fed to // find the pedestal. Currently, the simulation assumes that // the input has been stable for a sufficiently long time. for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { fADCF[iAdc][iTimeBin] = FilterPedestalNextSample(iAdc, iTimeBin, fADCR[iAdc][iTimeBin]); } } } void AliTRDmcmSim::FilterGainInit() { // Initializes the gain filter. In this case, only threshold // counters are reset. for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { // these are counters which in hardware continue // until maximum or reset fGainCounterA[iAdc] = 0; fGainCounterB[iAdc] = 0; } } UShort_t AliTRDmcmSim::FilterGainNextSample(Int_t adc, UShort_t value) { // Apply the gain filter to the given value. // BEGIN_LATEX O_{i}(t) = #gamma_{i} * I_{i}(t) + a_{i} END_LATEX // The output depends on the internal registers and, thus, the // history of the filter. UShort_t fgby = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFGBY); // bypass, active low UShort_t fgf = fTrapConfig->GetTrapReg(AliTRDtrapConfig::TrapReg_t(AliTRDtrapConfig::kFGF0 + adc)); // 0x700 + (0 & 0x1ff); UShort_t fga = fTrapConfig->GetTrapReg(AliTRDtrapConfig::TrapReg_t(AliTRDtrapConfig::kFGA0 + adc)); // 40; UShort_t fgta = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFGTA); // 20; UShort_t fgtb = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFGTB); // 2060; UInt_t corr; // corrected value value &= 0xFFF; corr = (value * fgf) >> 11; corr = corr > 0xfff ? 0xfff : corr; corr = AddUintClipping(corr, fga, 12); // Update threshold counters // not really useful as they are cleared with every new event if (!((fGainCounterA[adc] == 0x3FFFFFF) || (fGainCounterB[adc] == 0x3FFFFFF))) // stop when full { if (corr >= fgtb) fGainCounterB[adc]++; else if (corr >= fgta) fGainCounterA[adc]++; } if (fgby == 1) return corr; else return value; } void AliTRDmcmSim::FilterGain() { // Read data from fADCF and apply gain filter. for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { fADCF[iAdc][iTimeBin] = FilterGainNextSample(iAdc, fADCF[iAdc][iTimeBin]); } } } void AliTRDmcmSim::FilterTailInit(Int_t baseline) { // Initializes the tail filter assuming that the input has // been at the baseline value (configured by FTFP) for a // sufficiently long time. // exponents and weight calculated from configuration UShort_t alphaLong = 0x3ff & fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTAL); // the weight of the long component UShort_t lambdaLong = (1 << 10) | (1 << 9) | (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTLL) & 0x1FF); // the multiplier UShort_t lambdaShort = (0 << 10) | (1 << 9) | (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTLS) & 0x1FF); // the multiplier Float_t lambdaL = lambdaLong * 1.0 / (1 << 11); Float_t lambdaS = lambdaShort * 1.0 / (1 << 11); Float_t alphaL = alphaLong * 1.0 / (1 << 11); Float_t qup, qdn; qup = (1 - lambdaL) * (1 - lambdaS); qdn = 1 - lambdaS * alphaL - lambdaL * (1 - alphaL); Float_t kdc = qup/qdn; Float_t kt, ql, qs; UShort_t aout; if (baseline < 0) baseline = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP); ql = lambdaL * (1 - lambdaS) * alphaL; qs = lambdaS * (1 - lambdaL) * (1 - alphaL); for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { Int_t value = baseline & 0xFFF; Int_t corr = (value * fTrapConfig->GetTrapReg(AliTRDtrapConfig::TrapReg_t(AliTRDtrapConfig::kFGF0 + iAdc))) >> 11; corr = corr > 0xfff ? 0xfff : corr; corr = AddUintClipping(corr, fTrapConfig->GetTrapReg(AliTRDtrapConfig::TrapReg_t(AliTRDtrapConfig::kFGA0 + iAdc)), 12); kt = kdc * baseline; aout = baseline - (UShort_t) kt; fTailAmplLong[iAdc] = (UShort_t) (aout * ql / (ql + qs)); fTailAmplShort[iAdc] = (UShort_t) (aout * qs / (ql + qs)); } } UShort_t AliTRDmcmSim::FilterTailNextSample(Int_t adc, UShort_t value) { // Returns the output of the tail filter for the given input value. // The output depends on the internal registers and, thus, the // history of the filter. // exponents and weight calculated from configuration UShort_t alphaLong = 0x3ff & fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTAL); // the weight of the long component UShort_t lambdaLong = (1 << 10) | (1 << 9) | (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTLL) & 0x1FF); // the multiplier of the long component UShort_t lambdaShort = (0 << 10) | (1 << 9) | (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTLS) & 0x1FF); // the multiplier of the short component // intermediate signals UInt_t aDiff; UInt_t alInpv; UShort_t aQ; UInt_t tmp; UShort_t inpVolt = value & 0xFFF; // 12 bits // add the present generator outputs aQ = AddUintClipping(fTailAmplLong[adc], fTailAmplShort[adc], 12); // calculate the difference between the input and the generated signal if (inpVolt > aQ) aDiff = inpVolt - aQ; else aDiff = 0; // the inputs to the two generators, weighted alInpv = (aDiff * alphaLong) >> 11; // the new values of the registers, used next time // long component tmp = AddUintClipping(fTailAmplLong[adc], alInpv, 12); tmp = (tmp * lambdaLong) >> 11; fTailAmplLong[adc] = tmp & 0xFFF; // short component tmp = AddUintClipping(fTailAmplShort[adc], aDiff - alInpv, 12); tmp = (tmp * lambdaShort) >> 11; fTailAmplShort[adc] = tmp & 0xFFF; // the output of the filter if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTBY) == 0) // bypass mode, active low return value; else return aDiff; } void AliTRDmcmSim::FilterTail() { // Apply tail cancellation filter to all data. for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { fADCF[iAdc][iTimeBin] = FilterTailNextSample(iAdc, fADCF[iAdc][iTimeBin]); } } } void AliTRDmcmSim::ZSMapping() { // // Zero Suppression Mapping implemented in TRAP chip // only implemented for up to 30 timebins // // See detail TRAP manual "Data Indication" section: // http://www.kip.uni-heidelberg.de/ti/TRD/doc/trap/TRAP-UserManual.pdf // if( !CheckInitialized() ) return; Int_t eBIS = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBIS); Int_t eBIT = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBIT); Int_t eBIL = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBIL); Int_t eBIN = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBIN); Int_t **adc = fADCF; for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) fZSMap[iAdc] = -1; for( Int_t it = 0 ; it < fNTimeBin ; it++ ) { Int_t iAdc; // current ADC channel Int_t ap; Int_t ac; Int_t an; Int_t mask; Int_t supp; // suppression of the current channel (low active) // ----- first channel ----- iAdc = 0; ap = 0; // previous ac = adc[iAdc ][it]; // current an = adc[iAdc+1][it]; // next mask = ( ac >= ap && ac >= an ) ? 0 : 0x1; // peak center detection mask += ( ap + ac + an > eBIT ) ? 0 : 0x2; // cluster mask += ( ac > eBIS ) ? 0 : 0x4; // absolute large peak supp = (eBIL >> mask) & 1; fZSMap[iAdc] &= ~((1-supp) << it); if( eBIN == 0 ) { // neighbour sensitivity fZSMap[iAdc+1] &= ~((1-supp) << it); } // ----- last channel ----- iAdc = fgkNADC - 1; ap = adc[iAdc-1][it]; // previous ac = adc[iAdc ][it]; // current an = 0; // next mask = ( ac >= ap && ac >= an ) ? 0 : 0x1; // peak center detection mask += ( ap + ac + an > eBIT ) ? 0 : 0x2; // cluster mask += ( ac > eBIS ) ? 0 : 0x4; // absolute large peak supp = (eBIL >> mask) & 1; fZSMap[iAdc] &= ~((1-supp) << it); if( eBIN == 0 ) { // neighbour sensitivity fZSMap[iAdc-1] &= ~((1-supp) << it); } // ----- middle channels ----- for( iAdc = 1 ; iAdc < fgkNADC-1; iAdc++ ) { ap = adc[iAdc-1][it]; // previous ac = adc[iAdc ][it]; // current an = adc[iAdc+1][it]; // next mask = ( ac >= ap && ac >= an ) ? 0 : 0x1; // peak center detection mask += ( ap + ac + an > eBIT ) ? 0 : 0x2; // cluster mask += ( ac > eBIS ) ? 0 : 0x4; // absolute large peak supp = (eBIL >> mask) & 1; fZSMap[iAdc] &= ~((1-supp) << it); if( eBIN == 0 ) { // neighbour sensitivity fZSMap[iAdc-1] &= ~((1-supp) << it); fZSMap[iAdc+1] &= ~((1-supp) << it); } } } } void AliTRDmcmSim::AddHitToFitreg(Int_t adc, UShort_t timebin, UShort_t qtot, Short_t ypos, Int_t label[]) { // Add the given hit to the fit register which is lateron used for // the tracklet calculation. // In addition to the fit sums in the fit register MC information // is stored. if ((timebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS0)) && (timebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE0))) fFitReg[adc].fQ0 += qtot; if ((timebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS1)) && (timebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE1))) fFitReg[adc].fQ1 += qtot; if ((timebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFS) ) && (timebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFE))) { fFitReg[adc].fSumX += timebin; fFitReg[adc].fSumX2 += timebin*timebin; fFitReg[adc].fNhits++; fFitReg[adc].fSumY += ypos; fFitReg[adc].fSumY2 += ypos*ypos; fFitReg[adc].fSumXY += timebin*ypos; } // register hits (MC info) fHits[fNHits].fChannel = adc; fHits[fNHits].fQtot = qtot; fHits[fNHits].fYpos = ypos; fHits[fNHits].fTimebin = timebin; fHits[fNHits].fLabel[0] = label[0]; fHits[fNHits].fLabel[1] = label[1]; fHits[fNHits].fLabel[2] = label[2]; fNHits++; } void AliTRDmcmSim::CalcFitreg() { // Preprocessing. // Detect the hits and fill the fit registers. // Requires 12-bit data from fADCF which means Filter() // has to be called before even if all filters are bypassed. //??? to be clarified: UInt_t adcMask = 0xffffffff; UShort_t timebin, adcch, adcLeft, adcCentral, adcRight, hitQual, timebin1, timebin2, qtotTemp; Short_t ypos, fromLeft, fromRight, found; UShort_t qTotal[19+1]; // the last is dummy UShort_t marked[6], qMarked[6], worse1, worse2; timebin1 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFS); if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS0) < timebin1) timebin1 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS0); timebin2 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFE); if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE1) > timebin2) timebin2 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE1); // reset the fit registers fNHits = 0; for (adcch = 0; adcch < fgkNADC-2; adcch++) // due to border channels { fFitReg[adcch].fNhits = 0; fFitReg[adcch].fQ0 = 0; fFitReg[adcch].fQ1 = 0; fFitReg[adcch].fSumX = 0; fFitReg[adcch].fSumY = 0; fFitReg[adcch].fSumX2 = 0; fFitReg[adcch].fSumY2 = 0; fFitReg[adcch].fSumXY = 0; } for (timebin = timebin1; timebin < timebin2; timebin++) { // first find the hit candidates and store the total cluster charge in qTotal array // in case of not hit store 0 there. for (adcch = 0; adcch < fgkNADC-2; adcch++) { if ( ( (adcMask >> adcch) & 7) == 7) //??? all 3 channels are present in case of ZS { adcLeft = fADCF[adcch ][timebin]; adcCentral = fADCF[adcch+1][timebin]; adcRight = fADCF[adcch+2][timebin]; if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPVBY) == 1) hitQual = ( (adcLeft * adcRight) < (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPVT) * adcCentral) ); else hitQual = 1; // The accumulated charge is with the pedestal!!! qtotTemp = adcLeft + adcCentral + adcRight; if ( (hitQual) && (qtotTemp >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPHT)) && (adcLeft <= adcCentral) && (adcCentral > adcRight) ) qTotal[adcch] = qtotTemp; else qTotal[adcch] = 0; } else qTotal[adcch] = 0; //jkl if (qTotal[adcch] != 0) AliDebug(10,Form("ch %2d qTotal %5d",adcch, qTotal[adcch])); } fromLeft = -1; adcch = 0; found = 0; marked[4] = 19; // invalid channel marked[5] = 19; // invalid channel qTotal[19] = 0; while ((adcch < 16) && (found < 3)) { if (qTotal[adcch] > 0) { fromLeft = adcch; marked[2*found+1]=adcch; found++; } adcch++; } fromRight = -1; adcch = 18; found = 0; while ((adcch > 2) && (found < 3)) { if (qTotal[adcch] > 0) { marked[2*found]=adcch; found++; fromRight = adcch; } adcch--; } AliDebug(10,Form("Fromleft=%d, Fromright=%d",fromLeft, fromRight)); // here mask the hit candidates in the middle, if any if ((fromLeft >= 0) && (fromRight >= 0) && (fromLeft < fromRight)) for (adcch = fromLeft+1; adcch < fromRight; adcch++) qTotal[adcch] = 0; found = 0; for (adcch = 0; adcch < 19; adcch++) if (qTotal[adcch] > 0) found++; // NOT READY if (found > 4) // sorting like in the TRAP in case of 5 or 6 candidates! { if (marked[4] == marked[5]) marked[5] = 19; for (found=0; found<6; found++) { qMarked[found] = qTotal[marked[found]] >> 4; AliDebug(10,Form("ch_%d qTotal %d qTotals %d",marked[found],qTotal[marked[found]],qMarked[found])); } Sort6To2Worst(marked[0], marked[3], marked[4], marked[1], marked[2], marked[5], qMarked[0], qMarked[3], qMarked[4], qMarked[1], qMarked[2], qMarked[5], &worse1, &worse2); // Now mask the two channels with the smallest charge if (worse1 < 19) { qTotal[worse1] = 0; AliDebug(10,Form("Kill ch %d\n",worse1)); } if (worse2 < 19) { qTotal[worse2] = 0; AliDebug(10,Form("Kill ch %d\n",worse2)); } } for (adcch = 0; adcch < 19; adcch++) { if (qTotal[adcch] > 0) // the channel is marked for processing { adcLeft = fADCF[adcch ][timebin]; adcCentral = fADCF[adcch+1][timebin]; adcRight = fADCF[adcch+2][timebin]; // hit detected, in TRAP we have 4 units and a hit-selection, here we proceed all channels! // subtract the pedestal TPFP, clipping instead of wrapping Int_t regTPFP = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP); AliDebug(10, Form("Hit found, time=%d, adcch=%d/%d/%d, adc values=%d/%d/%d, regTPFP=%d, TPHT=%d\n", timebin, adcch, adcch+1, adcch+2, adcLeft, adcCentral, adcRight, regTPFP, fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPHT))); if (adcLeft < regTPFP) adcLeft = 0; else adcLeft -= regTPFP; if (adcCentral < regTPFP) adcCentral = 0; else adcCentral -= regTPFP; if (adcRight < regTPFP) adcRight = 0; else adcRight -= regTPFP; // Calculate the center of gravity // checking for adcCentral != 0 (in case of "bad" configuration) if (adcCentral == 0) continue; ypos = 128*(adcLeft - adcRight) / adcCentral; if (ypos < 0) ypos = -ypos; // make the correction using the position LUT ypos = ypos + fTrapConfig->GetTrapReg((AliTRDtrapConfig::TrapReg_t) (AliTRDtrapConfig::kTPL00 + (ypos & 0x7F)), fDetector, fRobPos, fMcmPos); if (adcLeft > adcRight) ypos = -ypos; // label calculation (up to 3) Int_t mcLabel[] = {-1, -1, -1}; if (fDigitsManager) { const Int_t maxLabels = 9; Int_t label[maxLabels] = { 0 }; // up to 9 different labels possible Int_t count[maxLabels] = { 0 }; Int_t nLabels = 0; Int_t padcol[3]; padcol[0] = fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, adcch); padcol[1] = fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, adcch+1); padcol[2] = fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, adcch+2); Int_t padrow = fFeeParam->GetPadRowFromMCM(fRobPos, fMcmPos); for (Int_t iDict = 0; iDict < 3; iDict++) { if (!fDict[iDict]) continue; for (Int_t iPad = 0; iPad < 3; iPad++) { if (padcol[iPad] < 0) continue; Int_t currLabel = fDict[iDict]->GetData(padrow, padcol[iPad], timebin); AliDebug(10, Form("Read label: %4i for det: %3i, row: %i, col: %i, tb: %i\n", currLabel, fDetector, padrow, padcol[iPad], timebin)); for (Int_t iLabel = 0; iLabel < nLabels; iLabel++) { if (currLabel == label[iLabel]) { count[iLabel]++; currLabel = -1; break; } } if (currLabel >= 0) { label[nLabels] = currLabel; count[nLabels] = 1; nLabels++; } } } Int_t index[2*maxLabels]; TMath::Sort(maxLabels, count, index); for (Int_t i = 0; i < 3; i++) { if (count[index[i]] <= 0) break; mcLabel[i] = label[index[i]]; } } // add the hit to the fitregister AddHitToFitreg(adcch, timebin, qTotal[adcch], ypos, mcLabel); } } } for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { if (fFitReg[iAdc].fNhits != 0) { AliDebug(2, Form("fitreg[%i]: nHits = %i, sumX = %i, sumY = %i, sumX2 = %i, sumY2 = %i, sumXY = %i", iAdc, fFitReg[iAdc].fNhits, fFitReg[iAdc].fSumX, fFitReg[iAdc].fSumY, fFitReg[iAdc].fSumX2, fFitReg[iAdc].fSumY2, fFitReg[iAdc].fSumXY )); } } } void AliTRDmcmSim::TrackletSelection() { // Select up to 4 tracklet candidates from the fit registers // and assign them to the CPUs. UShort_t adcIdx, i, j, ntracks, tmp; UShort_t trackletCand[18][2]; // store the adcch[0] and number of hits[1] for all tracklet candidates ntracks = 0; for (adcIdx = 0; adcIdx < 18; adcIdx++) // ADCs if ( (fFitReg[adcIdx].fNhits >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPCL)) && (fFitReg[adcIdx].fNhits+fFitReg[adcIdx+1].fNhits >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPCT))) { trackletCand[ntracks][0] = adcIdx; trackletCand[ntracks][1] = fFitReg[adcIdx].fNhits+fFitReg[adcIdx+1].fNhits; AliDebug(10,Form("%d %2d %4d\n", ntracks, trackletCand[ntracks][0], trackletCand[ntracks][1])); ntracks++; }; for (i=0; i<ntracks;i++) AliDebug(10,Form("%d %d %d\n",i,trackletCand[i][0], trackletCand[i][1])); if (ntracks > 4) { // primitive sorting according to the number of hits for (j = 0; j < (ntracks-1); j++) { for (i = j+1; i < ntracks; i++) { if ( (trackletCand[j][1] < trackletCand[i][1]) || ( (trackletCand[j][1] == trackletCand[i][1]) && (trackletCand[j][0] < trackletCand[i][0]) ) ) { // swap j & i tmp = trackletCand[j][1]; trackletCand[j][1] = trackletCand[i][1]; trackletCand[i][1] = tmp; tmp = trackletCand[j][0]; trackletCand[j][0] = trackletCand[i][0]; trackletCand[i][0] = tmp; } } } ntracks = 4; // cut the rest, 4 is the max } // else is not necessary to sort // now sort, so that the first tracklet going to CPU0 corresponds to the highest adc channel - as in the TRAP for (j = 0; j < (ntracks-1); j++) { for (i = j+1; i < ntracks; i++) { if (trackletCand[j][0] < trackletCand[i][0]) { // swap j & i tmp = trackletCand[j][1]; trackletCand[j][1] = trackletCand[i][1]; trackletCand[i][1] = tmp; tmp = trackletCand[j][0]; trackletCand[j][0] = trackletCand[i][0]; trackletCand[i][0] = tmp; } } } for (i = 0; i < ntracks; i++) // CPUs with tracklets. fFitPtr[i] = trackletCand[i][0]; // pointer to the left channel with tracklet for CPU[i] for (i = ntracks; i < 4; i++) // CPUs without tracklets fFitPtr[i] = 31; // pointer to the left channel with tracklet for CPU[i] = 31 (invalid) AliDebug(10,Form("found %i tracklet candidates\n", ntracks)); for (i = 0; i < 4; i++) AliDebug(10,Form("fitPtr[%i]: %i\n", i, fFitPtr[i])); } void AliTRDmcmSim::FitTracklet() { // Perform the actual tracklet fit based on the fit sums // which have been filled in the fit registers. // parameters in fitred.asm (fit program) Int_t rndAdd = 0; Int_t decPlaces = 5; // must be larger than 1 or change the following code // if (decPlaces > 1) rndAdd = (1 << (decPlaces-1)) + 1; // else if (decPlaces == 1) // rndAdd = 1; Int_t ndriftDp = 5; // decimal places for drift time Long64_t shift = ((Long64_t) 1 << 32); // calculated in fitred.asm Int_t padrow = ((fRobPos >> 1) << 2) | (fMcmPos >> 2); Int_t yoffs = (((((fRobPos & 0x1) << 2) + (fMcmPos & 0x3)) * 18) << 8) - ((18*4*2 - 18*2 - 1) << 7); yoffs = yoffs << decPlaces; // holds position of ADC channel 1 Int_t layer = fDetector % 6; UInt_t scaleY = (UInt_t) ((0.635 + 0.03 * layer)/(256.0 * 160.0e-4) * shift); UInt_t scaleD = (UInt_t) ((0.635 + 0.03 * layer)/(256.0 * 140.0e-4) * shift); Int_t deflCorr = (Int_t) fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrDeflCorr, fDetector, fRobPos, fMcmPos); Int_t ndrift = (Int_t) fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrNdrift, fDetector, fRobPos, fMcmPos); // local variables for calculation Long64_t mult, temp, denom; //??? UInt_t q0, q1, pid; // charges in the two windows and total charge UShort_t nHits; // number of hits Int_t slope, offset; // slope and offset of the tracklet Int_t sumX, sumY, sumXY, sumX2; // fit sums from fit registers Int_t sumY2; // not used in the current TRAP program, now used for error calculation (simulation only) Float_t fitError, fitSlope, fitOffset; FitReg_t *fit0, *fit1; // pointers to relevant fit registers // const uint32_t OneDivN[32] = { // 2**31/N : exactly like in the TRAP, the simple division here gives the same result! // 0x00000000, 0x80000000, 0x40000000, 0x2AAAAAA0, 0x20000000, 0x19999990, 0x15555550, 0x12492490, // 0x10000000, 0x0E38E380, 0x0CCCCCC0, 0x0BA2E8B0, 0x0AAAAAA0, 0x09D89D80, 0x09249240, 0x08888880, // 0x08000000, 0x07878780, 0x071C71C0, 0x06BCA1A0, 0x06666660, 0x06186180, 0x05D17450, 0x0590B210, // 0x05555550, 0x051EB850, 0x04EC4EC0, 0x04BDA120, 0x04924920, 0x0469EE50, 0x04444440, 0x04210840}; for (Int_t cpu = 0; cpu < 4; cpu++) { if (fFitPtr[cpu] == 31) { fMCMT[cpu] = 0x10001000; //??? AliTRDfeeParam::GetTrackletEndmarker(); } else { fit0 = &fFitReg[fFitPtr[cpu] ]; fit1 = &fFitReg[fFitPtr[cpu]+1]; // next channel mult = 1; mult = mult << (32 + decPlaces); mult = -mult; // Merging nHits = fit0->fNhits + fit1->fNhits; // number of hits sumX = fit0->fSumX + fit1->fSumX; sumX2 = fit0->fSumX2 + fit1->fSumX2; denom = ((Long64_t) nHits)*((Long64_t) sumX2) - ((Long64_t) sumX)*((Long64_t) sumX); mult = mult / denom; // exactly like in the TRAP program q0 = fit0->fQ0 + fit1->fQ0; q1 = fit0->fQ1 + fit1->fQ1; sumY = fit0->fSumY + fit1->fSumY + 256*fit1->fNhits; sumXY = fit0->fSumXY + fit1->fSumXY + 256*fit1->fSumX; sumY2 = fit0->fSumY2 + fit1->fSumY2 + 512*fit1->fSumY + 256*256*fit1->fNhits; slope = nHits*sumXY - sumX * sumY; offset = sumX2*sumY - sumX * sumXY; temp = mult * slope; slope = temp >> 32; // take the upper 32 bits slope = -slope; temp = mult * offset; offset = temp >> 32; // take the upper 32 bits offset = offset + yoffs; AliDebug(10, Form("slope = %i, slope * ndrift = %i, deflCorr: %i", slope, slope * ndrift, deflCorr)); slope = ((slope * ndrift) >> ndriftDp) + deflCorr; offset = offset - (fFitPtr[cpu] << (8 + decPlaces)); temp = slope; temp = temp * scaleD; slope = (temp >> 32); temp = offset; temp = temp * scaleY; offset = (temp >> 32); // rounding, like in the TRAP slope = (slope + rndAdd) >> decPlaces; offset = (offset + rndAdd) >> decPlaces; AliDebug(5, Form("Det: %3i, ROB: %i, MCM: %2i: deflection: %i, min: %i, max: %i", fDetector, fRobPos, fMcmPos, slope, (Int_t) fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrDeflCutStart + 2*fFitPtr[cpu], fDetector, fRobPos, fMcmPos), (Int_t) fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrDeflCutStart + 1 + 2*fFitPtr[cpu], fDetector, fRobPos, fMcmPos))); AliDebug(5, Form("Fit sums: x = %i, X = %i, y = %i, Y = %i, Z = %i", sumX, sumX2, sumY, sumY2, sumXY)); fitSlope = (Float_t) (nHits * sumXY - sumX * sumY) / (nHits * sumX2 - sumX*sumX); fitOffset = (Float_t) (sumX2 * sumY - sumX * sumXY) / (nHits * sumX2 - sumX*sumX); Float_t sx = (Float_t) sumX; Float_t sx2 = (Float_t) sumX2; Float_t sy = (Float_t) sumY; Float_t sy2 = (Float_t) sumY2; Float_t sxy = (Float_t) sumXY; fitError = sy2 - (sx2 * sy*sy - 2 * sx * sxy * sy + nHits * sxy*sxy) / (nHits * sx2 - sx*sx); //fitError = (Float_t) sumY2 - (Float_t) (sumY*sumY) / nHits - fitSlope * ((Float_t) (sumXY - sumX*sumY) / nHits); Bool_t rejected = kFALSE; // deflection range table from DMEM if ((slope < ((Int_t) fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrDeflCutStart + 2*fFitPtr[cpu], fDetector, fRobPos, fMcmPos))) || (slope > ((Int_t) fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrDeflCutStart + 1 + 2*fFitPtr[cpu], fDetector, fRobPos, fMcmPos)))) rejected = kTRUE; if (rejected && GetApplyCut()) { fMCMT[cpu] = 0x10001000; //??? AliTRDfeeParam::GetTrackletEndmarker(); } else { if (slope > 63 || slope < -64) { // wrapping in TRAP! AliError(Form("Overflow in slope: %i, tracklet discarded!", slope)); fMCMT[cpu] = 0x10001000; continue; } slope = slope & 0x7F; // 7 bit if (offset > 0xfff || offset < -0xfff) AliWarning("Overflow in offset"); offset = offset & 0x1FFF; // 13 bit pid = GetPID(q0 >> fgkAddDigits, q1 >> fgkAddDigits); // divided by 4 because in simulation there are two additional decimal places if (pid > 0xff) AliWarning("Overflow in PID"); pid = pid & 0xFF; // 8 bit, exactly like in the TRAP program // assemble and store the tracklet word fMCMT[cpu] = (pid << 24) | (padrow << 20) | (slope << 13) | offset; // calculate MC label Int_t mcLabel[] = { -1, -1, -1}; Int_t nHits0 = 0; Int_t nHits1 = 0; if (fDigitsManager) { const Int_t maxLabels = 30; Int_t label[maxLabels] = {0}; // up to 30 different labels possible Int_t count[maxLabels] = {0}; Int_t nLabels = 0; for (Int_t iHit = 0; iHit < fNHits; iHit++) { if ((fHits[iHit].fChannel - fFitPtr[cpu] < 0) || (fHits[iHit].fChannel - fFitPtr[cpu] > 1)) continue; // counting contributing hits if (fHits[iHit].fTimebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS0) && fHits[iHit].fTimebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE0)) nHits0++; if (fHits[iHit].fTimebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS1) && fHits[iHit].fTimebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE1)) nHits1++; for (Int_t i = 0; i < 3; i++) { Int_t currLabel = fHits[iHit].fLabel[i]; for (Int_t iLabel = 0; iLabel < nLabels; iLabel++) { if (currLabel == label[iLabel]) { count[iLabel]++; currLabel = -1; break; } } if (currLabel >= 0 && nLabels < maxLabels) { label[nLabels] = currLabel; count[nLabels]++; nLabels++; } } } Int_t index[2*maxLabels]; TMath::Sort(maxLabels, count, index); for (Int_t i = 0; i < 3; i++) { if (count[index[i]] <= 0) break; mcLabel[i] = label[index[i]]; } } new ((*fTrackletArray)[fTrackletArray->GetEntriesFast()]) AliTRDtrackletMCM((UInt_t) fMCMT[cpu], fDetector*2 + fRobPos%2, fRobPos, fMcmPos); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetLabel(mcLabel); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetNHits(fit0->fNhits + fit1->fNhits); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetNHits0(nHits0); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetNHits1(nHits1); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetQ0(q0); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetQ1(q1); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetSlope(fitSlope); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetOffset(fitOffset); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetError(TMath::Sqrt(TMath::Abs(fitError)/nHits)); // // cluster information // Float_t *res = new Float_t[nHits]; // Float_t *qtot = new Float_t[nHits]; // Int_t nCls = 0; // for (Int_t iHit = 0; iHit < fNHits; iHit++) { // // check if hit contributes // if (fHits[iHit].fChannel == fFitPtr[cpu]) { // res[nCls] = fHits[iHit].fYpos - (fitSlope * fHits[iHit].fTimebin + fitOffset); // qtot[nCls] = fHits[iHit].fQtot; // nCls++; // } // else if (fHits[iHit].fChannel == fFitPtr[cpu] + 1) { // res[nCls] = fHits[iHit].fYpos + 256 - (fitSlope * fHits[iHit].fTimebin + fitOffset); // qtot[nCls] = fHits[iHit].fQtot; // nCls++; // } // } // ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetClusters(res, qtot, nCls); // delete [] res; // delete [] qtot; if (fitError < 0) AliError(Form("Strange fit error: %f from Sx: %i, Sy: %i, Sxy: %i, Sx2: %i, Sy2: %i, nHits: %i", fitError, sumX, sumY, sumXY, sumX2, sumY2, nHits)); AliDebug(3, Form("fit slope: %f, offset: %f, error: %f", fitSlope, fitOffset, TMath::Sqrt(TMath::Abs(fitError)/nHits))); } } } } void AliTRDmcmSim::Tracklet() { // Run the tracklet calculation by calling sequentially: // CalcFitreg(); TrackletSelection(); FitTracklet() // and store the tracklets if (!fInitialized) { AliError("Called uninitialized! Nothing done!"); return; } fTrackletArray->Delete(); CalcFitreg(); if (fNHits == 0) return; TrackletSelection(); FitTracklet(); } Bool_t AliTRDmcmSim::StoreTracklets() { // store the found tracklets via the loader if (fTrackletArray->GetEntriesFast() == 0) return kTRUE; AliRunLoader *rl = AliRunLoader::Instance(); AliDataLoader *dl = 0x0; if (rl) dl = rl->GetLoader("TRDLoader")->GetDataLoader("tracklets"); if (!dl) { AliError("Could not get the tracklets data loader!"); return kFALSE; } TTree *trackletTree = dl->Tree(); if (!trackletTree) { dl->MakeTree(); trackletTree = dl->Tree(); } AliTRDtrackletMCM *trkl = 0x0; TBranch *trkbranch = trackletTree->GetBranch(fTrklBranchName.Data()); if (!trkbranch) trkbranch = trackletTree->Branch(fTrklBranchName.Data(), "AliTRDtrackletMCM", &trkl, 32000); for (Int_t iTracklet = 0; iTracklet < fTrackletArray->GetEntriesFast(); iTracklet++) { trkl = ((AliTRDtrackletMCM*) (*fTrackletArray)[iTracklet]); trkbranch->SetAddress(&trkl); trkbranch->Fill(); } return kTRUE; } void AliTRDmcmSim::WriteData(AliTRDarrayADC *digits) { // write back the processed data configured by EBSF // EBSF = 1: unfiltered data; EBSF = 0: filtered data // zero-suppressed valued are written as -1 to digits if( !CheckInitialized() ) return; Int_t offset = (fMcmPos % 4 + 1) * 21 + (fRobPos % 2) * 84 - 1; if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBSF) != 0) // store unfiltered data { for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { if (~fZSMap[iAdc] == 0) { for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { digits->SetDataByAdcCol(GetRow(), offset - iAdc, iTimeBin, -1); } } else if (iAdc < 2 || iAdc == 20) { for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { digits->SetDataByAdcCol(GetRow(), offset - iAdc, iTimeBin, (fADCR[iAdc][iTimeBin] >> fgkAddDigits) - fgAddBaseline); } } } } else { for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { if (~fZSMap[iAdc] != 0) { for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { digits->SetDataByAdcCol(GetRow(), offset - iAdc, iTimeBin, (fADCF[iAdc][iTimeBin] >> fgkAddDigits) - fgAddBaseline); } } else { for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { digits->SetDataByAdcCol(GetRow(), offset - iAdc, iTimeBin, -1); } } } } } // ****************************** // PID section // // Memory area for the LUT: 0xC100 to 0xC3FF // // The addresses for the parameters (the order is optimized for maximum calculation speed in the MCMs): // 0xC028: cor1 // 0xC029: nBins(sF) // 0xC02A: cor0 // 0xC02B: TableLength // Defined in AliTRDtrapConfig.h // // The algorithm implemented in the TRAP program of the MCMs (Venelin Angelov) // 1) set the read pointer to the beginning of the Parameters in DMEM // 2) shift right the FitReg with the Q0 + (Q1 << 16) to get Q1 // 3) read cor1 with rpointer++ // 4) start cor1*Q1 // 5) read nBins with rpointer++ // 6) start nBins*cor1*Q1 // 7) read cor0 with rpointer++ // 8) swap hi-low parts in FitReg, now is Q1 + (Q0 << 16) // 9) shift right to get Q0 // 10) start cor0*Q0 // 11) read TableLength // 12) compare cor0*Q0 with nBins // 13) if >=, clip cor0*Q0 to nBins-1 // 14) add cor0*Q0 to nBins*cor1*Q1 // 15) compare the result with TableLength // 16) if >=, clip to TableLength-1 // 17) read from the LUT 8 bits Int_t AliTRDmcmSim::GetPID(Int_t q0, Int_t q1) { // return PID calculated from charges accumulated in two time windows ULong64_t addrQ0; ULong64_t addr; UInt_t nBinsQ0 = fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrLUTnbins); // number of bins in q0 / 4 !! UInt_t pidTotalSize = fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrLUTLength); if(nBinsQ0==0 || pidTotalSize==0) // make sure we don't run into trouble if one of the values is not configured return 0; ULong_t corrQ0 = fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrLUTcor0, fDetector, fRobPos, fMcmPos); ULong_t corrQ1 = fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrLUTcor1, fDetector, fRobPos, fMcmPos); if(corrQ0==0 || corrQ1==0) // make sure we don't run into trouble if one of the values is not configured return 0; addrQ0 = corrQ0; addrQ0 = (((addrQ0*q0)>>16)>>16); // because addrQ0 = (q0 * corrQ0) >> 32; does not work for unknown reasons if(addrQ0 >= nBinsQ0) { // check for overflow AliDebug(5,Form("Overflow in q0: %llu/4 is bigger then %u", addrQ0, nBinsQ0)); addrQ0 = nBinsQ0 -1; } addr = corrQ1; addr = (((addr*q1)>>16)>>16); addr = addrQ0 + nBinsQ0*addr; // because addr = addrQ0 + nBinsQ0* (((corrQ1*q1)>>32); does not work if(addr >= pidTotalSize) { AliDebug(5,Form("Overflow in q1. Address %llu/4 is bigger then %u", addr, pidTotalSize)); addr = pidTotalSize -1; } // For a LUT with 11 input and 8 output bits, the first memory address is set to LUT[0] | (LUT[1] << 8) | (LUT[2] << 16) | (LUT[3] << 24) // and so on UInt_t result = fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrLUTStart+(addr/4)); return (result>>((addr%4)*8)) & 0xFF; } // help functions, to be cleaned up UInt_t AliTRDmcmSim::AddUintClipping(UInt_t a, UInt_t b, UInt_t nbits) const { // // This function adds a and b (unsigned) and clips to // the specified number of bits. // UInt_t sum = a + b; if (nbits < 32) { UInt_t maxv = (1 << nbits) - 1;; if (sum > maxv) sum = maxv; } else { if ((sum < a) || (sum < b)) sum = 0xFFFFFFFF; } return sum; } void AliTRDmcmSim::Sort2(UShort_t idx1i, UShort_t idx2i, \ UShort_t val1i, UShort_t val2i, \ UShort_t * const idx1o, UShort_t * const idx2o, \ UShort_t * const val1o, UShort_t * const val2o) const { // sorting for tracklet selection if (val1i > val2i) { *idx1o = idx1i; *idx2o = idx2i; *val1o = val1i; *val2o = val2i; } else { *idx1o = idx2i; *idx2o = idx1i; *val1o = val2i; *val2o = val1i; } } void AliTRDmcmSim::Sort3(UShort_t idx1i, UShort_t idx2i, UShort_t idx3i, \ UShort_t val1i, UShort_t val2i, UShort_t val3i, \ UShort_t * const idx1o, UShort_t * const idx2o, UShort_t * const idx3o, \ UShort_t * const val1o, UShort_t * const val2o, UShort_t * const val3o) { // sorting for tracklet selection Int_t sel; if (val1i > val2i) sel=4; else sel=0; if (val2i > val3i) sel=sel + 2; if (val3i > val1i) sel=sel + 1; switch(sel) { case 6 : // 1 > 2 > 3 => 1 2 3 case 0 : // 1 = 2 = 3 => 1 2 3 : in this case doesn't matter, but so is in hardware! *idx1o = idx1i; *idx2o = idx2i; *idx3o = idx3i; *val1o = val1i; *val2o = val2i; *val3o = val3i; break; case 4 : // 1 > 2, 2 <= 3, 3 <= 1 => 1 3 2 *idx1o = idx1i; *idx2o = idx3i; *idx3o = idx2i; *val1o = val1i; *val2o = val3i; *val3o = val2i; break; case 2 : // 1 <= 2, 2 > 3, 3 <= 1 => 2 1 3 *idx1o = idx2i; *idx2o = idx1i; *idx3o = idx3i; *val1o = val2i; *val2o = val1i; *val3o = val3i; break; case 3 : // 1 <= 2, 2 > 3, 3 > 1 => 2 3 1 *idx1o = idx2i; *idx2o = idx3i; *idx3o = idx1i; *val1o = val2i; *val2o = val3i; *val3o = val1i; break; case 1 : // 1 <= 2, 2 <= 3, 3 > 1 => 3 2 1 *idx1o = idx3i; *idx2o = idx2i; *idx3o = idx1i; *val1o = val3i; *val2o = val2i; *val3o = val1i; break; case 5 : // 1 > 2, 2 <= 3, 3 > 1 => 3 1 2 *idx1o = idx3i; *idx2o = idx1i; *idx3o = idx2i; *val1o = val3i; *val2o = val1i; *val3o = val2i; break; default: // the rest should NEVER happen! AliError("ERROR in Sort3!!!\n"); break; } } void AliTRDmcmSim::Sort6To4(UShort_t idx1i, UShort_t idx2i, UShort_t idx3i, UShort_t idx4i, UShort_t idx5i, UShort_t idx6i, \ UShort_t val1i, UShort_t val2i, UShort_t val3i, UShort_t val4i, UShort_t val5i, UShort_t val6i, \ UShort_t * const idx1o, UShort_t * const idx2o, UShort_t * const idx3o, UShort_t * const idx4o, \ UShort_t * const val1o, UShort_t * const val2o, UShort_t * const val3o, UShort_t * const val4o) { // sorting for tracklet selection UShort_t idx21s, idx22s, idx23s, dummy; UShort_t val21s, val22s, val23s; UShort_t idx23as, idx23bs; UShort_t val23as, val23bs; Sort3(idx1i, idx2i, idx3i, val1i, val2i, val3i, idx1o, &idx21s, &idx23as, val1o, &val21s, &val23as); Sort3(idx4i, idx5i, idx6i, val4i, val5i, val6i, idx2o, &idx22s, &idx23bs, val2o, &val22s, &val23bs); Sort2(idx23as, idx23bs, val23as, val23bs, &idx23s, &dummy, &val23s, &dummy); Sort3(idx21s, idx22s, idx23s, val21s, val22s, val23s, idx3o, idx4o, &dummy, val3o, val4o, &dummy); } void AliTRDmcmSim::Sort6To2Worst(UShort_t idx1i, UShort_t idx2i, UShort_t idx3i, UShort_t idx4i, UShort_t idx5i, UShort_t idx6i, \ UShort_t val1i, UShort_t val2i, UShort_t val3i, UShort_t val4i, UShort_t val5i, UShort_t val6i, \ UShort_t * const idx5o, UShort_t * const idx6o) { // sorting for tracklet selection UShort_t idx21s, idx22s, idx23s, dummy1, dummy2, dummy3, dummy4, dummy5; UShort_t val21s, val22s, val23s; UShort_t idx23as, idx23bs; UShort_t val23as, val23bs; Sort3(idx1i, idx2i, idx3i, val1i, val2i, val3i, &dummy1, &idx21s, &idx23as, &dummy2, &val21s, &val23as); Sort3(idx4i, idx5i, idx6i, val4i, val5i, val6i, &dummy1, &idx22s, &idx23bs, &dummy2, &val22s, &val23bs); Sort2(idx23as, idx23bs, val23as, val23bs, &idx23s, idx5o, &val23s, &dummy1); Sort3(idx21s, idx22s, idx23s, val21s, val22s, val23s, &dummy1, &dummy2, idx6o, &dummy3, &dummy4, &dummy5); } // ----- I/O implementation ----- ostream& AliTRDmcmSim::Text(ostream& os) { // manipulator to activate output in text format (default) os.iword(fgkFormatIndex) = 0; return os; } ostream& AliTRDmcmSim::Cfdat(ostream& os) { // manipulator to activate output in CFDAT format // to send to the FEE via SCSN os.iword(fgkFormatIndex) = 1; return os; } ostream& AliTRDmcmSim::Raw(ostream& os) { // manipulator to activate output as raw data dump os.iword(fgkFormatIndex) = 2; return os; } ostream& operator<<(ostream& os, const AliTRDmcmSim& mcm) { // output implementation // no output for non-initialized MCM if (!mcm.CheckInitialized()) return os; // ----- human-readable output ----- if (os.iword(AliTRDmcmSim::fgkFormatIndex) == 0) { os << "MCM " << mcm.fMcmPos << " on ROB " << mcm.fRobPos << " in detector " << mcm.fDetector << std::endl; os << "----- Unfiltered ADC data (10 bit) -----" << std::endl; os << "ch "; for (Int_t iChannel = 0; iChannel < mcm.fgkNADC; iChannel++) os << std::setw(5) << iChannel; os << std::endl; for (Int_t iTimeBin = 0; iTimeBin < mcm.fNTimeBin; iTimeBin++) { os << "tb " << std::setw(2) << iTimeBin << ":"; for (Int_t iChannel = 0; iChannel < mcm.fgkNADC; iChannel++) { os << std::setw(5) << (mcm.fADCR[iChannel][iTimeBin] >> mcm.fgkAddDigits); } os << std::endl; } os << "----- Filtered ADC data (10+2 bit) -----" << std::endl; os << "ch "; for (Int_t iChannel = 0; iChannel < mcm.fgkNADC; iChannel++) os << std::setw(4) << iChannel << ((~mcm.fZSMap[iChannel] != 0) ? "!" : " "); os << std::endl; for (Int_t iTimeBin = 0; iTimeBin < mcm.fNTimeBin; iTimeBin++) { os << "tb " << std::setw(2) << iTimeBin << ":"; for (Int_t iChannel = 0; iChannel < mcm.fgkNADC; iChannel++) { os << std::setw(4) << (mcm.fADCF[iChannel][iTimeBin]) << (((mcm.fZSMap[iChannel] & (1 << iTimeBin)) == 0) ? "!" : " "); } os << std::endl; } } // ----- CFDAT output ----- else if(os.iword(AliTRDmcmSim::fgkFormatIndex) == 1) { Int_t dest = 127; Int_t addrOffset = 0x2000; Int_t addrStep = 0x80; for (Int_t iTimeBin = 0; iTimeBin < mcm.fNTimeBin; iTimeBin++) { for (Int_t iChannel = 0; iChannel < mcm.fgkNADC; iChannel++) { os << std::setw(5) << 10 << std::setw(5) << addrOffset + iChannel * addrStep + iTimeBin << std::setw(5) << (mcm.fADCF[iChannel][iTimeBin]) << std::setw(5) << dest << std::endl; } os << std::endl; } } // ----- raw data ouptut ----- else if (os.iword(AliTRDmcmSim::fgkFormatIndex) == 2) { Int_t bufSize = 300; UInt_t *buf = new UInt_t[bufSize]; Int_t bufLength = mcm.ProduceRawStream(&buf[0], bufSize); for (Int_t i = 0; i < bufLength; i++) std::cout << "0x" << std::hex << buf[i] << std::dec << std::endl; delete [] buf; } else { os << "unknown format set" << std::endl; } return os; } void AliTRDmcmSim::PrintFitRegXml(ostream& os) const { // print fit registres in XML format bool tracklet=false; for (Int_t cpu = 0; cpu < 4; cpu++) { if(fFitPtr[cpu] != 31) tracklet=true; } if(tracklet==true) { os << "<nginject>" << std::endl; os << "<ack roc=\""<< fDetector << "\" cmndid=\"0\">" << std::endl; os << "<dmem-readout>" << std::endl; os << "<d det=\"" << fDetector << "\">" << std::endl; os << " <ro-board rob=\"" << fRobPos << "\">" << std::endl; os << " <m mcm=\"" << fMcmPos << "\">" << std::endl; for(int cpu=0; cpu<4; cpu++) { os << " <c cpu=\"" << cpu << "\">" << std::endl; if(fFitPtr[cpu] != 31) { for(int adcch=fFitPtr[cpu]; adcch<fFitPtr[cpu]+2; adcch++) { os << " <ch chnr=\"" << adcch << "\">"<< std::endl; os << " <hits>" << fFitReg[adcch].fNhits << "</hits>"<< std::endl; os << " <q0>" << fFitReg[adcch].fQ0/4 << "</q0>"<< std::endl; // divided by 4 because in simulation we have 2 additional decimal places os << " <q1>" << fFitReg[adcch].fQ1/4 << "</q1>"<< std::endl; // in the output os << " <sumx>" << fFitReg[adcch].fSumX << "</sumx>"<< std::endl; os << " <sumxsq>" << fFitReg[adcch].fSumX2 << "</sumxsq>"<< std::endl; os << " <sumy>" << fFitReg[adcch].fSumY << "</sumy>"<< std::endl; os << " <sumysq>" << fFitReg[adcch].fSumY2 << "</sumysq>"<< std::endl; os << " <sumxy>" << fFitReg[adcch].fSumXY << "</sumxy>"<< std::endl; os << " </ch>" << std::endl; } } os << " </c>" << std::endl; } os << " </m>" << std::endl; os << " </ro-board>" << std::endl; os << "</d>" << std::endl; os << "</dmem-readout>" << std::endl; os << "</ack>" << std::endl; os << "</nginject>" << std::endl; } } void AliTRDmcmSim::PrintTrackletsXml(ostream& os) const { // print tracklets in XML format os << "<nginject>" << std::endl; os << "<ack roc=\""<< fDetector << "\" cmndid=\"0\">" << std::endl; os << "<dmem-readout>" << std::endl; os << "<d det=\"" << fDetector << "\">" << std::endl; os << " <ro-board rob=\"" << fRobPos << "\">" << std::endl; os << " <m mcm=\"" << fMcmPos << "\">" << std::endl; Int_t pid, padrow, slope, offset; for(Int_t cpu=0; cpu<4; cpu++) { if(fMCMT[cpu] == 0x10001000) { pid=-1; padrow=-1; slope=-1; offset=-1; } else { pid = (fMCMT[cpu] & 0xFF000000) >> 24; padrow = (fMCMT[cpu] & 0xF00000 ) >> 20; slope = (fMCMT[cpu] & 0xFE000 ) >> 13; offset = (fMCMT[cpu] & 0x1FFF ) ; } os << " <trk> <pid>" << pid << "</pid>" << " <padrow>" << padrow << "</padrow>" << " <slope>" << slope << "</slope>" << " <offset>" << offset << "</offset>" << "</trk>" << std::endl; } os << " </m>" << std::endl; os << " </ro-board>" << std::endl; os << "</d>" << std::endl; os << "</dmem-readout>" << std::endl; os << "</ack>" << std::endl; os << "</nginject>" << std::endl; } void AliTRDmcmSim::PrintAdcDatHuman(ostream& os) const { // print ADC data in human-readable format os << "MCM " << fMcmPos << " on ROB " << fRobPos << " in detector " << fDetector << std::endl; os << "----- Unfiltered ADC data (10 bit) -----" << std::endl; os << "ch "; for (Int_t iChannel = 0; iChannel < fgkNADC; iChannel++) os << std::setw(5) << iChannel; os << std::endl; for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { os << "tb " << std::setw(2) << iTimeBin << ":"; for (Int_t iChannel = 0; iChannel < fgkNADC; iChannel++) { os << std::setw(5) << (fADCR[iChannel][iTimeBin] >> fgkAddDigits); } os << std::endl; } os << "----- Filtered ADC data (10+2 bit) -----" << std::endl; os << "ch "; for (Int_t iChannel = 0; iChannel < fgkNADC; iChannel++) os << std::setw(4) << iChannel << ((~fZSMap[iChannel] != 0) ? "!" : " "); os << std::endl; for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { os << "tb " << std::setw(2) << iTimeBin << ":"; for (Int_t iChannel = 0; iChannel < fgkNADC; iChannel++) { os << std::setw(4) << (fADCF[iChannel][iTimeBin]) << (((fZSMap[iChannel] & (1 << iTimeBin)) == 0) ? "!" : " "); } os << std::endl; } } void AliTRDmcmSim::PrintAdcDatXml(ostream& os) const { // print ADC data in XML format os << "<nginject>" << std::endl; os << "<ack roc=\""<< fDetector << "\" cmndid=\"0\">" << std::endl; os << "<dmem-readout>" << std::endl; os << "<d det=\"" << fDetector << "\">" << std::endl; os << " <ro-board rob=\"" << fRobPos << "\">" << std::endl; os << " <m mcm=\"" << fMcmPos << "\">" << std::endl; for(Int_t iChannel = 0; iChannel < fgkNADC; iChannel++) { os << " <ch chnr=\"" << iChannel << "\">" << std::endl; for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { os << "<tb>" << fADCF[iChannel][iTimeBin]/4 << "</tb>"; } os << " </ch>" << std::endl; } os << " </m>" << std::endl; os << " </ro-board>" << std::endl; os << "</d>" << std::endl; os << "</dmem-readout>" << std::endl; os << "</ack>" << std::endl; os << "</nginject>" << std::endl; } void AliTRDmcmSim::PrintAdcDatDatx(ostream& os, Bool_t broadcast) const { // print ADC data in datx format (to send to FEE) fTrapConfig->PrintDatx(os, 2602, 1, 0, 127); // command to enable the ADC clock - necessary to write ADC values to MCM os << std::endl; Int_t addrOffset = 0x2000; Int_t addrStep = 0x80; Int_t addrOffsetEBSIA = 0x20; for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { for (Int_t iChannel = 0; iChannel < fgkNADC; iChannel++) { if(broadcast==kFALSE) fTrapConfig->PrintDatx(os, addrOffset+iChannel*addrStep+addrOffsetEBSIA+iTimeBin, (fADCF[iChannel][iTimeBin]/4), GetRobPos(), GetMcmPos()); else fTrapConfig->PrintDatx(os, addrOffset+iChannel*addrStep+addrOffsetEBSIA+iTimeBin, (fADCF[iChannel][iTimeBin]/4), 0, 127); } os << std::endl; } } void AliTRDmcmSim::PrintPidLutHuman() { // print PID LUT in human readable format UInt_t result; UInt_t addrEnd = AliTRDtrapConfig::fgkDmemAddrLUTStart + fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrLUTLength)/4; // /4 because each addr contains 4 values UInt_t nBinsQ0 = fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrLUTnbins); std::cout << "nBinsQ0: " << nBinsQ0 << std::endl; std::cout << "LUT table length: " << fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrLUTLength) << std::endl; for(UInt_t addr=AliTRDtrapConfig::fgkDmemAddrLUTStart; addr< addrEnd; addr++) { result = fTrapConfig->GetDmemUnsigned(addr); std::cout << addr << " # x: " << ((addr-AliTRDtrapConfig::fgkDmemAddrLUTStart)%((nBinsQ0)/4))*4 << ", y: " <<(addr-AliTRDtrapConfig::fgkDmemAddrLUTStart)/(nBinsQ0/4) << " # " <<((result>>0)&0xFF) << " | " << ((result>>8)&0xFF) << " | " << ((result>>16)&0xFF) << " | " << ((result>>24)&0xFF) << std::endl; } } - update handling of arrayDictionary - shift Q0, Q1 in tracklet to remove additional digits /************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ /////////////////////////////////////////////////////////////////////////////// // // // TRD MCM (Multi Chip Module) simulator // // which simulates the TRAP processing after the AD-conversion. // // The relevant parameters (i.e. configuration settings of the TRAP) // // are taken from AliTRDtrapConfig. // // // /////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <iomanip> #include "TCanvas.h" #include "TH1F.h" #include "TH2F.h" #include "TGraph.h" #include "TLine.h" #include "TRandom.h" #include "TClonesArray.h" #include "TMath.h" #include "AliLog.h" #include "AliRunLoader.h" #include "AliLoader.h" #include "AliTRDfeeParam.h" #include "AliTRDtrapConfig.h" #include "AliTRDdigitsManager.h" #include "AliTRDarrayADC.h" #include "AliTRDarrayDictionary.h" #include "AliTRDtrackletMCM.h" #include "AliTRDmcmSim.h" ClassImp(AliTRDmcmSim) Bool_t AliTRDmcmSim::fgApplyCut = kTRUE; Int_t AliTRDmcmSim::fgAddBaseline = 0; const Int_t AliTRDmcmSim::fgkFormatIndex = std::ios_base::xalloc(); const Int_t AliTRDmcmSim::fgkNADC = AliTRDfeeParam::GetNadcMcm(); const UShort_t AliTRDmcmSim::fgkFPshifts[4] = {11, 14, 17, 21}; AliTRDmcmSim::AliTRDmcmSim() : TObject(), fInitialized(kFALSE), fDetector(-1), fRobPos(-1), fMcmPos(-1), fRow (-1), fNTimeBin(-1), fADCR(NULL), fADCF(NULL), fMCMT(NULL), fTrackletArray(NULL), fZSMap(NULL), fTrklBranchName("mcmtrklbranch"), fFeeParam(NULL), fTrapConfig(NULL), fDigitsManager(NULL), fPedAcc(NULL), fGainCounterA(NULL), fGainCounterB(NULL), fTailAmplLong(NULL), fTailAmplShort(NULL), fNHits(0), fFitReg(NULL) { // // AliTRDmcmSim default constructor // By default, nothing is initialized. // It is necessary to issue Init before use. for (Int_t iDict = 0; iDict < 3; iDict++) fDict[iDict] = 0x0; fFitPtr[0] = 0; fFitPtr[1] = 0; fFitPtr[2] = 0; fFitPtr[3] = 0; } AliTRDmcmSim::~AliTRDmcmSim() { // // AliTRDmcmSim destructor // if(fInitialized) { for( Int_t iAdc = 0 ; iAdc < fgkNADC; iAdc++ ) { delete [] fADCR[iAdc]; delete [] fADCF[iAdc]; } delete [] fADCR; delete [] fADCF; delete [] fZSMap; delete [] fMCMT; delete [] fPedAcc; delete [] fGainCounterA; delete [] fGainCounterB; delete [] fTailAmplLong; delete [] fTailAmplShort; delete [] fFitReg; fTrackletArray->Delete(); delete fTrackletArray; } } void AliTRDmcmSim::Init( Int_t det, Int_t robPos, Int_t mcmPos, Bool_t /* newEvent */ ) { // // Initialize the class with new MCM position information // memory is allocated in the first initialization // if (!fInitialized) { fFeeParam = AliTRDfeeParam::Instance(); fTrapConfig = AliTRDtrapConfig::Instance(); } fDetector = det; fRobPos = robPos; fMcmPos = mcmPos; fNTimeBin = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kC13CPUA); fRow = fFeeParam->GetPadRowFromMCM( fRobPos, fMcmPos ); if (!fInitialized) { fADCR = new Int_t *[fgkNADC]; fADCF = new Int_t *[fgkNADC]; fZSMap = new Int_t [fgkNADC]; fGainCounterA = new UInt_t[fgkNADC]; fGainCounterB = new UInt_t[fgkNADC]; for( Int_t iAdc = 0 ; iAdc < fgkNADC; iAdc++ ) { fADCR[iAdc] = new Int_t[fNTimeBin]; fADCF[iAdc] = new Int_t[fNTimeBin]; } // filter registers fPedAcc = new UInt_t[fgkNADC]; // accumulator for pedestal filter fTailAmplLong = new UShort_t[fgkNADC]; fTailAmplShort = new UShort_t[fgkNADC]; // tracklet calculation fFitReg = new FitReg_t[fgkNADC]; fTrackletArray = new TClonesArray("AliTRDtrackletMCM", fgkMaxTracklets); fMCMT = new UInt_t[fgkMaxTracklets]; } fInitialized = kTRUE; Reset(); } void AliTRDmcmSim::Reset() { // Resets the data values and internal filter registers // by re-initialising them if( !CheckInitialized() ) return; for( Int_t iAdc = 0 ; iAdc < fgkNADC; iAdc++ ) { for( Int_t it = 0 ; it < fNTimeBin ; it++ ) { fADCR[iAdc][it] = 0; fADCF[iAdc][it] = 0; } fZSMap[iAdc] = -1; // Default unread, low active bit mask fGainCounterA[iAdc] = 0; fGainCounterB[iAdc] = 0; } for(Int_t i = 0; i < fgkMaxTracklets; i++) { fMCMT[i] = 0; } for (Int_t iDict = 0; iDict < 3; iDict++) fDict[iDict] = 0x0; FilterPedestalInit(); FilterGainInit(); FilterTailInit(); } void AliTRDmcmSim::SetNTimebins(Int_t ntimebins) { // Reallocate memory if a change in the number of timebins // is needed (should not be the case for real data) if( !CheckInitialized() ) return; fNTimeBin = ntimebins; for( Int_t iAdc = 0 ; iAdc < fgkNADC; iAdc++ ) { delete fADCR[iAdc]; delete fADCF[iAdc]; fADCR[iAdc] = new Int_t[fNTimeBin]; fADCF[iAdc] = new Int_t[fNTimeBin]; } } Bool_t AliTRDmcmSim::LoadMCM(AliRunLoader* const runloader, Int_t det, Int_t rob, Int_t mcm) { // loads the ADC data as obtained from the digitsManager for the specified MCM. // This method is meant for rare execution, e.g. in the visualization. When called // frequently use SetData(...) instead. Init(det, rob, mcm); if (!runloader) { AliError("No Runloader given"); return kFALSE; } AliLoader *trdLoader = runloader->GetLoader("TRDLoader"); if (!trdLoader) { AliError("Could not get TRDLoader"); return kFALSE; } Bool_t retval = kTRUE; trdLoader->LoadDigits(); fDigitsManager = 0x0; AliTRDdigitsManager *digMgr = new AliTRDdigitsManager(); digMgr->SetSDigits(0); digMgr->CreateArrays(); digMgr->ReadDigits(trdLoader->TreeD()); AliTRDarrayADC *digits = (AliTRDarrayADC*) digMgr->GetDigits(det); if (digits->HasData()) { digits->Expand(); if (fNTimeBin != digits->GetNtime()) { AliWarning(Form("Changing no. of timebins from %i to %i", fNTimeBin, digits->GetNtime())); SetNTimebins(digits->GetNtime()); } SetData(digits); } else retval = kFALSE; delete digMgr; return retval; } void AliTRDmcmSim::NoiseTest(Int_t nsamples, Int_t mean, Int_t sigma, Int_t inputGain, Int_t inputTail) { // This function can be used to test the filters. // It feeds nsamples of ADC values with a gaussian distribution specified by mean and sigma. // The filter chain implemented here consists of: // Pedestal -> Gain -> Tail // With inputGain and inputTail the input to the gain and tail filter, respectively, // can be chosen where // 0: noise input // 1: pedestal output // 2: gain output // The input has to be chosen from a stage before. // The filter behaviour is controlled by the TRAP parameters from AliTRDtrapConfig in the // same way as in normal simulation. // The functions produces four histograms with the values at the different stages. if( !CheckInitialized() ) return; TString nameInputGain; TString nameInputTail; switch (inputGain) { case 0: nameInputGain = "Noise"; break; case 1: nameInputGain = "Pedestal"; break; default: AliError("Undefined input to tail cancellation filter"); return; } switch (inputTail) { case 0: nameInputTail = "Noise"; break; case 1: nameInputTail = "Pedestal"; break; case 2: nameInputTail = "Gain"; break; default: AliError("Undefined input to tail cancellation filter"); return; } TH1F *h = new TH1F("noise", "Gaussian Noise;sample;ADC count", nsamples, 0, nsamples); TH1F *hfp = new TH1F("ped", "Noise #rightarrow Pedestal filter;sample;ADC count", nsamples, 0, nsamples); TH1F *hfg = new TH1F("gain", (nameInputGain + "#rightarrow Gain;sample;ADC count").Data(), nsamples, 0, nsamples); TH1F *hft = new TH1F("tail", (nameInputTail + "#rightarrow Tail;sample;ADC count").Data(), nsamples, 0, nsamples); h->SetStats(kFALSE); hfp->SetStats(kFALSE); hfg->SetStats(kFALSE); hft->SetStats(kFALSE); Int_t value; // ADC count with noise (10 bit) Int_t valuep; // pedestal filter output (12 bit) Int_t valueg; // gain filter output (12 bit) Int_t valuet; // tail filter value (12 bit) for (Int_t i = 0; i < nsamples; i++) { value = (Int_t) gRandom->Gaus(mean, sigma); // generate noise with gaussian distribution h->SetBinContent(i, value); valuep = FilterPedestalNextSample(1, 0, ((Int_t) value) << 2); if (inputGain == 0) valueg = FilterGainNextSample(1, ((Int_t) value) << 2); else valueg = FilterGainNextSample(1, valuep); if (inputTail == 0) valuet = FilterTailNextSample(1, ((Int_t) value) << 2); else if (inputTail == 1) valuet = FilterTailNextSample(1, valuep); else valuet = FilterTailNextSample(1, valueg); hfp->SetBinContent(i, valuep >> 2); hfg->SetBinContent(i, valueg >> 2); hft->SetBinContent(i, valuet >> 2); } TCanvas *c = new TCanvas; c->Divide(2,2); c->cd(1); h->Draw(); c->cd(2); hfp->Draw(); c->cd(3); hfg->Draw(); c->cd(4); hft->Draw(); } Bool_t AliTRDmcmSim::CheckInitialized() const { // // Check whether object is initialized // if( ! fInitialized ) AliError(Form ("AliTRDmcmSim is not initialized but function other than Init() is called.")); return fInitialized; } void AliTRDmcmSim::Print(Option_t* const option) const { // Prints the data stored and/or calculated for this MCM. // The output is controlled by option which can be a sequence of any of // the following characters: // R - prints raw ADC data // F - prints filtered data // H - prints detected hits // T - prints found tracklets // The later stages are only meaningful after the corresponding calculations // have been performed. if ( !CheckInitialized() ) return; printf("MCM %i on ROB %i in detector %i\n", fMcmPos, fRobPos, fDetector); TString opt = option; if (opt.Contains("R") || opt.Contains("F")) { std::cout << *this; } if (opt.Contains("H")) { printf("Found %i hits:\n", fNHits); for (Int_t iHit = 0; iHit < fNHits; iHit++) { printf("Hit %3i in timebin %2i, ADC %2i has charge %3i and position %3i\n", iHit, fHits[iHit].fTimebin, fHits[iHit].fChannel, fHits[iHit].fQtot, fHits[iHit].fYpos); } } if (opt.Contains("T")) { printf("Tracklets:\n"); for (Int_t iTrkl = 0; iTrkl < fTrackletArray->GetEntriesFast(); iTrkl++) { printf("tracklet %i: 0x%08x\n", iTrkl, ((AliTRDtrackletMCM*) (*fTrackletArray)[iTrkl])->GetTrackletWord()); } } } void AliTRDmcmSim::Draw(Option_t* const option) { // Plots the data stored in a 2-dim. timebin vs. ADC channel plot. // The option selects what data is plotted and can be a sequence of // the following characters: // R - plot raw data (default) // F - plot filtered data (meaningless if R is specified) // In addition to the ADC values: // H - plot hits // T - plot tracklets if( !CheckInitialized() ) return; TString opt = option; TH2F *hist = new TH2F("mcmdata", Form("Data of MCM %i on ROB %i in detector %i", \ fMcmPos, fRobPos, fDetector), \ fgkNADC, -0.5, fgkNADC-.5, fNTimeBin, -.5, fNTimeBin-.5); hist->GetXaxis()->SetTitle("ADC Channel"); hist->GetYaxis()->SetTitle("Timebin"); hist->SetStats(kFALSE); if (opt.Contains("R")) { for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { hist->SetBinContent(iAdc+1, iTimeBin+1, fADCR[iAdc][iTimeBin] >> fgkAddDigits); } } } else { for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { hist->SetBinContent(iAdc+1, iTimeBin+1, fADCF[iAdc][iTimeBin] >> fgkAddDigits); } } } hist->Draw("colz"); if (opt.Contains("H")) { TGraph *grHits = new TGraph(); for (Int_t iHit = 0; iHit < fNHits; iHit++) { grHits->SetPoint(iHit, fHits[iHit].fChannel + 1 + fHits[iHit].fYpos/256., fHits[iHit].fTimebin); } grHits->Draw("*"); } if (opt.Contains("T")) { TLine *trklLines = new TLine[4]; for (Int_t iTrkl = 0; iTrkl < fTrackletArray->GetEntries(); iTrkl++) { AliTRDtrackletMCM *trkl = (AliTRDtrackletMCM*) (*fTrackletArray)[iTrkl]; Float_t padWidth = 0.635 + 0.03 * (fDetector % 6); Float_t offset = padWidth/256. * ((((((fRobPos & 0x1) << 2) + (fMcmPos & 0x3)) * 18) << 8) - ((18*4*2 - 18*2 - 3) << 7)); // revert adding offset in FitTracklet Int_t ndrift = fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrNdrift, fDetector, fRobPos, fMcmPos) >> 5; Float_t slope = trkl->GetdY() * 140e-4 / ndrift; Int_t t0 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFS); Int_t t1 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFE); trklLines[iTrkl].SetX1((offset - (trkl->GetY() - slope * t0)) / padWidth); // ??? sign? trklLines[iTrkl].SetY1(t0); trklLines[iTrkl].SetX2((offset - (trkl->GetY() - slope * t1)) / padWidth); // ??? sign? trklLines[iTrkl].SetY2(t1); trklLines[iTrkl].SetLineColor(2); trklLines[iTrkl].SetLineWidth(2); printf("Tracklet %i: y = %f, dy = %f, offset = %f\n", iTrkl, trkl->GetY(), (trkl->GetdY() * 140e-4), offset); trklLines[iTrkl].Draw(); } } } void AliTRDmcmSim::SetData( Int_t adc, Int_t* const data ) { // // Store ADC data into array of raw data // if( !CheckInitialized() ) return; if( adc < 0 || adc >= fgkNADC ) { AliError(Form ("Error: ADC %i is out of range (0 .. %d).", adc, fgkNADC-1)); return; } for( Int_t it = 0 ; it < fNTimeBin ; it++ ) { fADCR[adc][it] = (Int_t) (data[it]) << fgkAddDigits; fADCF[adc][it] = (Int_t) (data[it]) << fgkAddDigits; } } void AliTRDmcmSim::SetData( Int_t adc, Int_t it, Int_t data ) { // // Store ADC data into array of raw data // if( !CheckInitialized() ) return; if( adc < 0 || adc >= fgkNADC ) { AliError(Form ("Error: ADC %i is out of range (0 .. %d).", adc, fgkNADC-1)); return; } fADCR[adc][it] = data << fgkAddDigits; fADCF[adc][it] = data << fgkAddDigits; } void AliTRDmcmSim::SetData(AliTRDarrayADC* const adcArray, AliTRDdigitsManager * const digitsManager) { // Set the ADC data from an AliTRDarrayADC if( !CheckInitialized() ) return; fDigitsManager = digitsManager; if (fDigitsManager) { for (Int_t iDict = 0; iDict < 3; iDict++) { AliTRDarrayDictionary *newDict = (AliTRDarrayDictionary*) fDigitsManager->GetDictionary(fDetector, iDict); if (fDict[iDict] != 0x0 && newDict != 0x0) { if (fDict[iDict] == newDict) continue; fDict[iDict] = newDict; fDict[iDict]->Expand(); } else { fDict[iDict] = newDict; if (fDict[iDict]) fDict[iDict]->Expand(); } // If there is no data, set dictionary to zero to avoid crashes if (fDict[iDict]->GetDim() == 0) { AliError(Form("Dictionary %i of det. %i has dim. 0", fDetector, iDict)); fDict[iDict] = 0x0; } } } if (fNTimeBin != adcArray->GetNtime()) SetNTimebins(adcArray->GetNtime()); Int_t offset = (fMcmPos % 4 + 1) * 21 + (fRobPos % 2) * 84 - 1; for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { Int_t value = adcArray->GetDataByAdcCol(GetRow(), offset - iAdc, iTimeBin); if (value < 0 || (offset - iAdc < 1) || (offset - iAdc > 165)) { fADCR[iAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP) + (fgAddBaseline << fgkAddDigits); fADCF[iAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits); } else { fZSMap[iAdc] = 0; fADCR[iAdc][iTimeBin] = (value << fgkAddDigits) + (fgAddBaseline << fgkAddDigits); fADCF[iAdc][iTimeBin] = (value << fgkAddDigits) + (fgAddBaseline << fgkAddDigits); } } } } void AliTRDmcmSim::SetDataByPad(AliTRDarrayADC* const adcArray, AliTRDdigitsManager * const digitsManager) { // Set the ADC data from an AliTRDarrayADC // (by pad, to be used during initial reading in simulation) if( !CheckInitialized() ) return; fDigitsManager = digitsManager; if (fDigitsManager) { for (Int_t iDict = 0; iDict < 3; iDict++) { AliTRDarrayDictionary *newDict = (AliTRDarrayDictionary*) fDigitsManager->GetDictionary(fDetector, iDict); if (fDict[iDict] != 0x0 && newDict != 0x0) { if (fDict[iDict] == newDict) continue; fDict[iDict] = newDict; fDict[iDict]->Expand(); } else { fDict[iDict] = newDict; if (fDict[iDict]) fDict[iDict]->Expand(); } // If there is no data, set dictionary to zero to avoid crashes if (fDict[iDict]->GetDim() == 0) { AliError(Form("Dictionary %i of det. %i has dim. 0", fDetector, iDict)); fDict[iDict] = 0x0; } } } if (fNTimeBin != adcArray->GetNtime()) SetNTimebins(adcArray->GetNtime()); Int_t offset = (fMcmPos % 4 + 1) * 18 + (fRobPos % 2) * 72 + 1; for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { Int_t value = -1; Int_t pad = offset - iAdc; if (pad > -1 && pad < 144) value = adcArray->GetData(GetRow(), offset - iAdc, iTimeBin); // Int_t value = adcArray->GetDataByAdcCol(GetRow(), offset - iAdc, iTimeBin); if (value < 0 || (offset - iAdc < 1) || (offset - iAdc > 165)) { fADCR[iAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP) + (fgAddBaseline << fgkAddDigits); fADCF[iAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits); } else { fZSMap[iAdc] = 0; fADCR[iAdc][iTimeBin] = (value << fgkAddDigits) + (fgAddBaseline << fgkAddDigits); fADCF[iAdc][iTimeBin] = (value << fgkAddDigits) + (fgAddBaseline << fgkAddDigits); } } } } void AliTRDmcmSim::SetDataPedestal( Int_t adc ) { // // Store ADC data into array of raw data // if( !CheckInitialized() ) return; if( adc < 0 || adc >= fgkNADC ) { return; } for( Int_t it = 0 ; it < fNTimeBin ; it++ ) { fADCR[adc][it] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP) + (fgAddBaseline << fgkAddDigits); fADCF[adc][it] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits); } } Bool_t AliTRDmcmSim::GetHit(Int_t index, Int_t &channel, Int_t &timebin, Int_t &qtot, Int_t &ypos, Float_t &y, Int_t &label) const { // retrieve the MC hit information (not available in TRAP hardware) if (index < 0 || index >= fNHits) return kFALSE; channel = fHits[index].fChannel; timebin = fHits[index].fTimebin; qtot = fHits[index].fQtot; ypos = fHits[index].fYpos; y = (Float_t) ((((((fRobPos & 0x1) << 2) + (fMcmPos & 0x3)) * 18) << 8) - ((18*4*2 - 18*2 - 1) << 7) - (channel << 8) - ypos) * (0.635 + 0.03 * (fDetector % 6)) / 256.0; label = fHits[index].fLabel[0]; return kTRUE; } Int_t AliTRDmcmSim::GetCol( Int_t adc ) { // // Return column id of the pad for the given ADC channel // if( !CheckInitialized() ) return -1; Int_t col = fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, adc); if (col < 0 || col >= fFeeParam->GetNcol()) return -1; else return col; } Int_t AliTRDmcmSim::ProduceRawStream( UInt_t *buf, Int_t bufSize, UInt_t iEv) const { // // Produce raw data stream from this MCM and put in buf // Returns number of words filled, or negative value // with -1 * number of overflowed words // if( !CheckInitialized() ) return 0; UInt_t x; UInt_t mcmHeader = 0; UInt_t adcMask = 0; Int_t nw = 0; // Number of written words Int_t of = 0; // Number of overflowed words Int_t rawVer = fFeeParam->GetRAWversion(); Int_t **adc; Int_t nActiveADC = 0; // number of activated ADC bits in a word if( !CheckInitialized() ) return 0; if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBSF) != 0) // store unfiltered data adc = fADCR; else adc = fADCF; // Produce ADC mask : nncc cccm mmmm mmmm mmmm mmmm mmmm 1100 // n : unused , c : ADC count, m : selected ADCs if( rawVer >= 3 && (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kC15CPUA) & (1 << 13))) { // check for zs flag in TRAP configuration for( Int_t iAdc = 0 ; iAdc < fgkNADC ; iAdc++ ) { if( ~fZSMap[iAdc] != 0 ) { // 0 means not suppressed adcMask |= (1 << (iAdc+4) ); // last 4 digit reserved for 1100=0xc nActiveADC++; // number of 1 in mmm....m } } if ((nActiveADC == 0) && (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kC15CPUA) & (1 << 8))) // check for DEH flag in TRAP configuration return 0; // assemble adc mask word adcMask |= (1 << 30) | ( ( 0x3FFFFFFC ) & (~(nActiveADC) << 25) ) | 0xC; // nn = 01, ccccc are inverted, 0xc=1100 } // MCM header mcmHeader = (1<<31) | (fRobPos << 28) | (fMcmPos << 24) | ((iEv % 0x100000) << 4) | 0xC; if (nw < bufSize) buf[nw++] = mcmHeader; else of++; // ADC mask if( adcMask != 0 ) { if (nw < bufSize) buf[nw++] = adcMask; else of++; } // Produce ADC data. 3 timebins are packed into one 32 bits word // In this version, different ADC channel will NOT share the same word UInt_t aa=0, a1=0, a2=0, a3=0; for (Int_t iAdc = 0; iAdc < 21; iAdc++ ) { if( rawVer>= 3 && ~fZSMap[iAdc] == 0 ) continue; // Zero Suppression, 0 means not suppressed aa = !(iAdc & 1) + 2; for (Int_t iT = 0; iT < fNTimeBin; iT+=3 ) { a1 = ((iT ) < fNTimeBin ) ? adc[iAdc][iT ] >> fgkAddDigits : 0; a2 = ((iT + 1) < fNTimeBin ) ? adc[iAdc][iT+1] >> fgkAddDigits : 0; a3 = ((iT + 2) < fNTimeBin ) ? adc[iAdc][iT+2] >> fgkAddDigits : 0; x = (a3 << 22) | (a2 << 12) | (a1 << 2) | aa; if (nw < bufSize) { buf[nw++] = x; } else { of++; } } } if( of != 0 ) return -of; else return nw; } Int_t AliTRDmcmSim::ProduceTrackletStream( UInt_t *buf, Int_t bufSize ) { // // Produce tracklet data stream from this MCM and put in buf // Returns number of words filled, or negative value // with -1 * number of overflowed words // if( !CheckInitialized() ) return 0; Int_t nw = 0; // Number of written words Int_t of = 0; // Number of overflowed words // Produce tracklet data. A maximum of four 32 Bit words will be written per MCM // fMCMT is filled continuously until no more tracklet words available for (Int_t iTracklet = 0; iTracklet < fTrackletArray->GetEntriesFast(); iTracklet++) { if (nw < bufSize) buf[nw++] = ((AliTRDtrackletMCM*) (*fTrackletArray)[iTracklet])->GetTrackletWord(); else of++; } if( of != 0 ) return -of; else return nw; } void AliTRDmcmSim::Filter() { // // Filter the raw ADC values. The active filter stages and their // parameters are taken from AliTRDtrapConfig. // The raw data is stored separate from the filtered data. Thus, // it is possible to run the filters on a set of raw values // sequentially for parameter tuning. // if( !CheckInitialized() ) return; // Apply filters sequentially. Bypass is handled by filters // since counters and internal registers may be updated even // if the filter is bypassed. // The first filter takes the data from fADCR and // outputs to fADCF. // Non-linearity filter not implemented. FilterPedestal(); FilterGain(); FilterTail(); // Crosstalk filter not implemented. } void AliTRDmcmSim::FilterPedestalInit(Int_t baseline) { // Initializes the pedestal filter assuming that the input has // been constant for a long time (compared to the time constant). UShort_t fptc = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPTC); // 0..3, 0 - fastest, 3 - slowest for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) fPedAcc[iAdc] = (baseline << 2) * (1 << fgkFPshifts[fptc]); } UShort_t AliTRDmcmSim::FilterPedestalNextSample(Int_t adc, Int_t timebin, UShort_t value) { // Returns the output of the pedestal filter given the input value. // The output depends on the internal registers and, thus, the // history of the filter. UShort_t fpnp = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP); // 0..511 -> 0..127.75, pedestal at the output UShort_t fptc = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPTC); // 0..3, 0 - fastest, 3 - slowest UShort_t fpby = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPBY); // 0..1 bypass, active low UShort_t accumulatorShifted; Int_t correction; UShort_t inpAdd; inpAdd = value + fpnp; accumulatorShifted = (fPedAcc[adc] >> fgkFPshifts[fptc]) & 0x3FF; // 10 bits if (timebin == 0) // the accumulator is disabled in the drift time { correction = (value & 0x3FF) - accumulatorShifted; fPedAcc[adc] = (fPedAcc[adc] + correction) & 0x7FFFFFFF; // 31 bits } if (fpby == 0) return value; if (inpAdd <= accumulatorShifted) return 0; else { inpAdd = inpAdd - accumulatorShifted; if (inpAdd > 0xFFF) return 0xFFF; else return inpAdd; } } void AliTRDmcmSim::FilterPedestal() { // // Apply pedestal filter // // As the first filter in the chain it reads data from fADCR // and outputs to fADCF. // It has only an effect if previous samples have been fed to // find the pedestal. Currently, the simulation assumes that // the input has been stable for a sufficiently long time. for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { fADCF[iAdc][iTimeBin] = FilterPedestalNextSample(iAdc, iTimeBin, fADCR[iAdc][iTimeBin]); } } } void AliTRDmcmSim::FilterGainInit() { // Initializes the gain filter. In this case, only threshold // counters are reset. for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { // these are counters which in hardware continue // until maximum or reset fGainCounterA[iAdc] = 0; fGainCounterB[iAdc] = 0; } } UShort_t AliTRDmcmSim::FilterGainNextSample(Int_t adc, UShort_t value) { // Apply the gain filter to the given value. // BEGIN_LATEX O_{i}(t) = #gamma_{i} * I_{i}(t) + a_{i} END_LATEX // The output depends on the internal registers and, thus, the // history of the filter. UShort_t fgby = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFGBY); // bypass, active low UShort_t fgf = fTrapConfig->GetTrapReg(AliTRDtrapConfig::TrapReg_t(AliTRDtrapConfig::kFGF0 + adc)); // 0x700 + (0 & 0x1ff); UShort_t fga = fTrapConfig->GetTrapReg(AliTRDtrapConfig::TrapReg_t(AliTRDtrapConfig::kFGA0 + adc)); // 40; UShort_t fgta = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFGTA); // 20; UShort_t fgtb = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFGTB); // 2060; UInt_t corr; // corrected value value &= 0xFFF; corr = (value * fgf) >> 11; corr = corr > 0xfff ? 0xfff : corr; corr = AddUintClipping(corr, fga, 12); // Update threshold counters // not really useful as they are cleared with every new event if (!((fGainCounterA[adc] == 0x3FFFFFF) || (fGainCounterB[adc] == 0x3FFFFFF))) // stop when full { if (corr >= fgtb) fGainCounterB[adc]++; else if (corr >= fgta) fGainCounterA[adc]++; } if (fgby == 1) return corr; else return value; } void AliTRDmcmSim::FilterGain() { // Read data from fADCF and apply gain filter. for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { fADCF[iAdc][iTimeBin] = FilterGainNextSample(iAdc, fADCF[iAdc][iTimeBin]); } } } void AliTRDmcmSim::FilterTailInit(Int_t baseline) { // Initializes the tail filter assuming that the input has // been at the baseline value (configured by FTFP) for a // sufficiently long time. // exponents and weight calculated from configuration UShort_t alphaLong = 0x3ff & fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTAL); // the weight of the long component UShort_t lambdaLong = (1 << 10) | (1 << 9) | (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTLL) & 0x1FF); // the multiplier UShort_t lambdaShort = (0 << 10) | (1 << 9) | (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTLS) & 0x1FF); // the multiplier Float_t lambdaL = lambdaLong * 1.0 / (1 << 11); Float_t lambdaS = lambdaShort * 1.0 / (1 << 11); Float_t alphaL = alphaLong * 1.0 / (1 << 11); Float_t qup, qdn; qup = (1 - lambdaL) * (1 - lambdaS); qdn = 1 - lambdaS * alphaL - lambdaL * (1 - alphaL); Float_t kdc = qup/qdn; Float_t kt, ql, qs; UShort_t aout; if (baseline < 0) baseline = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP); ql = lambdaL * (1 - lambdaS) * alphaL; qs = lambdaS * (1 - lambdaL) * (1 - alphaL); for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { Int_t value = baseline & 0xFFF; Int_t corr = (value * fTrapConfig->GetTrapReg(AliTRDtrapConfig::TrapReg_t(AliTRDtrapConfig::kFGF0 + iAdc))) >> 11; corr = corr > 0xfff ? 0xfff : corr; corr = AddUintClipping(corr, fTrapConfig->GetTrapReg(AliTRDtrapConfig::TrapReg_t(AliTRDtrapConfig::kFGA0 + iAdc)), 12); kt = kdc * baseline; aout = baseline - (UShort_t) kt; fTailAmplLong[iAdc] = (UShort_t) (aout * ql / (ql + qs)); fTailAmplShort[iAdc] = (UShort_t) (aout * qs / (ql + qs)); } } UShort_t AliTRDmcmSim::FilterTailNextSample(Int_t adc, UShort_t value) { // Returns the output of the tail filter for the given input value. // The output depends on the internal registers and, thus, the // history of the filter. // exponents and weight calculated from configuration UShort_t alphaLong = 0x3ff & fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTAL); // the weight of the long component UShort_t lambdaLong = (1 << 10) | (1 << 9) | (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTLL) & 0x1FF); // the multiplier of the long component UShort_t lambdaShort = (0 << 10) | (1 << 9) | (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTLS) & 0x1FF); // the multiplier of the short component // intermediate signals UInt_t aDiff; UInt_t alInpv; UShort_t aQ; UInt_t tmp; UShort_t inpVolt = value & 0xFFF; // 12 bits // add the present generator outputs aQ = AddUintClipping(fTailAmplLong[adc], fTailAmplShort[adc], 12); // calculate the difference between the input and the generated signal if (inpVolt > aQ) aDiff = inpVolt - aQ; else aDiff = 0; // the inputs to the two generators, weighted alInpv = (aDiff * alphaLong) >> 11; // the new values of the registers, used next time // long component tmp = AddUintClipping(fTailAmplLong[adc], alInpv, 12); tmp = (tmp * lambdaLong) >> 11; fTailAmplLong[adc] = tmp & 0xFFF; // short component tmp = AddUintClipping(fTailAmplShort[adc], aDiff - alInpv, 12); tmp = (tmp * lambdaShort) >> 11; fTailAmplShort[adc] = tmp & 0xFFF; // the output of the filter if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTBY) == 0) // bypass mode, active low return value; else return aDiff; } void AliTRDmcmSim::FilterTail() { // Apply tail cancellation filter to all data. for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { fADCF[iAdc][iTimeBin] = FilterTailNextSample(iAdc, fADCF[iAdc][iTimeBin]); } } } void AliTRDmcmSim::ZSMapping() { // // Zero Suppression Mapping implemented in TRAP chip // only implemented for up to 30 timebins // // See detail TRAP manual "Data Indication" section: // http://www.kip.uni-heidelberg.de/ti/TRD/doc/trap/TRAP-UserManual.pdf // if( !CheckInitialized() ) return; Int_t eBIS = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBIS); Int_t eBIT = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBIT); Int_t eBIL = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBIL); Int_t eBIN = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBIN); Int_t **adc = fADCF; for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) fZSMap[iAdc] = -1; for( Int_t it = 0 ; it < fNTimeBin ; it++ ) { Int_t iAdc; // current ADC channel Int_t ap; Int_t ac; Int_t an; Int_t mask; Int_t supp; // suppression of the current channel (low active) // ----- first channel ----- iAdc = 0; ap = 0; // previous ac = adc[iAdc ][it]; // current an = adc[iAdc+1][it]; // next mask = ( ac >= ap && ac >= an ) ? 0 : 0x1; // peak center detection mask += ( ap + ac + an > eBIT ) ? 0 : 0x2; // cluster mask += ( ac > eBIS ) ? 0 : 0x4; // absolute large peak supp = (eBIL >> mask) & 1; fZSMap[iAdc] &= ~((1-supp) << it); if( eBIN == 0 ) { // neighbour sensitivity fZSMap[iAdc+1] &= ~((1-supp) << it); } // ----- last channel ----- iAdc = fgkNADC - 1; ap = adc[iAdc-1][it]; // previous ac = adc[iAdc ][it]; // current an = 0; // next mask = ( ac >= ap && ac >= an ) ? 0 : 0x1; // peak center detection mask += ( ap + ac + an > eBIT ) ? 0 : 0x2; // cluster mask += ( ac > eBIS ) ? 0 : 0x4; // absolute large peak supp = (eBIL >> mask) & 1; fZSMap[iAdc] &= ~((1-supp) << it); if( eBIN == 0 ) { // neighbour sensitivity fZSMap[iAdc-1] &= ~((1-supp) << it); } // ----- middle channels ----- for( iAdc = 1 ; iAdc < fgkNADC-1; iAdc++ ) { ap = adc[iAdc-1][it]; // previous ac = adc[iAdc ][it]; // current an = adc[iAdc+1][it]; // next mask = ( ac >= ap && ac >= an ) ? 0 : 0x1; // peak center detection mask += ( ap + ac + an > eBIT ) ? 0 : 0x2; // cluster mask += ( ac > eBIS ) ? 0 : 0x4; // absolute large peak supp = (eBIL >> mask) & 1; fZSMap[iAdc] &= ~((1-supp) << it); if( eBIN == 0 ) { // neighbour sensitivity fZSMap[iAdc-1] &= ~((1-supp) << it); fZSMap[iAdc+1] &= ~((1-supp) << it); } } } } void AliTRDmcmSim::AddHitToFitreg(Int_t adc, UShort_t timebin, UShort_t qtot, Short_t ypos, Int_t label[]) { // Add the given hit to the fit register which is lateron used for // the tracklet calculation. // In addition to the fit sums in the fit register MC information // is stored. if ((timebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS0)) && (timebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE0))) fFitReg[adc].fQ0 += qtot; if ((timebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS1)) && (timebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE1))) fFitReg[adc].fQ1 += qtot; if ((timebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFS) ) && (timebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFE))) { fFitReg[adc].fSumX += timebin; fFitReg[adc].fSumX2 += timebin*timebin; fFitReg[adc].fNhits++; fFitReg[adc].fSumY += ypos; fFitReg[adc].fSumY2 += ypos*ypos; fFitReg[adc].fSumXY += timebin*ypos; } // register hits (MC info) fHits[fNHits].fChannel = adc; fHits[fNHits].fQtot = qtot; fHits[fNHits].fYpos = ypos; fHits[fNHits].fTimebin = timebin; fHits[fNHits].fLabel[0] = label[0]; fHits[fNHits].fLabel[1] = label[1]; fHits[fNHits].fLabel[2] = label[2]; fNHits++; } void AliTRDmcmSim::CalcFitreg() { // Preprocessing. // Detect the hits and fill the fit registers. // Requires 12-bit data from fADCF which means Filter() // has to be called before even if all filters are bypassed. //??? to be clarified: UInt_t adcMask = 0xffffffff; UShort_t timebin, adcch, adcLeft, adcCentral, adcRight, hitQual, timebin1, timebin2, qtotTemp; Short_t ypos, fromLeft, fromRight, found; UShort_t qTotal[19+1]; // the last is dummy UShort_t marked[6], qMarked[6], worse1, worse2; timebin1 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFS); if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS0) < timebin1) timebin1 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS0); timebin2 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFE); if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE1) > timebin2) timebin2 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE1); // reset the fit registers fNHits = 0; for (adcch = 0; adcch < fgkNADC-2; adcch++) // due to border channels { fFitReg[adcch].fNhits = 0; fFitReg[adcch].fQ0 = 0; fFitReg[adcch].fQ1 = 0; fFitReg[adcch].fSumX = 0; fFitReg[adcch].fSumY = 0; fFitReg[adcch].fSumX2 = 0; fFitReg[adcch].fSumY2 = 0; fFitReg[adcch].fSumXY = 0; } for (timebin = timebin1; timebin < timebin2; timebin++) { // first find the hit candidates and store the total cluster charge in qTotal array // in case of not hit store 0 there. for (adcch = 0; adcch < fgkNADC-2; adcch++) { if ( ( (adcMask >> adcch) & 7) == 7) //??? all 3 channels are present in case of ZS { adcLeft = fADCF[adcch ][timebin]; adcCentral = fADCF[adcch+1][timebin]; adcRight = fADCF[adcch+2][timebin]; if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPVBY) == 1) hitQual = ( (adcLeft * adcRight) < (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPVT) * adcCentral) ); else hitQual = 1; // The accumulated charge is with the pedestal!!! qtotTemp = adcLeft + adcCentral + adcRight; if ( (hitQual) && (qtotTemp >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPHT)) && (adcLeft <= adcCentral) && (adcCentral > adcRight) ) qTotal[adcch] = qtotTemp; else qTotal[adcch] = 0; } else qTotal[adcch] = 0; //jkl if (qTotal[adcch] != 0) AliDebug(10,Form("ch %2d qTotal %5d",adcch, qTotal[adcch])); } fromLeft = -1; adcch = 0; found = 0; marked[4] = 19; // invalid channel marked[5] = 19; // invalid channel qTotal[19] = 0; while ((adcch < 16) && (found < 3)) { if (qTotal[adcch] > 0) { fromLeft = adcch; marked[2*found+1]=adcch; found++; } adcch++; } fromRight = -1; adcch = 18; found = 0; while ((adcch > 2) && (found < 3)) { if (qTotal[adcch] > 0) { marked[2*found]=adcch; found++; fromRight = adcch; } adcch--; } AliDebug(10,Form("Fromleft=%d, Fromright=%d",fromLeft, fromRight)); // here mask the hit candidates in the middle, if any if ((fromLeft >= 0) && (fromRight >= 0) && (fromLeft < fromRight)) for (adcch = fromLeft+1; adcch < fromRight; adcch++) qTotal[adcch] = 0; found = 0; for (adcch = 0; adcch < 19; adcch++) if (qTotal[adcch] > 0) found++; // NOT READY if (found > 4) // sorting like in the TRAP in case of 5 or 6 candidates! { if (marked[4] == marked[5]) marked[5] = 19; for (found=0; found<6; found++) { qMarked[found] = qTotal[marked[found]] >> 4; AliDebug(10,Form("ch_%d qTotal %d qTotals %d",marked[found],qTotal[marked[found]],qMarked[found])); } Sort6To2Worst(marked[0], marked[3], marked[4], marked[1], marked[2], marked[5], qMarked[0], qMarked[3], qMarked[4], qMarked[1], qMarked[2], qMarked[5], &worse1, &worse2); // Now mask the two channels with the smallest charge if (worse1 < 19) { qTotal[worse1] = 0; AliDebug(10,Form("Kill ch %d\n",worse1)); } if (worse2 < 19) { qTotal[worse2] = 0; AliDebug(10,Form("Kill ch %d\n",worse2)); } } for (adcch = 0; adcch < 19; adcch++) { if (qTotal[adcch] > 0) // the channel is marked for processing { adcLeft = fADCF[adcch ][timebin]; adcCentral = fADCF[adcch+1][timebin]; adcRight = fADCF[adcch+2][timebin]; // hit detected, in TRAP we have 4 units and a hit-selection, here we proceed all channels! // subtract the pedestal TPFP, clipping instead of wrapping Int_t regTPFP = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP); AliDebug(10, Form("Hit found, time=%d, adcch=%d/%d/%d, adc values=%d/%d/%d, regTPFP=%d, TPHT=%d\n", timebin, adcch, adcch+1, adcch+2, adcLeft, adcCentral, adcRight, regTPFP, fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPHT))); if (adcLeft < regTPFP) adcLeft = 0; else adcLeft -= regTPFP; if (adcCentral < regTPFP) adcCentral = 0; else adcCentral -= regTPFP; if (adcRight < regTPFP) adcRight = 0; else adcRight -= regTPFP; // Calculate the center of gravity // checking for adcCentral != 0 (in case of "bad" configuration) if (adcCentral == 0) continue; ypos = 128*(adcLeft - adcRight) / adcCentral; if (ypos < 0) ypos = -ypos; // make the correction using the position LUT ypos = ypos + fTrapConfig->GetTrapReg((AliTRDtrapConfig::TrapReg_t) (AliTRDtrapConfig::kTPL00 + (ypos & 0x7F)), fDetector, fRobPos, fMcmPos); if (adcLeft > adcRight) ypos = -ypos; // label calculation (up to 3) Int_t mcLabel[] = {-1, -1, -1}; if (fDigitsManager) { const Int_t maxLabels = 9; Int_t label[maxLabels] = { 0 }; // up to 9 different labels possible Int_t count[maxLabels] = { 0 }; Int_t nLabels = 0; Int_t padcol[3]; padcol[0] = fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, adcch); padcol[1] = fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, adcch+1); padcol[2] = fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, adcch+2); Int_t padrow = fFeeParam->GetPadRowFromMCM(fRobPos, fMcmPos); for (Int_t iDict = 0; iDict < 3; iDict++) { if (!fDict[iDict]) continue; for (Int_t iPad = 0; iPad < 3; iPad++) { if (padcol[iPad] < 0) continue; Int_t currLabel = fDict[iDict]->GetData(padrow, padcol[iPad], timebin); AliDebug(10, Form("Read label: %4i for det: %3i, row: %i, col: %i, tb: %i\n", currLabel, fDetector, padrow, padcol[iPad], timebin)); for (Int_t iLabel = 0; iLabel < nLabels; iLabel++) { if (currLabel == label[iLabel]) { count[iLabel]++; currLabel = -1; break; } } if (currLabel >= 0) { label[nLabels] = currLabel; count[nLabels] = 1; nLabels++; } } } Int_t index[2*maxLabels]; TMath::Sort(maxLabels, count, index); for (Int_t i = 0; i < 3; i++) { if (count[index[i]] <= 0) break; mcLabel[i] = label[index[i]]; } } // add the hit to the fitregister AddHitToFitreg(adcch, timebin, qTotal[adcch], ypos, mcLabel); } } } for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { if (fFitReg[iAdc].fNhits != 0) { AliDebug(2, Form("fitreg[%i]: nHits = %i, sumX = %i, sumY = %i, sumX2 = %i, sumY2 = %i, sumXY = %i", iAdc, fFitReg[iAdc].fNhits, fFitReg[iAdc].fSumX, fFitReg[iAdc].fSumY, fFitReg[iAdc].fSumX2, fFitReg[iAdc].fSumY2, fFitReg[iAdc].fSumXY )); } } } void AliTRDmcmSim::TrackletSelection() { // Select up to 4 tracklet candidates from the fit registers // and assign them to the CPUs. UShort_t adcIdx, i, j, ntracks, tmp; UShort_t trackletCand[18][2]; // store the adcch[0] and number of hits[1] for all tracklet candidates ntracks = 0; for (adcIdx = 0; adcIdx < 18; adcIdx++) // ADCs if ( (fFitReg[adcIdx].fNhits >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPCL)) && (fFitReg[adcIdx].fNhits+fFitReg[adcIdx+1].fNhits >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPCT))) { trackletCand[ntracks][0] = adcIdx; trackletCand[ntracks][1] = fFitReg[adcIdx].fNhits+fFitReg[adcIdx+1].fNhits; AliDebug(10,Form("%d %2d %4d\n", ntracks, trackletCand[ntracks][0], trackletCand[ntracks][1])); ntracks++; }; for (i=0; i<ntracks;i++) AliDebug(10,Form("%d %d %d\n",i,trackletCand[i][0], trackletCand[i][1])); if (ntracks > 4) { // primitive sorting according to the number of hits for (j = 0; j < (ntracks-1); j++) { for (i = j+1; i < ntracks; i++) { if ( (trackletCand[j][1] < trackletCand[i][1]) || ( (trackletCand[j][1] == trackletCand[i][1]) && (trackletCand[j][0] < trackletCand[i][0]) ) ) { // swap j & i tmp = trackletCand[j][1]; trackletCand[j][1] = trackletCand[i][1]; trackletCand[i][1] = tmp; tmp = trackletCand[j][0]; trackletCand[j][0] = trackletCand[i][0]; trackletCand[i][0] = tmp; } } } ntracks = 4; // cut the rest, 4 is the max } // else is not necessary to sort // now sort, so that the first tracklet going to CPU0 corresponds to the highest adc channel - as in the TRAP for (j = 0; j < (ntracks-1); j++) { for (i = j+1; i < ntracks; i++) { if (trackletCand[j][0] < trackletCand[i][0]) { // swap j & i tmp = trackletCand[j][1]; trackletCand[j][1] = trackletCand[i][1]; trackletCand[i][1] = tmp; tmp = trackletCand[j][0]; trackletCand[j][0] = trackletCand[i][0]; trackletCand[i][0] = tmp; } } } for (i = 0; i < ntracks; i++) // CPUs with tracklets. fFitPtr[i] = trackletCand[i][0]; // pointer to the left channel with tracklet for CPU[i] for (i = ntracks; i < 4; i++) // CPUs without tracklets fFitPtr[i] = 31; // pointer to the left channel with tracklet for CPU[i] = 31 (invalid) AliDebug(10,Form("found %i tracklet candidates\n", ntracks)); for (i = 0; i < 4; i++) AliDebug(10,Form("fitPtr[%i]: %i\n", i, fFitPtr[i])); } void AliTRDmcmSim::FitTracklet() { // Perform the actual tracklet fit based on the fit sums // which have been filled in the fit registers. // parameters in fitred.asm (fit program) Int_t rndAdd = 0; Int_t decPlaces = 5; // must be larger than 1 or change the following code // if (decPlaces > 1) rndAdd = (1 << (decPlaces-1)) + 1; // else if (decPlaces == 1) // rndAdd = 1; Int_t ndriftDp = 5; // decimal places for drift time Long64_t shift = ((Long64_t) 1 << 32); // calculated in fitred.asm Int_t padrow = ((fRobPos >> 1) << 2) | (fMcmPos >> 2); Int_t yoffs = (((((fRobPos & 0x1) << 2) + (fMcmPos & 0x3)) * 18) << 8) - ((18*4*2 - 18*2 - 1) << 7); yoffs = yoffs << decPlaces; // holds position of ADC channel 1 Int_t layer = fDetector % 6; UInt_t scaleY = (UInt_t) ((0.635 + 0.03 * layer)/(256.0 * 160.0e-4) * shift); UInt_t scaleD = (UInt_t) ((0.635 + 0.03 * layer)/(256.0 * 140.0e-4) * shift); Int_t deflCorr = (Int_t) fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrDeflCorr, fDetector, fRobPos, fMcmPos); Int_t ndrift = (Int_t) fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrNdrift, fDetector, fRobPos, fMcmPos); // local variables for calculation Long64_t mult, temp, denom; //??? UInt_t q0, q1, pid; // charges in the two windows and total charge UShort_t nHits; // number of hits Int_t slope, offset; // slope and offset of the tracklet Int_t sumX, sumY, sumXY, sumX2; // fit sums from fit registers Int_t sumY2; // not used in the current TRAP program, now used for error calculation (simulation only) Float_t fitError, fitSlope, fitOffset; FitReg_t *fit0, *fit1; // pointers to relevant fit registers // const uint32_t OneDivN[32] = { // 2**31/N : exactly like in the TRAP, the simple division here gives the same result! // 0x00000000, 0x80000000, 0x40000000, 0x2AAAAAA0, 0x20000000, 0x19999990, 0x15555550, 0x12492490, // 0x10000000, 0x0E38E380, 0x0CCCCCC0, 0x0BA2E8B0, 0x0AAAAAA0, 0x09D89D80, 0x09249240, 0x08888880, // 0x08000000, 0x07878780, 0x071C71C0, 0x06BCA1A0, 0x06666660, 0x06186180, 0x05D17450, 0x0590B210, // 0x05555550, 0x051EB850, 0x04EC4EC0, 0x04BDA120, 0x04924920, 0x0469EE50, 0x04444440, 0x04210840}; for (Int_t cpu = 0; cpu < 4; cpu++) { if (fFitPtr[cpu] == 31) { fMCMT[cpu] = 0x10001000; //??? AliTRDfeeParam::GetTrackletEndmarker(); } else { fit0 = &fFitReg[fFitPtr[cpu] ]; fit1 = &fFitReg[fFitPtr[cpu]+1]; // next channel mult = 1; mult = mult << (32 + decPlaces); mult = -mult; // Merging nHits = fit0->fNhits + fit1->fNhits; // number of hits sumX = fit0->fSumX + fit1->fSumX; sumX2 = fit0->fSumX2 + fit1->fSumX2; denom = ((Long64_t) nHits)*((Long64_t) sumX2) - ((Long64_t) sumX)*((Long64_t) sumX); mult = mult / denom; // exactly like in the TRAP program q0 = fit0->fQ0 + fit1->fQ0; q1 = fit0->fQ1 + fit1->fQ1; sumY = fit0->fSumY + fit1->fSumY + 256*fit1->fNhits; sumXY = fit0->fSumXY + fit1->fSumXY + 256*fit1->fSumX; sumY2 = fit0->fSumY2 + fit1->fSumY2 + 512*fit1->fSumY + 256*256*fit1->fNhits; slope = nHits*sumXY - sumX * sumY; offset = sumX2*sumY - sumX * sumXY; temp = mult * slope; slope = temp >> 32; // take the upper 32 bits slope = -slope; temp = mult * offset; offset = temp >> 32; // take the upper 32 bits offset = offset + yoffs; AliDebug(10, Form("slope = %i, slope * ndrift = %i, deflCorr: %i", slope, slope * ndrift, deflCorr)); slope = ((slope * ndrift) >> ndriftDp) + deflCorr; offset = offset - (fFitPtr[cpu] << (8 + decPlaces)); temp = slope; temp = temp * scaleD; slope = (temp >> 32); temp = offset; temp = temp * scaleY; offset = (temp >> 32); // rounding, like in the TRAP slope = (slope + rndAdd) >> decPlaces; offset = (offset + rndAdd) >> decPlaces; AliDebug(5, Form("Det: %3i, ROB: %i, MCM: %2i: deflection: %i, min: %i, max: %i", fDetector, fRobPos, fMcmPos, slope, (Int_t) fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrDeflCutStart + 2*fFitPtr[cpu], fDetector, fRobPos, fMcmPos), (Int_t) fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrDeflCutStart + 1 + 2*fFitPtr[cpu], fDetector, fRobPos, fMcmPos))); AliDebug(5, Form("Fit sums: x = %i, X = %i, y = %i, Y = %i, Z = %i", sumX, sumX2, sumY, sumY2, sumXY)); fitSlope = (Float_t) (nHits * sumXY - sumX * sumY) / (nHits * sumX2 - sumX*sumX); fitOffset = (Float_t) (sumX2 * sumY - sumX * sumXY) / (nHits * sumX2 - sumX*sumX); Float_t sx = (Float_t) sumX; Float_t sx2 = (Float_t) sumX2; Float_t sy = (Float_t) sumY; Float_t sy2 = (Float_t) sumY2; Float_t sxy = (Float_t) sumXY; fitError = sy2 - (sx2 * sy*sy - 2 * sx * sxy * sy + nHits * sxy*sxy) / (nHits * sx2 - sx*sx); //fitError = (Float_t) sumY2 - (Float_t) (sumY*sumY) / nHits - fitSlope * ((Float_t) (sumXY - sumX*sumY) / nHits); Bool_t rejected = kFALSE; // deflection range table from DMEM if ((slope < ((Int_t) fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrDeflCutStart + 2*fFitPtr[cpu], fDetector, fRobPos, fMcmPos))) || (slope > ((Int_t) fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrDeflCutStart + 1 + 2*fFitPtr[cpu], fDetector, fRobPos, fMcmPos)))) rejected = kTRUE; if (rejected && GetApplyCut()) { fMCMT[cpu] = 0x10001000; //??? AliTRDfeeParam::GetTrackletEndmarker(); } else { if (slope > 63 || slope < -64) { // wrapping in TRAP! AliDebug(1,Form("Overflow in slope: %i, tracklet discarded!", slope)); fMCMT[cpu] = 0x10001000; continue; } slope = slope & 0x7F; // 7 bit if (offset > 0xfff || offset < -0xfff) AliWarning("Overflow in offset"); offset = offset & 0x1FFF; // 13 bit pid = GetPID(q0 >> fgkAddDigits, q1 >> fgkAddDigits); // divided by 4 because in simulation there are two additional decimal places if (pid > 0xff) AliWarning("Overflow in PID"); pid = pid & 0xFF; // 8 bit, exactly like in the TRAP program // assemble and store the tracklet word fMCMT[cpu] = (pid << 24) | (padrow << 20) | (slope << 13) | offset; // calculate MC label Int_t mcLabel[] = { -1, -1, -1}; Int_t nHits0 = 0; Int_t nHits1 = 0; if (fDigitsManager) { const Int_t maxLabels = 30; Int_t label[maxLabels] = {0}; // up to 30 different labels possible Int_t count[maxLabels] = {0}; Int_t nLabels = 0; for (Int_t iHit = 0; iHit < fNHits; iHit++) { if ((fHits[iHit].fChannel - fFitPtr[cpu] < 0) || (fHits[iHit].fChannel - fFitPtr[cpu] > 1)) continue; // counting contributing hits if (fHits[iHit].fTimebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS0) && fHits[iHit].fTimebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE0)) nHits0++; if (fHits[iHit].fTimebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS1) && fHits[iHit].fTimebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE1)) nHits1++; for (Int_t i = 0; i < 3; i++) { Int_t currLabel = fHits[iHit].fLabel[i]; for (Int_t iLabel = 0; iLabel < nLabels; iLabel++) { if (currLabel == label[iLabel]) { count[iLabel]++; currLabel = -1; break; } } if (currLabel >= 0 && nLabels < maxLabels) { label[nLabels] = currLabel; count[nLabels]++; nLabels++; } } } Int_t index[2*maxLabels]; TMath::Sort(maxLabels, count, index); for (Int_t i = 0; i < 3; i++) { if (count[index[i]] <= 0) break; mcLabel[i] = label[index[i]]; } } new ((*fTrackletArray)[fTrackletArray->GetEntriesFast()]) AliTRDtrackletMCM((UInt_t) fMCMT[cpu], fDetector*2 + fRobPos%2, fRobPos, fMcmPos); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetLabel(mcLabel); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetNHits(fit0->fNhits + fit1->fNhits); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetNHits0(nHits0); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetNHits1(nHits1); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetQ0(q0 >> fgkAddDigits); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetQ1(q1 >> fgkAddDigits); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetSlope(fitSlope); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetOffset(fitOffset); ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetError(TMath::Sqrt(TMath::Abs(fitError)/nHits)); // // cluster information // Float_t *res = new Float_t[nHits]; // Float_t *qtot = new Float_t[nHits]; // Int_t nCls = 0; // for (Int_t iHit = 0; iHit < fNHits; iHit++) { // // check if hit contributes // if (fHits[iHit].fChannel == fFitPtr[cpu]) { // res[nCls] = fHits[iHit].fYpos - (fitSlope * fHits[iHit].fTimebin + fitOffset); // qtot[nCls] = fHits[iHit].fQtot; // nCls++; // } // else if (fHits[iHit].fChannel == fFitPtr[cpu] + 1) { // res[nCls] = fHits[iHit].fYpos + 256 - (fitSlope * fHits[iHit].fTimebin + fitOffset); // qtot[nCls] = fHits[iHit].fQtot; // nCls++; // } // } // ((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetClusters(res, qtot, nCls); // delete [] res; // delete [] qtot; if (fitError < 0) AliError(Form("Strange fit error: %f from Sx: %i, Sy: %i, Sxy: %i, Sx2: %i, Sy2: %i, nHits: %i", fitError, sumX, sumY, sumXY, sumX2, sumY2, nHits)); AliDebug(3, Form("fit slope: %f, offset: %f, error: %f", fitSlope, fitOffset, TMath::Sqrt(TMath::Abs(fitError)/nHits))); } } } } void AliTRDmcmSim::Tracklet() { // Run the tracklet calculation by calling sequentially: // CalcFitreg(); TrackletSelection(); FitTracklet() // and store the tracklets if (!fInitialized) { AliError("Called uninitialized! Nothing done!"); return; } fTrackletArray->Delete(); CalcFitreg(); if (fNHits == 0) return; TrackletSelection(); FitTracklet(); } Bool_t AliTRDmcmSim::StoreTracklets() { // store the found tracklets via the loader if (fTrackletArray->GetEntriesFast() == 0) return kTRUE; AliRunLoader *rl = AliRunLoader::Instance(); AliDataLoader *dl = 0x0; if (rl) dl = rl->GetLoader("TRDLoader")->GetDataLoader("tracklets"); if (!dl) { AliError("Could not get the tracklets data loader!"); return kFALSE; } TTree *trackletTree = dl->Tree(); if (!trackletTree) { dl->MakeTree(); trackletTree = dl->Tree(); } AliTRDtrackletMCM *trkl = 0x0; TBranch *trkbranch = trackletTree->GetBranch(fTrklBranchName.Data()); if (!trkbranch) trkbranch = trackletTree->Branch(fTrklBranchName.Data(), "AliTRDtrackletMCM", &trkl, 32000); for (Int_t iTracklet = 0; iTracklet < fTrackletArray->GetEntriesFast(); iTracklet++) { trkl = ((AliTRDtrackletMCM*) (*fTrackletArray)[iTracklet]); trkbranch->SetAddress(&trkl); trkbranch->Fill(); } return kTRUE; } void AliTRDmcmSim::WriteData(AliTRDarrayADC *digits) { // write back the processed data configured by EBSF // EBSF = 1: unfiltered data; EBSF = 0: filtered data // zero-suppressed valued are written as -1 to digits if( !CheckInitialized() ) return; Int_t offset = (fMcmPos % 4 + 1) * 21 + (fRobPos % 2) * 84 - 1; if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBSF) != 0) // store unfiltered data { for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { if (~fZSMap[iAdc] == 0) { for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { digits->SetDataByAdcCol(GetRow(), offset - iAdc, iTimeBin, -1); } } else if (iAdc < 2 || iAdc == 20) { for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { digits->SetDataByAdcCol(GetRow(), offset - iAdc, iTimeBin, (fADCR[iAdc][iTimeBin] >> fgkAddDigits) - fgAddBaseline); } } } } else { for (Int_t iAdc = 0; iAdc < fgkNADC; iAdc++) { if (~fZSMap[iAdc] != 0) { for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { digits->SetDataByAdcCol(GetRow(), offset - iAdc, iTimeBin, (fADCF[iAdc][iTimeBin] >> fgkAddDigits) - fgAddBaseline); } } else { for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { digits->SetDataByAdcCol(GetRow(), offset - iAdc, iTimeBin, -1); } } } } } // ****************************** // PID section // // Memory area for the LUT: 0xC100 to 0xC3FF // // The addresses for the parameters (the order is optimized for maximum calculation speed in the MCMs): // 0xC028: cor1 // 0xC029: nBins(sF) // 0xC02A: cor0 // 0xC02B: TableLength // Defined in AliTRDtrapConfig.h // // The algorithm implemented in the TRAP program of the MCMs (Venelin Angelov) // 1) set the read pointer to the beginning of the Parameters in DMEM // 2) shift right the FitReg with the Q0 + (Q1 << 16) to get Q1 // 3) read cor1 with rpointer++ // 4) start cor1*Q1 // 5) read nBins with rpointer++ // 6) start nBins*cor1*Q1 // 7) read cor0 with rpointer++ // 8) swap hi-low parts in FitReg, now is Q1 + (Q0 << 16) // 9) shift right to get Q0 // 10) start cor0*Q0 // 11) read TableLength // 12) compare cor0*Q0 with nBins // 13) if >=, clip cor0*Q0 to nBins-1 // 14) add cor0*Q0 to nBins*cor1*Q1 // 15) compare the result with TableLength // 16) if >=, clip to TableLength-1 // 17) read from the LUT 8 bits Int_t AliTRDmcmSim::GetPID(Int_t q0, Int_t q1) { // return PID calculated from charges accumulated in two time windows ULong64_t addrQ0; ULong64_t addr; UInt_t nBinsQ0 = fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrLUTnbins); // number of bins in q0 / 4 !! UInt_t pidTotalSize = fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrLUTLength); if(nBinsQ0==0 || pidTotalSize==0) // make sure we don't run into trouble if the value for Q0 is not configured return 0; // Q1 not configured is ok for 1D LUT ULong_t corrQ0 = fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrLUTcor0, fDetector, fRobPos, fMcmPos); ULong_t corrQ1 = fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrLUTcor1, fDetector, fRobPos, fMcmPos); if(corrQ0==0) // make sure we don't run into trouble if one of the values is not configured return 0; addrQ0 = corrQ0; addrQ0 = (((addrQ0*q0)>>16)>>16); // because addrQ0 = (q0 * corrQ0) >> 32; does not work for unknown reasons if(addrQ0 >= nBinsQ0) { // check for overflow AliDebug(5,Form("Overflow in q0: %llu/4 is bigger then %u", addrQ0, nBinsQ0)); addrQ0 = nBinsQ0 -1; } addr = corrQ1; addr = (((addr*q1)>>16)>>16); addr = addrQ0 + nBinsQ0*addr; // because addr = addrQ0 + nBinsQ0* (((corrQ1*q1)>>32); does not work if(addr >= pidTotalSize) { AliDebug(5,Form("Overflow in q1. Address %llu/4 is bigger then %u", addr, pidTotalSize)); addr = pidTotalSize -1; } // For a LUT with 11 input and 8 output bits, the first memory address is set to LUT[0] | (LUT[1] << 8) | (LUT[2] << 16) | (LUT[3] << 24) // and so on UInt_t result = fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrLUTStart+(addr/4)); return (result>>((addr%4)*8)) & 0xFF; } // help functions, to be cleaned up UInt_t AliTRDmcmSim::AddUintClipping(UInt_t a, UInt_t b, UInt_t nbits) const { // // This function adds a and b (unsigned) and clips to // the specified number of bits. // UInt_t sum = a + b; if (nbits < 32) { UInt_t maxv = (1 << nbits) - 1;; if (sum > maxv) sum = maxv; } else { if ((sum < a) || (sum < b)) sum = 0xFFFFFFFF; } return sum; } void AliTRDmcmSim::Sort2(UShort_t idx1i, UShort_t idx2i, \ UShort_t val1i, UShort_t val2i, \ UShort_t * const idx1o, UShort_t * const idx2o, \ UShort_t * const val1o, UShort_t * const val2o) const { // sorting for tracklet selection if (val1i > val2i) { *idx1o = idx1i; *idx2o = idx2i; *val1o = val1i; *val2o = val2i; } else { *idx1o = idx2i; *idx2o = idx1i; *val1o = val2i; *val2o = val1i; } } void AliTRDmcmSim::Sort3(UShort_t idx1i, UShort_t idx2i, UShort_t idx3i, \ UShort_t val1i, UShort_t val2i, UShort_t val3i, \ UShort_t * const idx1o, UShort_t * const idx2o, UShort_t * const idx3o, \ UShort_t * const val1o, UShort_t * const val2o, UShort_t * const val3o) { // sorting for tracklet selection Int_t sel; if (val1i > val2i) sel=4; else sel=0; if (val2i > val3i) sel=sel + 2; if (val3i > val1i) sel=sel + 1; switch(sel) { case 6 : // 1 > 2 > 3 => 1 2 3 case 0 : // 1 = 2 = 3 => 1 2 3 : in this case doesn't matter, but so is in hardware! *idx1o = idx1i; *idx2o = idx2i; *idx3o = idx3i; *val1o = val1i; *val2o = val2i; *val3o = val3i; break; case 4 : // 1 > 2, 2 <= 3, 3 <= 1 => 1 3 2 *idx1o = idx1i; *idx2o = idx3i; *idx3o = idx2i; *val1o = val1i; *val2o = val3i; *val3o = val2i; break; case 2 : // 1 <= 2, 2 > 3, 3 <= 1 => 2 1 3 *idx1o = idx2i; *idx2o = idx1i; *idx3o = idx3i; *val1o = val2i; *val2o = val1i; *val3o = val3i; break; case 3 : // 1 <= 2, 2 > 3, 3 > 1 => 2 3 1 *idx1o = idx2i; *idx2o = idx3i; *idx3o = idx1i; *val1o = val2i; *val2o = val3i; *val3o = val1i; break; case 1 : // 1 <= 2, 2 <= 3, 3 > 1 => 3 2 1 *idx1o = idx3i; *idx2o = idx2i; *idx3o = idx1i; *val1o = val3i; *val2o = val2i; *val3o = val1i; break; case 5 : // 1 > 2, 2 <= 3, 3 > 1 => 3 1 2 *idx1o = idx3i; *idx2o = idx1i; *idx3o = idx2i; *val1o = val3i; *val2o = val1i; *val3o = val2i; break; default: // the rest should NEVER happen! AliError("ERROR in Sort3!!!\n"); break; } } void AliTRDmcmSim::Sort6To4(UShort_t idx1i, UShort_t idx2i, UShort_t idx3i, UShort_t idx4i, UShort_t idx5i, UShort_t idx6i, \ UShort_t val1i, UShort_t val2i, UShort_t val3i, UShort_t val4i, UShort_t val5i, UShort_t val6i, \ UShort_t * const idx1o, UShort_t * const idx2o, UShort_t * const idx3o, UShort_t * const idx4o, \ UShort_t * const val1o, UShort_t * const val2o, UShort_t * const val3o, UShort_t * const val4o) { // sorting for tracklet selection UShort_t idx21s, idx22s, idx23s, dummy; UShort_t val21s, val22s, val23s; UShort_t idx23as, idx23bs; UShort_t val23as, val23bs; Sort3(idx1i, idx2i, idx3i, val1i, val2i, val3i, idx1o, &idx21s, &idx23as, val1o, &val21s, &val23as); Sort3(idx4i, idx5i, idx6i, val4i, val5i, val6i, idx2o, &idx22s, &idx23bs, val2o, &val22s, &val23bs); Sort2(idx23as, idx23bs, val23as, val23bs, &idx23s, &dummy, &val23s, &dummy); Sort3(idx21s, idx22s, idx23s, val21s, val22s, val23s, idx3o, idx4o, &dummy, val3o, val4o, &dummy); } void AliTRDmcmSim::Sort6To2Worst(UShort_t idx1i, UShort_t idx2i, UShort_t idx3i, UShort_t idx4i, UShort_t idx5i, UShort_t idx6i, \ UShort_t val1i, UShort_t val2i, UShort_t val3i, UShort_t val4i, UShort_t val5i, UShort_t val6i, \ UShort_t * const idx5o, UShort_t * const idx6o) { // sorting for tracklet selection UShort_t idx21s, idx22s, idx23s, dummy1, dummy2, dummy3, dummy4, dummy5; UShort_t val21s, val22s, val23s; UShort_t idx23as, idx23bs; UShort_t val23as, val23bs; Sort3(idx1i, idx2i, idx3i, val1i, val2i, val3i, &dummy1, &idx21s, &idx23as, &dummy2, &val21s, &val23as); Sort3(idx4i, idx5i, idx6i, val4i, val5i, val6i, &dummy1, &idx22s, &idx23bs, &dummy2, &val22s, &val23bs); Sort2(idx23as, idx23bs, val23as, val23bs, &idx23s, idx5o, &val23s, &dummy1); Sort3(idx21s, idx22s, idx23s, val21s, val22s, val23s, &dummy1, &dummy2, idx6o, &dummy3, &dummy4, &dummy5); } // ----- I/O implementation ----- ostream& AliTRDmcmSim::Text(ostream& os) { // manipulator to activate output in text format (default) os.iword(fgkFormatIndex) = 0; return os; } ostream& AliTRDmcmSim::Cfdat(ostream& os) { // manipulator to activate output in CFDAT format // to send to the FEE via SCSN os.iword(fgkFormatIndex) = 1; return os; } ostream& AliTRDmcmSim::Raw(ostream& os) { // manipulator to activate output as raw data dump os.iword(fgkFormatIndex) = 2; return os; } ostream& operator<<(ostream& os, const AliTRDmcmSim& mcm) { // output implementation // no output for non-initialized MCM if (!mcm.CheckInitialized()) return os; // ----- human-readable output ----- if (os.iword(AliTRDmcmSim::fgkFormatIndex) == 0) { os << "MCM " << mcm.fMcmPos << " on ROB " << mcm.fRobPos << " in detector " << mcm.fDetector << std::endl; os << "----- Unfiltered ADC data (10 bit) -----" << std::endl; os << "ch "; for (Int_t iChannel = 0; iChannel < mcm.fgkNADC; iChannel++) os << std::setw(5) << iChannel; os << std::endl; for (Int_t iTimeBin = 0; iTimeBin < mcm.fNTimeBin; iTimeBin++) { os << "tb " << std::setw(2) << iTimeBin << ":"; for (Int_t iChannel = 0; iChannel < mcm.fgkNADC; iChannel++) { os << std::setw(5) << (mcm.fADCR[iChannel][iTimeBin] >> mcm.fgkAddDigits); } os << std::endl; } os << "----- Filtered ADC data (10+2 bit) -----" << std::endl; os << "ch "; for (Int_t iChannel = 0; iChannel < mcm.fgkNADC; iChannel++) os << std::setw(4) << iChannel << ((~mcm.fZSMap[iChannel] != 0) ? "!" : " "); os << std::endl; for (Int_t iTimeBin = 0; iTimeBin < mcm.fNTimeBin; iTimeBin++) { os << "tb " << std::setw(2) << iTimeBin << ":"; for (Int_t iChannel = 0; iChannel < mcm.fgkNADC; iChannel++) { os << std::setw(4) << (mcm.fADCF[iChannel][iTimeBin]) << (((mcm.fZSMap[iChannel] & (1 << iTimeBin)) == 0) ? "!" : " "); } os << std::endl; } } // ----- CFDAT output ----- else if(os.iword(AliTRDmcmSim::fgkFormatIndex) == 1) { Int_t dest = 127; Int_t addrOffset = 0x2000; Int_t addrStep = 0x80; for (Int_t iTimeBin = 0; iTimeBin < mcm.fNTimeBin; iTimeBin++) { for (Int_t iChannel = 0; iChannel < mcm.fgkNADC; iChannel++) { os << std::setw(5) << 10 << std::setw(5) << addrOffset + iChannel * addrStep + iTimeBin << std::setw(5) << (mcm.fADCF[iChannel][iTimeBin]) << std::setw(5) << dest << std::endl; } os << std::endl; } } // ----- raw data ouptut ----- else if (os.iword(AliTRDmcmSim::fgkFormatIndex) == 2) { Int_t bufSize = 300; UInt_t *buf = new UInt_t[bufSize]; Int_t bufLength = mcm.ProduceRawStream(&buf[0], bufSize); for (Int_t i = 0; i < bufLength; i++) std::cout << "0x" << std::hex << buf[i] << std::dec << std::endl; delete [] buf; } else { os << "unknown format set" << std::endl; } return os; } void AliTRDmcmSim::PrintFitRegXml(ostream& os) const { // print fit registres in XML format bool tracklet=false; for (Int_t cpu = 0; cpu < 4; cpu++) { if(fFitPtr[cpu] != 31) tracklet=true; } if(tracklet==true) { os << "<nginject>" << std::endl; os << "<ack roc=\""<< fDetector << "\" cmndid=\"0\">" << std::endl; os << "<dmem-readout>" << std::endl; os << "<d det=\"" << fDetector << "\">" << std::endl; os << " <ro-board rob=\"" << fRobPos << "\">" << std::endl; os << " <m mcm=\"" << fMcmPos << "\">" << std::endl; for(int cpu=0; cpu<4; cpu++) { os << " <c cpu=\"" << cpu << "\">" << std::endl; if(fFitPtr[cpu] != 31) { for(int adcch=fFitPtr[cpu]; adcch<fFitPtr[cpu]+2; adcch++) { os << " <ch chnr=\"" << adcch << "\">"<< std::endl; os << " <hits>" << fFitReg[adcch].fNhits << "</hits>"<< std::endl; os << " <q0>" << fFitReg[adcch].fQ0/4 << "</q0>"<< std::endl; // divided by 4 because in simulation we have 2 additional decimal places os << " <q1>" << fFitReg[adcch].fQ1/4 << "</q1>"<< std::endl; // in the output os << " <sumx>" << fFitReg[adcch].fSumX << "</sumx>"<< std::endl; os << " <sumxsq>" << fFitReg[adcch].fSumX2 << "</sumxsq>"<< std::endl; os << " <sumy>" << fFitReg[adcch].fSumY << "</sumy>"<< std::endl; os << " <sumysq>" << fFitReg[adcch].fSumY2 << "</sumysq>"<< std::endl; os << " <sumxy>" << fFitReg[adcch].fSumXY << "</sumxy>"<< std::endl; os << " </ch>" << std::endl; } } os << " </c>" << std::endl; } os << " </m>" << std::endl; os << " </ro-board>" << std::endl; os << "</d>" << std::endl; os << "</dmem-readout>" << std::endl; os << "</ack>" << std::endl; os << "</nginject>" << std::endl; } } void AliTRDmcmSim::PrintTrackletsXml(ostream& os) const { // print tracklets in XML format os << "<nginject>" << std::endl; os << "<ack roc=\""<< fDetector << "\" cmndid=\"0\">" << std::endl; os << "<dmem-readout>" << std::endl; os << "<d det=\"" << fDetector << "\">" << std::endl; os << " <ro-board rob=\"" << fRobPos << "\">" << std::endl; os << " <m mcm=\"" << fMcmPos << "\">" << std::endl; Int_t pid, padrow, slope, offset; for(Int_t cpu=0; cpu<4; cpu++) { if(fMCMT[cpu] == 0x10001000) { pid=-1; padrow=-1; slope=-1; offset=-1; } else { pid = (fMCMT[cpu] & 0xFF000000) >> 24; padrow = (fMCMT[cpu] & 0xF00000 ) >> 20; slope = (fMCMT[cpu] & 0xFE000 ) >> 13; offset = (fMCMT[cpu] & 0x1FFF ) ; } os << " <trk> <pid>" << pid << "</pid>" << " <padrow>" << padrow << "</padrow>" << " <slope>" << slope << "</slope>" << " <offset>" << offset << "</offset>" << "</trk>" << std::endl; } os << " </m>" << std::endl; os << " </ro-board>" << std::endl; os << "</d>" << std::endl; os << "</dmem-readout>" << std::endl; os << "</ack>" << std::endl; os << "</nginject>" << std::endl; } void AliTRDmcmSim::PrintAdcDatHuman(ostream& os) const { // print ADC data in human-readable format os << "MCM " << fMcmPos << " on ROB " << fRobPos << " in detector " << fDetector << std::endl; os << "----- Unfiltered ADC data (10 bit) -----" << std::endl; os << "ch "; for (Int_t iChannel = 0; iChannel < fgkNADC; iChannel++) os << std::setw(5) << iChannel; os << std::endl; for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { os << "tb " << std::setw(2) << iTimeBin << ":"; for (Int_t iChannel = 0; iChannel < fgkNADC; iChannel++) { os << std::setw(5) << (fADCR[iChannel][iTimeBin] >> fgkAddDigits); } os << std::endl; } os << "----- Filtered ADC data (10+2 bit) -----" << std::endl; os << "ch "; for (Int_t iChannel = 0; iChannel < fgkNADC; iChannel++) os << std::setw(4) << iChannel << ((~fZSMap[iChannel] != 0) ? "!" : " "); os << std::endl; for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { os << "tb " << std::setw(2) << iTimeBin << ":"; for (Int_t iChannel = 0; iChannel < fgkNADC; iChannel++) { os << std::setw(4) << (fADCF[iChannel][iTimeBin]) << (((fZSMap[iChannel] & (1 << iTimeBin)) == 0) ? "!" : " "); } os << std::endl; } } void AliTRDmcmSim::PrintAdcDatXml(ostream& os) const { // print ADC data in XML format os << "<nginject>" << std::endl; os << "<ack roc=\""<< fDetector << "\" cmndid=\"0\">" << std::endl; os << "<dmem-readout>" << std::endl; os << "<d det=\"" << fDetector << "\">" << std::endl; os << " <ro-board rob=\"" << fRobPos << "\">" << std::endl; os << " <m mcm=\"" << fMcmPos << "\">" << std::endl; for(Int_t iChannel = 0; iChannel < fgkNADC; iChannel++) { os << " <ch chnr=\"" << iChannel << "\">" << std::endl; for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { os << "<tb>" << fADCF[iChannel][iTimeBin]/4 << "</tb>"; } os << " </ch>" << std::endl; } os << " </m>" << std::endl; os << " </ro-board>" << std::endl; os << "</d>" << std::endl; os << "</dmem-readout>" << std::endl; os << "</ack>" << std::endl; os << "</nginject>" << std::endl; } void AliTRDmcmSim::PrintAdcDatDatx(ostream& os, Bool_t broadcast) const { // print ADC data in datx format (to send to FEE) fTrapConfig->PrintDatx(os, 2602, 1, 0, 127); // command to enable the ADC clock - necessary to write ADC values to MCM os << std::endl; Int_t addrOffset = 0x2000; Int_t addrStep = 0x80; Int_t addrOffsetEBSIA = 0x20; for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) { for (Int_t iChannel = 0; iChannel < fgkNADC; iChannel++) { if(broadcast==kFALSE) fTrapConfig->PrintDatx(os, addrOffset+iChannel*addrStep+addrOffsetEBSIA+iTimeBin, (fADCF[iChannel][iTimeBin]/4), GetRobPos(), GetMcmPos()); else fTrapConfig->PrintDatx(os, addrOffset+iChannel*addrStep+addrOffsetEBSIA+iTimeBin, (fADCF[iChannel][iTimeBin]/4), 0, 127); } os << std::endl; } } void AliTRDmcmSim::PrintPidLutHuman() { // print PID LUT in human readable format UInt_t result; UInt_t addrEnd = AliTRDtrapConfig::fgkDmemAddrLUTStart + fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrLUTLength)/4; // /4 because each addr contains 4 values UInt_t nBinsQ0 = fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrLUTnbins); std::cout << "nBinsQ0: " << nBinsQ0 << std::endl; std::cout << "LUT table length: " << fTrapConfig->GetDmemUnsigned(AliTRDtrapConfig::fgkDmemAddrLUTLength) << std::endl; for(UInt_t addr=AliTRDtrapConfig::fgkDmemAddrLUTStart; addr< addrEnd; addr++) { result = fTrapConfig->GetDmemUnsigned(addr); std::cout << addr << " # x: " << ((addr-AliTRDtrapConfig::fgkDmemAddrLUTStart)%((nBinsQ0)/4))*4 << ", y: " <<(addr-AliTRDtrapConfig::fgkDmemAddrLUTStart)/(nBinsQ0/4) << " # " <<((result>>0)&0xFF) << " | " << ((result>>8)&0xFF) << " | " << ((result>>16)&0xFF) << " | " << ((result>>24)&0xFF) << std::endl; } }
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //////////////////////////////////////////////////////////////////////////// // // // The TRD track seed // // // // Authors: // // Alex Bercuci <A.Bercuci@gsi.de> // // Markus Fasel <M.Fasel@gsi.de> // // // //////////////////////////////////////////////////////////////////////////// #include "TMath.h" #include "TLinearFitter.h" #include "TClonesArray.h" // tmp #include <TTreeStream.h> #include "AliLog.h" #include "AliMathBase.h" #include "AliCDBManager.h" #include "AliTracker.h" #include "AliTRDpadPlane.h" #include "AliTRDcluster.h" #include "AliTRDseedV1.h" #include "AliTRDtrackV1.h" #include "AliTRDcalibDB.h" #include "AliTRDchamberTimeBin.h" #include "AliTRDtrackingChamber.h" #include "AliTRDtrackerV1.h" #include "AliTRDReconstructor.h" #include "AliTRDrecoParam.h" #include "Cal/AliTRDCalPID.h" #include "Cal/AliTRDCalROC.h" #include "Cal/AliTRDCalDet.h" ClassImp(AliTRDseedV1) //____________________________________________________________________ AliTRDseedV1::AliTRDseedV1(Int_t det) :AliTRDseed() ,fReconstructor(0x0) ,fClusterIter(0x0) ,fClusterIdx(0) ,fDet(det) ,fMom(0.) ,fSnp(0.) ,fTgl(0.) ,fdX(0.) ,fXref(0.) ,fExB(0.) { // // Constructor // for(int islice=0; islice < knSlices; islice++) fdEdx[islice] = 0.; for(int ispec=0; ispec<AliPID::kSPECIES; ispec++) fProb[ispec] = -1.; fRefCov[0] = 1.; fRefCov[1] = 0.; fRefCov[2] = 1.; // covariance matrix [diagonal] // default sy = 200um and sz = 2.3 cm fCov[0] = 4.e-4; fCov[1] = 0.; fCov[2] = 5.3; } //____________________________________________________________________ AliTRDseedV1::AliTRDseedV1(const AliTRDseedV1 &ref) :AliTRDseed((AliTRDseed&)ref) ,fReconstructor(ref.fReconstructor) ,fClusterIter(0x0) ,fClusterIdx(0) ,fDet(ref.fDet) ,fMom(ref.fMom) ,fSnp(ref.fSnp) ,fTgl(ref.fTgl) ,fdX(ref.fdX) ,fXref(ref.fXref) ,fExB(ref.fExB) { // // Copy Constructor performing a deep copy // //printf("AliTRDseedV1::AliTRDseedV1(const AliTRDseedV1 &)\n"); SetBit(kOwner, kFALSE); for(int islice=0; islice < knSlices; islice++) fdEdx[islice] = ref.fdEdx[islice]; for(int ispec=0; ispec<AliPID::kSPECIES; ispec++) fProb[ispec] = ref.fProb[ispec]; memcpy(fRefCov, ref.fRefCov, 3*sizeof(Double_t)); memcpy(fCov, ref.fCov, 3*sizeof(Double_t)); } //____________________________________________________________________ AliTRDseedV1& AliTRDseedV1::operator=(const AliTRDseedV1 &ref) { // // Assignment Operator using the copy function // if(this != &ref){ ref.Copy(*this); } SetBit(kOwner, kFALSE); return *this; } //____________________________________________________________________ AliTRDseedV1::~AliTRDseedV1() { // // Destructor. The RecoParam object belongs to the underlying tracker. // //printf("I-AliTRDseedV1::~AliTRDseedV1() : Owner[%s]\n", IsOwner()?"YES":"NO"); if(IsOwner()) for(int itb=0; itb<knTimebins; itb++){ if(!fClusters[itb]) continue; //AliInfo(Form("deleting c %p @ %d", fClusters[itb], itb)); delete fClusters[itb]; fClusters[itb] = 0x0; } } //____________________________________________________________________ void AliTRDseedV1::Copy(TObject &ref) const { // // Copy function // //AliInfo(""); AliTRDseedV1 &target = (AliTRDseedV1 &)ref; target.fClusterIter = 0x0; target.fClusterIdx = 0; target.fDet = fDet; target.fMom = fMom; target.fSnp = fSnp; target.fTgl = fTgl; target.fdX = fdX; target.fXref = fXref; target.fExB = fExB; target.fReconstructor = fReconstructor; for(int islice=0; islice < knSlices; islice++) target.fdEdx[islice] = fdEdx[islice]; for(int ispec=0; ispec<AliPID::kSPECIES; ispec++) target.fProb[ispec] = fProb[ispec]; memcpy(target.fRefCov, fRefCov, 3*sizeof(Double_t)); memcpy(target.fCov, fCov, 3*sizeof(Double_t)); AliTRDseed::Copy(target); } //____________________________________________________________ Bool_t AliTRDseedV1::Init(AliTRDtrackV1 *track) { // Initialize this tracklet using the track information // // Parameters: // track - the TRD track used to initialize the tracklet // // Detailed description // The function sets the starting point and direction of the // tracklet according to the information from the TRD track. // // Caution // The TRD track has to be propagated to the beginning of the // chamber where the tracklet will be constructed // Double_t y, z; if(!track->GetProlongation(fX0, y, z)) return kFALSE; UpDate(track); return kTRUE; } //____________________________________________________________________ void AliTRDseedV1::UpDate(const AliTRDtrackV1 *trk) { // update tracklet reference position from the TRD track // Funny name to avoid the clash with the function AliTRDseed::Update() (has to be made obselete) fSnp = trk->GetSnp(); fTgl = trk->GetTgl(); fMom = trk->GetP(); fYref[1] = fSnp/(1. - fSnp*fSnp); fZref[1] = fTgl; SetCovRef(trk->GetCovariance()); Double_t dx = trk->GetX() - fX0; fYref[0] = trk->GetY() - dx*fYref[1]; fZref[0] = trk->GetZ() - dx*fZref[1]; } //____________________________________________________________________ void AliTRDseedV1::CookdEdx(Int_t nslices) { // Calculates average dE/dx for all slices and store them in the internal array fdEdx. // // Parameters: // nslices : number of slices for which dE/dx should be calculated // Output: // store results in the internal array fdEdx. This can be accessed with the method // AliTRDseedV1::GetdEdx() // // Detailed description // Calculates average dE/dx for all slices. Depending on the PID methode // the number of slices can be 3 (LQ) or 8(NN). // The calculation of dQ/dl are done using the tracklet fit results (see AliTRDseedV1::GetdQdl(Int_t)) i.e. // // dQ/dl = qc/(dx * sqrt(1 + dy/dx^2 + dz/dx^2)) // // The following effects are included in the calculation: // 1. calibration values for t0 and vdrift (using x coordinate to calculate slice) // 2. cluster sharing (optional see AliTRDrecoParam::SetClusterSharing()) // 3. cluster size // Int_t nclusters[knSlices]; for(int i=0; i<knSlices; i++){ fdEdx[i] = 0.; nclusters[i] = 0; } Float_t clength = (/*.5 * */AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick()); AliTRDcluster *cluster = 0x0; for(int ic=0; ic<AliTRDtrackerV1::GetNTimeBins(); ic++){ if(!(cluster = fClusters[ic])) continue; Float_t x = cluster->GetX(); // Filter clusters for dE/dx calculation // 1.consider calibration effects for slice determination Int_t slice; if(cluster->IsInChamber()) slice = Int_t(TMath::Abs(fX0 - x) * nslices / clength); else slice = x < fX0 ? 0 : nslices-1; // 2. take sharing into account Float_t w = cluster->IsShared() ? .5 : 1.; // 3. take into account large clusters TODO //w *= c->GetNPads() > 3 ? .8 : 1.; //CHECK !!! fdEdx[slice] += w * GetdQdl(ic); //fdQdl[ic]; nclusters[slice]++; } // End of loop over clusters //if(fReconstructor->GetPIDMethod() == AliTRDReconstructor::kLQPID){ if(nslices == AliTRDReconstructor::kLQslices){ // calculate mean charge per slice (only LQ PID) for(int is=0; is<nslices; is++){ if(nclusters[is]) fdEdx[is] /= nclusters[is]; } } } //____________________________________________________________________ void AliTRDseedV1::GetClusterXY(const AliTRDcluster *c, Double_t &x, Double_t &y) { // Return corrected position of the cluster taking into // account variation of the drift velocity with drift length. // drift velocity correction TODO to be moved to the clusterizer const Float_t cx[] = { -9.6280e-02, 1.3091e-01,-1.7415e-02,-9.9221e-02,-1.2040e-01,-9.5493e-02, -5.0041e-02,-1.6726e-02, 3.5756e-03, 1.8611e-02, 2.6378e-02, 3.3823e-02, 3.4811e-02, 3.5282e-02, 3.5386e-02, 3.6047e-02, 3.5201e-02, 3.4384e-02, 3.2864e-02, 3.1932e-02, 3.2051e-02, 2.2539e-02,-2.5154e-02,-1.2050e-01, -1.2050e-01 }; // PRF correction TODO to be replaced by the gaussian // approximation with full error parametrization and // moved to the clusterizer const Float_t cy[AliTRDgeometry::kNlayer][3] = { { 4.014e-04, 8.605e-03, -6.880e+00}, {-3.061e-04, 9.663e-03, -6.789e+00}, { 1.124e-03, 1.105e-02, -6.825e+00}, {-1.527e-03, 1.231e-02, -6.777e+00}, { 2.150e-03, 1.387e-02, -6.783e+00}, {-1.296e-03, 1.486e-02, -6.825e+00} }; Int_t ily = AliTRDgeometry::GetLayer(c->GetDetector()); x = c->GetX() - cx[c->GetLocalTimeBin()]; y = c->GetY() + cy[ily][0] + cy[ily][1] * TMath::Sin(cy[ily][2] * c->GetCenter()); return; } //____________________________________________________________________ Float_t AliTRDseedV1::GetdQdl(Int_t ic) const { return fClusters[ic] ? TMath::Abs(fClusters[ic]->GetQ()) /fdX / TMath::Sqrt(1. + fYfit[1]*fYfit[1] + fZref[1]*fZref[1]) : 0.; } //____________________________________________________________________ Double_t* AliTRDseedV1::GetProbability() { // Fill probability array for tracklet from the DB. // // Parameters // // Output // returns pointer to the probability array and 0x0 if missing DB access // // Detailed description // retrive calibration db AliTRDcalibDB *calibration = AliTRDcalibDB::Instance(); if (!calibration) { AliError("No access to calibration data"); return 0x0; } if (!fReconstructor) { AliError("Reconstructor not set."); return 0x0; } // Retrieve the CDB container class with the parametric detector response const AliTRDCalPID *pd = calibration->GetPIDObject(fReconstructor->GetPIDMethod()); if (!pd) { AliError("No access to AliTRDCalPID object"); return 0x0; } //AliInfo(Form("Method[%d] : %s", fReconstructor->GetRecoParam() ->GetPIDMethod(), pd->IsA()->GetName())); // calculate tracklet length TO DO Float_t length = (AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick()); /// TMath::Sqrt((1.0 - fSnp[iPlane]*fSnp[iPlane]) / (1.0 + fTgl[iPlane]*fTgl[iPlane])); //calculate dE/dx CookdEdx(fReconstructor->GetNdEdxSlices()); // Sets the a priori probabilities for(int ispec=0; ispec<AliPID::kSPECIES; ispec++) { fProb[ispec] = pd->GetProbability(ispec, fMom, &fdEdx[0], length, GetPlane()); } return &fProb[0]; } //____________________________________________________________________ Float_t AliTRDseedV1::GetQuality(Bool_t kZcorr) const { // // Returns a quality measurement of the current seed // Float_t zcorr = kZcorr ? fTilt * (fZProb - fZref[0]) : 0.; return .5 * TMath::Abs(18.0 - fN2) + 10.* TMath::Abs(fYfit[1] - fYref[1]) + 5. * TMath::Abs(fYfit[0] - fYref[0] + zcorr) + 2. * TMath::Abs(fMeanz - fZref[0]) / fPadLength; } //____________________________________________________________________ void AliTRDseedV1::GetCovAt(Double_t x, Double_t *cov) const { // Computes covariance in the y-z plane at radial point x (in tracking coordinates) // and returns the results in the preallocated array cov[3] as : // cov[0] = Var(y) // cov[1] = Cov(yz) // cov[2] = Var(z) // // Details // // For the linear transformation // BEGIN_LATEX // Y = T_{x} X^{T} // END_LATEX // The error propagation has the general form // BEGIN_LATEX // C_{Y} = T_{x} C_{X} T_{x}^{T} // END_LATEX // We apply this formula 2 times. First to calculate the covariance of the tracklet // at point x we consider: // BEGIN_LATEX // T_{x} = (1 x); X=(y0 dy/dx); C_{X}=#(){#splitline{Var(y0) Cov(y0, dy/dx)}{Cov(y0, dy/dx) Var(dy/dx)}} // END_LATEX // and secondly to take into account the tilt angle // BEGIN_LATEX // T_{#alpha} = #(){#splitline{cos(#alpha) __ sin(#alpha)}{-sin(#alpha) __ cos(#alpha)}}; X=(y z); C_{X}=#(){#splitline{Var(y) 0}{0 Var(z)}} // END_LATEX // // using simple trigonometrics one can write for this last case // BEGIN_LATEX // C_{Y}=#frac{1}{1+tg^{2}#alpha} #(){#splitline{(#sigma_{y}^{2}+tg^{2}#alpha#sigma_{z}^{2}) __ tg#alpha(#sigma_{z}^{2}-#sigma_{y}^{2})}{tg#alpha(#sigma_{z}^{2}-#sigma_{y}^{2}) __ (#sigma_{z}^{2}+tg^{2}#alpha#sigma_{y}^{2})}} // END_LATEX // which can be aproximated for small alphas (2 deg) with // BEGIN_LATEX // C_{Y}=#(){#splitline{#sigma_{y}^{2} __ (#sigma_{z}^{2}-#sigma_{y}^{2})tg#alpha}{((#sigma_{z}^{2}-#sigma_{y}^{2})tg#alpha __ #sigma_{z}^{2}}} // END_LATEX // // before applying the tilt rotation we also apply systematic uncertainties to the tracklet // position which can be tunned from outside via the AliTRDrecoParam::SetSysCovMatrix(). They might // account for extra misalignment/miscalibration uncertainties. // // Author : // Alex Bercuci <A.Bercuci@gsi.de> // Date : Jan 8th 2009 // Double_t xr = fX0-x; Double_t sy2 = fCov[0] +2.*xr*fCov[1] + xr*xr*fCov[2]; Double_t sz2 = fPadLength*fPadLength/12.; // insert systematic uncertainties Double_t sys[15]; fReconstructor->GetRecoParam()->GetSysCovMatrix(sys); sy2 += sys[0]; sz2 += sys[1]; // rotate covariance matrix Double_t t2 = fTilt*fTilt; Double_t correction = 1./(1. + t2); cov[0] = (sy2+t2*sz2)*correction; cov[1] = fTilt*(sz2 - sy2)*correction; cov[2] = (t2*sy2+sz2)*correction; } //____________________________________________________________________ void AliTRDseedV1::SetExB() { // Retrive the tg(a_L) from OCDB. The following information are used // - detector index // - column and row position of first attached cluster. // // If no clusters are attached to the tracklet a random central chamber // position (c=70, r=7) will be used to retrieve the drift velocity. // // Author : // Alex Bercuci <A.Bercuci@gsi.de> // Date : Jan 8th 2009 // AliCDBManager *cdb = AliCDBManager::Instance(); if(cdb->GetRun() < 0){ AliError("OCDB manager not properly initialized"); return; } AliTRDcalibDB *fCalib = AliTRDcalibDB::Instance(); AliTRDCalROC *fCalVdriftROC = fCalib->GetVdriftROC(fDet); const AliTRDCalDet *fCalVdriftDet = fCalib->GetVdriftDet(); Int_t col = 70, row = 7; AliTRDcluster **c = &fClusters[0]; if(fN){ Int_t ic = 0; while (ic<AliTRDseed::knTimebins && !(*c)){ic++; c++;} if(*c){ col = (*c)->GetPadCol(); row = (*c)->GetPadRow(); } } Double_t vd = fCalVdriftDet->GetValue(fDet) * fCalVdriftROC->GetValue(col, row); fExB = fCalib->GetOmegaTau(vd, -0.1*AliTracker::GetBz()); } //____________________________________________________________________ void AliTRDseedV1::SetOwner() { //AliInfo(Form("own [%s] fOwner[%s]", own?"YES":"NO", fOwner?"YES":"NO")); if(TestBit(kOwner)) return; for(int ic=0; ic<knTimebins; ic++){ if(!fClusters[ic]) continue; fClusters[ic] = new AliTRDcluster(*fClusters[ic]); } SetBit(kOwner); } //____________________________________________________________________ Bool_t AliTRDseedV1::AttachClustersIter(AliTRDtrackingChamber *chamber, Float_t quality, Bool_t kZcorr, AliTRDcluster *c) { // // Iterative process to register clusters to the seed. // In iteration 0 we try only one pad-row and if quality not // sufficient we try 2 pad-rows (about 5% of tracks cross 2 pad-rows) // // debug level 7 // if(!fReconstructor->GetRecoParam() ){ AliError("Seed can not be used without a valid RecoParam."); return kFALSE; } AliTRDchamberTimeBin *layer = 0x0; if(fReconstructor->GetStreamLevel(AliTRDReconstructor::kTracker)>=7){ AliTRDtrackingChamber ch(*chamber); ch.SetOwner(); TTreeSRedirector &cstreamer = *fReconstructor->GetDebugStream(AliTRDReconstructor::kTracker); cstreamer << "AttachClustersIter" << "chamber.=" << &ch << "tracklet.=" << this << "\n"; } Float_t tquality; Double_t kroady = fReconstructor->GetRecoParam() ->GetRoad1y(); Double_t kroadz = fPadLength * .5 + 1.; // initialize configuration parameters Float_t zcorr = kZcorr ? fTilt * (fZProb - fZref[0]) : 0.; Int_t niter = kZcorr ? 1 : 2; Double_t yexp, zexp; Int_t ncl = 0; // start seed update for (Int_t iter = 0; iter < niter; iter++) { ncl = 0; for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) { if(!(layer = chamber->GetTB(iTime))) continue; if(!Int_t(*layer)) continue; // define searching configuration Double_t dxlayer = layer->GetX() - fX0; if(c){ zexp = c->GetZ(); //Try 2 pad-rows in second iteration if (iter > 0) { zexp = fZref[0] + fZref[1] * dxlayer - zcorr; if (zexp > c->GetZ()) zexp = c->GetZ() + fPadLength*0.5; if (zexp < c->GetZ()) zexp = c->GetZ() - fPadLength*0.5; } } else zexp = fZref[0] + (kZcorr ? fZref[1] * dxlayer : 0.); yexp = fYref[0] + fYref[1] * dxlayer - zcorr; // Get and register cluster Int_t index = layer->SearchNearestCluster(yexp, zexp, kroady, kroadz); if (index < 0) continue; AliTRDcluster *cl = (*layer)[index]; fIndexes[iTime] = layer->GetGlobalIndex(index); fClusters[iTime] = cl; fY[iTime] = cl->GetY(); fZ[iTime] = cl->GetZ(); ncl++; } if(fReconstructor->GetStreamLevel(AliTRDReconstructor::kTracker)>=7) AliInfo(Form("iter = %d ncl [%d] = %d", iter, fDet, ncl)); if(ncl>1){ // calculate length of the time bin (calibration aware) Int_t irp = 0; Float_t x[2]; Int_t tb[2]; for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) { if(!fClusters[iTime]) continue; x[irp] = fClusters[iTime]->GetX(); tb[irp] = iTime; irp++; if(irp==2) break; } fdX = (x[1] - x[0]) / (tb[0] - tb[1]); // update X0 from the clusters (calibration/alignment aware) for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) { if(!(layer = chamber->GetTB(iTime))) continue; if(!layer->IsT0()) continue; if(fClusters[iTime]){ fX0 = fClusters[iTime]->GetX(); break; } else { // we have to infere the position of the anode wire from the other clusters for (Int_t jTime = iTime+1; jTime < AliTRDtrackerV1::GetNTimeBins(); jTime++) { if(!fClusters[jTime]) continue; fX0 = fClusters[jTime]->GetX() + fdX * (jTime - iTime); break; } } } // update YZ reference point // TODO // update x reference positions (calibration/alignment aware) for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) { if(!fClusters[iTime]) continue; fX[iTime] = fX0 - fClusters[iTime]->GetX(); } AliTRDseed::Update(); } if(fReconstructor->GetStreamLevel(AliTRDReconstructor::kTracker)>=7) AliInfo(Form("iter = %d nclFit [%d] = %d", iter, fDet, fN2)); if(IsOK()){ tquality = GetQuality(kZcorr); if(tquality < quality) break; else quality = tquality; } kroadz *= 2.; } // Loop: iter if (!IsOK()) return kFALSE; if(fReconstructor->GetStreamLevel(AliTRDReconstructor::kTracker)>=1) CookLabels(); // set ExB angle SetExB(); UpdateUsed(); return kTRUE; } //____________________________________________________________________ Bool_t AliTRDseedV1::AttachClusters(AliTRDtrackingChamber *chamber, Bool_t tilt) { // // Projective algorithm to attach clusters to seeding tracklets // // Parameters // // Output // // Detailed description // 1. Collapse x coordinate for the full detector plane // 2. truncated mean on y (r-phi) direction // 3. purge clusters // 4. truncated mean on z direction // 5. purge clusters // 6. fit tracklet // Bool_t kPRINT = kFALSE; if(!fReconstructor->GetRecoParam() ){ AliError("Seed can not be used without a valid RecoParam."); return kFALSE; } // Initialize reco params for this tracklet // 1. first time bin in the drift region Int_t t0 = 4; Int_t kClmin = Int_t(fReconstructor->GetRecoParam() ->GetFindableClusters()*AliTRDtrackerV1::GetNTimeBins()); Double_t syRef = TMath::Sqrt(fRefCov[0]); //define roads Double_t kroady = 1.; //fReconstructor->GetRecoParam() ->GetRoad1y(); Double_t kroadz = fPadLength * 1.5 + 1.; if(kPRINT) printf("AttachClusters() sy[%f] road[%f]\n", syRef, kroady); // working variables const Int_t kNrows = 16; AliTRDcluster *clst[kNrows][knTimebins]; Double_t cond[4], dx, dy, yt, zt, yres[kNrows][knTimebins]; Int_t idxs[kNrows][knTimebins], ncl[kNrows], ncls = 0; memset(ncl, 0, kNrows*sizeof(Int_t)); memset(clst, 0, kNrows*knTimebins*sizeof(AliTRDcluster*)); // Do cluster projection AliTRDcluster *c = 0x0; AliTRDchamberTimeBin *layer = 0x0; Bool_t kBUFFER = kFALSE; for (Int_t it = 0; it < AliTRDtrackerV1::GetNTimeBins(); it++) { if(!(layer = chamber->GetTB(it))) continue; if(!Int_t(*layer)) continue; dx = fX0 - layer->GetX(); yt = fYref[0] - fYref[1] * dx; zt = fZref[0] - fZref[1] * dx; if(kPRINT) printf("\t%2d dx[%f] yt[%f] zt[%f]\n", it, dx, yt, zt); // select clusters on a 5 sigmaKalman level cond[0] = yt; cond[2] = kroady; cond[1] = zt; cond[3] = kroadz; Int_t n=0, idx[6]; layer->GetClusters(cond, idx, n, 6); for(Int_t ic = n; ic--;){ c = (*layer)[idx[ic]]; dy = yt - c->GetY(); dy += tilt ? fTilt * (c->GetZ() - zt) : 0.; // select clusters on a 3 sigmaKalman level /* if(tilt && TMath::Abs(dy) > 3.*syRef){ printf("too large !!!\n"); continue; }*/ Int_t r = c->GetPadRow(); if(kPRINT) printf("\t\t%d dy[%f] yc[%f] r[%d]\n", ic, TMath::Abs(dy), c->GetY(), r); clst[r][ncl[r]] = c; idxs[r][ncl[r]] = idx[ic]; yres[r][ncl[r]] = dy; ncl[r]++; ncls++; if(ncl[r] >= knTimebins) { AliWarning(Form("Cluster candidates reached limit %d. Some may be lost.", knTimebins)); kBUFFER = kTRUE; break; } } if(kBUFFER) break; } if(kPRINT) printf("Found %d clusters\n", ncls); if(ncls<kClmin) return kFALSE; // analyze each row individualy Double_t mean, syDis; Int_t nrow[] = {0, 0, 0}, nr = 0, lr=-1; for(Int_t ir=kNrows; ir--;){ if(!(ncl[ir])) continue; if(lr>0 && lr-ir != 1){ if(kPRINT) printf("W - gap in rows attached !!\n"); } if(kPRINT) printf("\tir[%d] lr[%d] n[%d]\n", ir, lr, ncl[ir]); // Evaluate truncated mean on the y direction if(ncl[ir] > 3) AliMathBase::EvaluateUni(ncl[ir], yres[ir], mean, syDis, Int_t(ncl[ir]*.8)); else { mean = 0.; syDis = 0.; } // TODO check mean and sigma agains cluster resolution !! if(kPRINT) printf("\tr[%2d] m[%f %5.3fsigma] s[%f]\n", ir, mean, TMath::Abs(mean/syRef), syDis); // select clusters on a 3 sigmaDistr level Bool_t kFOUND = kFALSE; for(Int_t ic = ncl[ir]; ic--;){ if(yres[ir][ic] - mean > 3. * syDis){ clst[ir][ic] = 0x0; continue; } nrow[nr]++; kFOUND = kTRUE; } // exit loop if(kFOUND) nr++; lr = ir; if(nr>=3) break; } if(kPRINT) printf("lr[%d] nr[%d] nrow[0]=%d nrow[1]=%d nrow[2]=%d\n", lr, nr, nrow[0], nrow[1], nrow[2]); // classify cluster rows Int_t row = -1; switch(nr){ case 1: row = lr; break; case 2: SetBit(kRowCross, kTRUE); // mark pad row crossing if(nrow[0] > nrow[1]){ row = lr+1; lr = -1;} else{ row = lr; lr = 1; nrow[2] = nrow[1]; nrow[1] = nrow[0]; nrow[0] = nrow[2]; } break; case 3: SetBit(kRowCross, kTRUE); // mark pad row crossing break; } if(kPRINT) printf("\trow[%d] n[%d]\n\n", row, nrow[0]); if(row<0) return kFALSE; // Select and store clusters // We should consider here : // 1. How far is the chamber boundary // 2. How big is the mean fN2 = 0; for (Int_t ir = 0; ir < nr; ir++) { Int_t jr = row + ir*lr; if(kPRINT) printf("\tattach %d clusters for row %d\n", ncl[jr], jr); for (Int_t ic = 0; ic < ncl[jr]; ic++) { if(!(c = clst[jr][ic])) continue; Int_t it = c->GetPadTime(); // TODO proper indexing of clusters !! fIndexes[it+35*ir] = chamber->GetTB(it)->GetGlobalIndex(idxs[jr][ic]); fClusters[it+35*ir] = c; //printf("\tid[%2d] it[%d] idx[%d]\n", ic, it, fIndexes[it]); fN2++; } } // number of minimum numbers of clusters expected for the tracklet if (fN2 < kClmin){ AliWarning(Form("Not enough clusters to fit the tracklet %d [%d].", fN2, kClmin)); fN2 = 0; return kFALSE; } // update used clusters and select fNUsed = 0; for (Int_t it = 0; it < AliTRDtrackerV1::GetNTimeBins(); it++) { if(fClusters[it] && fClusters[it]->IsUsed()) fNUsed++; if(fClusters[it+35] && fClusters[it+35]->IsUsed()) fNUsed++; } if (fN2-fNUsed < kClmin){ //AliWarning(Form("Too many clusters already in use %d (from %d).", fNUsed, fN2)); fN2 = 0; return kFALSE; } // set the Lorentz angle for this tracklet SetExB(); // calculate dx for time bins in the drift region (calibration aware) Int_t irp = 0; Float_t x[2]; Int_t tb[2]; for (Int_t it = t0; it < AliTRDtrackerV1::GetNTimeBins(); it++) { if(!fClusters[it]) continue; x[irp] = fClusters[it]->GetX(); tb[irp] = it; irp++; if(irp==2) break; } fdX = (x[1] - x[0]) / (tb[0] - tb[1]); // update X0 from the clusters (calibration/alignment aware) TODO remove dependence on x0 !! for (Int_t it = 0; it < AliTRDtrackerV1::GetNTimeBins(); it++) { if(!(layer = chamber->GetTB(it))) continue; if(!layer->IsT0()) continue; if(fClusters[it]){ fX0 = fClusters[it]->GetX(); break; } else { // we have to infere the position of the anode wire from the other clusters for (Int_t jt = it+1; jt < AliTRDtrackerV1::GetNTimeBins(); jt++) { if(!fClusters[jt]) continue; fX0 = fClusters[jt]->GetX() + fdX * (jt - it); break; } } } return kTRUE; } //____________________________________________________________ void AliTRDseedV1::Bootstrap(const AliTRDReconstructor *rec) { // Fill in all derived information. It has to be called after recovery from file or HLT. // The primitive data are // - list of clusters // - detector (as the detector will be removed from clusters) // - position of anode wire (fX0) - temporary // - track reference position and direction // - momentum of the track // - time bin length [cm] // // A.Bercuci <A.Bercuci@gsi.de> Oct 30th 2008 // fReconstructor = rec; AliTRDgeometry g; AliTRDpadPlane *pp = g.GetPadPlane(fDet); fTilt = TMath::Tan(TMath::DegToRad()*pp->GetTiltingAngle()); fPadLength = pp->GetLengthIPad(); fSnp = fYref[1]/TMath::Sqrt(1+fYref[1]*fYref[1]); fTgl = fZref[1]; fN = 0; fN2 = 0; fMPads = 0.; AliTRDcluster **cit = &fClusters[0]; for(Int_t ic = knTimebins; ic--; cit++){ if(!(*cit)) return; fN++; fN2++; fX[ic] = (*cit)->GetX() - fX0; fY[ic] = (*cit)->GetY(); fZ[ic] = (*cit)->GetZ(); } Update(); // Fit(); CookLabels(); GetProbability(); } //____________________________________________________________________ Bool_t AliTRDseedV1::Fit(Bool_t tilt, Int_t errors) { // // Linear fit of the tracklet // // Parameters : // // Output : // True if successful // // Detailed description // 2. Check if tracklet crosses pad row boundary // 1. Calculate residuals in the y (r-phi) direction // 3. Do a Least Square Fit to the data // const Int_t kClmin = 8; // cluster error parametrization parameters // 1. sy total charge const Float_t sq0inv = 0.019962; // [1/q0] const Float_t sqb = 1.0281564; //[cm] // 2. sy for the PRF const Float_t scy[AliTRDgeometry::kNlayer][4] = { {2.827e-02, 9.600e-04, 4.296e-01, 2.271e-02}, {2.952e-02,-2.198e-04, 4.146e-01, 2.339e-02}, {3.090e-02, 1.514e-03, 4.020e-01, 2.402e-02}, {3.260e-02,-2.037e-03, 3.946e-01, 2.509e-02}, {3.439e-02,-3.601e-04, 3.883e-01, 2.623e-02}, {3.510e-02, 2.066e-03, 3.651e-01, 2.588e-02}, }; // 3. sy parallel to the track const Float_t sy0 = 2.649e-02; // [cm] const Float_t sya = -8.864e-04; // [cm] const Float_t syb = -2.435e-01; // [cm] // 4. sx parallel to the track const Float_t sxgc = 5.427e-02; const Float_t sxgm = 7.783e-01; const Float_t sxgs = 2.743e-01; const Float_t sxe0 =-2.065e+00; const Float_t sxe1 =-2.978e-02; // 5. sx perpendicular to the track // const Float_t sxd0 = 1.881e-02; // const Float_t sxd1 =-4.101e-01; // const Float_t sxd2 = 1.572e+00; // get track direction Double_t y0 = fYref[0]; Double_t dydx = fYref[1]; Double_t z0 = fZref[0]; Double_t dzdx = fZref[1]; Double_t yt, zt; const Int_t kNtb = AliTRDtrackerV1::GetNTimeBins(); //AliTRDtrackerV1::AliTRDLeastSquare fitterZ; TLinearFitter fitterY(1, "pol1"); // convertion factor from square to gauss distribution for sigma //Double_t convert = 1./TMath::Sqrt(12.); // book cluster information Double_t q, xc[knTimebins], yc[knTimebins], zc[knTimebins], sy[knTimebins]/*, sz[knTimebins]*/; // Int_t zRow[knTimebins]; Int_t ily = AliTRDgeometry::GetLayer(fDet); fN = 0; //fXref = 0.; Double_t ssx = 0.; AliTRDcluster *c=0x0, **jc = &fClusters[0]; for (Int_t ic=0; ic<kNtb; ic++, ++jc) { //zRow[ic] = -1; xc[ic] = -1.; yc[ic] = 999.; zc[ic] = 999.; sy[ic] = 0.; //sz[ic] = 0.; if(!(c = (*jc))) continue; if(!c->IsInChamber()) continue; Float_t w = 1.; if(c->GetNPads()>4) w = .5; if(c->GetNPads()>5) w = .2; //zRow[fN] = c->GetPadRow(); // correct cluster position for PRF and v drift Double_t x, y; GetClusterXY(c, x, y); xc[fN] = fX0 - x; yc[fN] = y; zc[fN] = c->GetZ(); // extrapolated y value for the track yt = y0 - xc[fN]*dydx; // extrapolated z value for the track zt = z0 - xc[fN]*dzdx; // tilt correction if(tilt) yc[fN] -= fTilt*(zc[fN] - zt); // ELABORATE CLUSTER ERROR // TODO to be moved to AliTRDcluster q = TMath::Abs(c->GetQ()); Double_t tgg = (dydx-fExB)/(1.+dydx*fExB); tgg *= tgg; // basic y error (|| to track). sy[fN] = xc[fN] < AliTRDgeometry::CamHght() ? 2. : sy0 + sya*TMath::Exp(1./(xc[fN]+syb)); //printf("cluster[%d]\n\tsy[0] = %5.3e [um]\n", fN, sy[fN]*1.e4); // y error due to total charge sy[fN] += sqb*(1./q - sq0inv); //printf("\tsy[1] = %5.3e [um]\n", sy[fN]*1.e4); // y error due to PRF sy[fN] += scy[ily][0]*TMath::Gaus(c->GetCenter(), scy[ily][1], scy[ily][2]) - scy[ily][3]; //printf("\tsy[2] = %5.3e [um]\n", sy[fN]*1.e4); sy[fN] *= sy[fN]; // ADD ERROR ON x // error of drift length parallel to the track Double_t sx = sxgc*TMath::Gaus(xc[fN], sxgm, sxgs) + TMath::Exp(sxe0+sxe1*xc[fN]); // [cm] //printf("\tsx[0] = %5.3e [um]\n", sx*1.e4); // error of drift length perpendicular to the track //sx += sxd0 + sxd1*d + sxd2*d*d; sx *= sx; // square sx // update xref //fXref += xc[fN]/sx; ssx+=1./sx; // add error from ExB if(errors>0) sy[fN] += fExB*fExB*sx; //printf("\tsy[3] = %5.3e [um^2]\n", sy[fN]*1.e8); // global radial error due to misalignment/miscalibration Double_t sx0 = 0.; sx0 *= sx0; // add sx contribution to sy due to track angle if(errors>1) sy[fN] += tgg*(sx+sx0); // TODO we should add tilt pad correction here //printf("\tsy[4] = %5.3e [um^2]\n", sy[fN]*1.e8); c->SetSigmaY2(sy[fN]); sy[fN] = TMath::Sqrt(sy[fN]); fitterY.AddPoint(&xc[fN], yc[fN]/*-yt*/, sy[fN]); fN++; } // to few clusters if (fN < kClmin) return kFALSE; // fit XY fitterY.Eval(); fYfit[0] = fitterY.GetParameter(0); fYfit[1] = -fitterY.GetParameter(1); // store covariance Double_t *p = fitterY.GetCovarianceMatrix(); fCov[0] = p[0]; // variance of y0 fCov[1] = p[1]; // covariance of y0, dydx fCov[2] = p[3]; // variance of dydx // the ref radial position is set at the minimum of // the y variance of the tracklet fXref = -fCov[1]/fCov[2]; //fXref = fX0 - fXref; // fit XZ if(IsRowCross()){ // TODO pad row cross position estimation !!! //AliInfo(Form("Padrow cross in detector %d", fDet)); fZfit[0] = .5*(zc[0]+zc[fN-1]); fZfit[1] = 0.; } else { fZfit[0] = zc[0]; fZfit[1] = 0.; } // // determine z offset of the fit // Float_t zslope = 0.; // Int_t nchanges = 0, nCross = 0; // if(nz==2){ // tracklet is crossing pad row // // Find the break time allowing one chage on pad-rows // // with maximal number of accepted clusters // Int_t padRef = zRow[0]; // for (Int_t ic=1; ic<fN; ic++) { // if(zRow[ic] == padRef) continue; // // // debug // if(zRow[ic-1] == zRow[ic]){ // printf("ERROR in pad row change!!!\n"); // } // // // evaluate parameters of the crossing point // Float_t sx = (xc[ic-1] - xc[ic])*convert; // fCross[0] = .5 * (xc[ic-1] + xc[ic]); // fCross[2] = .5 * (zc[ic-1] + zc[ic]); // fCross[3] = TMath::Max(dzdx * sx, .01); // zslope = zc[ic-1] > zc[ic] ? 1. : -1.; // padRef = zRow[ic]; // nCross = ic; // nchanges++; // } // } // // // condition on nCross and reset nchanges TODO // // if(nchanges==1){ // if(dzdx * zslope < 0.){ // AliInfo("Tracklet-Track mismatch in dzdx. TODO."); // } // // // //zc[nc] = fitterZ.GetFunctionParameter(0); // fCross[1] = fYfit[0] - fCross[0] * fYfit[1]; // fCross[0] = fX0 - fCross[0]; // } UpdateUsed(); return kTRUE; } //___________________________________________________________________ void AliTRDseedV1::Print(Option_t *o) const { // // Printing the seedstatus // AliInfo(Form("Det[%3d] Tilt[%+6.2f] Pad[%5.2f]", fDet, fTilt, fPadLength)); AliInfo(Form("Nattach[%2d] Nfit[%2d] Nuse[%2d] pads[%f]", fN, fN2, fNUsed, fMPads)); AliInfo(Form("x[%7.2f] y[%7.2f] z[%7.2f] dydx[%5.2f] dzdx[%5.2f]", fX0, fYfit[0], fZfit[0], fYfit[1], fZfit[1])); AliInfo(Form("Ref y[%7.2f] z[%7.2f] dydx[%5.2f] dzdx[%5.2f]", fYref[0], fZref[0], fYref[1], fZref[1])) if(strcmp(o, "a")!=0) return; AliTRDcluster* const* jc = &fClusters[0]; for(int ic=0; ic<AliTRDtrackerV1::GetNTimeBins(); ic++, jc++) { if(!(*jc)) continue; (*jc)->Print(o); } } //___________________________________________________________________ Bool_t AliTRDseedV1::IsEqual(const TObject *o) const { // Checks if current instance of the class has the same essential members // as the given one if(!o) return kFALSE; const AliTRDseedV1 *inTracklet = dynamic_cast<const AliTRDseedV1*>(o); if(!inTracklet) return kFALSE; for (Int_t i = 0; i < 2; i++){ if ( fYref[i] != inTracklet->GetYref(i) ) return kFALSE; if ( fZref[i] != inTracklet->GetZref(i) ) return kFALSE; } if ( fSigmaY != inTracklet->GetSigmaY() ) return kFALSE; if ( fSigmaY2 != inTracklet->GetSigmaY2() ) return kFALSE; if ( fTilt != inTracklet->GetTilt() ) return kFALSE; if ( fPadLength != inTracklet->GetPadLength() ) return kFALSE; for (Int_t i = 0; i < knTimebins; i++){ if ( fX[i] != inTracklet->GetX(i) ) return kFALSE; if ( fY[i] != inTracklet->GetY(i) ) return kFALSE; if ( fZ[i] != inTracklet->GetZ(i) ) return kFALSE; if ( fIndexes[i] != inTracklet->GetIndexes(i) ) return kFALSE; if ( fUsable[i] != inTracklet->IsUsable(i) ) return kFALSE; } for (Int_t i=0; i < 2; i++){ if ( fYfit[i] != inTracklet->GetYfit(i) ) return kFALSE; if ( fZfit[i] != inTracklet->GetZfit(i) ) return kFALSE; if ( fYfitR[i] != inTracklet->GetYfitR(i) ) return kFALSE; if ( fZfitR[i] != inTracklet->GetZfitR(i) ) return kFALSE; if ( fLabels[i] != inTracklet->GetLabels(i) ) return kFALSE; } if ( fMeanz != inTracklet->GetMeanz() ) return kFALSE; if ( fZProb != inTracklet->GetZProb() ) return kFALSE; if ( fN2 != inTracklet->GetN2() ) return kFALSE; if ( fNUsed != inTracklet->GetNUsed() ) return kFALSE; if ( fFreq != inTracklet->GetFreq() ) return kFALSE; if ( fNChange != inTracklet->GetNChange() ) return kFALSE; if ( fNChange != inTracklet->GetNChange() ) return kFALSE; if ( fC != inTracklet->GetC() ) return kFALSE; if ( fCC != inTracklet->GetCC() ) return kFALSE; if ( fChi2 != inTracklet->GetChi2() ) return kFALSE; // if ( fChi2Z != inTracklet->GetChi2Z() ) return kFALSE; if ( fDet != inTracklet->GetDetector() ) return kFALSE; if ( fMom != inTracklet->GetMomentum() ) return kFALSE; if ( fdX != inTracklet->GetdX() ) return kFALSE; for (Int_t iCluster = 0; iCluster < knTimebins; iCluster++){ AliTRDcluster *curCluster = fClusters[iCluster]; AliTRDcluster *inCluster = inTracklet->GetClusters(iCluster); if (curCluster && inCluster){ if (! curCluster->IsEqual(inCluster) ) { curCluster->Print(); inCluster->Print(); return kFALSE; } } else { // if one cluster exists, and corresponding // in other tracklet doesn't - return kFALSE if(curCluster || inCluster) return kFALSE; } } return kTRUE; } correct dEdx calculations for pad row cross As a first approximation we add the charge of all clusters attached to the tracklet. No tail cancelation effects or charge asymmetry is taken into account /************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //////////////////////////////////////////////////////////////////////////// // // // The TRD track seed // // // // Authors: // // Alex Bercuci <A.Bercuci@gsi.de> // // Markus Fasel <M.Fasel@gsi.de> // // // //////////////////////////////////////////////////////////////////////////// #include "TMath.h" #include "TLinearFitter.h" #include "TClonesArray.h" // tmp #include <TTreeStream.h> #include "AliLog.h" #include "AliMathBase.h" #include "AliCDBManager.h" #include "AliTracker.h" #include "AliTRDpadPlane.h" #include "AliTRDcluster.h" #include "AliTRDseedV1.h" #include "AliTRDtrackV1.h" #include "AliTRDcalibDB.h" #include "AliTRDchamberTimeBin.h" #include "AliTRDtrackingChamber.h" #include "AliTRDtrackerV1.h" #include "AliTRDReconstructor.h" #include "AliTRDrecoParam.h" #include "Cal/AliTRDCalPID.h" #include "Cal/AliTRDCalROC.h" #include "Cal/AliTRDCalDet.h" ClassImp(AliTRDseedV1) //____________________________________________________________________ AliTRDseedV1::AliTRDseedV1(Int_t det) :AliTRDseed() ,fReconstructor(0x0) ,fClusterIter(0x0) ,fClusterIdx(0) ,fDet(det) ,fMom(0.) ,fSnp(0.) ,fTgl(0.) ,fdX(0.) ,fXref(0.) ,fExB(0.) { // // Constructor // for(int islice=0; islice < knSlices; islice++) fdEdx[islice] = 0.; for(int ispec=0; ispec<AliPID::kSPECIES; ispec++) fProb[ispec] = -1.; fRefCov[0] = 1.; fRefCov[1] = 0.; fRefCov[2] = 1.; // covariance matrix [diagonal] // default sy = 200um and sz = 2.3 cm fCov[0] = 4.e-4; fCov[1] = 0.; fCov[2] = 5.3; } //____________________________________________________________________ AliTRDseedV1::AliTRDseedV1(const AliTRDseedV1 &ref) :AliTRDseed((AliTRDseed&)ref) ,fReconstructor(ref.fReconstructor) ,fClusterIter(0x0) ,fClusterIdx(0) ,fDet(ref.fDet) ,fMom(ref.fMom) ,fSnp(ref.fSnp) ,fTgl(ref.fTgl) ,fdX(ref.fdX) ,fXref(ref.fXref) ,fExB(ref.fExB) { // // Copy Constructor performing a deep copy // //printf("AliTRDseedV1::AliTRDseedV1(const AliTRDseedV1 &)\n"); SetBit(kOwner, kFALSE); for(int islice=0; islice < knSlices; islice++) fdEdx[islice] = ref.fdEdx[islice]; for(int ispec=0; ispec<AliPID::kSPECIES; ispec++) fProb[ispec] = ref.fProb[ispec]; memcpy(fRefCov, ref.fRefCov, 3*sizeof(Double_t)); memcpy(fCov, ref.fCov, 3*sizeof(Double_t)); } //____________________________________________________________________ AliTRDseedV1& AliTRDseedV1::operator=(const AliTRDseedV1 &ref) { // // Assignment Operator using the copy function // if(this != &ref){ ref.Copy(*this); } SetBit(kOwner, kFALSE); return *this; } //____________________________________________________________________ AliTRDseedV1::~AliTRDseedV1() { // // Destructor. The RecoParam object belongs to the underlying tracker. // //printf("I-AliTRDseedV1::~AliTRDseedV1() : Owner[%s]\n", IsOwner()?"YES":"NO"); if(IsOwner()) for(int itb=0; itb<knTimebins; itb++){ if(!fClusters[itb]) continue; //AliInfo(Form("deleting c %p @ %d", fClusters[itb], itb)); delete fClusters[itb]; fClusters[itb] = 0x0; } } //____________________________________________________________________ void AliTRDseedV1::Copy(TObject &ref) const { // // Copy function // //AliInfo(""); AliTRDseedV1 &target = (AliTRDseedV1 &)ref; target.fClusterIter = 0x0; target.fClusterIdx = 0; target.fDet = fDet; target.fMom = fMom; target.fSnp = fSnp; target.fTgl = fTgl; target.fdX = fdX; target.fXref = fXref; target.fExB = fExB; target.fReconstructor = fReconstructor; for(int islice=0; islice < knSlices; islice++) target.fdEdx[islice] = fdEdx[islice]; for(int ispec=0; ispec<AliPID::kSPECIES; ispec++) target.fProb[ispec] = fProb[ispec]; memcpy(target.fRefCov, fRefCov, 3*sizeof(Double_t)); memcpy(target.fCov, fCov, 3*sizeof(Double_t)); AliTRDseed::Copy(target); } //____________________________________________________________ Bool_t AliTRDseedV1::Init(AliTRDtrackV1 *track) { // Initialize this tracklet using the track information // // Parameters: // track - the TRD track used to initialize the tracklet // // Detailed description // The function sets the starting point and direction of the // tracklet according to the information from the TRD track. // // Caution // The TRD track has to be propagated to the beginning of the // chamber where the tracklet will be constructed // Double_t y, z; if(!track->GetProlongation(fX0, y, z)) return kFALSE; UpDate(track); return kTRUE; } //____________________________________________________________________ void AliTRDseedV1::UpDate(const AliTRDtrackV1 *trk) { // update tracklet reference position from the TRD track // Funny name to avoid the clash with the function AliTRDseed::Update() (has to be made obselete) fSnp = trk->GetSnp(); fTgl = trk->GetTgl(); fMom = trk->GetP(); fYref[1] = fSnp/(1. - fSnp*fSnp); fZref[1] = fTgl; SetCovRef(trk->GetCovariance()); Double_t dx = trk->GetX() - fX0; fYref[0] = trk->GetY() - dx*fYref[1]; fZref[0] = trk->GetZ() - dx*fZref[1]; } //____________________________________________________________________ void AliTRDseedV1::CookdEdx(Int_t nslices) { // Calculates average dE/dx for all slices and store them in the internal array fdEdx. // // Parameters: // nslices : number of slices for which dE/dx should be calculated // Output: // store results in the internal array fdEdx. This can be accessed with the method // AliTRDseedV1::GetdEdx() // // Detailed description // Calculates average dE/dx for all slices. Depending on the PID methode // the number of slices can be 3 (LQ) or 8(NN). // The calculation of dQ/dl are done using the tracklet fit results (see AliTRDseedV1::GetdQdl(Int_t)) // // The following effects are included in the calculation: // 1. calibration values for t0 and vdrift (using x coordinate to calculate slice) // 2. cluster sharing (optional see AliTRDrecoParam::SetClusterSharing()) // 3. cluster size // Int_t nclusters[knSlices]; for(int i=0; i<knSlices; i++){ fdEdx[i] = 0.; nclusters[i] = 0; } Float_t pathLength = (.5 * AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick()); AliTRDcluster *c = 0x0; for(int ic=0; ic<AliTRDtrackerV1::GetNTimeBins(); ic++){ if(!(c = fClusters[ic]) && !(c = fClusters[knTimebins+ic])) continue; Float_t x = c->GetX(); // Filter clusters for dE/dx calculation // 1.consider calibration effects for slice determination Int_t slice; if(c->IsInChamber()) slice = Int_t(TMath::Abs(fX0 - x) * nslices / pathLength); else slice = x < fX0 ? 0 : nslices-1; // 2. take sharing into account Float_t w = c->IsShared() ? .5 : 1.; // 3. take into account large clusters TODO //w *= c->GetNPads() > 3 ? .8 : 1.; //CHECK !!! fdEdx[slice] += w * GetdQdl(ic); //fdQdl[ic]; nclusters[slice]++; } // End of loop over clusters //if(fReconstructor->GetPIDMethod() == AliTRDReconstructor::kLQPID){ if(nslices == AliTRDReconstructor::kLQslices){ // calculate mean charge per slice (only LQ PID) for(int is=0; is<nslices; is++){ if(nclusters[is]) fdEdx[is] /= nclusters[is]; } } } //____________________________________________________________________ void AliTRDseedV1::GetClusterXY(const AliTRDcluster *c, Double_t &x, Double_t &y) { // Return corrected position of the cluster taking into // account variation of the drift velocity with drift length. // drift velocity correction TODO to be moved to the clusterizer const Float_t cx[] = { -9.6280e-02, 1.3091e-01,-1.7415e-02,-9.9221e-02,-1.2040e-01,-9.5493e-02, -5.0041e-02,-1.6726e-02, 3.5756e-03, 1.8611e-02, 2.6378e-02, 3.3823e-02, 3.4811e-02, 3.5282e-02, 3.5386e-02, 3.6047e-02, 3.5201e-02, 3.4384e-02, 3.2864e-02, 3.1932e-02, 3.2051e-02, 2.2539e-02,-2.5154e-02,-1.2050e-01, -1.2050e-01 }; // PRF correction TODO to be replaced by the gaussian // approximation with full error parametrization and // moved to the clusterizer const Float_t cy[AliTRDgeometry::kNlayer][3] = { { 4.014e-04, 8.605e-03, -6.880e+00}, {-3.061e-04, 9.663e-03, -6.789e+00}, { 1.124e-03, 1.105e-02, -6.825e+00}, {-1.527e-03, 1.231e-02, -6.777e+00}, { 2.150e-03, 1.387e-02, -6.783e+00}, {-1.296e-03, 1.486e-02, -6.825e+00} }; Int_t ily = AliTRDgeometry::GetLayer(c->GetDetector()); x = c->GetX() - cx[c->GetLocalTimeBin()]; y = c->GetY() + cy[ily][0] + cy[ily][1] * TMath::Sin(cy[ily][2] * c->GetCenter()); return; } //____________________________________________________________________ Float_t AliTRDseedV1::GetdQdl(Int_t ic) const { // Using the linear approximation of the track inside one TRD chamber (TRD tracklet) // the charge per unit length can be written as: // BEGIN_LATEX // #frac{dq}{dl} = #frac{q_{c}}{dx * #sqrt{1 + #(){#frac{dy}{dx}}^{2}_{fit} + #(){#frac{dy}{dx}}^{2}_{ref}}} // END_LATEX // where qc is the total charge collected in the current time bin and dx is the length // of the time bin. For the moment (Jan 20 2009) only pad row cross corrections are // considered for the charge but none are applied for drift velocity variations along // the drift region or assymetry of the TRF // // Author : Alex Bercuci <A.Bercuci@gsi.de> // Float_t dq = 0.; if(fClusters[ic]) dq += TMath::Abs(fClusters[ic]->GetQ()); if(fClusters[knTimebins+ic]) dq += TMath::Abs(fClusters[knTimebins+ic]->GetQ()); return dq/fdX/TMath::Sqrt(1. + fYfit[1]*fYfit[1] + fZref[1]*fZref[1]); } //____________________________________________________________________ Double_t* AliTRDseedV1::GetProbability() { // Fill probability array for tracklet from the DB. // // Parameters // // Output // returns pointer to the probability array and 0x0 if missing DB access // // Detailed description // retrive calibration db AliTRDcalibDB *calibration = AliTRDcalibDB::Instance(); if (!calibration) { AliError("No access to calibration data"); return 0x0; } if (!fReconstructor) { AliError("Reconstructor not set."); return 0x0; } // Retrieve the CDB container class with the parametric detector response const AliTRDCalPID *pd = calibration->GetPIDObject(fReconstructor->GetPIDMethod()); if (!pd) { AliError("No access to AliTRDCalPID object"); return 0x0; } //AliInfo(Form("Method[%d] : %s", fReconstructor->GetRecoParam() ->GetPIDMethod(), pd->IsA()->GetName())); // calculate tracklet length TO DO Float_t length = (AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick()); /// TMath::Sqrt((1.0 - fSnp[iPlane]*fSnp[iPlane]) / (1.0 + fTgl[iPlane]*fTgl[iPlane])); //calculate dE/dx CookdEdx(fReconstructor->GetNdEdxSlices()); // Sets the a priori probabilities for(int ispec=0; ispec<AliPID::kSPECIES; ispec++) { fProb[ispec] = pd->GetProbability(ispec, fMom, &fdEdx[0], length, GetPlane()); } return &fProb[0]; } //____________________________________________________________________ Float_t AliTRDseedV1::GetQuality(Bool_t kZcorr) const { // // Returns a quality measurement of the current seed // Float_t zcorr = kZcorr ? fTilt * (fZProb - fZref[0]) : 0.; return .5 * TMath::Abs(18.0 - fN2) + 10.* TMath::Abs(fYfit[1] - fYref[1]) + 5. * TMath::Abs(fYfit[0] - fYref[0] + zcorr) + 2. * TMath::Abs(fMeanz - fZref[0]) / fPadLength; } //____________________________________________________________________ void AliTRDseedV1::GetCovAt(Double_t x, Double_t *cov) const { // Computes covariance in the y-z plane at radial point x (in tracking coordinates) // and returns the results in the preallocated array cov[3] as : // cov[0] = Var(y) // cov[1] = Cov(yz) // cov[2] = Var(z) // // Details // // For the linear transformation // BEGIN_LATEX // Y = T_{x} X^{T} // END_LATEX // The error propagation has the general form // BEGIN_LATEX // C_{Y} = T_{x} C_{X} T_{x}^{T} // END_LATEX // We apply this formula 2 times. First to calculate the covariance of the tracklet // at point x we consider: // BEGIN_LATEX // T_{x} = (1 x); X=(y0 dy/dx); C_{X}=#(){#splitline{Var(y0) Cov(y0, dy/dx)}{Cov(y0, dy/dx) Var(dy/dx)}} // END_LATEX // and secondly to take into account the tilt angle // BEGIN_LATEX // T_{#alpha} = #(){#splitline{cos(#alpha) __ sin(#alpha)}{-sin(#alpha) __ cos(#alpha)}}; X=(y z); C_{X}=#(){#splitline{Var(y) 0}{0 Var(z)}} // END_LATEX // // using simple trigonometrics one can write for this last case // BEGIN_LATEX // C_{Y}=#frac{1}{1+tg^{2}#alpha} #(){#splitline{(#sigma_{y}^{2}+tg^{2}#alpha#sigma_{z}^{2}) __ tg#alpha(#sigma_{z}^{2}-#sigma_{y}^{2})}{tg#alpha(#sigma_{z}^{2}-#sigma_{y}^{2}) __ (#sigma_{z}^{2}+tg^{2}#alpha#sigma_{y}^{2})}} // END_LATEX // which can be aproximated for small alphas (2 deg) with // BEGIN_LATEX // C_{Y}=#(){#splitline{#sigma_{y}^{2} __ (#sigma_{z}^{2}-#sigma_{y}^{2})tg#alpha}{((#sigma_{z}^{2}-#sigma_{y}^{2})tg#alpha __ #sigma_{z}^{2}}} // END_LATEX // // before applying the tilt rotation we also apply systematic uncertainties to the tracklet // position which can be tunned from outside via the AliTRDrecoParam::SetSysCovMatrix(). They might // account for extra misalignment/miscalibration uncertainties. // // Author : // Alex Bercuci <A.Bercuci@gsi.de> // Date : Jan 8th 2009 // Double_t xr = fX0-x; Double_t sy2 = fCov[0] +2.*xr*fCov[1] + xr*xr*fCov[2]; Double_t sz2 = fPadLength*fPadLength/12.; // insert systematic uncertainties Double_t sys[15]; fReconstructor->GetRecoParam()->GetSysCovMatrix(sys); sy2 += sys[0]; sz2 += sys[1]; // rotate covariance matrix Double_t t2 = fTilt*fTilt; Double_t correction = 1./(1. + t2); cov[0] = (sy2+t2*sz2)*correction; cov[1] = fTilt*(sz2 - sy2)*correction; cov[2] = (t2*sy2+sz2)*correction; } //____________________________________________________________________ void AliTRDseedV1::SetExB() { // Retrive the tg(a_L) from OCDB. The following information are used // - detector index // - column and row position of first attached cluster. // // If no clusters are attached to the tracklet a random central chamber // position (c=70, r=7) will be used to retrieve the drift velocity. // // Author : // Alex Bercuci <A.Bercuci@gsi.de> // Date : Jan 8th 2009 // AliCDBManager *cdb = AliCDBManager::Instance(); if(cdb->GetRun() < 0){ AliError("OCDB manager not properly initialized"); return; } AliTRDcalibDB *fCalib = AliTRDcalibDB::Instance(); AliTRDCalROC *fCalVdriftROC = fCalib->GetVdriftROC(fDet); const AliTRDCalDet *fCalVdriftDet = fCalib->GetVdriftDet(); Int_t col = 70, row = 7; AliTRDcluster **c = &fClusters[0]; if(fN){ Int_t ic = 0; while (ic<AliTRDseed::knTimebins && !(*c)){ic++; c++;} if(*c){ col = (*c)->GetPadCol(); row = (*c)->GetPadRow(); } } Double_t vd = fCalVdriftDet->GetValue(fDet) * fCalVdriftROC->GetValue(col, row); fExB = fCalib->GetOmegaTau(vd, -0.1*AliTracker::GetBz()); } //____________________________________________________________________ void AliTRDseedV1::SetOwner() { //AliInfo(Form("own [%s] fOwner[%s]", own?"YES":"NO", fOwner?"YES":"NO")); if(TestBit(kOwner)) return; for(int ic=0; ic<knTimebins; ic++){ if(!fClusters[ic]) continue; fClusters[ic] = new AliTRDcluster(*fClusters[ic]); } SetBit(kOwner); } //____________________________________________________________________ Bool_t AliTRDseedV1::AttachClustersIter(AliTRDtrackingChamber *chamber, Float_t quality, Bool_t kZcorr, AliTRDcluster *c) { // // Iterative process to register clusters to the seed. // In iteration 0 we try only one pad-row and if quality not // sufficient we try 2 pad-rows (about 5% of tracks cross 2 pad-rows) // // debug level 7 // if(!fReconstructor->GetRecoParam() ){ AliError("Seed can not be used without a valid RecoParam."); return kFALSE; } AliTRDchamberTimeBin *layer = 0x0; if(fReconstructor->GetStreamLevel(AliTRDReconstructor::kTracker)>=7){ AliTRDtrackingChamber ch(*chamber); ch.SetOwner(); TTreeSRedirector &cstreamer = *fReconstructor->GetDebugStream(AliTRDReconstructor::kTracker); cstreamer << "AttachClustersIter" << "chamber.=" << &ch << "tracklet.=" << this << "\n"; } Float_t tquality; Double_t kroady = fReconstructor->GetRecoParam() ->GetRoad1y(); Double_t kroadz = fPadLength * .5 + 1.; // initialize configuration parameters Float_t zcorr = kZcorr ? fTilt * (fZProb - fZref[0]) : 0.; Int_t niter = kZcorr ? 1 : 2; Double_t yexp, zexp; Int_t ncl = 0; // start seed update for (Int_t iter = 0; iter < niter; iter++) { ncl = 0; for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) { if(!(layer = chamber->GetTB(iTime))) continue; if(!Int_t(*layer)) continue; // define searching configuration Double_t dxlayer = layer->GetX() - fX0; if(c){ zexp = c->GetZ(); //Try 2 pad-rows in second iteration if (iter > 0) { zexp = fZref[0] + fZref[1] * dxlayer - zcorr; if (zexp > c->GetZ()) zexp = c->GetZ() + fPadLength*0.5; if (zexp < c->GetZ()) zexp = c->GetZ() - fPadLength*0.5; } } else zexp = fZref[0] + (kZcorr ? fZref[1] * dxlayer : 0.); yexp = fYref[0] + fYref[1] * dxlayer - zcorr; // Get and register cluster Int_t index = layer->SearchNearestCluster(yexp, zexp, kroady, kroadz); if (index < 0) continue; AliTRDcluster *cl = (*layer)[index]; fIndexes[iTime] = layer->GetGlobalIndex(index); fClusters[iTime] = cl; fY[iTime] = cl->GetY(); fZ[iTime] = cl->GetZ(); ncl++; } if(fReconstructor->GetStreamLevel(AliTRDReconstructor::kTracker)>=7) AliInfo(Form("iter = %d ncl [%d] = %d", iter, fDet, ncl)); if(ncl>1){ // calculate length of the time bin (calibration aware) Int_t irp = 0; Float_t x[2]; Int_t tb[2]; for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) { if(!fClusters[iTime]) continue; x[irp] = fClusters[iTime]->GetX(); tb[irp] = iTime; irp++; if(irp==2) break; } fdX = (x[1] - x[0]) / (tb[0] - tb[1]); // update X0 from the clusters (calibration/alignment aware) for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) { if(!(layer = chamber->GetTB(iTime))) continue; if(!layer->IsT0()) continue; if(fClusters[iTime]){ fX0 = fClusters[iTime]->GetX(); break; } else { // we have to infere the position of the anode wire from the other clusters for (Int_t jTime = iTime+1; jTime < AliTRDtrackerV1::GetNTimeBins(); jTime++) { if(!fClusters[jTime]) continue; fX0 = fClusters[jTime]->GetX() + fdX * (jTime - iTime); break; } } } // update YZ reference point // TODO // update x reference positions (calibration/alignment aware) for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) { if(!fClusters[iTime]) continue; fX[iTime] = fX0 - fClusters[iTime]->GetX(); } AliTRDseed::Update(); } if(fReconstructor->GetStreamLevel(AliTRDReconstructor::kTracker)>=7) AliInfo(Form("iter = %d nclFit [%d] = %d", iter, fDet, fN2)); if(IsOK()){ tquality = GetQuality(kZcorr); if(tquality < quality) break; else quality = tquality; } kroadz *= 2.; } // Loop: iter if (!IsOK()) return kFALSE; if(fReconstructor->GetStreamLevel(AliTRDReconstructor::kTracker)>=1) CookLabels(); // set ExB angle SetExB(); UpdateUsed(); return kTRUE; } //____________________________________________________________________ Bool_t AliTRDseedV1::AttachClusters(AliTRDtrackingChamber *chamber, Bool_t tilt) { // // Projective algorithm to attach clusters to seeding tracklets // // Parameters // // Output // // Detailed description // 1. Collapse x coordinate for the full detector plane // 2. truncated mean on y (r-phi) direction // 3. purge clusters // 4. truncated mean on z direction // 5. purge clusters // 6. fit tracklet // Bool_t kPRINT = kFALSE; if(!fReconstructor->GetRecoParam() ){ AliError("Seed can not be used without a valid RecoParam."); return kFALSE; } // Initialize reco params for this tracklet // 1. first time bin in the drift region Int_t t0 = 4; Int_t kClmin = Int_t(fReconstructor->GetRecoParam() ->GetFindableClusters()*AliTRDtrackerV1::GetNTimeBins()); Double_t syRef = TMath::Sqrt(fRefCov[0]); //define roads Double_t kroady = 1.; //fReconstructor->GetRecoParam() ->GetRoad1y(); Double_t kroadz = fPadLength * 1.5 + 1.; if(kPRINT) printf("AttachClusters() sy[%f] road[%f]\n", syRef, kroady); // working variables const Int_t kNrows = 16; AliTRDcluster *clst[kNrows][knTimebins]; Double_t cond[4], dx, dy, yt, zt, yres[kNrows][knTimebins]; Int_t idxs[kNrows][knTimebins], ncl[kNrows], ncls = 0; memset(ncl, 0, kNrows*sizeof(Int_t)); memset(clst, 0, kNrows*knTimebins*sizeof(AliTRDcluster*)); // Do cluster projection AliTRDcluster *c = 0x0; AliTRDchamberTimeBin *layer = 0x0; Bool_t kBUFFER = kFALSE; for (Int_t it = 0; it < AliTRDtrackerV1::GetNTimeBins(); it++) { if(!(layer = chamber->GetTB(it))) continue; if(!Int_t(*layer)) continue; dx = fX0 - layer->GetX(); yt = fYref[0] - fYref[1] * dx; zt = fZref[0] - fZref[1] * dx; if(kPRINT) printf("\t%2d dx[%f] yt[%f] zt[%f]\n", it, dx, yt, zt); // select clusters on a 5 sigmaKalman level cond[0] = yt; cond[2] = kroady; cond[1] = zt; cond[3] = kroadz; Int_t n=0, idx[6]; layer->GetClusters(cond, idx, n, 6); for(Int_t ic = n; ic--;){ c = (*layer)[idx[ic]]; dy = yt - c->GetY(); dy += tilt ? fTilt * (c->GetZ() - zt) : 0.; // select clusters on a 3 sigmaKalman level /* if(tilt && TMath::Abs(dy) > 3.*syRef){ printf("too large !!!\n"); continue; }*/ Int_t r = c->GetPadRow(); if(kPRINT) printf("\t\t%d dy[%f] yc[%f] r[%d]\n", ic, TMath::Abs(dy), c->GetY(), r); clst[r][ncl[r]] = c; idxs[r][ncl[r]] = idx[ic]; yres[r][ncl[r]] = dy; ncl[r]++; ncls++; if(ncl[r] >= knTimebins) { AliWarning(Form("Cluster candidates reached limit %d. Some may be lost.", knTimebins)); kBUFFER = kTRUE; break; } } if(kBUFFER) break; } if(kPRINT) printf("Found %d clusters\n", ncls); if(ncls<kClmin) return kFALSE; // analyze each row individualy Double_t mean, syDis; Int_t nrow[] = {0, 0, 0}, nr = 0, lr=-1; for(Int_t ir=kNrows; ir--;){ if(!(ncl[ir])) continue; if(lr>0 && lr-ir != 1){ if(kPRINT) printf("W - gap in rows attached !!\n"); } if(kPRINT) printf("\tir[%d] lr[%d] n[%d]\n", ir, lr, ncl[ir]); // Evaluate truncated mean on the y direction if(ncl[ir] > 3) AliMathBase::EvaluateUni(ncl[ir], yres[ir], mean, syDis, Int_t(ncl[ir]*.8)); else { mean = 0.; syDis = 0.; } // TODO check mean and sigma agains cluster resolution !! if(kPRINT) printf("\tr[%2d] m[%f %5.3fsigma] s[%f]\n", ir, mean, TMath::Abs(mean/syRef), syDis); // select clusters on a 3 sigmaDistr level Bool_t kFOUND = kFALSE; for(Int_t ic = ncl[ir]; ic--;){ if(yres[ir][ic] - mean > 3. * syDis){ clst[ir][ic] = 0x0; continue; } nrow[nr]++; kFOUND = kTRUE; } // exit loop if(kFOUND) nr++; lr = ir; if(nr>=3) break; } if(kPRINT) printf("lr[%d] nr[%d] nrow[0]=%d nrow[1]=%d nrow[2]=%d\n", lr, nr, nrow[0], nrow[1], nrow[2]); // classify cluster rows Int_t row = -1; switch(nr){ case 1: row = lr; break; case 2: SetBit(kRowCross, kTRUE); // mark pad row crossing if(nrow[0] > nrow[1]){ row = lr+1; lr = -1;} else{ row = lr; lr = 1; nrow[2] = nrow[1]; nrow[1] = nrow[0]; nrow[0] = nrow[2]; } break; case 3: SetBit(kRowCross, kTRUE); // mark pad row crossing break; } if(kPRINT) printf("\trow[%d] n[%d]\n\n", row, nrow[0]); if(row<0) return kFALSE; // Select and store clusters // We should consider here : // 1. How far is the chamber boundary // 2. How big is the mean fN2 = 0; for (Int_t ir = 0; ir < nr; ir++) { Int_t jr = row + ir*lr; if(kPRINT) printf("\tattach %d clusters for row %d\n", ncl[jr], jr); for (Int_t ic = 0; ic < ncl[jr]; ic++) { if(!(c = clst[jr][ic])) continue; Int_t it = c->GetPadTime(); // TODO proper indexing of clusters !! fIndexes[it+35*ir] = chamber->GetTB(it)->GetGlobalIndex(idxs[jr][ic]); fClusters[it+35*ir] = c; //printf("\tid[%2d] it[%d] idx[%d]\n", ic, it, fIndexes[it]); fN2++; } } // number of minimum numbers of clusters expected for the tracklet if (fN2 < kClmin){ AliWarning(Form("Not enough clusters to fit the tracklet %d [%d].", fN2, kClmin)); fN2 = 0; return kFALSE; } // update used clusters and select fNUsed = 0; for (Int_t it = 0; it < AliTRDtrackerV1::GetNTimeBins(); it++) { if(fClusters[it] && fClusters[it]->IsUsed()) fNUsed++; if(fClusters[it+35] && fClusters[it+35]->IsUsed()) fNUsed++; } if (fN2-fNUsed < kClmin){ //AliWarning(Form("Too many clusters already in use %d (from %d).", fNUsed, fN2)); fN2 = 0; return kFALSE; } // set the Lorentz angle for this tracklet SetExB(); // calculate dx for time bins in the drift region (calibration aware) Int_t irp = 0; Float_t x[2]; Int_t tb[2]; for (Int_t it = t0; it < AliTRDtrackerV1::GetNTimeBins(); it++) { if(!fClusters[it]) continue; x[irp] = fClusters[it]->GetX(); tb[irp] = it; irp++; if(irp==2) break; } fdX = (x[1] - x[0]) / (tb[0] - tb[1]); // update X0 from the clusters (calibration/alignment aware) TODO remove dependence on x0 !! for (Int_t it = 0; it < AliTRDtrackerV1::GetNTimeBins(); it++) { if(!(layer = chamber->GetTB(it))) continue; if(!layer->IsT0()) continue; if(fClusters[it]){ fX0 = fClusters[it]->GetX(); break; } else { // we have to infere the position of the anode wire from the other clusters for (Int_t jt = it+1; jt < AliTRDtrackerV1::GetNTimeBins(); jt++) { if(!fClusters[jt]) continue; fX0 = fClusters[jt]->GetX() + fdX * (jt - it); break; } } } return kTRUE; } //____________________________________________________________ void AliTRDseedV1::Bootstrap(const AliTRDReconstructor *rec) { // Fill in all derived information. It has to be called after recovery from file or HLT. // The primitive data are // - list of clusters // - detector (as the detector will be removed from clusters) // - position of anode wire (fX0) - temporary // - track reference position and direction // - momentum of the track // - time bin length [cm] // // A.Bercuci <A.Bercuci@gsi.de> Oct 30th 2008 // fReconstructor = rec; AliTRDgeometry g; AliTRDpadPlane *pp = g.GetPadPlane(fDet); fTilt = TMath::Tan(TMath::DegToRad()*pp->GetTiltingAngle()); fPadLength = pp->GetLengthIPad(); fSnp = fYref[1]/TMath::Sqrt(1+fYref[1]*fYref[1]); fTgl = fZref[1]; fN = 0; fN2 = 0; fMPads = 0.; AliTRDcluster **cit = &fClusters[0]; for(Int_t ic = knTimebins; ic--; cit++){ if(!(*cit)) return; fN++; fN2++; fX[ic] = (*cit)->GetX() - fX0; fY[ic] = (*cit)->GetY(); fZ[ic] = (*cit)->GetZ(); } Update(); // Fit(); CookLabels(); GetProbability(); } //____________________________________________________________________ Bool_t AliTRDseedV1::Fit(Bool_t tilt, Int_t errors) { // // Linear fit of the tracklet // // Parameters : // // Output : // True if successful // // Detailed description // 2. Check if tracklet crosses pad row boundary // 1. Calculate residuals in the y (r-phi) direction // 3. Do a Least Square Fit to the data // const Int_t kClmin = 8; // cluster error parametrization parameters // 1. sy total charge const Float_t sq0inv = 0.019962; // [1/q0] const Float_t sqb = 1.0281564; //[cm] // 2. sy for the PRF const Float_t scy[AliTRDgeometry::kNlayer][4] = { {2.827e-02, 9.600e-04, 4.296e-01, 2.271e-02}, {2.952e-02,-2.198e-04, 4.146e-01, 2.339e-02}, {3.090e-02, 1.514e-03, 4.020e-01, 2.402e-02}, {3.260e-02,-2.037e-03, 3.946e-01, 2.509e-02}, {3.439e-02,-3.601e-04, 3.883e-01, 2.623e-02}, {3.510e-02, 2.066e-03, 3.651e-01, 2.588e-02}, }; // 3. sy parallel to the track const Float_t sy0 = 2.649e-02; // [cm] const Float_t sya = -8.864e-04; // [cm] const Float_t syb = -2.435e-01; // [cm] // 4. sx parallel to the track const Float_t sxgc = 5.427e-02; const Float_t sxgm = 7.783e-01; const Float_t sxgs = 2.743e-01; const Float_t sxe0 =-2.065e+00; const Float_t sxe1 =-2.978e-02; // 5. sx perpendicular to the track // const Float_t sxd0 = 1.881e-02; // const Float_t sxd1 =-4.101e-01; // const Float_t sxd2 = 1.572e+00; // get track direction Double_t y0 = fYref[0]; Double_t dydx = fYref[1]; Double_t z0 = fZref[0]; Double_t dzdx = fZref[1]; Double_t yt, zt; const Int_t kNtb = AliTRDtrackerV1::GetNTimeBins(); //AliTRDtrackerV1::AliTRDLeastSquare fitterZ; TLinearFitter fitterY(1, "pol1"); // convertion factor from square to gauss distribution for sigma //Double_t convert = 1./TMath::Sqrt(12.); // book cluster information Double_t q, xc[knTimebins], yc[knTimebins], zc[knTimebins], sy[knTimebins]/*, sz[knTimebins]*/; // Int_t zRow[knTimebins]; Int_t ily = AliTRDgeometry::GetLayer(fDet); fN = 0; //fXref = 0.; Double_t ssx = 0.; AliTRDcluster *c=0x0, **jc = &fClusters[0]; for (Int_t ic=0; ic<kNtb; ic++, ++jc) { //zRow[ic] = -1; xc[ic] = -1.; yc[ic] = 999.; zc[ic] = 999.; sy[ic] = 0.; //sz[ic] = 0.; if(!(c = (*jc))) continue; if(!c->IsInChamber()) continue; Float_t w = 1.; if(c->GetNPads()>4) w = .5; if(c->GetNPads()>5) w = .2; //zRow[fN] = c->GetPadRow(); // correct cluster position for PRF and v drift Double_t x, y; GetClusterXY(c, x, y); xc[fN] = fX0 - x; yc[fN] = y; zc[fN] = c->GetZ(); // extrapolated y value for the track yt = y0 - xc[fN]*dydx; // extrapolated z value for the track zt = z0 - xc[fN]*dzdx; // tilt correction if(tilt) yc[fN] -= fTilt*(zc[fN] - zt); // ELABORATE CLUSTER ERROR // TODO to be moved to AliTRDcluster q = TMath::Abs(c->GetQ()); Double_t tgg = (dydx-fExB)/(1.+dydx*fExB); tgg *= tgg; // basic y error (|| to track). sy[fN] = xc[fN] < AliTRDgeometry::CamHght() ? 2. : sy0 + sya*TMath::Exp(1./(xc[fN]+syb)); //printf("cluster[%d]\n\tsy[0] = %5.3e [um]\n", fN, sy[fN]*1.e4); // y error due to total charge sy[fN] += sqb*(1./q - sq0inv); //printf("\tsy[1] = %5.3e [um]\n", sy[fN]*1.e4); // y error due to PRF sy[fN] += scy[ily][0]*TMath::Gaus(c->GetCenter(), scy[ily][1], scy[ily][2]) - scy[ily][3]; //printf("\tsy[2] = %5.3e [um]\n", sy[fN]*1.e4); sy[fN] *= sy[fN]; // ADD ERROR ON x // error of drift length parallel to the track Double_t sx = sxgc*TMath::Gaus(xc[fN], sxgm, sxgs) + TMath::Exp(sxe0+sxe1*xc[fN]); // [cm] //printf("\tsx[0] = %5.3e [um]\n", sx*1.e4); // error of drift length perpendicular to the track //sx += sxd0 + sxd1*d + sxd2*d*d; sx *= sx; // square sx // update xref //fXref += xc[fN]/sx; ssx+=1./sx; // add error from ExB if(errors>0) sy[fN] += fExB*fExB*sx; //printf("\tsy[3] = %5.3e [um^2]\n", sy[fN]*1.e8); // global radial error due to misalignment/miscalibration Double_t sx0 = 0.; sx0 *= sx0; // add sx contribution to sy due to track angle if(errors>1) sy[fN] += tgg*(sx+sx0); // TODO we should add tilt pad correction here //printf("\tsy[4] = %5.3e [um^2]\n", sy[fN]*1.e8); c->SetSigmaY2(sy[fN]); sy[fN] = TMath::Sqrt(sy[fN]); fitterY.AddPoint(&xc[fN], yc[fN]/*-yt*/, sy[fN]); fN++; } // to few clusters if (fN < kClmin) return kFALSE; // fit XY fitterY.Eval(); fYfit[0] = fitterY.GetParameter(0); fYfit[1] = -fitterY.GetParameter(1); // store covariance Double_t *p = fitterY.GetCovarianceMatrix(); fCov[0] = p[0]; // variance of y0 fCov[1] = p[1]; // covariance of y0, dydx fCov[2] = p[3]; // variance of dydx // the ref radial position is set at the minimum of // the y variance of the tracklet fXref = -fCov[1]/fCov[2]; //fXref = fX0 - fXref; // fit XZ if(IsRowCross()){ // TODO pad row cross position estimation !!! //AliInfo(Form("Padrow cross in detector %d", fDet)); fZfit[0] = .5*(zc[0]+zc[fN-1]); fZfit[1] = 0.; } else { fZfit[0] = zc[0]; fZfit[1] = 0.; } // // determine z offset of the fit // Float_t zslope = 0.; // Int_t nchanges = 0, nCross = 0; // if(nz==2){ // tracklet is crossing pad row // // Find the break time allowing one chage on pad-rows // // with maximal number of accepted clusters // Int_t padRef = zRow[0]; // for (Int_t ic=1; ic<fN; ic++) { // if(zRow[ic] == padRef) continue; // // // debug // if(zRow[ic-1] == zRow[ic]){ // printf("ERROR in pad row change!!!\n"); // } // // // evaluate parameters of the crossing point // Float_t sx = (xc[ic-1] - xc[ic])*convert; // fCross[0] = .5 * (xc[ic-1] + xc[ic]); // fCross[2] = .5 * (zc[ic-1] + zc[ic]); // fCross[3] = TMath::Max(dzdx * sx, .01); // zslope = zc[ic-1] > zc[ic] ? 1. : -1.; // padRef = zRow[ic]; // nCross = ic; // nchanges++; // } // } // // // condition on nCross and reset nchanges TODO // // if(nchanges==1){ // if(dzdx * zslope < 0.){ // AliInfo("Tracklet-Track mismatch in dzdx. TODO."); // } // // // //zc[nc] = fitterZ.GetFunctionParameter(0); // fCross[1] = fYfit[0] - fCross[0] * fYfit[1]; // fCross[0] = fX0 - fCross[0]; // } UpdateUsed(); return kTRUE; } //___________________________________________________________________ void AliTRDseedV1::Print(Option_t *o) const { // // Printing the seedstatus // AliInfo(Form("Det[%3d] Tilt[%+6.2f] Pad[%5.2f]", fDet, fTilt, fPadLength)); AliInfo(Form("Nattach[%2d] Nfit[%2d] Nuse[%2d] pads[%f]", fN, fN2, fNUsed, fMPads)); AliInfo(Form("x[%7.2f] y[%7.2f] z[%7.2f] dydx[%5.2f] dzdx[%5.2f]", fX0, fYfit[0], fZfit[0], fYfit[1], fZfit[1])); AliInfo(Form("Ref y[%7.2f] z[%7.2f] dydx[%5.2f] dzdx[%5.2f]", fYref[0], fZref[0], fYref[1], fZref[1])) if(strcmp(o, "a")!=0) return; AliTRDcluster* const* jc = &fClusters[0]; for(int ic=0; ic<AliTRDtrackerV1::GetNTimeBins(); ic++, jc++) { if(!(*jc)) continue; (*jc)->Print(o); } } //___________________________________________________________________ Bool_t AliTRDseedV1::IsEqual(const TObject *o) const { // Checks if current instance of the class has the same essential members // as the given one if(!o) return kFALSE; const AliTRDseedV1 *inTracklet = dynamic_cast<const AliTRDseedV1*>(o); if(!inTracklet) return kFALSE; for (Int_t i = 0; i < 2; i++){ if ( fYref[i] != inTracklet->GetYref(i) ) return kFALSE; if ( fZref[i] != inTracklet->GetZref(i) ) return kFALSE; } if ( fSigmaY != inTracklet->GetSigmaY() ) return kFALSE; if ( fSigmaY2 != inTracklet->GetSigmaY2() ) return kFALSE; if ( fTilt != inTracklet->GetTilt() ) return kFALSE; if ( fPadLength != inTracklet->GetPadLength() ) return kFALSE; for (Int_t i = 0; i < knTimebins; i++){ if ( fX[i] != inTracklet->GetX(i) ) return kFALSE; if ( fY[i] != inTracklet->GetY(i) ) return kFALSE; if ( fZ[i] != inTracklet->GetZ(i) ) return kFALSE; if ( fIndexes[i] != inTracklet->GetIndexes(i) ) return kFALSE; if ( fUsable[i] != inTracklet->IsUsable(i) ) return kFALSE; } for (Int_t i=0; i < 2; i++){ if ( fYfit[i] != inTracklet->GetYfit(i) ) return kFALSE; if ( fZfit[i] != inTracklet->GetZfit(i) ) return kFALSE; if ( fYfitR[i] != inTracklet->GetYfitR(i) ) return kFALSE; if ( fZfitR[i] != inTracklet->GetZfitR(i) ) return kFALSE; if ( fLabels[i] != inTracklet->GetLabels(i) ) return kFALSE; } if ( fMeanz != inTracklet->GetMeanz() ) return kFALSE; if ( fZProb != inTracklet->GetZProb() ) return kFALSE; if ( fN2 != inTracklet->GetN2() ) return kFALSE; if ( fNUsed != inTracklet->GetNUsed() ) return kFALSE; if ( fFreq != inTracklet->GetFreq() ) return kFALSE; if ( fNChange != inTracklet->GetNChange() ) return kFALSE; if ( fNChange != inTracklet->GetNChange() ) return kFALSE; if ( fC != inTracklet->GetC() ) return kFALSE; if ( fCC != inTracklet->GetCC() ) return kFALSE; if ( fChi2 != inTracklet->GetChi2() ) return kFALSE; // if ( fChi2Z != inTracklet->GetChi2Z() ) return kFALSE; if ( fDet != inTracklet->GetDetector() ) return kFALSE; if ( fMom != inTracklet->GetMomentum() ) return kFALSE; if ( fdX != inTracklet->GetdX() ) return kFALSE; for (Int_t iCluster = 0; iCluster < knTimebins; iCluster++){ AliTRDcluster *curCluster = fClusters[iCluster]; AliTRDcluster *inCluster = inTracklet->GetClusters(iCluster); if (curCluster && inCluster){ if (! curCluster->IsEqual(inCluster) ) { curCluster->Print(); inCluster->Print(); return kFALSE; } } else { // if one cluster exists, and corresponding // in other tracklet doesn't - return kFALSE if(curCluster || inCluster) return kFALSE; } } return kTRUE; }
// Copyright 2016-2017 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cstddef> #include <cstdio> #include <cstring> #include <list> #include <string> #include <fstream> #include <sstream> #include "rcutils/types/string_array.h" #include "Poco/SharedLibrary.h" #include "rmw/error_handling.h" #include "rmw/rmw.h" std::string get_env_var(const char * env_var) { char * value = nullptr; #ifndef _WIN32 value = getenv(env_var); #else size_t value_size; _dupenv_s(&value, &value_size, env_var); #endif std::string value_str = ""; if (value) { value_str = value; #ifdef _WIN32 free(value); #endif } // printf("get_env_var(%s) = %s\n", env_var, value_str.c_str()); return value_str; } std::list<std::string> split(const std::string & value, const char delimiter) { std::list<std::string> list; std::istringstream ss(value); std::string s; while (std::getline(ss, s, delimiter)) { list.push_back(s); } // printf("split(%s) = %zu\n", value.c_str(), list.size()); return list; } bool is_file_exist(const char * filename) { std::ifstream h(filename); // printf("is_file_exist(%s) = %s\n", filename, h.good() ? "true" : "false"); return h.good(); } std::string find_library_path(const std::string & library_name) { const char * env_var; char separator; const char * filename_prefix; const char * filename_extension; #ifdef _WIN32 env_var = "PATH"; separator = ';'; filename_prefix = ""; filename_extension = ".dll"; #elif __APPLE__ env_var = "DYLD_LIBRARY_PATH"; separator = ':'; filename_prefix = "lib"; filename_extension = ".dylib"; #else env_var = "LD_LIBRARY_PATH"; separator = ':'; filename_prefix = "lib"; filename_extension = ".so"; #endif std::string search_path = get_env_var(env_var); std::list<std::string> search_paths = split(search_path, separator); std::string filename = filename_prefix; filename += library_name + filename_extension; for (auto it : search_paths) { std::string path = it + "/" + filename; if (is_file_exist(path.c_str())) { return path; } } return ""; } #define STRINGIFY_(s) #s #define STRINGIFY(s) STRINGIFY_(s) Poco::SharedLibrary * get_library() { static Poco::SharedLibrary * lib = nullptr; if (!lib) { std::string env_var = get_env_var("RMW_IMPLEMENTATION"); if (env_var.empty()) { env_var = STRINGIFY(DEFAULT_RMW_IMPLEMENTATION); } std::string library_path = find_library_path(env_var); if (library_path.empty()) { RMW_SET_ERROR_MSG("failed to find shared library of rmw implementation"); return nullptr; } try { lib = new Poco::SharedLibrary(library_path); } catch (...) { RMW_SET_ERROR_MSG("failed to load shared library of rmw implementation"); return nullptr; } } return lib; } void * get_symbol(const char * symbol_name) { Poco::SharedLibrary * lib = get_library(); if (!lib) { // error message set by get_library() return nullptr; } if (!lib->hasSymbol(symbol_name)) { RMW_SET_ERROR_MSG("failed to resolve symbol in shared library of rmw implementation"); return nullptr; } return lib->getSymbol(symbol_name); } #if __cplusplus extern "C" { #endif #define ARG_TYPES(...) __VA_ARGS__ #define ARG_VALUES(...) __VA_ARGS__ #define CALL_SYMBOL(symbol_name, ReturnType, error_value, ArgTypes, arg_values) \ void * symbol = get_symbol(symbol_name); \ if (!symbol) { \ /* error message set by get_symbol() */ \ return error_value; \ } \ typedef ReturnType (* FunctionSignature)(ArgTypes); \ FunctionSignature func = reinterpret_cast<FunctionSignature>(symbol); \ return func(arg_values); const char * rmw_get_implementation_identifier(void) { CALL_SYMBOL( "rmw_get_implementation_identifier", const char *, nullptr, ARG_TYPES(void), ARG_VALUES()); } rmw_ret_t rmw_init(void) { CALL_SYMBOL( "rmw_init", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(void), ARG_VALUES()); } rmw_node_t * rmw_create_node(const char * name, const char * namespace_, size_t domain_id, const rmw_node_security_options_t * security_options) { CALL_SYMBOL( "rmw_create_node", rmw_node_t *, nullptr, ARG_TYPES(const char *, const char *, size_t, const rmw_node_security_options_t *), ARG_VALUES(name, namespace_, domain_id, security_options)); } rmw_ret_t rmw_destroy_node(rmw_node_t * node) { CALL_SYMBOL( "rmw_destroy_node", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(rmw_node_t *), ARG_VALUES(node)); } const rmw_guard_condition_t * rmw_node_get_graph_guard_condition(const rmw_node_t * node) { CALL_SYMBOL( "rmw_node_get_graph_guard_condition", const rmw_guard_condition_t *, nullptr, ARG_TYPES(const rmw_node_t *), ARG_VALUES(node)); } rmw_publisher_t * rmw_create_publisher( const rmw_node_t * node, const rosidl_message_type_support_t * type_support, const char * topic_name, const rmw_qos_profile_t * qos_policies) { CALL_SYMBOL( "rmw_create_publisher", rmw_publisher_t *, nullptr, ARG_TYPES( const rmw_node_t *, const rosidl_message_type_support_t *, const char *, const rmw_qos_profile_t *), ARG_VALUES(node, type_support, topic_name, qos_policies)); } rmw_ret_t rmw_destroy_publisher(rmw_node_t * node, rmw_publisher_t * publisher) { CALL_SYMBOL( "rmw_destroy_publisher", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(rmw_node_t *, rmw_publisher_t *), ARG_VALUES(node, publisher)); } rmw_ret_t rmw_publish(const rmw_publisher_t * publisher, const void * ros_message) { CALL_SYMBOL( "rmw_publish", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_publisher_t *, const void *), ARG_VALUES(publisher, ros_message)); } rmw_subscription_t * rmw_create_subscription( const rmw_node_t * node, const rosidl_message_type_support_t * type_support, const char * topic_name, const rmw_qos_profile_t * qos_policies, bool ignore_local_publications) { CALL_SYMBOL( "rmw_create_subscription", rmw_subscription_t *, nullptr, ARG_TYPES( const rmw_node_t *, const rosidl_message_type_support_t *, const char *, const rmw_qos_profile_t *, bool), ARG_VALUES(node, type_support, topic_name, qos_policies, ignore_local_publications)); } rmw_ret_t rmw_destroy_subscription(rmw_node_t * node, rmw_subscription_t * subscription) { CALL_SYMBOL( "rmw_destroy_subscription", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(rmw_node_t *, rmw_subscription_t *), ARG_VALUES(node, subscription)); } rmw_ret_t rmw_take(const rmw_subscription_t * subscription, void * ros_message, bool * taken) { CALL_SYMBOL( "rmw_take", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_subscription_t *, void *, bool *), ARG_VALUES(subscription, ros_message, taken)); } rmw_ret_t rmw_take_with_info( const rmw_subscription_t * subscription, void * ros_message, bool * taken, rmw_message_info_t * message_info) { CALL_SYMBOL( "rmw_take_with_info", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_subscription_t *, void *, bool *, rmw_message_info_t *), ARG_VALUES(subscription, ros_message, taken, message_info)); } rmw_client_t * rmw_create_client( const rmw_node_t * node, const rosidl_service_type_support_t * type_support, const char * service_name, const rmw_qos_profile_t * qos_policies) { CALL_SYMBOL( "rmw_create_client", rmw_client_t *, nullptr, ARG_TYPES( const rmw_node_t *, const rosidl_service_type_support_t *, const char *, const rmw_qos_profile_t *), ARG_VALUES(node, type_support, service_name, qos_policies)); } rmw_ret_t rmw_destroy_client(rmw_node_t * node, rmw_client_t * client) { CALL_SYMBOL( "rmw_destroy_client", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(rmw_node_t *, rmw_client_t *), ARG_VALUES(node, client)); } rmw_ret_t rmw_send_request( const rmw_client_t * client, const void * ros_request, int64_t * sequence_id) { CALL_SYMBOL( "rmw_send_request", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_client_t *, const void *, int64_t *), ARG_VALUES(client, ros_request, sequence_id)); } rmw_ret_t rmw_take_response( const rmw_client_t * client, rmw_request_id_t * request_header, void * ros_response, bool * taken) { CALL_SYMBOL( "rmw_take_response", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_client_t *, rmw_request_id_t *, void *, bool *), ARG_VALUES(client, request_header, ros_response, taken)); } rmw_service_t * rmw_create_service( const rmw_node_t * node, const rosidl_service_type_support_t * type_support, const char * service_name, const rmw_qos_profile_t * qos_policies) { CALL_SYMBOL( "rmw_create_service", rmw_service_t *, nullptr, ARG_TYPES( const rmw_node_t *, const rosidl_service_type_support_t *, const char *, const rmw_qos_profile_t *), ARG_VALUES(node, type_support, service_name, qos_policies)); } rmw_ret_t rmw_destroy_service(rmw_node_t * node, rmw_service_t * service) { CALL_SYMBOL( "rmw_destroy_service", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(rmw_node_t *, rmw_service_t *), ARG_VALUES(node, service)); } rmw_ret_t rmw_take_request( const rmw_service_t * service, rmw_request_id_t * request_header, void * ros_request, bool * taken) { CALL_SYMBOL( "rmw_take_request", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_service_t *, rmw_request_id_t *, void *, bool *), ARG_VALUES(service, request_header, ros_request, taken)); } rmw_ret_t rmw_send_response( const rmw_service_t * service, rmw_request_id_t * request_header, void * ros_response) { CALL_SYMBOL( "rmw_send_response", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_service_t *, rmw_request_id_t *, void *), ARG_VALUES(service, request_header, ros_response)); } rmw_guard_condition_t * rmw_create_guard_condition(void) { CALL_SYMBOL( "rmw_create_guard_condition", rmw_guard_condition_t *, nullptr, ARG_TYPES(void), ARG_VALUES()); } rmw_ret_t rmw_destroy_guard_condition(rmw_guard_condition_t * guard_condition) { CALL_SYMBOL( "rmw_destroy_guard_condition", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(rmw_guard_condition_t *), ARG_VALUES(guard_condition)); } rmw_ret_t rmw_trigger_guard_condition(const rmw_guard_condition_t * guard_condition) { CALL_SYMBOL( "rmw_trigger_guard_condition", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_guard_condition_t *), ARG_VALUES(guard_condition)); } rmw_waitset_t * rmw_create_waitset(size_t max_conditions) { CALL_SYMBOL( "rmw_create_waitset", rmw_waitset_t *, nullptr, ARG_TYPES(size_t), ARG_VALUES(max_conditions)); } rmw_ret_t rmw_destroy_waitset(rmw_waitset_t * waitset) { CALL_SYMBOL( "rmw_destroy_waitset", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(rmw_waitset_t *), ARG_VALUES(waitset)); } rmw_ret_t rmw_wait( rmw_subscriptions_t * subscriptions, rmw_guard_conditions_t * guard_conditions, rmw_services_t * services, rmw_clients_t * clients, rmw_waitset_t * waitset, const rmw_time_t * wait_timeout) { CALL_SYMBOL( "rmw_wait", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES( rmw_subscriptions_t *, rmw_guard_conditions_t *, rmw_services_t *, rmw_clients_t *, rmw_waitset_t *, const rmw_time_t *), ARG_VALUES( subscriptions, guard_conditions, services, clients, waitset, wait_timeout)); } rmw_ret_t rmw_get_topic_names_and_types( const rmw_node_t * node, rmw_topic_names_and_types_t * topic_names_and_types) { CALL_SYMBOL( "rmw_get_topic_names_and_types", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_node_t *, rmw_topic_names_and_types_t *), ARG_VALUES(node, topic_names_and_types)); } rmw_ret_t rmw_destroy_topic_names_and_types( rmw_topic_names_and_types_t * topic_names_and_types) { CALL_SYMBOL( "rmw_destroy_topic_names_and_types", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(rmw_topic_names_and_types_t *), ARG_VALUES(topic_names_and_types)); } rmw_ret_t rmw_get_node_names( const rmw_node_t * node, rcutils_string_array_t * node_names) { CALL_SYMBOL( "rmw_get_node_names", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_node_t *, rcutils_string_array_t *), ARG_VALUES(node, node_names)); } rmw_ret_t rmw_count_publishers( const rmw_node_t * node, const char * topic_name, size_t * count) { CALL_SYMBOL( "rmw_count_publishers", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_node_t *, const char *, size_t *), ARG_VALUES(node, topic_name, count)); } rmw_ret_t rmw_count_subscribers( const rmw_node_t * node, const char * topic_name, size_t * count) { CALL_SYMBOL( "rmw_count_subscribers", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_node_t *, const char *, size_t *), ARG_VALUES(node, topic_name, count)); } rmw_ret_t rmw_get_gid_for_publisher(const rmw_publisher_t * publisher, rmw_gid_t * gid) { CALL_SYMBOL( "rmw_get_gid_for_publisher", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES( const rmw_publisher_t *, rmw_gid_t *), ARG_VALUES(publisher, gid)); } rmw_ret_t rmw_compare_gids_equal(const rmw_gid_t * gid1, const rmw_gid_t * gid2, bool * result) { CALL_SYMBOL( "rmw_compare_gids_equal", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_gid_t *, const rmw_gid_t *, bool *), ARG_VALUES(gid1, gid2, result)); } rmw_ret_t rmw_service_server_is_available( const rmw_node_t * node, const rmw_client_t * client, bool * is_available) { CALL_SYMBOL( "rmw_service_server_is_available", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_node_t *, const rmw_client_t *, bool *), ARG_VALUES(node, client, is_available)); } #if __cplusplus } #endif Refactor get topic names and types (#24) * api changes * improve error message for easier debugging // Copyright 2016-2017 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cstddef> #include <cstdio> #include <cstring> #include <list> #include <string> #include <fstream> #include <sstream> #include "rcutils/allocator.h" #include "rcutils/format_string.h" #include "rcutils/types/string_array.h" #include "Poco/SharedLibrary.h" #include "rmw/error_handling.h" #include "rmw/names_and_types.h" #include "rmw/get_service_names_and_types.h" #include "rmw/get_topic_names_and_types.h" #include "rmw/rmw.h" std::string get_env_var(const char * env_var) { char * value = nullptr; #ifndef _WIN32 value = getenv(env_var); #else size_t value_size; _dupenv_s(&value, &value_size, env_var); #endif std::string value_str = ""; if (value) { value_str = value; #ifdef _WIN32 free(value); #endif } // printf("get_env_var(%s) = %s\n", env_var, value_str.c_str()); return value_str; } std::list<std::string> split(const std::string & value, const char delimiter) { std::list<std::string> list; std::istringstream ss(value); std::string s; while (std::getline(ss, s, delimiter)) { list.push_back(s); } // printf("split(%s) = %zu\n", value.c_str(), list.size()); return list; } bool is_file_exist(const char * filename) { std::ifstream h(filename); // printf("is_file_exist(%s) = %s\n", filename, h.good() ? "true" : "false"); return h.good(); } std::string find_library_path(const std::string & library_name) { const char * env_var; char separator; const char * filename_prefix; const char * filename_extension; #ifdef _WIN32 env_var = "PATH"; separator = ';'; filename_prefix = ""; filename_extension = ".dll"; #elif __APPLE__ env_var = "DYLD_LIBRARY_PATH"; separator = ':'; filename_prefix = "lib"; filename_extension = ".dylib"; #else env_var = "LD_LIBRARY_PATH"; separator = ':'; filename_prefix = "lib"; filename_extension = ".so"; #endif std::string search_path = get_env_var(env_var); std::list<std::string> search_paths = split(search_path, separator); std::string filename = filename_prefix; filename += library_name + filename_extension; for (auto it : search_paths) { std::string path = it + "/" + filename; if (is_file_exist(path.c_str())) { return path; } } return ""; } #define STRINGIFY_(s) #s #define STRINGIFY(s) STRINGIFY_(s) Poco::SharedLibrary * get_library() { static Poco::SharedLibrary * lib = nullptr; if (!lib) { std::string env_var = get_env_var("RMW_IMPLEMENTATION"); if (env_var.empty()) { env_var = STRINGIFY(DEFAULT_RMW_IMPLEMENTATION); } std::string library_path = find_library_path(env_var); if (library_path.empty()) { RMW_SET_ERROR_MSG("failed to find shared library of rmw implementation"); return nullptr; } try { lib = new Poco::SharedLibrary(library_path); } catch (...) { RMW_SET_ERROR_MSG("failed to load shared library of rmw implementation"); return nullptr; } } return lib; } void * get_symbol(const char * symbol_name) { Poco::SharedLibrary * lib = get_library(); if (!lib) { // error message set by get_library() return nullptr; } if (!lib->hasSymbol(symbol_name)) { rcutils_allocator_t allocator = rcutils_get_default_allocator(); char * msg = rcutils_format_string( allocator, "failed to resolve symbol in shared library '%s'", lib->getPath().c_str()); if (msg) { RMW_SET_ERROR_MSG(msg); allocator.deallocate(msg, allocator.state); } else { RMW_SET_ERROR_MSG("failed to allocate memory for error message") } return nullptr; } return lib->getSymbol(symbol_name); } #if __cplusplus extern "C" { #endif #define ARG_TYPES(...) __VA_ARGS__ #define ARG_VALUES(...) __VA_ARGS__ #define CALL_SYMBOL(symbol_name, ReturnType, error_value, ArgTypes, arg_values) \ void * symbol = get_symbol(symbol_name); \ if (!symbol) { \ /* error message set by get_symbol() */ \ return error_value; \ } \ typedef ReturnType (* FunctionSignature)(ArgTypes); \ FunctionSignature func = reinterpret_cast<FunctionSignature>(symbol); \ return func(arg_values); const char * rmw_get_implementation_identifier(void) { CALL_SYMBOL( "rmw_get_implementation_identifier", const char *, nullptr, ARG_TYPES(void), ARG_VALUES()); } rmw_ret_t rmw_init(void) { CALL_SYMBOL( "rmw_init", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(void), ARG_VALUES()); } rmw_node_t * rmw_create_node(const char * name, const char * namespace_, size_t domain_id, const rmw_node_security_options_t * security_options) { CALL_SYMBOL( "rmw_create_node", rmw_node_t *, nullptr, ARG_TYPES(const char *, const char *, size_t, const rmw_node_security_options_t *), ARG_VALUES(name, namespace_, domain_id, security_options)); } rmw_ret_t rmw_destroy_node(rmw_node_t * node) { CALL_SYMBOL( "rmw_destroy_node", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(rmw_node_t *), ARG_VALUES(node)); } const rmw_guard_condition_t * rmw_node_get_graph_guard_condition(const rmw_node_t * node) { CALL_SYMBOL( "rmw_node_get_graph_guard_condition", const rmw_guard_condition_t *, nullptr, ARG_TYPES(const rmw_node_t *), ARG_VALUES(node)); } rmw_publisher_t * rmw_create_publisher( const rmw_node_t * node, const rosidl_message_type_support_t * type_support, const char * topic_name, const rmw_qos_profile_t * qos_policies) { CALL_SYMBOL( "rmw_create_publisher", rmw_publisher_t *, nullptr, ARG_TYPES( const rmw_node_t *, const rosidl_message_type_support_t *, const char *, const rmw_qos_profile_t *), ARG_VALUES(node, type_support, topic_name, qos_policies)); } rmw_ret_t rmw_destroy_publisher(rmw_node_t * node, rmw_publisher_t * publisher) { CALL_SYMBOL( "rmw_destroy_publisher", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(rmw_node_t *, rmw_publisher_t *), ARG_VALUES(node, publisher)); } rmw_ret_t rmw_publish(const rmw_publisher_t * publisher, const void * ros_message) { CALL_SYMBOL( "rmw_publish", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_publisher_t *, const void *), ARG_VALUES(publisher, ros_message)); } rmw_subscription_t * rmw_create_subscription( const rmw_node_t * node, const rosidl_message_type_support_t * type_support, const char * topic_name, const rmw_qos_profile_t * qos_policies, bool ignore_local_publications) { CALL_SYMBOL( "rmw_create_subscription", rmw_subscription_t *, nullptr, ARG_TYPES( const rmw_node_t *, const rosidl_message_type_support_t *, const char *, const rmw_qos_profile_t *, bool), ARG_VALUES(node, type_support, topic_name, qos_policies, ignore_local_publications)); } rmw_ret_t rmw_destroy_subscription(rmw_node_t * node, rmw_subscription_t * subscription) { CALL_SYMBOL( "rmw_destroy_subscription", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(rmw_node_t *, rmw_subscription_t *), ARG_VALUES(node, subscription)); } rmw_ret_t rmw_take(const rmw_subscription_t * subscription, void * ros_message, bool * taken) { CALL_SYMBOL( "rmw_take", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_subscription_t *, void *, bool *), ARG_VALUES(subscription, ros_message, taken)); } rmw_ret_t rmw_take_with_info( const rmw_subscription_t * subscription, void * ros_message, bool * taken, rmw_message_info_t * message_info) { CALL_SYMBOL( "rmw_take_with_info", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_subscription_t *, void *, bool *, rmw_message_info_t *), ARG_VALUES(subscription, ros_message, taken, message_info)); } rmw_client_t * rmw_create_client( const rmw_node_t * node, const rosidl_service_type_support_t * type_support, const char * service_name, const rmw_qos_profile_t * qos_policies) { CALL_SYMBOL( "rmw_create_client", rmw_client_t *, nullptr, ARG_TYPES( const rmw_node_t *, const rosidl_service_type_support_t *, const char *, const rmw_qos_profile_t *), ARG_VALUES(node, type_support, service_name, qos_policies)); } rmw_ret_t rmw_destroy_client(rmw_node_t * node, rmw_client_t * client) { CALL_SYMBOL( "rmw_destroy_client", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(rmw_node_t *, rmw_client_t *), ARG_VALUES(node, client)); } rmw_ret_t rmw_send_request( const rmw_client_t * client, const void * ros_request, int64_t * sequence_id) { CALL_SYMBOL( "rmw_send_request", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_client_t *, const void *, int64_t *), ARG_VALUES(client, ros_request, sequence_id)); } rmw_ret_t rmw_take_response( const rmw_client_t * client, rmw_request_id_t * request_header, void * ros_response, bool * taken) { CALL_SYMBOL( "rmw_take_response", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_client_t *, rmw_request_id_t *, void *, bool *), ARG_VALUES(client, request_header, ros_response, taken)); } rmw_service_t * rmw_create_service( const rmw_node_t * node, const rosidl_service_type_support_t * type_support, const char * service_name, const rmw_qos_profile_t * qos_policies) { CALL_SYMBOL( "rmw_create_service", rmw_service_t *, nullptr, ARG_TYPES( const rmw_node_t *, const rosidl_service_type_support_t *, const char *, const rmw_qos_profile_t *), ARG_VALUES(node, type_support, service_name, qos_policies)); } rmw_ret_t rmw_destroy_service(rmw_node_t * node, rmw_service_t * service) { CALL_SYMBOL( "rmw_destroy_service", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(rmw_node_t *, rmw_service_t *), ARG_VALUES(node, service)); } rmw_ret_t rmw_take_request( const rmw_service_t * service, rmw_request_id_t * request_header, void * ros_request, bool * taken) { CALL_SYMBOL( "rmw_take_request", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_service_t *, rmw_request_id_t *, void *, bool *), ARG_VALUES(service, request_header, ros_request, taken)); } rmw_ret_t rmw_send_response( const rmw_service_t * service, rmw_request_id_t * request_header, void * ros_response) { CALL_SYMBOL( "rmw_send_response", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_service_t *, rmw_request_id_t *, void *), ARG_VALUES(service, request_header, ros_response)); } rmw_guard_condition_t * rmw_create_guard_condition(void) { CALL_SYMBOL( "rmw_create_guard_condition", rmw_guard_condition_t *, nullptr, ARG_TYPES(void), ARG_VALUES()); } rmw_ret_t rmw_destroy_guard_condition(rmw_guard_condition_t * guard_condition) { CALL_SYMBOL( "rmw_destroy_guard_condition", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(rmw_guard_condition_t *), ARG_VALUES(guard_condition)); } rmw_ret_t rmw_trigger_guard_condition(const rmw_guard_condition_t * guard_condition) { CALL_SYMBOL( "rmw_trigger_guard_condition", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_guard_condition_t *), ARG_VALUES(guard_condition)); } rmw_waitset_t * rmw_create_waitset(size_t max_conditions) { CALL_SYMBOL( "rmw_create_waitset", rmw_waitset_t *, nullptr, ARG_TYPES(size_t), ARG_VALUES(max_conditions)); } rmw_ret_t rmw_destroy_waitset(rmw_waitset_t * waitset) { CALL_SYMBOL( "rmw_destroy_waitset", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(rmw_waitset_t *), ARG_VALUES(waitset)); } rmw_ret_t rmw_wait( rmw_subscriptions_t * subscriptions, rmw_guard_conditions_t * guard_conditions, rmw_services_t * services, rmw_clients_t * clients, rmw_waitset_t * waitset, const rmw_time_t * wait_timeout) { CALL_SYMBOL( "rmw_wait", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES( rmw_subscriptions_t *, rmw_guard_conditions_t *, rmw_services_t *, rmw_clients_t *, rmw_waitset_t *, const rmw_time_t *), ARG_VALUES( subscriptions, guard_conditions, services, clients, waitset, wait_timeout)); } rmw_ret_t rmw_get_topic_names_and_types( const rmw_node_t * node, rcutils_allocator_t * allocator, bool no_demangle, rmw_names_and_types_t * topic_names_and_types) { CALL_SYMBOL( "rmw_get_topic_names_and_types", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_node_t *, rcutils_allocator_t *, bool, rmw_names_and_types_t *), ARG_VALUES(node, allocator, no_demangle, topic_names_and_types)); } rmw_ret_t rmw_get_service_names_and_types( const rmw_node_t * node, rcutils_allocator_t * allocator, rmw_names_and_types_t * service_names_and_types) { CALL_SYMBOL( "rmw_get_service_names_and_types", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_node_t *, rcutils_allocator_t *, rmw_names_and_types_t *), ARG_VALUES(node, allocator, service_names_and_types)); } rmw_ret_t rmw_get_node_names( const rmw_node_t * node, rcutils_string_array_t * node_names) { CALL_SYMBOL( "rmw_get_node_names", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_node_t *, rcutils_string_array_t *), ARG_VALUES(node, node_names)); } rmw_ret_t rmw_count_publishers( const rmw_node_t * node, const char * topic_name, size_t * count) { CALL_SYMBOL( "rmw_count_publishers", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_node_t *, const char *, size_t *), ARG_VALUES(node, topic_name, count)); } rmw_ret_t rmw_count_subscribers( const rmw_node_t * node, const char * topic_name, size_t * count) { CALL_SYMBOL( "rmw_count_subscribers", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_node_t *, const char *, size_t *), ARG_VALUES(node, topic_name, count)); } rmw_ret_t rmw_get_gid_for_publisher(const rmw_publisher_t * publisher, rmw_gid_t * gid) { CALL_SYMBOL( "rmw_get_gid_for_publisher", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES( const rmw_publisher_t *, rmw_gid_t *), ARG_VALUES(publisher, gid)); } rmw_ret_t rmw_compare_gids_equal(const rmw_gid_t * gid1, const rmw_gid_t * gid2, bool * result) { CALL_SYMBOL( "rmw_compare_gids_equal", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_gid_t *, const rmw_gid_t *, bool *), ARG_VALUES(gid1, gid2, result)); } rmw_ret_t rmw_service_server_is_available( const rmw_node_t * node, const rmw_client_t * client, bool * is_available) { CALL_SYMBOL( "rmw_service_server_is_available", rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(const rmw_node_t *, const rmw_client_t *, bool *), ARG_VALUES(node, client, is_available)); } #if __cplusplus } #endif
// Copyright 2016-2017 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cstddef> #include <cstdio> #include <cstring> #include <list> #include <string> #include <fstream> #include <sstream> #include "rcutils/allocator.h" #include "rcutils/format_string.h" #include "rcutils/types/string_array.h" #include "Poco/SharedLibrary.h" #include "rmw/error_handling.h" #include "rmw/names_and_types.h" #include "rmw/get_service_names_and_types.h" #include "rmw/get_topic_names_and_types.h" #include "rmw/rmw.h" std::string get_env_var(const char * env_var) { char * value = nullptr; #ifndef _WIN32 value = getenv(env_var); #else size_t value_size; _dupenv_s(&value, &value_size, env_var); #endif std::string value_str = ""; if (value) { value_str = value; #ifdef _WIN32 free(value); #endif } // printf("get_env_var(%s) = %s\n", env_var, value_str.c_str()); return value_str; } std::list<std::string> split(const std::string & value, const char delimiter) { std::list<std::string> list; std::istringstream ss(value); std::string s; while (std::getline(ss, s, delimiter)) { list.push_back(s); } // printf("split(%s) = %zu\n", value.c_str(), list.size()); return list; } bool is_file_exist(const char * filename) { std::ifstream h(filename); // printf("is_file_exist(%s) = %s\n", filename, h.good() ? "true" : "false"); return h.good(); } std::string find_library_path(const std::string & library_name) { const char * env_var; char separator; const char * filename_prefix; const char * filename_extension; #ifdef _WIN32 env_var = "PATH"; separator = ';'; filename_prefix = ""; filename_extension = ".dll"; #elif __APPLE__ env_var = "DYLD_LIBRARY_PATH"; separator = ':'; filename_prefix = "lib"; filename_extension = ".dylib"; #else env_var = "LD_LIBRARY_PATH"; separator = ':'; filename_prefix = "lib"; filename_extension = ".so"; #endif std::string search_path = get_env_var(env_var); std::list<std::string> search_paths = split(search_path, separator); std::string filename = filename_prefix; filename += library_name + filename_extension; for (auto it : search_paths) { std::string path = it + "/" + filename; if (is_file_exist(path.c_str())) { return path; } } return ""; } #define STRINGIFY_(s) #s #define STRINGIFY(s) STRINGIFY_(s) Poco::SharedLibrary * get_library() { static Poco::SharedLibrary * lib = nullptr; if (!lib) { std::string env_var = get_env_var("RMW_IMPLEMENTATION"); if (env_var.empty()) { env_var = STRINGIFY(DEFAULT_RMW_IMPLEMENTATION); } std::string library_path = find_library_path(env_var); if (library_path.empty()) { RMW_SET_ERROR_MSG( ("failed to find shared library of rmw implementation. Searched " + env_var).c_str()); return nullptr; } try { lib = new Poco::SharedLibrary(library_path); } catch (Poco::LibraryLoadException & e) { RMW_SET_ERROR_MSG(("failed to load shared library of rmw implementation. Exception: " + e.displayText()).c_str()); return nullptr; } catch (...) { RMW_SET_ERROR_MSG("failed to load shared library of rmw implementation"); RMW_SET_ERROR_MSG( ("failed to load shared library of rmw implementation: " + library_path).c_str()); return nullptr; } } return lib; } void * get_symbol(const char * symbol_name) { Poco::SharedLibrary * lib = get_library(); if (!lib) { // error message set by get_library() return nullptr; } if (!lib->hasSymbol(symbol_name)) { rcutils_allocator_t allocator = rcutils_get_default_allocator(); char * msg = rcutils_format_string( allocator, "failed to resolve symbol in shared library '%s'", lib->getPath().c_str()); if (msg) { RMW_SET_ERROR_MSG(msg); allocator.deallocate(msg, allocator.state); } else { RMW_SET_ERROR_MSG("failed to allocate memory for error message") } return nullptr; } return lib->getSymbol(symbol_name); } #ifdef __cplusplus extern "C" { #endif #define EXPAND(x) x #define ARG_TYPES(...) __VA_ARGS__ #define ARG_VALUES_0(...) #define ARG_VALUES_1(t1) v1 #define ARG_VALUES_2(t2, ...) v2, EXPAND(ARG_VALUES_1(__VA_ARGS__)) #define ARG_VALUES_3(t3, ...) v3, EXPAND(ARG_VALUES_2(__VA_ARGS__)) #define ARG_VALUES_4(t4, ...) v4, EXPAND(ARG_VALUES_3(__VA_ARGS__)) #define ARG_VALUES_5(t5, ...) v5, EXPAND(ARG_VALUES_4(__VA_ARGS__)) #define ARG_VALUES_6(t6, ...) v6, EXPAND(ARG_VALUES_5(__VA_ARGS__)) #define ARGS_0(...) __VA_ARGS__ #define ARGS_1(t1) t1 v1 #define ARGS_2(t2, ...) t2 v2, EXPAND(ARGS_1(__VA_ARGS__)) #define ARGS_3(t3, ...) t3 v3, EXPAND(ARGS_2(__VA_ARGS__)) #define ARGS_4(t4, ...) t4 v4, EXPAND(ARGS_3(__VA_ARGS__)) #define ARGS_5(t5, ...) t5 v5, EXPAND(ARGS_4(__VA_ARGS__)) #define ARGS_6(t6, ...) t6 v6, EXPAND(ARGS_5(__VA_ARGS__)) #define CALL_SYMBOL(symbol_name, ReturnType, error_value, ArgTypes, arg_values) \ if (!symbol_ ## symbol_name) { \ /* only necessary for functions called before rmw_init */ \ symbol_ ## symbol_name = get_symbol(#symbol_name); \ } \ if (!symbol_ ## symbol_name) { \ /* error message set by get_symbol() */ \ return error_value; \ } \ typedef ReturnType (* FunctionSignature)(ArgTypes); \ FunctionSignature func = reinterpret_cast<FunctionSignature>(symbol_ ## symbol_name); \ return func(arg_values); // cppcheck-suppress preprocessorErrorDirective #define RMW_INTERFACE_FN(name, ReturnType, error_value, _NR, ...) \ void * symbol_ ## name = nullptr; \ ReturnType name(EXPAND(ARGS_ ## _NR(__VA_ARGS__))) \ { \ CALL_SYMBOL(name, ReturnType, error_value, ARG_TYPES(__VA_ARGS__), \ EXPAND(ARG_VALUES_ ## _NR(__VA_ARGS__))); \ } RMW_INTERFACE_FN(rmw_get_implementation_identifier, const char *, nullptr, 0, ARG_TYPES(void)) RMW_INTERFACE_FN(rmw_create_node, rmw_node_t *, nullptr, 4, ARG_TYPES( const char *, const char *, size_t, const rmw_node_security_options_t *)) RMW_INTERFACE_FN(rmw_destroy_node, rmw_ret_t, RMW_RET_ERROR, 1, ARG_TYPES(rmw_node_t *)) RMW_INTERFACE_FN(rmw_node_get_graph_guard_condition, const rmw_guard_condition_t *, nullptr, 1, ARG_TYPES(const rmw_node_t *)) RMW_INTERFACE_FN(rmw_create_publisher, rmw_publisher_t *, nullptr, 4, ARG_TYPES( const rmw_node_t *, const rosidl_message_type_support_t *, const char *, const rmw_qos_profile_t *)) RMW_INTERFACE_FN(rmw_destroy_publisher, rmw_ret_t, RMW_RET_ERROR, 2, ARG_TYPES(rmw_node_t *, rmw_publisher_t *)) RMW_INTERFACE_FN(rmw_publish, rmw_ret_t, RMW_RET_ERROR, 2, ARG_TYPES(const rmw_publisher_t *, const void *)) RMW_INTERFACE_FN(rmw_create_subscription, rmw_subscription_t *, nullptr, 5, ARG_TYPES( const rmw_node_t *, const rosidl_message_type_support_t *, const char *, const rmw_qos_profile_t *, bool)) RMW_INTERFACE_FN(rmw_destroy_subscription, rmw_ret_t, RMW_RET_ERROR, 2, ARG_TYPES(rmw_node_t *, rmw_subscription_t *)) RMW_INTERFACE_FN(rmw_take, rmw_ret_t, RMW_RET_ERROR, 3, ARG_TYPES(const rmw_subscription_t *, void *, bool *)) RMW_INTERFACE_FN(rmw_take_with_info, rmw_ret_t, RMW_RET_ERROR, 4, ARG_TYPES(const rmw_subscription_t *, void *, bool *, rmw_message_info_t *)) RMW_INTERFACE_FN(rmw_create_client, rmw_client_t *, nullptr, 4, ARG_TYPES( const rmw_node_t *, const rosidl_service_type_support_t *, const char *, const rmw_qos_profile_t *)) RMW_INTERFACE_FN(rmw_destroy_client, rmw_ret_t, RMW_RET_ERROR, 2, ARG_TYPES(rmw_node_t *, rmw_client_t *)) RMW_INTERFACE_FN(rmw_send_request, rmw_ret_t, RMW_RET_ERROR, 3, ARG_TYPES(const rmw_client_t *, const void *, int64_t *)) RMW_INTERFACE_FN(rmw_take_response, rmw_ret_t, RMW_RET_ERROR, 4, ARG_TYPES(const rmw_client_t *, rmw_request_id_t *, void *, bool *)) RMW_INTERFACE_FN(rmw_create_service, rmw_service_t *, nullptr, 4, ARG_TYPES( const rmw_node_t *, const rosidl_service_type_support_t *, const char *, const rmw_qos_profile_t *)) RMW_INTERFACE_FN(rmw_destroy_service, rmw_ret_t, RMW_RET_ERROR, 2, ARG_TYPES(rmw_node_t *, rmw_service_t *)) RMW_INTERFACE_FN(rmw_take_request, rmw_ret_t, RMW_RET_ERROR, 4, ARG_TYPES(const rmw_service_t *, rmw_request_id_t *, void *, bool *)) RMW_INTERFACE_FN(rmw_send_response, rmw_ret_t, RMW_RET_ERROR, 3, ARG_TYPES(const rmw_service_t *, rmw_request_id_t *, void *)) RMW_INTERFACE_FN(rmw_create_guard_condition, rmw_guard_condition_t *, nullptr, 0, ARG_TYPES(void)) RMW_INTERFACE_FN(rmw_destroy_guard_condition, rmw_ret_t, RMW_RET_ERROR, 1, ARG_TYPES(rmw_guard_condition_t *)) RMW_INTERFACE_FN(rmw_trigger_guard_condition, rmw_ret_t, RMW_RET_ERROR, 1, ARG_TYPES(const rmw_guard_condition_t *)) RMW_INTERFACE_FN(rmw_create_wait_set, rmw_wait_set_t *, nullptr, 1, ARG_TYPES(size_t)) RMW_INTERFACE_FN(rmw_destroy_wait_set, rmw_ret_t, RMW_RET_ERROR, 1, ARG_TYPES(rmw_wait_set_t *)) RMW_INTERFACE_FN(rmw_wait, rmw_ret_t, RMW_RET_ERROR, 6, ARG_TYPES( rmw_subscriptions_t *, rmw_guard_conditions_t *, rmw_services_t *, rmw_clients_t *, rmw_wait_set_t *, const rmw_time_t *)) RMW_INTERFACE_FN(rmw_get_topic_names_and_types, rmw_ret_t, RMW_RET_ERROR, 4, ARG_TYPES( const rmw_node_t *, rcutils_allocator_t *, bool, rmw_names_and_types_t *)) RMW_INTERFACE_FN(rmw_get_service_names_and_types, rmw_ret_t, RMW_RET_ERROR, 3, ARG_TYPES( const rmw_node_t *, rcutils_allocator_t *, rmw_names_and_types_t *)) RMW_INTERFACE_FN(rmw_get_node_names, rmw_ret_t, RMW_RET_ERROR, 2, ARG_TYPES(const rmw_node_t *, rcutils_string_array_t *)) RMW_INTERFACE_FN(rmw_count_publishers, rmw_ret_t, RMW_RET_ERROR, 3, ARG_TYPES(const rmw_node_t *, const char *, size_t *)) RMW_INTERFACE_FN(rmw_count_subscribers, rmw_ret_t, RMW_RET_ERROR, 3, ARG_TYPES(const rmw_node_t *, const char *, size_t *)) RMW_INTERFACE_FN(rmw_get_gid_for_publisher, rmw_ret_t, RMW_RET_ERROR, 2, ARG_TYPES(const rmw_publisher_t *, rmw_gid_t *)) RMW_INTERFACE_FN(rmw_compare_gids_equal, rmw_ret_t, RMW_RET_ERROR, 3, ARG_TYPES(const rmw_gid_t *, const rmw_gid_t *, bool *)) RMW_INTERFACE_FN(rmw_service_server_is_available, rmw_ret_t, RMW_RET_ERROR, 3, ARG_TYPES(const rmw_node_t *, const rmw_client_t *, bool *)) RMW_INTERFACE_FN(rmw_set_log_severity, rmw_ret_t, RMW_RET_ERROR, 1, ARG_TYPES(rmw_log_severity_t)) #define GET_SYMBOL(x) symbol_ ## x = get_symbol(#x); void prefetch_symbols(void) { // get all symbols to avoid race conditions later since the passed // symbol name is expected to be a std::string which requires allocation GET_SYMBOL(rmw_get_implementation_identifier) GET_SYMBOL(rmw_create_node) GET_SYMBOL(rmw_destroy_node) GET_SYMBOL(rmw_node_get_graph_guard_condition) GET_SYMBOL(rmw_create_publisher) GET_SYMBOL(rmw_destroy_publisher) GET_SYMBOL(rmw_publish) GET_SYMBOL(rmw_create_subscription) GET_SYMBOL(rmw_destroy_subscription) GET_SYMBOL(rmw_take) GET_SYMBOL(rmw_take_with_info) GET_SYMBOL(rmw_create_client) GET_SYMBOL(rmw_destroy_client) GET_SYMBOL(rmw_send_request) GET_SYMBOL(rmw_take_response) GET_SYMBOL(rmw_create_service) GET_SYMBOL(rmw_destroy_service) GET_SYMBOL(rmw_take_request) GET_SYMBOL(rmw_send_response) GET_SYMBOL(rmw_create_guard_condition) GET_SYMBOL(rmw_destroy_guard_condition) GET_SYMBOL(rmw_trigger_guard_condition) GET_SYMBOL(rmw_create_wait_set) GET_SYMBOL(rmw_destroy_wait_set) GET_SYMBOL(rmw_wait) GET_SYMBOL(rmw_get_topic_names_and_types) GET_SYMBOL(rmw_get_service_names_and_types) GET_SYMBOL(rmw_get_node_names) GET_SYMBOL(rmw_count_publishers) GET_SYMBOL(rmw_count_subscribers) GET_SYMBOL(rmw_get_gid_for_publisher) GET_SYMBOL(rmw_compare_gids_equal) GET_SYMBOL(rmw_service_server_is_available) } void * symbol_rmw_init = nullptr; rmw_ret_t rmw_init(void) { prefetch_symbols(); CALL_SYMBOL( rmw_init, rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(void), ARG_VALUES_0()) } #ifdef __cplusplus } #endif print missing symbol name (#40) // Copyright 2016-2017 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cstddef> #include <cstdio> #include <cstring> #include <list> #include <string> #include <fstream> #include <sstream> #include "rcutils/allocator.h" #include "rcutils/format_string.h" #include "rcutils/types/string_array.h" #include "Poco/SharedLibrary.h" #include "rmw/error_handling.h" #include "rmw/names_and_types.h" #include "rmw/get_service_names_and_types.h" #include "rmw/get_topic_names_and_types.h" #include "rmw/rmw.h" std::string get_env_var(const char * env_var) { char * value = nullptr; #ifndef _WIN32 value = getenv(env_var); #else size_t value_size; _dupenv_s(&value, &value_size, env_var); #endif std::string value_str = ""; if (value) { value_str = value; #ifdef _WIN32 free(value); #endif } // printf("get_env_var(%s) = %s\n", env_var, value_str.c_str()); return value_str; } std::list<std::string> split(const std::string & value, const char delimiter) { std::list<std::string> list; std::istringstream ss(value); std::string s; while (std::getline(ss, s, delimiter)) { list.push_back(s); } // printf("split(%s) = %zu\n", value.c_str(), list.size()); return list; } bool is_file_exist(const char * filename) { std::ifstream h(filename); // printf("is_file_exist(%s) = %s\n", filename, h.good() ? "true" : "false"); return h.good(); } std::string find_library_path(const std::string & library_name) { const char * env_var; char separator; const char * filename_prefix; const char * filename_extension; #ifdef _WIN32 env_var = "PATH"; separator = ';'; filename_prefix = ""; filename_extension = ".dll"; #elif __APPLE__ env_var = "DYLD_LIBRARY_PATH"; separator = ':'; filename_prefix = "lib"; filename_extension = ".dylib"; #else env_var = "LD_LIBRARY_PATH"; separator = ':'; filename_prefix = "lib"; filename_extension = ".so"; #endif std::string search_path = get_env_var(env_var); std::list<std::string> search_paths = split(search_path, separator); std::string filename = filename_prefix; filename += library_name + filename_extension; for (auto it : search_paths) { std::string path = it + "/" + filename; if (is_file_exist(path.c_str())) { return path; } } return ""; } #define STRINGIFY_(s) #s #define STRINGIFY(s) STRINGIFY_(s) Poco::SharedLibrary * get_library() { static Poco::SharedLibrary * lib = nullptr; if (!lib) { std::string env_var = get_env_var("RMW_IMPLEMENTATION"); if (env_var.empty()) { env_var = STRINGIFY(DEFAULT_RMW_IMPLEMENTATION); } std::string library_path = find_library_path(env_var); if (library_path.empty()) { RMW_SET_ERROR_MSG( ("failed to find shared library of rmw implementation. Searched " + env_var).c_str()); return nullptr; } try { lib = new Poco::SharedLibrary(library_path); } catch (Poco::LibraryLoadException & e) { RMW_SET_ERROR_MSG(("failed to load shared library of rmw implementation. Exception: " + e.displayText()).c_str()); return nullptr; } catch (...) { RMW_SET_ERROR_MSG("failed to load shared library of rmw implementation"); RMW_SET_ERROR_MSG( ("failed to load shared library of rmw implementation: " + library_path).c_str()); return nullptr; } } return lib; } void * get_symbol(const char * symbol_name) { Poco::SharedLibrary * lib = get_library(); if (!lib) { // error message set by get_library() return nullptr; } if (!lib->hasSymbol(symbol_name)) { rcutils_allocator_t allocator = rcutils_get_default_allocator(); char * msg = rcutils_format_string( allocator, "failed to resolve symbol '%s' in shared library '%s'", symbol_name, lib->getPath().c_str()); if (msg) { RMW_SET_ERROR_MSG(msg); allocator.deallocate(msg, allocator.state); } else { RMW_SET_ERROR_MSG("failed to allocate memory for error message") } return nullptr; } return lib->getSymbol(symbol_name); } #ifdef __cplusplus extern "C" { #endif #define EXPAND(x) x #define ARG_TYPES(...) __VA_ARGS__ #define ARG_VALUES_0(...) #define ARG_VALUES_1(t1) v1 #define ARG_VALUES_2(t2, ...) v2, EXPAND(ARG_VALUES_1(__VA_ARGS__)) #define ARG_VALUES_3(t3, ...) v3, EXPAND(ARG_VALUES_2(__VA_ARGS__)) #define ARG_VALUES_4(t4, ...) v4, EXPAND(ARG_VALUES_3(__VA_ARGS__)) #define ARG_VALUES_5(t5, ...) v5, EXPAND(ARG_VALUES_4(__VA_ARGS__)) #define ARG_VALUES_6(t6, ...) v6, EXPAND(ARG_VALUES_5(__VA_ARGS__)) #define ARGS_0(...) __VA_ARGS__ #define ARGS_1(t1) t1 v1 #define ARGS_2(t2, ...) t2 v2, EXPAND(ARGS_1(__VA_ARGS__)) #define ARGS_3(t3, ...) t3 v3, EXPAND(ARGS_2(__VA_ARGS__)) #define ARGS_4(t4, ...) t4 v4, EXPAND(ARGS_3(__VA_ARGS__)) #define ARGS_5(t5, ...) t5 v5, EXPAND(ARGS_4(__VA_ARGS__)) #define ARGS_6(t6, ...) t6 v6, EXPAND(ARGS_5(__VA_ARGS__)) #define CALL_SYMBOL(symbol_name, ReturnType, error_value, ArgTypes, arg_values) \ if (!symbol_ ## symbol_name) { \ /* only necessary for functions called before rmw_init */ \ symbol_ ## symbol_name = get_symbol(#symbol_name); \ } \ if (!symbol_ ## symbol_name) { \ /* error message set by get_symbol() */ \ return error_value; \ } \ typedef ReturnType (* FunctionSignature)(ArgTypes); \ FunctionSignature func = reinterpret_cast<FunctionSignature>(symbol_ ## symbol_name); \ return func(arg_values); // cppcheck-suppress preprocessorErrorDirective #define RMW_INTERFACE_FN(name, ReturnType, error_value, _NR, ...) \ void * symbol_ ## name = nullptr; \ ReturnType name(EXPAND(ARGS_ ## _NR(__VA_ARGS__))) \ { \ CALL_SYMBOL(name, ReturnType, error_value, ARG_TYPES(__VA_ARGS__), \ EXPAND(ARG_VALUES_ ## _NR(__VA_ARGS__))); \ } RMW_INTERFACE_FN(rmw_get_implementation_identifier, const char *, nullptr, 0, ARG_TYPES(void)) RMW_INTERFACE_FN(rmw_create_node, rmw_node_t *, nullptr, 4, ARG_TYPES( const char *, const char *, size_t, const rmw_node_security_options_t *)) RMW_INTERFACE_FN(rmw_destroy_node, rmw_ret_t, RMW_RET_ERROR, 1, ARG_TYPES(rmw_node_t *)) RMW_INTERFACE_FN(rmw_node_get_graph_guard_condition, const rmw_guard_condition_t *, nullptr, 1, ARG_TYPES(const rmw_node_t *)) RMW_INTERFACE_FN(rmw_create_publisher, rmw_publisher_t *, nullptr, 4, ARG_TYPES( const rmw_node_t *, const rosidl_message_type_support_t *, const char *, const rmw_qos_profile_t *)) RMW_INTERFACE_FN(rmw_destroy_publisher, rmw_ret_t, RMW_RET_ERROR, 2, ARG_TYPES(rmw_node_t *, rmw_publisher_t *)) RMW_INTERFACE_FN(rmw_publish, rmw_ret_t, RMW_RET_ERROR, 2, ARG_TYPES(const rmw_publisher_t *, const void *)) RMW_INTERFACE_FN(rmw_create_subscription, rmw_subscription_t *, nullptr, 5, ARG_TYPES( const rmw_node_t *, const rosidl_message_type_support_t *, const char *, const rmw_qos_profile_t *, bool)) RMW_INTERFACE_FN(rmw_destroy_subscription, rmw_ret_t, RMW_RET_ERROR, 2, ARG_TYPES(rmw_node_t *, rmw_subscription_t *)) RMW_INTERFACE_FN(rmw_take, rmw_ret_t, RMW_RET_ERROR, 3, ARG_TYPES(const rmw_subscription_t *, void *, bool *)) RMW_INTERFACE_FN(rmw_take_with_info, rmw_ret_t, RMW_RET_ERROR, 4, ARG_TYPES(const rmw_subscription_t *, void *, bool *, rmw_message_info_t *)) RMW_INTERFACE_FN(rmw_create_client, rmw_client_t *, nullptr, 4, ARG_TYPES( const rmw_node_t *, const rosidl_service_type_support_t *, const char *, const rmw_qos_profile_t *)) RMW_INTERFACE_FN(rmw_destroy_client, rmw_ret_t, RMW_RET_ERROR, 2, ARG_TYPES(rmw_node_t *, rmw_client_t *)) RMW_INTERFACE_FN(rmw_send_request, rmw_ret_t, RMW_RET_ERROR, 3, ARG_TYPES(const rmw_client_t *, const void *, int64_t *)) RMW_INTERFACE_FN(rmw_take_response, rmw_ret_t, RMW_RET_ERROR, 4, ARG_TYPES(const rmw_client_t *, rmw_request_id_t *, void *, bool *)) RMW_INTERFACE_FN(rmw_create_service, rmw_service_t *, nullptr, 4, ARG_TYPES( const rmw_node_t *, const rosidl_service_type_support_t *, const char *, const rmw_qos_profile_t *)) RMW_INTERFACE_FN(rmw_destroy_service, rmw_ret_t, RMW_RET_ERROR, 2, ARG_TYPES(rmw_node_t *, rmw_service_t *)) RMW_INTERFACE_FN(rmw_take_request, rmw_ret_t, RMW_RET_ERROR, 4, ARG_TYPES(const rmw_service_t *, rmw_request_id_t *, void *, bool *)) RMW_INTERFACE_FN(rmw_send_response, rmw_ret_t, RMW_RET_ERROR, 3, ARG_TYPES(const rmw_service_t *, rmw_request_id_t *, void *)) RMW_INTERFACE_FN(rmw_create_guard_condition, rmw_guard_condition_t *, nullptr, 0, ARG_TYPES(void)) RMW_INTERFACE_FN(rmw_destroy_guard_condition, rmw_ret_t, RMW_RET_ERROR, 1, ARG_TYPES(rmw_guard_condition_t *)) RMW_INTERFACE_FN(rmw_trigger_guard_condition, rmw_ret_t, RMW_RET_ERROR, 1, ARG_TYPES(const rmw_guard_condition_t *)) RMW_INTERFACE_FN(rmw_create_wait_set, rmw_wait_set_t *, nullptr, 1, ARG_TYPES(size_t)) RMW_INTERFACE_FN(rmw_destroy_wait_set, rmw_ret_t, RMW_RET_ERROR, 1, ARG_TYPES(rmw_wait_set_t *)) RMW_INTERFACE_FN(rmw_wait, rmw_ret_t, RMW_RET_ERROR, 6, ARG_TYPES( rmw_subscriptions_t *, rmw_guard_conditions_t *, rmw_services_t *, rmw_clients_t *, rmw_wait_set_t *, const rmw_time_t *)) RMW_INTERFACE_FN(rmw_get_topic_names_and_types, rmw_ret_t, RMW_RET_ERROR, 4, ARG_TYPES( const rmw_node_t *, rcutils_allocator_t *, bool, rmw_names_and_types_t *)) RMW_INTERFACE_FN(rmw_get_service_names_and_types, rmw_ret_t, RMW_RET_ERROR, 3, ARG_TYPES( const rmw_node_t *, rcutils_allocator_t *, rmw_names_and_types_t *)) RMW_INTERFACE_FN(rmw_get_node_names, rmw_ret_t, RMW_RET_ERROR, 2, ARG_TYPES(const rmw_node_t *, rcutils_string_array_t *)) RMW_INTERFACE_FN(rmw_count_publishers, rmw_ret_t, RMW_RET_ERROR, 3, ARG_TYPES(const rmw_node_t *, const char *, size_t *)) RMW_INTERFACE_FN(rmw_count_subscribers, rmw_ret_t, RMW_RET_ERROR, 3, ARG_TYPES(const rmw_node_t *, const char *, size_t *)) RMW_INTERFACE_FN(rmw_get_gid_for_publisher, rmw_ret_t, RMW_RET_ERROR, 2, ARG_TYPES(const rmw_publisher_t *, rmw_gid_t *)) RMW_INTERFACE_FN(rmw_compare_gids_equal, rmw_ret_t, RMW_RET_ERROR, 3, ARG_TYPES(const rmw_gid_t *, const rmw_gid_t *, bool *)) RMW_INTERFACE_FN(rmw_service_server_is_available, rmw_ret_t, RMW_RET_ERROR, 3, ARG_TYPES(const rmw_node_t *, const rmw_client_t *, bool *)) RMW_INTERFACE_FN(rmw_set_log_severity, rmw_ret_t, RMW_RET_ERROR, 1, ARG_TYPES(rmw_log_severity_t)) #define GET_SYMBOL(x) symbol_ ## x = get_symbol(#x); void prefetch_symbols(void) { // get all symbols to avoid race conditions later since the passed // symbol name is expected to be a std::string which requires allocation GET_SYMBOL(rmw_get_implementation_identifier) GET_SYMBOL(rmw_create_node) GET_SYMBOL(rmw_destroy_node) GET_SYMBOL(rmw_node_get_graph_guard_condition) GET_SYMBOL(rmw_create_publisher) GET_SYMBOL(rmw_destroy_publisher) GET_SYMBOL(rmw_publish) GET_SYMBOL(rmw_create_subscription) GET_SYMBOL(rmw_destroy_subscription) GET_SYMBOL(rmw_take) GET_SYMBOL(rmw_take_with_info) GET_SYMBOL(rmw_create_client) GET_SYMBOL(rmw_destroy_client) GET_SYMBOL(rmw_send_request) GET_SYMBOL(rmw_take_response) GET_SYMBOL(rmw_create_service) GET_SYMBOL(rmw_destroy_service) GET_SYMBOL(rmw_take_request) GET_SYMBOL(rmw_send_response) GET_SYMBOL(rmw_create_guard_condition) GET_SYMBOL(rmw_destroy_guard_condition) GET_SYMBOL(rmw_trigger_guard_condition) GET_SYMBOL(rmw_create_wait_set) GET_SYMBOL(rmw_destroy_wait_set) GET_SYMBOL(rmw_wait) GET_SYMBOL(rmw_get_topic_names_and_types) GET_SYMBOL(rmw_get_service_names_and_types) GET_SYMBOL(rmw_get_node_names) GET_SYMBOL(rmw_count_publishers) GET_SYMBOL(rmw_count_subscribers) GET_SYMBOL(rmw_get_gid_for_publisher) GET_SYMBOL(rmw_compare_gids_equal) GET_SYMBOL(rmw_service_server_is_available) } void * symbol_rmw_init = nullptr; rmw_ret_t rmw_init(void) { prefetch_symbols(); CALL_SYMBOL( rmw_init, rmw_ret_t, RMW_RET_ERROR, ARG_TYPES(void), ARG_VALUES_0()) } #ifdef __cplusplus } #endif
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 * * (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef SOFA_COMPONENT_PROJECTIVECONSTRAINTSET_LINEARMOVEMENTCONSTRAINT_INL #define SOFA_COMPONENT_PROJECTIVECONSTRAINTSET_LINEARMOVEMENTCONSTRAINT_INL #include <sofa/component/projectiveconstraintset/LinearMovementConstraint.h> #include <sofa/core/topology/BaseMeshTopology.h> #include <sofa/core/behavior/ProjectiveConstraintSet.inl> #include <sofa/simulation/common/Simulation.h> #include <sofa/helper/gl/template.h> #include <sofa/defaulttype/RigidTypes.h> #include <iostream> #include <sofa/component/topology/PointSubset.h> namespace sofa { namespace component { namespace projectiveconstraintset { using namespace core::topology; using namespace sofa::defaulttype; using namespace sofa::helper; using namespace sofa::core::behavior; // Define TestNewPointFunction template< class DataTypes> bool LinearMovementConstraint<DataTypes>::FCTestNewPointFunction(int /*nbPoints*/, void* param, const sofa::helper::vector< unsigned int > &, const sofa::helper::vector< double >& ) { LinearMovementConstraint<DataTypes> *fc = (LinearMovementConstraint<DataTypes> *)param; return fc != 0; } // Define RemovalFunction template< class DataTypes> void LinearMovementConstraint<DataTypes>::FCRemovalFunction(int pointIndex, void* param) { LinearMovementConstraint<DataTypes> *fc= (LinearMovementConstraint<DataTypes> *)param; if (fc) { fc->removeIndex((unsigned int) pointIndex); } return; } template <class DataTypes> LinearMovementConstraint<DataTypes>::LinearMovementConstraint() : core::behavior::ProjectiveConstraintSet<DataTypes>(NULL) , data(new LinearMovementConstraintInternalData<DataTypes>) , m_indices( initData(&m_indices,"indices","Indices of the constrained points") ) , m_keyTimes( initData(&m_keyTimes,"keyTimes","key times for the movements") ) , m_keyMovements( initData(&m_keyMovements,"movements","movements corresponding to the key times") ) , showMovement( initData(&showMovement, (bool)false, "showMovement", "Visualization of the movement to be applied to constrained dofs.")) { // default to indice 0 m_indices.beginEdit()->push_back(0); m_indices.endEdit(); //default valueEvent to 0 m_keyTimes.beginEdit()->push_back( 0.0 ); m_keyTimes.endEdit(); m_keyMovements.beginEdit()->push_back( Deriv() ); m_keyMovements.endEdit(); } // Handle topological changes template <class DataTypes> void LinearMovementConstraint<DataTypes>::handleTopologyChange() { std::list<const TopologyChange *>::const_iterator itBegin=topology->beginChange(); std::list<const TopologyChange *>::const_iterator itEnd=topology->endChange(); m_indices.beginEdit()->handleTopologyEvents(itBegin,itEnd,this->getMState()->getSize()); } template <class DataTypes> LinearMovementConstraint<DataTypes>::~LinearMovementConstraint() { } template <class DataTypes> void LinearMovementConstraint<DataTypes>::clearIndices() { m_indices.beginEdit()->clear(); m_indices.endEdit(); } template <class DataTypes> void LinearMovementConstraint<DataTypes>::addIndex(unsigned int index) { m_indices.beginEdit()->push_back(index); m_indices.endEdit(); } template <class DataTypes> void LinearMovementConstraint<DataTypes>::removeIndex(unsigned int index) { removeValue(*m_indices.beginEdit(),index); m_indices.endEdit(); } template <class DataTypes> void LinearMovementConstraint<DataTypes>::clearKeyMovements() { m_keyTimes.beginEdit()->clear(); m_keyTimes.endEdit(); m_keyMovements.beginEdit()->clear(); m_keyMovements.endEdit(); } template <class DataTypes> void LinearMovementConstraint<DataTypes>::addKeyMovement(Real time, Deriv movement) { m_keyTimes.beginEdit()->push_back( time ); m_keyTimes.endEdit(); m_keyMovements.beginEdit()->push_back( movement ); m_keyMovements.endEdit(); } // -- Constraint interface template <class DataTypes> void LinearMovementConstraint<DataTypes>::init() { this->core::behavior::ProjectiveConstraintSet<DataTypes>::init(); topology = this->getContext()->getMeshTopology(); // Initialize functions and parameters topology::PointSubset my_subset = m_indices.getValue(); my_subset.setTestFunction(FCTestNewPointFunction); my_subset.setRemovalFunction(FCRemovalFunction); my_subset.setTestParameter( (void *) this ); my_subset.setRemovalParameter( (void *) this ); x0.resize(0); nextM = prevM = Deriv(); currentTime = -1.0; finished = false; } template <class DataTypes> void LinearMovementConstraint<DataTypes>::reset() { nextT = prevT = 0.0; nextM = prevM = Deriv(); currentTime = -1.0; finished = false; } template <class DataTypes> template <class DataDeriv> void LinearMovementConstraint<DataTypes>::projectResponseT(const core::MechanicalParams* /*mparams*/ /* PARAMS FIRST */, DataDeriv& dx) { Real cT = (Real) this->getContext()->getTime(); if ((cT != currentTime) || !finished) { findKeyTimes(); } if (finished && nextT != prevT) { const SetIndexArray & indices = m_indices.getValue().getArray(); //set the motion to the Dofs for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it) { dx[*it] = Deriv(); } } } template <class DataTypes> void LinearMovementConstraint<DataTypes>::projectResponse(const core::MechanicalParams* mparams /* PARAMS FIRST */, DataVecDeriv& resData) { helper::WriteAccessor<DataVecDeriv> res = resData; projectResponseT<VecDeriv>(mparams /* PARAMS FIRST */, res.wref()); } template <class DataTypes> void LinearMovementConstraint<DataTypes>::projectVelocity(const core::MechanicalParams* /*mparams*/ /* PARAMS FIRST */, DataVecDeriv& vData) { helper::WriteAccessor<DataVecDeriv> dx = vData; Real cT = (Real) this->getContext()->getTime(); if ((cT != currentTime) || !finished) { findKeyTimes(); } if (finished && nextT != prevT) { const SetIndexArray & indices = m_indices.getValue().getArray(); //set the motion to the Dofs for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it) { dx[*it] = (nextM - prevM)*(1.0 / (nextT - prevT)); } } } template <class DataTypes> void LinearMovementConstraint<DataTypes>::projectPosition(const core::MechanicalParams* /*mparams*/ /* PARAMS FIRST */, DataVecCoord& xData) { helper::WriteAccessor<DataVecCoord> x = xData; Real cT = (Real) this->getContext()->getTime(); //initialize initial Dofs positions, if it's not done if (x0.size() == 0) { const SetIndexArray & indices = m_indices.getValue().getArray(); x0.resize(x.size()); for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it) { x0[*it] = x[*it]; } } if ((cT != currentTime) || !finished) { findKeyTimes(); } //if we found 2 keyTimes, we have to interpolate a velocity (linear interpolation) if(finished && nextT != prevT) { interpolatePosition<Coord>(cT, x.wref()); } } template <class DataTypes> template <class MyCoord> void LinearMovementConstraint<DataTypes>::interpolatePosition(Real cT, typename boost::disable_if<boost::is_same<MyCoord, RigidCoord<3, Real> >, VecCoord>::type& x) { const SetIndexArray & indices = m_indices.getValue().getArray(); Real dt = (cT - prevT) / (nextT - prevT); Deriv m = prevM + (nextM-prevM)*dt; cerr<<"LinearMovementConstraint<DataTypes>::interpolatePosition, current X = "<< x << endl; //set the motion to the Dofs for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it) { x[*it] = x0[*it] + m ; } cerr<<"LinearMovementConstraint<DataTypes>::interpolatePosition, prevT = "<< prevT <<", prevM = "<< prevM << endl; cerr<<"LinearMovementConstraint<DataTypes>::interpolatePosition, nextT = "<< nextT <<", nextM = "<< nextM << endl; cerr<<"LinearMovementConstraint<DataTypes>::interpolatePosition, t = "<< cT <<", M = "<< m << endl; cerr<<"LinearMovementConstraint<DataTypes>::interpolatePosition, new X = "<< x << endl; } template <class DataTypes> template <class MyCoord> void LinearMovementConstraint<DataTypes>::interpolatePosition(Real cT, typename boost::enable_if<boost::is_same<MyCoord, RigidCoord<3, Real> >, VecCoord>::type& x) { const SetIndexArray & indices = m_indices.getValue().getArray(); Real dt = (cT - prevT) / (nextT - prevT); Deriv m = prevM + (nextM-prevM)*dt; Quater<Real> prevOrientation = Quater<Real>::createQuaterFromEuler(getVOrientation(prevM)); Quater<Real> nextOrientation = Quater<Real>::createQuaterFromEuler(getVOrientation(nextM)); //set the motion to the Dofs for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it) { x[*it].getCenter() = x0[*it].getCenter() + getVCenter(m) ; x[*it].getOrientation() = x0[*it].getOrientation() * prevOrientation.slerp2(nextOrientation, dt); } } template <class DataTypes> void LinearMovementConstraint<DataTypes>::projectJacobianMatrix(const core::MechanicalParams* mparams /* PARAMS FIRST */, DataMatrixDeriv& cData) { helper::WriteAccessor<DataMatrixDeriv> c = cData; MatrixDerivRowIterator rowIt = c->begin(); MatrixDerivRowIterator rowItEnd = c->end(); while (rowIt != rowItEnd) { projectResponseT<MatrixDerivRowType>(mparams /* PARAMS FIRST */, rowIt.row()); ++rowIt; } } template <class DataTypes> void LinearMovementConstraint<DataTypes>::findKeyTimes() { Real cT = (Real) this->getContext()->getTime(); finished = false; if(m_keyTimes.getValue().size() != 0 && cT >= *m_keyTimes.getValue().begin() && cT <= *m_keyTimes.getValue().rbegin()) { nextT = *m_keyTimes.getValue().begin(); prevT = nextT; typename helper::vector<Real>::const_iterator it_t = m_keyTimes.getValue().begin(); typename VecDeriv::const_iterator it_m = m_keyMovements.getValue().begin(); //WARNING : we consider that the key-events are in chronological order //here we search between which keyTimes we are, to know which are the motion to interpolate while( it_t != m_keyTimes.getValue().end() && !finished) { if( *it_t <= cT) { prevT = *it_t; prevM = *it_m; } else { nextT = *it_t; nextM = *it_m; finished = true; } it_t++; it_m++; } } } //display the path the constrained dofs will go through template <class DataTypes> void LinearMovementConstraint<DataTypes>::draw() { if (!this->getContext()->getShowBehaviorModels() || m_keyTimes.getValue().size() == 0) return; if (showMovement.getValue()) { glDisable(GL_LIGHTING); glPointSize(10); glColor4f(1, 0.5, 0.5, 1); glBegin(GL_LINES); const SetIndexArray & indices = m_indices.getValue().getArray(); for (unsigned int i = 0; i < m_keyMovements.getValue().size() - 1; i++) { for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it) { gl::glVertexT(DataTypes::getCPos(x0[*it]) + DataTypes::getDPos(m_keyMovements.getValue()[i])); gl::glVertexT(DataTypes::getCPos(x0[*it]) + DataTypes::getDPos(m_keyMovements.getValue()[i + 1])); } } glEnd(); } else { const VecCoord& x = *this->mstate->getX(); sofa::helper::vector<Vector3> points; Vector3 point; const SetIndexArray & indices = m_indices.getValue().getArray(); for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it) { point = DataTypes::getCPos(x[*it]); points.push_back(point); } simulation::getSimulation()->DrawUtility().drawPoints(points, 10, Vec<4, float> (1, 0.5, 0.5, 1)); } } } // namespace constraint } // namespace component } // namespace sofa #endif r9880/sofa-dev : CHANGE: remove debug read-out. /****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 * * (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef SOFA_COMPONENT_PROJECTIVECONSTRAINTSET_LINEARMOVEMENTCONSTRAINT_INL #define SOFA_COMPONENT_PROJECTIVECONSTRAINTSET_LINEARMOVEMENTCONSTRAINT_INL #include <sofa/component/projectiveconstraintset/LinearMovementConstraint.h> #include <sofa/core/topology/BaseMeshTopology.h> #include <sofa/core/behavior/ProjectiveConstraintSet.inl> #include <sofa/simulation/common/Simulation.h> #include <sofa/helper/gl/template.h> #include <sofa/defaulttype/RigidTypes.h> #include <iostream> #include <sofa/component/topology/PointSubset.h> namespace sofa { namespace component { namespace projectiveconstraintset { using namespace core::topology; using namespace sofa::defaulttype; using namespace sofa::helper; using namespace sofa::core::behavior; // Define TestNewPointFunction template< class DataTypes> bool LinearMovementConstraint<DataTypes>::FCTestNewPointFunction(int /*nbPoints*/, void* param, const sofa::helper::vector< unsigned int > &, const sofa::helper::vector< double >& ) { LinearMovementConstraint<DataTypes> *fc = (LinearMovementConstraint<DataTypes> *)param; return fc != 0; } // Define RemovalFunction template< class DataTypes> void LinearMovementConstraint<DataTypes>::FCRemovalFunction(int pointIndex, void* param) { LinearMovementConstraint<DataTypes> *fc= (LinearMovementConstraint<DataTypes> *)param; if (fc) { fc->removeIndex((unsigned int) pointIndex); } return; } template <class DataTypes> LinearMovementConstraint<DataTypes>::LinearMovementConstraint() : core::behavior::ProjectiveConstraintSet<DataTypes>(NULL) , data(new LinearMovementConstraintInternalData<DataTypes>) , m_indices( initData(&m_indices,"indices","Indices of the constrained points") ) , m_keyTimes( initData(&m_keyTimes,"keyTimes","key times for the movements") ) , m_keyMovements( initData(&m_keyMovements,"movements","movements corresponding to the key times") ) , showMovement( initData(&showMovement, (bool)false, "showMovement", "Visualization of the movement to be applied to constrained dofs.")) { // default to indice 0 m_indices.beginEdit()->push_back(0); m_indices.endEdit(); //default valueEvent to 0 m_keyTimes.beginEdit()->push_back( 0.0 ); m_keyTimes.endEdit(); m_keyMovements.beginEdit()->push_back( Deriv() ); m_keyMovements.endEdit(); } // Handle topological changes template <class DataTypes> void LinearMovementConstraint<DataTypes>::handleTopologyChange() { std::list<const TopologyChange *>::const_iterator itBegin=topology->beginChange(); std::list<const TopologyChange *>::const_iterator itEnd=topology->endChange(); m_indices.beginEdit()->handleTopologyEvents(itBegin,itEnd,this->getMState()->getSize()); } template <class DataTypes> LinearMovementConstraint<DataTypes>::~LinearMovementConstraint() { } template <class DataTypes> void LinearMovementConstraint<DataTypes>::clearIndices() { m_indices.beginEdit()->clear(); m_indices.endEdit(); } template <class DataTypes> void LinearMovementConstraint<DataTypes>::addIndex(unsigned int index) { m_indices.beginEdit()->push_back(index); m_indices.endEdit(); } template <class DataTypes> void LinearMovementConstraint<DataTypes>::removeIndex(unsigned int index) { removeValue(*m_indices.beginEdit(),index); m_indices.endEdit(); } template <class DataTypes> void LinearMovementConstraint<DataTypes>::clearKeyMovements() { m_keyTimes.beginEdit()->clear(); m_keyTimes.endEdit(); m_keyMovements.beginEdit()->clear(); m_keyMovements.endEdit(); } template <class DataTypes> void LinearMovementConstraint<DataTypes>::addKeyMovement(Real time, Deriv movement) { m_keyTimes.beginEdit()->push_back( time ); m_keyTimes.endEdit(); m_keyMovements.beginEdit()->push_back( movement ); m_keyMovements.endEdit(); } // -- Constraint interface template <class DataTypes> void LinearMovementConstraint<DataTypes>::init() { this->core::behavior::ProjectiveConstraintSet<DataTypes>::init(); topology = this->getContext()->getMeshTopology(); // Initialize functions and parameters topology::PointSubset my_subset = m_indices.getValue(); my_subset.setTestFunction(FCTestNewPointFunction); my_subset.setRemovalFunction(FCRemovalFunction); my_subset.setTestParameter( (void *) this ); my_subset.setRemovalParameter( (void *) this ); x0.resize(0); nextM = prevM = Deriv(); currentTime = -1.0; finished = false; } template <class DataTypes> void LinearMovementConstraint<DataTypes>::reset() { nextT = prevT = 0.0; nextM = prevM = Deriv(); currentTime = -1.0; finished = false; } template <class DataTypes> template <class DataDeriv> void LinearMovementConstraint<DataTypes>::projectResponseT(const core::MechanicalParams* /*mparams*/ /* PARAMS FIRST */, DataDeriv& dx) { Real cT = (Real) this->getContext()->getTime(); if ((cT != currentTime) || !finished) { findKeyTimes(); } if (finished && nextT != prevT) { const SetIndexArray & indices = m_indices.getValue().getArray(); //set the motion to the Dofs for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it) { dx[*it] = Deriv(); } } } template <class DataTypes> void LinearMovementConstraint<DataTypes>::projectResponse(const core::MechanicalParams* mparams /* PARAMS FIRST */, DataVecDeriv& resData) { helper::WriteAccessor<DataVecDeriv> res = resData; projectResponseT<VecDeriv>(mparams /* PARAMS FIRST */, res.wref()); } template <class DataTypes> void LinearMovementConstraint<DataTypes>::projectVelocity(const core::MechanicalParams* /*mparams*/ /* PARAMS FIRST */, DataVecDeriv& vData) { helper::WriteAccessor<DataVecDeriv> dx = vData; Real cT = (Real) this->getContext()->getTime(); if ((cT != currentTime) || !finished) { findKeyTimes(); } if (finished && nextT != prevT) { const SetIndexArray & indices = m_indices.getValue().getArray(); //set the motion to the Dofs for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it) { dx[*it] = (nextM - prevM)*(1.0 / (nextT - prevT)); } } } template <class DataTypes> void LinearMovementConstraint<DataTypes>::projectPosition(const core::MechanicalParams* /*mparams*/ /* PARAMS FIRST */, DataVecCoord& xData) { helper::WriteAccessor<DataVecCoord> x = xData; Real cT = (Real) this->getContext()->getTime(); //initialize initial Dofs positions, if it's not done if (x0.size() == 0) { const SetIndexArray & indices = m_indices.getValue().getArray(); x0.resize(x.size()); for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it) { x0[*it] = x[*it]; } } if ((cT != currentTime) || !finished) { findKeyTimes(); } //if we found 2 keyTimes, we have to interpolate a velocity (linear interpolation) if(finished && nextT != prevT) { interpolatePosition<Coord>(cT, x.wref()); } } template <class DataTypes> template <class MyCoord> void LinearMovementConstraint<DataTypes>::interpolatePosition(Real cT, typename boost::disable_if<boost::is_same<MyCoord, RigidCoord<3, Real> >, VecCoord>::type& x) { const SetIndexArray & indices = m_indices.getValue().getArray(); Real dt = (cT - prevT) / (nextT - prevT); Deriv m = prevM + (nextM-prevM)*dt; // cerr<<"LinearMovementConstraint<DataTypes>::interpolatePosition, current X = "<< x << endl; //set the motion to the Dofs for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it) { x[*it] = x0[*it] + m ; } // cerr<<"LinearMovementConstraint<DataTypes>::interpolatePosition, prevT = "<< prevT <<", prevM = "<< prevM << endl; // cerr<<"LinearMovementConstraint<DataTypes>::interpolatePosition, nextT = "<< nextT <<", nextM = "<< nextM << endl; // cerr<<"LinearMovementConstraint<DataTypes>::interpolatePosition, t = "<< cT <<", M = "<< m << endl; // cerr<<"LinearMovementConstraint<DataTypes>::interpolatePosition, new X = "<< x << endl; } template <class DataTypes> template <class MyCoord> void LinearMovementConstraint<DataTypes>::interpolatePosition(Real cT, typename boost::enable_if<boost::is_same<MyCoord, RigidCoord<3, Real> >, VecCoord>::type& x) { const SetIndexArray & indices = m_indices.getValue().getArray(); Real dt = (cT - prevT) / (nextT - prevT); Deriv m = prevM + (nextM-prevM)*dt; Quater<Real> prevOrientation = Quater<Real>::createQuaterFromEuler(getVOrientation(prevM)); Quater<Real> nextOrientation = Quater<Real>::createQuaterFromEuler(getVOrientation(nextM)); //set the motion to the Dofs for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it) { x[*it].getCenter() = x0[*it].getCenter() + getVCenter(m) ; x[*it].getOrientation() = x0[*it].getOrientation() * prevOrientation.slerp2(nextOrientation, dt); } } template <class DataTypes> void LinearMovementConstraint<DataTypes>::projectJacobianMatrix(const core::MechanicalParams* mparams /* PARAMS FIRST */, DataMatrixDeriv& cData) { helper::WriteAccessor<DataMatrixDeriv> c = cData; MatrixDerivRowIterator rowIt = c->begin(); MatrixDerivRowIterator rowItEnd = c->end(); while (rowIt != rowItEnd) { projectResponseT<MatrixDerivRowType>(mparams /* PARAMS FIRST */, rowIt.row()); ++rowIt; } } template <class DataTypes> void LinearMovementConstraint<DataTypes>::findKeyTimes() { Real cT = (Real) this->getContext()->getTime(); finished = false; if(m_keyTimes.getValue().size() != 0 && cT >= *m_keyTimes.getValue().begin() && cT <= *m_keyTimes.getValue().rbegin()) { nextT = *m_keyTimes.getValue().begin(); prevT = nextT; typename helper::vector<Real>::const_iterator it_t = m_keyTimes.getValue().begin(); typename VecDeriv::const_iterator it_m = m_keyMovements.getValue().begin(); //WARNING : we consider that the key-events are in chronological order //here we search between which keyTimes we are, to know which are the motion to interpolate while( it_t != m_keyTimes.getValue().end() && !finished) { if( *it_t <= cT) { prevT = *it_t; prevM = *it_m; } else { nextT = *it_t; nextM = *it_m; finished = true; } it_t++; it_m++; } } } //display the path the constrained dofs will go through template <class DataTypes> void LinearMovementConstraint<DataTypes>::draw() { if (!this->getContext()->getShowBehaviorModels() || m_keyTimes.getValue().size() == 0) return; if (showMovement.getValue()) { glDisable(GL_LIGHTING); glPointSize(10); glColor4f(1, 0.5, 0.5, 1); glBegin(GL_LINES); const SetIndexArray & indices = m_indices.getValue().getArray(); for (unsigned int i = 0; i < m_keyMovements.getValue().size() - 1; i++) { for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it) { gl::glVertexT(DataTypes::getCPos(x0[*it]) + DataTypes::getDPos(m_keyMovements.getValue()[i])); gl::glVertexT(DataTypes::getCPos(x0[*it]) + DataTypes::getDPos(m_keyMovements.getValue()[i + 1])); } } glEnd(); } else { const VecCoord& x = *this->mstate->getX(); sofa::helper::vector<Vector3> points; Vector3 point; const SetIndexArray & indices = m_indices.getValue().getArray(); for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it) { point = DataTypes::getCPos(x[*it]); points.push_back(point); } simulation::getSimulation()->DrawUtility().drawPoints(points, 10, Vec<4, float> (1, 0.5, 0.5, 1)); } } } // namespace constraint } // namespace component } // namespace sofa #endif
/* -*- Mode:C++; c-file-style:"gnu" -*- */ /* * Copyright 2014 Waseda University, Sato Laboratory * Author: Jairo Eduardo Lopez <jairo@ruri.waseda.jp> * * nnnsim-do.cc is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nnnsim-do.cc is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with nnnsim-do.cc. If not, see <http://www.gnu.org/licenses/>. */ #include "nnnsim-do.h" NNN_NAMESPACE_BEGIN namespace wire { namespace nnnSIM { NS_OBJECT_ENSURE_REGISTERED (DO); NS_LOG_COMPONENT_DEFINE ("nnn.wire.nnnSIM.DO"); DO::DO () : CommonHeader<nnn::DO> () { } DO::DO (Ptr<nnn::DO> do_p) : CommonHeader<nnn::DO> (do_p) { } TypeId DO::GetTypeId (void) { static TypeId tid = TypeId ("ns3::nnn::DO::nnnSIM") .SetGroupName ("Nnn") .SetParent<Header> () .AddConstructor<DO> () ; return tid; } TypeId DO::GetInstanceTypeId (void) const { return GetTypeId (); } Ptr<Packet> DO::ToWire (Ptr<const nnn::DO> do_p) { Ptr<const Packet> p = do_p->GetWire (); if (!p) { Ptr<Packet> packet = Create<Packet> (*do_p->GetPayload ()); DO wireEncoding (ConstCast<nnn::DO> (do_p)); packet->AddHeader (wireEncoding); do_p->SetWire (packet); p = packet; } return p->Copy (); } Ptr<nnn::DO> DO::FromWire (Ptr<Packet> packet) { Ptr<nnn::DO> do_p = Create<nnn::DO> (); Ptr<Packet> wire = packet->Copy (); DO wireEncoding (do_p); packet->RemoveHeader (wireEncoding); do_p->SetPayload (packet); do_p->SetWire (wire); return do_p; } uint32_t DO::GetSerializedSize (void) const { size_t size = CommonGetSerializedSize() + /* Common header */ 2 + /* PDU Data type */ NnnSim::SerializedSizeName (m_ptr->GetName ()) /* Name size */ //m_ptr->GetPayload ()->GetSerializedSize() /* Payload data size */ ; return size; } void DO::Serialize (Buffer::Iterator start) const { // Serialize the header CommonSerialize(start); // Remember that CommonSerialize doesn't write the Packet length // Move the iterator forward start.Next(CommonGetSerializedSize() -2); NS_LOG_INFO ("Serialize -> PktID = " << m_ptr->GetPacketId()); NS_LOG_INFO ("Serialize -> TTL = " << Seconds(static_cast<uint16_t> (m_ptr->GetLifetime ().ToInteger (Time::S)))); NS_LOG_INFO ("Serialize -> Version = " << m_ptr->GetVersion ()); NS_LOG_INFO ("Serialize -> Pkt Len = " << GetSerializedSize()); // Serialize the packet size start.WriteU16(GetSerializedSize()); // Serialize the PDU Data type start.WriteU16(m_ptr->GetPDUPayloadType()); NS_LOG_INFO("Finished serialization"); } uint32_t DO::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; // Deserialize the header uint32_t skip = CommonDeserialize (i); NS_LOG_INFO ("Deserialize -> PktID = " << m_ptr->GetPacketId()); NS_LOG_INFO ("Deserialize -> TTL = " << Seconds(static_cast<uint16_t> (m_ptr->GetLifetime ().ToInteger (Time::S)))); NS_LOG_INFO ("Deserialize -> Version = " << m_ptr->GetVersion ()); NS_LOG_INFO ("Deserialize -> Pkt len = " << m_packet_len); // Check packet ID if (m_ptr->GetPacketId() != nnn::DO_NNN) throw new DOException (); // Move the iterator forward i.Next(skip); // Deserialize the PDU Data type m_ptr->SetPDUPayloadType(i.ReadU16()); // Deserialize the name m_ptr->SetName(NnnSim::DeserializeName(i)); NS_ASSERT (GetSerializedSize () == (i.GetDistanceFrom (start))); return i.GetDistanceFrom (start); } } } NNN_NAMESPACE_END Forgot to serialize name in DO Wire class Has been added /* -*- Mode:C++; c-file-style:"gnu" -*- */ /* * Copyright 2014 Waseda University, Sato Laboratory * Author: Jairo Eduardo Lopez <jairo@ruri.waseda.jp> * * nnnsim-do.cc is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nnnsim-do.cc is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with nnnsim-do.cc. If not, see <http://www.gnu.org/licenses/>. */ #include "nnnsim-do.h" NNN_NAMESPACE_BEGIN namespace wire { namespace nnnSIM { NS_OBJECT_ENSURE_REGISTERED (DO); NS_LOG_COMPONENT_DEFINE ("nnn.wire.nnnSIM.DO"); DO::DO () : CommonHeader<nnn::DO> () { } DO::DO (Ptr<nnn::DO> do_p) : CommonHeader<nnn::DO> (do_p) { } TypeId DO::GetTypeId (void) { static TypeId tid = TypeId ("ns3::nnn::DO::nnnSIM") .SetGroupName ("Nnn") .SetParent<Header> () .AddConstructor<DO> () ; return tid; } TypeId DO::GetInstanceTypeId (void) const { return GetTypeId (); } Ptr<Packet> DO::ToWire (Ptr<const nnn::DO> do_p) { Ptr<const Packet> p = do_p->GetWire (); if (!p) { Ptr<Packet> packet = Create<Packet> (*do_p->GetPayload ()); DO wireEncoding (ConstCast<nnn::DO> (do_p)); packet->AddHeader (wireEncoding); do_p->SetWire (packet); p = packet; } return p->Copy (); } Ptr<nnn::DO> DO::FromWire (Ptr<Packet> packet) { Ptr<nnn::DO> do_p = Create<nnn::DO> (); Ptr<Packet> wire = packet->Copy (); DO wireEncoding (do_p); packet->RemoveHeader (wireEncoding); do_p->SetPayload (packet); do_p->SetWire (wire); return do_p; } uint32_t DO::GetSerializedSize (void) const { size_t size = CommonGetSerializedSize() + /* Common header */ 2 + /* PDU Data type */ NnnSim::SerializedSizeName (m_ptr->GetName ()) /* Name size */ //m_ptr->GetPayload ()->GetSerializedSize() /* Payload data size */ ; return size; } void DO::Serialize (Buffer::Iterator start) const { // Serialize the header CommonSerialize(start); // Remember that CommonSerialize doesn't write the Packet length // Move the iterator forward start.Next(CommonGetSerializedSize() -2); NS_LOG_INFO ("Serialize -> PktID = " << m_ptr->GetPacketId()); NS_LOG_INFO ("Serialize -> TTL = " << Seconds(static_cast<uint16_t> (m_ptr->GetLifetime ().ToInteger (Time::S)))); NS_LOG_INFO ("Serialize -> Version = " << m_ptr->GetVersion ()); NS_LOG_INFO ("Serialize -> Pkt Len = " << GetSerializedSize()); // Serialize the packet size start.WriteU16(GetSerializedSize()); // Serialize the PDU Data type start.WriteU16(m_ptr->GetPDUPayloadType()); // Serialize NnnSim::SerializeName(start, m_ptr->GetName()); NS_LOG_INFO("Finished serialization"); } uint32_t DO::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; // Deserialize the header uint32_t skip = CommonDeserialize (i); NS_LOG_INFO ("Deserialize -> PktID = " << m_ptr->GetPacketId()); NS_LOG_INFO ("Deserialize -> TTL = " << Seconds(static_cast<uint16_t> (m_ptr->GetLifetime ().ToInteger (Time::S)))); NS_LOG_INFO ("Deserialize -> Version = " << m_ptr->GetVersion ()); NS_LOG_INFO ("Deserialize -> Pkt len = " << m_packet_len); // Check packet ID if (m_ptr->GetPacketId() != nnn::DO_NNN) throw new DOException (); // Move the iterator forward i.Next(skip); // Deserialize the PDU Data type m_ptr->SetPDUPayloadType(i.ReadU16()); // Deserialize the name m_ptr->SetName(NnnSim::DeserializeName(i)); NS_ASSERT (GetSerializedSize () == (i.GetDistanceFrom (start))); return i.GetDistanceFrom (start); } } } NNN_NAMESPACE_END
/************************************************************************* * * $RCSfile: plugcon.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2001-10-26 07:40:28 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _PLUGCON_HXX #define _PLUGCON_HXX #include <stdarg.h> #include <string.h> #include <stl/list> #ifndef _LIST_HXX #include <tools/list.hxx> #endif #ifndef _MEDIATOR_HXX #include <plugin/unx/mediator.hxx> #endif #if defined SOLARIS #define USE_MOTIF #endif #define Window XLIB_Window #define Font XLIB_Font #define KeyCode XLIB_KeyCode #define Time XLIB_Time #define Cursor XLIB_Cursor #define Region XLIB_Region #define String XLIB_String #define Boolean XLIB_Boolean #define XPointer XLIB_XPointer #include <X11/Xlib.h> #include <X11/Intrinsic.h> #include <X11/Shell.h> #include <X11/IntrinsicP.h> /* Intrinsics Definitions*/ #include <X11/StringDefs.h> /* Standard Name-String definitions*/ #if defined USE_MOTIF #include <Xm/DrawingA.h> #else #include <X11/Xaw/Label.h> #endif #include <X11/Xatom.h> #define XP_UNIX #include <stdio.h> #ifndef _NPAPI_H_ #include <npsdk/npupp.h> #include <npsdk/npapi.h> #endif #undef Window #undef Font #undef KeyCode #undef Time #undef Cursor #undef String #undef Region #undef Boolean #undef XPointer class ConnectorInstance { public: NPP instance; NPWindow window; NPSetWindowCallbackStruct ws_info; char* pMimeType; void* pShell; void* pWidget; int nArg; char** argn; char** argv; char* pArgnBuf; char* pArgvBuf; NPSavedData aData; ConnectorInstance( NPP inst, char* type, int args, char* pargnbuf, ULONG nargnbytes, char* pargvbuf, ULONG nargvbytes, char* savedata, ULONG savebytes ); ~ConnectorInstance(); }; class PluginConnector; DECLARE_LIST( NPStreamList, NPStream* ); DECLARE_LIST( InstanceList, ConnectorInstance* ); DECLARE_LIST( PluginConnectorList, PluginConnector* ); class PluginConnector : public Mediator { friend NPError NPN_DestroyStream( NPP, NPStream*, NPError ); friend NPError NPN_NewStream( NPP, NPMIMEType, const char*, NPStream** ); protected: NAMESPACE_VOS(OMutex) m_aUserEventMutex; static PluginConnectorList allConnectors; DECL_LINK( NewMessageHdl, Mediator* ); DECL_LINK( WorkOnNewMessageHdl, Mediator* ); NPStreamList m_aNPWrapStreams; InstanceList m_aInstances; ULONG FillBuffer( char*&, char*, ULONG, va_list ); public: PluginConnector( int nSocket ); ~PluginConnector(); virtual MediatorMessage* WaitForAnswer( ULONG nMessageID ); MediatorMessage* Transact( char*, ULONG, ... ); MediatorMessage* Transact( UINT32, ... ); void Respond( ULONG nID, char*, ULONG, ... ); ULONG Send( UINT32, ... ); UINT32 GetStreamID( NPStream* pStream ); UINT32 GetNPPID( NPP ); NPError GetNPError( MediatorMessage* pMes ) { NPError* pErr = (NPError*)pMes->GetBytes(); NPError aErr = *pErr; delete pErr; return aErr; } void CallWorkHandler() { LINK( this, PluginConnector, WorkOnNewMessageHdl ). Call( (Mediator*)this ); } }; enum CommandAtoms { eNPN_GetURL, eNPN_GetURLNotify, eNPN_DestroyStream, eNPN_NewStream, eNPN_PostURLNotify, eNPN_PostURL, eNPN_RequestRead, eNPN_Status, eNPN_Version, eNPN_Write, eNPN_UserAgent, eNPP_DestroyStream, eNPP_Destroy, eNPP_NewStream, eNPP_New, eNPP_SetWindow, eNPP_StreamAsFile, eNPP_URLNotify, eNPP_WriteReady, eNPP_Write, eNPP_GetMIMEDescription, eNPP_Initialize, eNPP_Shutdown, eMaxCommand }; char* GetCommandName( CommandAtoms ); void resizePlugin( NPP, UINT32, UINT32 ); #define POST_STRING( x ) x ? x : "", x ? strlen(x) : 1 #endif // _PLUGCON_HXX #92924#: cast /************************************************************************* * * $RCSfile: plugcon.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2001-11-02 12:10:34 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _PLUGCON_HXX #define _PLUGCON_HXX #include <stdarg.h> #include <string.h> #include <stl/list> #ifndef _LIST_HXX #include <tools/list.hxx> #endif #ifndef _MEDIATOR_HXX #include <plugin/unx/mediator.hxx> #endif #if defined SOLARIS #define USE_MOTIF #endif #define Window XLIB_Window #define Font XLIB_Font #define KeyCode XLIB_KeyCode #define Time XLIB_Time #define Cursor XLIB_Cursor #define Region XLIB_Region #define String XLIB_String #define Boolean XLIB_Boolean #define XPointer XLIB_XPointer #include <X11/Xlib.h> #include <X11/Intrinsic.h> #include <X11/Shell.h> #include <X11/IntrinsicP.h> /* Intrinsics Definitions*/ #include <X11/StringDefs.h> /* Standard Name-String definitions*/ #if defined USE_MOTIF #include <Xm/DrawingA.h> #else #include <X11/Xaw/Label.h> #endif #include <X11/Xatom.h> #define XP_UNIX #include <stdio.h> #ifndef _NPAPI_H_ #include <npsdk/npupp.h> #include <npsdk/npapi.h> #endif #undef Window #undef Font #undef KeyCode #undef Time #undef Cursor #undef String #undef Region #undef Boolean #undef XPointer class ConnectorInstance { public: NPP instance; NPWindow window; NPSetWindowCallbackStruct ws_info; char* pMimeType; void* pShell; void* pWidget; int nArg; char** argn; char** argv; char* pArgnBuf; char* pArgvBuf; NPSavedData aData; ConnectorInstance( NPP inst, char* type, int args, char* pargnbuf, ULONG nargnbytes, char* pargvbuf, ULONG nargvbytes, char* savedata, ULONG savebytes ); ~ConnectorInstance(); }; class PluginConnector; DECLARE_LIST( NPStreamList, NPStream* ); DECLARE_LIST( InstanceList, ConnectorInstance* ); DECLARE_LIST( PluginConnectorList, PluginConnector* ); class PluginConnector : public Mediator { friend NPError NPN_DestroyStream( NPP, NPStream*, NPError ); friend NPError NPN_NewStream( NPP, NPMIMEType, const char*, NPStream** ); protected: NAMESPACE_VOS(OMutex) m_aUserEventMutex; static PluginConnectorList allConnectors; DECL_LINK( NewMessageHdl, Mediator* ); DECL_LINK( WorkOnNewMessageHdl, Mediator* ); NPStreamList m_aNPWrapStreams; InstanceList m_aInstances; ULONG FillBuffer( char*&, char*, ULONG, va_list ); public: PluginConnector( int nSocket ); ~PluginConnector(); virtual MediatorMessage* WaitForAnswer( ULONG nMessageID ); MediatorMessage* Transact( char*, ULONG, ... ); MediatorMessage* Transact( UINT32, ... ); void Respond( ULONG nID, char*, ULONG, ... ); ULONG Send( UINT32, ... ); UINT32 GetStreamID( NPStream* pStream ); UINT32 GetNPPID( NPP ); NPError GetNPError( MediatorMessage* pMes ) { NPError* pErr = (NPError*)pMes->GetBytes(); NPError aErr = *pErr; delete pErr; return aErr; } void CallWorkHandler() { LINK( this, PluginConnector, WorkOnNewMessageHdl ). Call( (Mediator*)this ); } }; enum CommandAtoms { eNPN_GetURL, eNPN_GetURLNotify, eNPN_DestroyStream, eNPN_NewStream, eNPN_PostURLNotify, eNPN_PostURL, eNPN_RequestRead, eNPN_Status, eNPN_Version, eNPN_Write, eNPN_UserAgent, eNPP_DestroyStream, eNPP_Destroy, eNPP_NewStream, eNPP_New, eNPP_SetWindow, eNPP_StreamAsFile, eNPP_URLNotify, eNPP_WriteReady, eNPP_Write, eNPP_GetMIMEDescription, eNPP_Initialize, eNPP_Shutdown, eMaxCommand }; char* GetCommandName( CommandAtoms ); void resizePlugin( NPP, UINT32, UINT32 ); #define POST_STRING( x ) x ? x : const_cast<char*>(""), x ? strlen(x) : 1 #endif // _PLUGCON_HXX
// ftpd is a server implementation based on the following: // - RFC 959 (https://tools.ietf.org/html/rfc959) // - RFC 3659 (https://tools.ietf.org/html/rfc3659) // - suggested implementation details from https://cr.yp.to/ftp/filesystem.html // // Copyright (C) 2020 Michael Theall // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #ifndef CLASSIC #include "imgui_ctru.h" #include "imgui.h" #include "fs.h" #include "platform.h" #include <chrono> #include <cstring> #include <functional> #include <string> #include <tuple> using namespace std::chrono_literals; namespace { /// \brief Clipboard std::string s_clipboard; /// \brief Get clipboard text callback /// \param userData_ User data char const *getClipboardText (void *const userData_) { (void)userData_; return s_clipboard.c_str (); } /// \brief Set clipboard text callback /// \param userData_ User data /// \param text_ Clipboard text void setClipboardText (void *const userData_, char const *const text_) { (void)userData_; s_clipboard = text_; } /// \brief Update touch position /// \param io_ ImGui IO void updateTouch (ImGuiIO &io_) { // check if touchpad was touched if (!(hidKeysHeld () & KEY_TOUCH)) { // set mouse cursor off-screen io_.MousePos = ImVec2 (-10.0f, -10.0f); io_.MouseDown[0] = false; return; } // read touch position touchPosition pos; hidTouchRead (&pos); // transform to bottom-screen space io_.MousePos = ImVec2 ((pos.px + 40.0f) * 2.0f, (pos.py + 240.0f) * 2.0f); io_.MouseDown[0] = true; } /// \brief Update gamepad inputs /// \param io_ ImGui IO void updateGamepads (ImGuiIO &io_) { // clear navigation inputs std::memset (io_.NavInputs, 0, sizeof (io_.NavInputs)); auto const buttonMapping = { std::make_pair (KEY_A, ImGuiNavInput_Activate), std::make_pair (KEY_B, ImGuiNavInput_Cancel), std::make_pair (KEY_X, ImGuiNavInput_Input), std::make_pair (KEY_Y, ImGuiNavInput_Menu), std::make_pair (KEY_L, ImGuiNavInput_FocusPrev), std::make_pair (KEY_L, ImGuiNavInput_TweakSlow), std::make_pair (KEY_ZL, ImGuiNavInput_FocusPrev), std::make_pair (KEY_ZL, ImGuiNavInput_TweakSlow), std::make_pair (KEY_R, ImGuiNavInput_FocusNext), std::make_pair (KEY_R, ImGuiNavInput_TweakFast), std::make_pair (KEY_ZR, ImGuiNavInput_FocusNext), std::make_pair (KEY_ZR, ImGuiNavInput_TweakFast), std::make_pair (KEY_DUP, ImGuiNavInput_DpadUp), std::make_pair (KEY_DRIGHT, ImGuiNavInput_DpadRight), std::make_pair (KEY_DDOWN, ImGuiNavInput_DpadDown), std::make_pair (KEY_DLEFT, ImGuiNavInput_DpadLeft), }; // read buttons from 3DS auto const keys = hidKeysHeld (); for (auto const &[in, out] : buttonMapping) { if (keys & in) io_.NavInputs[out] = 1.0f; } // update joystick circlePosition cpad; auto const analogMapping = { std::make_tuple (std::ref (cpad.dx), ImGuiNavInput_LStickLeft, -0.3f, -0.9f), std::make_tuple (std::ref (cpad.dx), ImGuiNavInput_LStickRight, +0.3f, +0.9f), std::make_tuple (std::ref (cpad.dy), ImGuiNavInput_LStickUp, +0.3f, +0.9f), std::make_tuple (std::ref (cpad.dy), ImGuiNavInput_LStickDown, -0.3f, -0.9f), }; // read left joystick from circle pad hidCircleRead (&cpad); for (auto const &[in, out, min, max] : analogMapping) { auto const value = in / static_cast<float> (0x9C); io_.NavInputs[out] = std::clamp ((value - min) / (max - min), 0.0f, 1.0f); } } } bool imgui::ctru::init () { auto &io = ImGui::GetIO (); // setup config flags io.ConfigFlags |= ImGuiConfigFlags_IsTouchScreen; io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // setup platform backend io.BackendFlags |= ImGuiBackendFlags_HasGamepad; io.BackendPlatformName = "3DS"; // disable mouse cursor io.MouseDrawCursor = false; // clipboard callbacks io.SetClipboardTextFn = setClipboardText; io.GetClipboardTextFn = getClipboardText; io.ClipboardUserData = nullptr; return true; } void imgui::ctru::newFrame () { auto &io = ImGui::GetIO (); // check that font was built IM_ASSERT (io.Fonts->IsBuilt () && "Font atlas not built! It is generally built by the renderer back-end. Missing call " "to renderer _NewFrame() function?"); // time step static auto const start = platform::steady_clock::now (); static auto prev = start; auto const now = platform::steady_clock::now (); io.DeltaTime = std::chrono::duration<float> (now - prev).count (); prev = now; updateTouch (io); updateGamepads (io); } #endif Fix 3DS mouse coords // ftpd is a server implementation based on the following: // - RFC 959 (https://tools.ietf.org/html/rfc959) // - RFC 3659 (https://tools.ietf.org/html/rfc3659) // - suggested implementation details from https://cr.yp.to/ftp/filesystem.html // // Copyright (C) 2020 Michael Theall // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #ifndef CLASSIC #include "imgui_ctru.h" #include "imgui.h" #include "fs.h" #include "platform.h" #include <chrono> #include <cstring> #include <functional> #include <string> #include <tuple> using namespace std::chrono_literals; namespace { /// \brief Clipboard std::string s_clipboard; /// \brief Get clipboard text callback /// \param userData_ User data char const *getClipboardText (void *const userData_) { (void)userData_; return s_clipboard.c_str (); } /// \brief Set clipboard text callback /// \param userData_ User data /// \param text_ Clipboard text void setClipboardText (void *const userData_, char const *const text_) { (void)userData_; s_clipboard = text_; } /// \brief Update touch position /// \param io_ ImGui IO void updateTouch (ImGuiIO &io_) { // check if touchpad was released if (hidKeysUp () & KEY_TOUCH) { // keep mouse position for one frame for release event io_.MouseDown[0] = false; return; } // check if touchpad is touched if (!(hidKeysHeld () & KEY_TOUCH)) { // set mouse cursor off-screen io_.MousePos = ImVec2 (-10.0f, -10.0f); io_.MouseDown[0] = false; return; } // read touch position touchPosition pos; hidTouchRead (&pos); // transform to bottom-screen space io_.MousePos = ImVec2 (pos.px + 40.0f, pos.py + 240.0f); io_.MouseDown[0] = true; } /// \brief Update gamepad inputs /// \param io_ ImGui IO void updateGamepads (ImGuiIO &io_) { // clear navigation inputs std::memset (io_.NavInputs, 0, sizeof (io_.NavInputs)); auto const buttonMapping = { std::make_pair (KEY_A, ImGuiNavInput_Activate), std::make_pair (KEY_B, ImGuiNavInput_Cancel), std::make_pair (KEY_X, ImGuiNavInput_Input), std::make_pair (KEY_Y, ImGuiNavInput_Menu), std::make_pair (KEY_L, ImGuiNavInput_FocusPrev), std::make_pair (KEY_L, ImGuiNavInput_TweakSlow), std::make_pair (KEY_ZL, ImGuiNavInput_FocusPrev), std::make_pair (KEY_ZL, ImGuiNavInput_TweakSlow), std::make_pair (KEY_R, ImGuiNavInput_FocusNext), std::make_pair (KEY_R, ImGuiNavInput_TweakFast), std::make_pair (KEY_ZR, ImGuiNavInput_FocusNext), std::make_pair (KEY_ZR, ImGuiNavInput_TweakFast), std::make_pair (KEY_DUP, ImGuiNavInput_DpadUp), std::make_pair (KEY_DRIGHT, ImGuiNavInput_DpadRight), std::make_pair (KEY_DDOWN, ImGuiNavInput_DpadDown), std::make_pair (KEY_DLEFT, ImGuiNavInput_DpadLeft), }; // read buttons from 3DS auto const keys = hidKeysHeld (); for (auto const &[in, out] : buttonMapping) { if (keys & in) io_.NavInputs[out] = 1.0f; } // update joystick circlePosition cpad; auto const analogMapping = { std::make_tuple (std::ref (cpad.dx), ImGuiNavInput_LStickLeft, -0.3f, -0.9f), std::make_tuple (std::ref (cpad.dx), ImGuiNavInput_LStickRight, +0.3f, +0.9f), std::make_tuple (std::ref (cpad.dy), ImGuiNavInput_LStickUp, +0.3f, +0.9f), std::make_tuple (std::ref (cpad.dy), ImGuiNavInput_LStickDown, -0.3f, -0.9f), }; // read left joystick from circle pad hidCircleRead (&cpad); for (auto const &[in, out, min, max] : analogMapping) { auto const value = in / static_cast<float> (0x9C); io_.NavInputs[out] = std::clamp ((value - min) / (max - min), 0.0f, 1.0f); } } } bool imgui::ctru::init () { auto &io = ImGui::GetIO (); // setup config flags io.ConfigFlags |= ImGuiConfigFlags_IsTouchScreen; io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // setup platform backend io.BackendFlags |= ImGuiBackendFlags_HasGamepad; io.BackendPlatformName = "3DS"; // disable mouse cursor io.MouseDrawCursor = false; // clipboard callbacks io.SetClipboardTextFn = setClipboardText; io.GetClipboardTextFn = getClipboardText; io.ClipboardUserData = nullptr; return true; } void imgui::ctru::newFrame () { auto &io = ImGui::GetIO (); // check that font was built IM_ASSERT (io.Fonts->IsBuilt () && "Font atlas not built! It is generally built by the renderer back-end. Missing call " "to renderer _NewFrame() function?"); // time step static auto const start = platform::steady_clock::now (); static auto prev = start; auto const now = platform::steady_clock::now (); io.DeltaTime = std::chrono::duration<float> (now - prev).count (); prev = now; updateTouch (io); updateGamepads (io); } #endif
// ------------------------------------------------------------------------------------------------ #include "Base/ScriptSrc.hpp" // ------------------------------------------------------------------------------------------------ #include <cstdio> #include <algorithm> #include <stdexcept> // ------------------------------------------------------------------------------------------------ namespace SqMod { /* ------------------------------------------------------------------------------------------------ * Helper class to ensure the file handle is closed regardless of the situation. */ class FileHandle { public: // -------------------------------------------------------------------------------------------- std::FILE * mFile; // Handle to the opened file. /* -------------------------------------------------------------------------------------------- * Default constructor. */ FileHandle(CSStr path) : mFile(std::fopen(path, "rb")) { if (!mFile) { throw std::runtime_error(ToStrF("Unable to open script source (%s)", path)); } } /* -------------------------------------------------------------------------------------------- * Copy constructor. (disabled) */ FileHandle(const FileHandle & o) = delete; /* -------------------------------------------------------------------------------------------- * Move constructor. (disabled) */ FileHandle(FileHandle && o) = delete; /* -------------------------------------------------------------------------------------------- * Destructor. */ ~FileHandle() { if (mFile) { std::fclose(mFile); } } /* -------------------------------------------------------------------------------------------- * Copy assignment operator. (disabled) */ FileHandle & operator = (const FileHandle & o) = delete; /* -------------------------------------------------------------------------------------------- * Move assignment operator. (disabled) */ FileHandle & operator = (FileHandle && o) = delete; /* -------------------------------------------------------------------------------------------- * Implicit conversion to the managed file handle. */ operator std::FILE * () { return mFile; } /* -------------------------------------------------------------------------------------------- * Implicit conversion to the managed file handle. */ operator std::FILE * () const { return mFile; } }; // ------------------------------------------------------------------------------------------------ void ScriptSrc::Process() { // Attempt to open the specified file FileHandle fp(mPath.c_str()); // First 2 bytes of the file will tell if this is a compiled script std::uint16_t tag; // Go to the end of the file std::fseek(fp, 0, SEEK_END); // Calculate buffer size from beginning to current position const LongI length = std::ftell(fp); // Go back to the beginning std::fseek(fp, 0, SEEK_SET); // Read the first 2 bytes of the file and determine the file type if ((length >= 2) && (std::fread(&tag, 1, 2, fp) != 2 || tag == SQ_BYTECODE_STREAM_TAG)) { return; // Probably an empty file or compiled script } // Allocate enough space to hold the file data mData.resize(length, 0); // Read the file contents into allocated data std::fread(&mData[0], 1, length, fp); // Where the last line ended size_t line_start = 0, line_end = 0; // Process the file data and locate new lines for (String::const_iterator itr = mData.cbegin(); itr != mData.cend();) { // Is this a Unix style line ending? if (*itr == '\n') { // Extract the line length line_end = std::distance(mData.cbegin(), itr); // Store the beginning of the line mLine.emplace_back(line_start, line_end); // Advance to the next line line_start = line_end+1; // The line end character was not included ++itr; } // Is this a Windows style line ending? else if (*itr == '\r') { if (*(++itr) == '\n') { // Extract the line length line_end = std::distance(mData.cbegin(), itr)-1; // Store the beginning of the line mLine.emplace_back(line_start, line_end); // Advance to the next line line_start = line_end+2; // The line end character was not included ++itr; } } else { ++itr; } } // Should we add the last line as well? if (mData.size() - line_start > 0) { mLine.emplace_back(line_start, mData.size()); } // Specify that this script contains line information mInfo = true; } // ------------------------------------------------------------------------------------------------ ScriptSrc::ScriptSrc(HSQUIRRELVM vm, String && path, bool delay, bool info) : mExec(vm) , mPath(std::move(path)) , mData() , mLine() , mInfo(info) , mDelay(delay) { // Is the specified virtual machine invalid? if (!vm) { throw std::runtime_error("Invalid virtual machine pointer"); } // Is the specified path empty? else if (mPath.empty()) { throw std::runtime_error("Invalid or empty script path"); } // Should we load the file contents for debugging purposes? else if (mInfo) { Process(); } } // ------------------------------------------------------------------------------------------------ String ScriptSrc::FetchLine(size_t line, bool trim) const { // Do we have such line? if (line > mLine.size()) { return String(); // Nope! } // Grab it's range in the file Line::const_reference l = mLine.at(line); // Grab the code from that line String code = mData.substr(l.first, l.second - l.first); // Trim whitespace from the beginning of the code code if (trim) { code.erase(0, code.find_first_not_of(" \t\n\r\f\v")); } // Return the resulting string return code; } } // Namespace:: SqMod Fix script loading. Forgot to go back to the beginning of the file after reading the header. Bug was introduced in recent changes. // ------------------------------------------------------------------------------------------------ #include "Base/ScriptSrc.hpp" // ------------------------------------------------------------------------------------------------ #include <cstdio> #include <algorithm> #include <stdexcept> // ------------------------------------------------------------------------------------------------ namespace SqMod { /* ------------------------------------------------------------------------------------------------ * Helper class to ensure the file handle is closed regardless of the situation. */ class FileHandle { public: // -------------------------------------------------------------------------------------------- std::FILE * mFile; // Handle to the opened file. /* -------------------------------------------------------------------------------------------- * Default constructor. */ FileHandle(CSStr path) : mFile(std::fopen(path, "rb")) { if (!mFile) { throw std::runtime_error(ToStrF("Unable to open script source (%s)", path)); } } /* -------------------------------------------------------------------------------------------- * Copy constructor. (disabled) */ FileHandle(const FileHandle & o) = delete; /* -------------------------------------------------------------------------------------------- * Move constructor. (disabled) */ FileHandle(FileHandle && o) = delete; /* -------------------------------------------------------------------------------------------- * Destructor. */ ~FileHandle() { if (mFile) { std::fclose(mFile); } } /* -------------------------------------------------------------------------------------------- * Copy assignment operator. (disabled) */ FileHandle & operator = (const FileHandle & o) = delete; /* -------------------------------------------------------------------------------------------- * Move assignment operator. (disabled) */ FileHandle & operator = (FileHandle && o) = delete; /* -------------------------------------------------------------------------------------------- * Implicit conversion to the managed file handle. */ operator std::FILE * () { return mFile; } /* -------------------------------------------------------------------------------------------- * Implicit conversion to the managed file handle. */ operator std::FILE * () const { return mFile; } }; // ------------------------------------------------------------------------------------------------ void ScriptSrc::Process() { // Attempt to open the specified file FileHandle fp(mPath.c_str()); // First 2 bytes of the file will tell if this is a compiled script std::uint16_t tag; // Go to the end of the file std::fseek(fp, 0, SEEK_END); // Calculate buffer size from beginning to current position const LongI length = std::ftell(fp); // Go back to the beginning std::fseek(fp, 0, SEEK_SET); // Read the first 2 bytes of the file and determine the file type if ((length >= 2) && (std::fread(&tag, 1, 2, fp) != 2 || tag == SQ_BYTECODE_STREAM_TAG)) { return; // Probably an empty file or compiled script } // Allocate enough space to hold the file data mData.resize(length, 0); // Go back to the beginning std::fseek(fp, 0, SEEK_SET); // Read the file contents into allocated data std::fread(&mData[0], 1, length, fp); // Where the last line ended size_t line_start = 0, line_end = 0; // Process the file data and locate new lines for (String::const_iterator itr = mData.cbegin(); itr != mData.cend();) { // Is this a Unix style line ending? if (*itr == '\n') { // Extract the line length line_end = std::distance(mData.cbegin(), itr); // Store the beginning of the line mLine.emplace_back(line_start, line_end); // Advance to the next line line_start = line_end+1; // The line end character was not included ++itr; } // Is this a Windows style line ending? else if (*itr == '\r') { if (*(++itr) == '\n') { // Extract the line length line_end = std::distance(mData.cbegin(), itr)-1; // Store the beginning of the line mLine.emplace_back(line_start, line_end); // Advance to the next line line_start = line_end+2; // The line end character was not included ++itr; } } else { ++itr; } } // Should we add the last line as well? if (mData.size() - line_start > 0) { mLine.emplace_back(line_start, mData.size()); } // Specify that this script contains line information mInfo = true; } // ------------------------------------------------------------------------------------------------ ScriptSrc::ScriptSrc(HSQUIRRELVM vm, String && path, bool delay, bool info) : mExec(vm) , mPath(std::move(path)) , mData() , mLine() , mInfo(info) , mDelay(delay) { // Is the specified virtual machine invalid? if (!vm) { throw std::runtime_error("Invalid virtual machine pointer"); } // Is the specified path empty? else if (mPath.empty()) { throw std::runtime_error("Invalid or empty script path"); } // Should we load the file contents for debugging purposes? else if (mInfo) { Process(); } } // ------------------------------------------------------------------------------------------------ String ScriptSrc::FetchLine(size_t line, bool trim) const { // Do we have such line? if (line > mLine.size()) { return String(); // Nope! } // Grab it's range in the file Line::const_reference l = mLine.at(line); // Grab the code from that line String code = mData.substr(l.first, l.second - l.first); // Trim whitespace from the beginning of the code code if (trim) { code.erase(0, code.find_first_not_of(" \t\n\r\f\v")); } // Return the resulting string return code; } } // Namespace:: SqMod
// $Id: logStream.C,v 1.13 2000/01/10 15:51:09 oliver Exp $ #include <BALL/COMMON/logStream.h> #include <BALL/CONCEPT/notification.h> #include <sys/time.h> #include <stdio.h> #define BUFFER_LENGTH 32768 using std::endl; using std::ostream; using std::streambuf; using std::cout; using std::cerr; #ifdef BALL_HAS_ANSI_IOSTREAM # define BALL_IOS std::basic_ios<char> # define BALL_OSTREAM std::ostream #else # define BALL_IOS std::ios # define BALL_OSTREAM std::ostream #endif namespace BALL { LogStreamBuf::LogStreamBuf() : streambuf(), level_(0), tmp_level_(0), incomplete_line_() { pbuf_ = new char [BUFFER_LENGTH]; streambuf::setp(pbuf_, pbuf_ + BUFFER_LENGTH - 1); } LogStreamBuf::~LogStreamBuf() { sync(); delete [] pbuf_; } void LogStreamBuf::dump(ostream& stream) { char buf[BUFFER_LENGTH]; Size line; for (line = loglines_.size(); line > 0; --line) { strftime(&(buf[0]), BUFFER_LENGTH - 1, "%d.%m.%Y %T ", localtime(&(loglines_[line - 1].time))); stream << buf << "[" << loglines_[line - 1].level << "]:" << loglines_[line - 1].text.c_str() << endl; } } int LogStreamBuf::sync() { static char buf[BUFFER_LENGTH]; // sync our streambuffer... if (pptr() != pbase()) { char* line_start = pbase(); char* line_end = pbase(); while (line_end <= pptr()) { // search for the first end of line for (; line_end < pptr() && *line_end != '\n'; line_end++); if (line_end >= pptr()) { // copy the incomplete line to the incomplete_line_ buffer strncpy(&(buf[0]), line_start, line_end - line_start + 1); buf[line_end - line_start] = '\0'; incomplete_line_ += &(buf[0]); // mark everything as read line_end = pptr() + 1; } else { memcpy(&(buf[0]), line_start, line_end - line_start + 1); buf[line_end - line_start] = '\0'; // assemble the string to be written // (consider leftovers of the last buffer from incomplete_line_) string outstring = incomplete_line_; incomplete_line_ = ""; outstring += &(buf[0]); // if there are any streams in our list, we // copy the line into that streams, too and flush them using ::std::list; list<StreamStruct>::iterator list_it = stream_list_.begin(); for (; list_it != stream_list_.end(); ++list_it) { // if the stream is open for that level, write to it... if ((list_it->min_level <= tmp_level_) && (list_it->max_level >= tmp_level_)) { *(list_it->stream) << expandPrefix_(list_it->prefix, tmp_level_, time(0)).c_str() << outstring.c_str() << endl; if (list_it->target != 0) { list_it->target->notify(); } } } // update the line pointers (increment both) line_start = ++line_end; // remove cr/lf from the end of the line while (outstring[outstring.size() - 1] == 10 || outstring[outstring.size() - 1] == 13) { outstring.erase(outstring.end()); } // store the line Logline logline; logline.text = outstring; logline.level = tmp_level_; logline.time = time(0); // store the new line loglines_.push_back(logline); // reset tmp_level_ to the previous level // (needed for LogStream::level() only) tmp_level_ = level_; } } // remove all processed lines from the buffer pbump((int)(pbase() - pptr())); } return 0; } string LogStreamBuf::expandPrefix_(const string& prefix, int level, time_t time) const { Size index = 0; Size copied_index = 0; string result(""); while ((index = prefix.find("%", index)) != string::npos) { // append any constant parts of the string to the result if (copied_index < index) { result.append(prefix.substr(copied_index, index - copied_index)); copied_index = index; } if (index < prefix.size()) { char buffer[64]; char* buf = &(buffer[0]); switch (prefix[index + 1]) { case '%': // append a '%' (escape sequence) result.append("%"); break; case 'l': // append the loglevel sprintf(buf, "%d", level); result.append(buf); break; case 'y': // append the message type (error/warning/information) if (level >= LogStream::ERROR) { result.append("ERROR"); } else if (level >= LogStream::WARNING) { result.append("WARNING"); } else if (level >= LogStream::INFORMATION) { result.append("INFORMATION"); } else { result.append("LOG"); } break; case 'T': // time: HH:MM:SS strftime(buf, BUFFER_LENGTH - 1, "%T", localtime(&time)); result.append(buf); break; case 't': // time: HH:MM strftime(buf, BUFFER_LENGTH - 1, "%R", localtime(&time)); result.append(buf); break; case 'D': // date: DD.MM.YYYY strftime(buf, BUFFER_LENGTH - 1, "%d.%m.%Y", localtime(&time)); result.append(buf); break; case 'd': // date: DD.MM. strftime(buf, BUFFER_LENGTH - 1, "%d.%m.", localtime(&time)); result.append(buf); break; case 'S': // time+date: DD.MM.YYYY, HH:MM:SS strftime(buf, BUFFER_LENGTH - 1, "%d.%m.%Y, %R", localtime(&time)); result.append(buf); break; case 's': // time+date: DD.MM., HH:MM strftime(buf, BUFFER_LENGTH - 1, "%d.%m., %T", localtime(&time)); result.append(buf); break; default: break; } index += 2; copied_index += 2; } } if (copied_index < prefix.size()) { result.append(prefix.substr(copied_index, prefix.size() - copied_index)); } return result; } LogStreamNotifier::LogStreamNotifier() { } LogStreamNotifier::LogStreamNotifier(const LogStream::Target& target) { NotificationRegister(*this, const_cast<LogStream::Target &>(target)); } LogStreamNotifier::~LogStreamNotifier() { NotificationUnregister(*this); } void LogStreamNotifier::notify() const { Notify(const_cast<LogStreamNotifier&>(*this)); } // keep the given buffer LogStream::LogStream(LogStreamBuf* buf) : BALL_IOS(buf), BALL_OSTREAM(buf), delete_buffer_(false) { } // create a new buffer LogStream::LogStream(bool associate_stdio) : BALL_IOS(new LogStreamBuf), BALL_OSTREAM(new LogStreamBuf), delete_buffer_(true) { if (associate_stdio == true) { // associate cout to informations and warnings, // cerr to errors by default insert(std::cout, INFORMATION, ERROR - 1); insert(std::cerr, ERROR); } } // remove the streambuffer LogStream::~LogStream() { if (delete_buffer_) { delete rdbuf(); } } void LogStream::insert(ostream& stream, int min_level, int max_level) { // return if no LogStreamBuf is defined! if (rdbuf() == 0) { return; } // first, check whether the stream is already associated (avoid // multiple insertions) using std::list; list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin(); for (; list_it != rdbuf()->stream_list_.end(); ++list_it) { if ((*list_it).stream == &stream) { return; } } // we didn`t find it - create a new entry in the list LogStreamBuf::StreamStruct s_struct; s_struct.min_level = min_level; s_struct.max_level = max_level; s_struct.stream = &stream; rdbuf()->stream_list_.push_back(s_struct); } void LogStream::remove(ostream& stream) { // return if no LogStreamBuf is defined! if (rdbuf() == 0) { return; } // find the stream in the LogStreamBuf's list using std::list; list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin(); for (; list_it != rdbuf()->stream_list_.end(); ++list_it) { if ((*list_it).stream == &stream) { // remove the stream - iterator becomes invalid, so exit rdbuf()->stream_list_.erase(list_it); break; } } // if the stream is not found nothing happens! } void LogStream::insertNotification(const ostream& s, const LogStream::Target& target) { // return if no LogStreamBuf is defined! if (rdbuf() == 0) { return; } // find the stream in the LogStreamBuf's list using std::list; list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin(); for (; list_it != rdbuf()->stream_list_.end(); ++list_it) { if (list_it->stream == &s) { // set the notification target list_it->target = new LogStreamNotifier(const_cast<LogStream::Target&>(target)); break; } } // if the stream is not found nothing happens! } void LogStream::removeNotification(const ostream& s) { // return if no LogStreamBuf is defined! if (rdbuf() == 0) { return; } // find the stream in the LogStreamBuf's list using std::list; list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin(); for (; list_it != rdbuf()->stream_list_.end(); ++list_it) { if (list_it->stream == &s) { // destroy and remove the notification target delete list_it->target; list_it->target = 0; break; } } // if the stream is not found nothing happens! } void LogStream::setMinLevel(const ostream& stream, int level) { // return if no LogStreamBuf is defined! if (rdbuf() == 0) { return; } // find the stream in the LogStreamBuf's list using std::list; list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin(); for (; list_it != rdbuf()->stream_list_.end(); ++list_it) { if ((*list_it).stream == &stream) { // change the streams min_level and exit the loop (*list_it).min_level = level; break; } } } void LogStream::setMaxLevel(const ostream& stream, int level) { // return if no LogStreamBuf is defined! if (rdbuf() == 0) { return; } // find the stream in the LogStreamBuf's list: // iterate over the list until you find the stream`s pointer using std::list; list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin(); for (; list_it != rdbuf()->stream_list_.end(); ++list_it) { if ((*list_it).stream == &stream) { // change the streams max_level and exit the loop (*list_it).max_level = level; break; } } } void LogStream::setPrefix(const ostream& s, const string& prefix) { // return if no LogStreamBuf is defined! if (rdbuf() == 0) { return; } // find the stream in the LogStreamBuf's list: // iterate over the list until you find the stream`s pointer using std::list; list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin(); for (; list_it != rdbuf()->stream_list_.end(); ++list_it) { if ((*list_it).stream == &s) { // change the streams max_level and exit the loop (*list_it).prefix = prefix; return; } } } Size LogStream::getNumberOfLines(int min_level, int max_level) const { // cast this to const, to access non const method rdbuf() which // is usually const, but declared non const LogStream* non_const_this = const_cast<LogStream*>(this); // if rdbuf() is NULL, return if (non_const_this->rdbuf() == 0) { return 0; } // iterate over all loglines and count the lines of interest vector<LogStreamBuf::Logline>::iterator it = non_const_this->rdbuf()->loglines_.begin(); Size count = 0; for (; it != non_const_this->rdbuf()->loglines_.end(); ++it) { if ((*it).level >= min_level && (*it).level <= max_level) { count++; } } return count; } // global default logstream LogStream Log(true); # ifdef BALL_NO_INLINE_FUNCTIONS # include <BALL/COMMON/logStream.iC> # endif } // namespace BALL added: getLineTime, getLineLevel, getLineText // $Id: logStream.C,v 1.14 2000/05/24 00:05:34 amoll Exp $ #include <BALL/COMMON/logStream.h> #include <BALL/CONCEPT/notification.h> #include <sys/time.h> #include <stdio.h> #define BUFFER_LENGTH 32768 using std::endl; using std::ostream; using std::streambuf; using std::cout; using std::cerr; #ifdef BALL_HAS_ANSI_IOSTREAM # define BALL_IOS std::basic_ios<char> # define BALL_OSTREAM std::ostream #else # define BALL_IOS std::ios # define BALL_OSTREAM std::ostream #endif namespace BALL { LogStreamBuf::LogStreamBuf() : streambuf(), level_(0), tmp_level_(0), incomplete_line_() { pbuf_ = new char [BUFFER_LENGTH]; streambuf::setp(pbuf_, pbuf_ + BUFFER_LENGTH - 1); } LogStreamBuf::~LogStreamBuf() { sync(); delete [] pbuf_; } void LogStreamBuf::dump(ostream& stream) { char buf[BUFFER_LENGTH]; Size line; for (line = loglines_.size(); line > 0; --line) { strftime(&(buf[0]), BUFFER_LENGTH - 1, "%d.%m.%Y %T ", localtime(&(loglines_[line - 1].time))); stream << buf << "[" << loglines_[line - 1].level << "]:" << loglines_[line - 1].text.c_str() << endl; } } int LogStreamBuf::sync() { static char buf[BUFFER_LENGTH]; // sync our streambuffer... if (pptr() != pbase()) { char* line_start = pbase(); char* line_end = pbase(); while (line_end <= pptr()) { // search for the first end of line for (; line_end < pptr() && *line_end != '\n'; line_end++); if (line_end >= pptr()) { // copy the incomplete line to the incomplete_line_ buffer strncpy(&(buf[0]), line_start, line_end - line_start + 1); buf[line_end - line_start] = '\0'; incomplete_line_ += &(buf[0]); // mark everything as read line_end = pptr() + 1; } else { memcpy(&(buf[0]), line_start, line_end - line_start + 1); buf[line_end - line_start] = '\0'; // assemble the string to be written // (consider leftovers of the last buffer from incomplete_line_) string outstring = incomplete_line_; incomplete_line_ = ""; outstring += &(buf[0]); // if there are any streams in our list, we // copy the line into that streams, too and flush them using ::std::list; list<StreamStruct>::iterator list_it = stream_list_.begin(); for (; list_it != stream_list_.end(); ++list_it) { // if the stream is open for that level, write to it... if ((list_it->min_level <= tmp_level_) && (list_it->max_level >= tmp_level_)) { *(list_it->stream) << expandPrefix_(list_it->prefix, tmp_level_, time(0)).c_str() << outstring.c_str() << endl; if (list_it->target != 0) { list_it->target->notify(); } } } // update the line pointers (increment both) line_start = ++line_end; // remove cr/lf from the end of the line while (outstring[outstring.size() - 1] == 10 || outstring[outstring.size() - 1] == 13) { outstring.erase(outstring.end()); } // store the line Logline logline; logline.text = outstring; logline.level = tmp_level_; logline.time = time(0); // store the new line loglines_.push_back(logline); // reset tmp_level_ to the previous level // (needed for LogStream::level() only) tmp_level_ = level_; } } // remove all processed lines from the buffer pbump((int)(pbase() - pptr())); } return 0; } string LogStreamBuf::expandPrefix_(const string& prefix, int level, time_t time) const { Size index = 0; Size copied_index = 0; string result(""); while ((index = prefix.find("%", index)) != string::npos) { // append any constant parts of the string to the result if (copied_index < index) { result.append(prefix.substr(copied_index, index - copied_index)); copied_index = index; } if (index < prefix.size()) { char buffer[64]; char* buf = &(buffer[0]); switch (prefix[index + 1]) { case '%': // append a '%' (escape sequence) result.append("%"); break; case 'l': // append the loglevel sprintf(buf, "%d", level); result.append(buf); break; case 'y': // append the message type (error/warning/information) if (level >= LogStream::ERROR) { result.append("ERROR"); } else if (level >= LogStream::WARNING) { result.append("WARNING"); } else if (level >= LogStream::INFORMATION) { result.append("INFORMATION"); } else { result.append("LOG"); } break; case 'T': // time: HH:MM:SS strftime(buf, BUFFER_LENGTH - 1, "%T", localtime(&time)); result.append(buf); break; case 't': // time: HH:MM strftime(buf, BUFFER_LENGTH - 1, "%R", localtime(&time)); result.append(buf); break; case 'D': // date: DD.MM.YYYY strftime(buf, BUFFER_LENGTH - 1, "%d.%m.%Y", localtime(&time)); result.append(buf); break; case 'd': // date: DD.MM. strftime(buf, BUFFER_LENGTH - 1, "%d.%m.", localtime(&time)); result.append(buf); break; case 'S': // time+date: DD.MM.YYYY, HH:MM:SS strftime(buf, BUFFER_LENGTH - 1, "%d.%m.%Y, %R", localtime(&time)); result.append(buf); break; case 's': // time+date: DD.MM., HH:MM strftime(buf, BUFFER_LENGTH - 1, "%d.%m., %T", localtime(&time)); result.append(buf); break; default: break; } index += 2; copied_index += 2; } } if (copied_index < prefix.size()) { result.append(prefix.substr(copied_index, prefix.size() - copied_index)); } return result; } LogStreamNotifier::LogStreamNotifier() { } LogStreamNotifier::LogStreamNotifier(const LogStream::Target& target) { NotificationRegister(*this, const_cast<LogStream::Target &>(target)); } LogStreamNotifier::~LogStreamNotifier() { NotificationUnregister(*this); } void LogStreamNotifier::notify() const { Notify(const_cast<LogStreamNotifier&>(*this)); } // keep the given buffer LogStream::LogStream(LogStreamBuf* buf) : BALL_IOS(buf), BALL_OSTREAM(buf), delete_buffer_(false) { } // create a new buffer LogStream::LogStream(bool associate_stdio) : BALL_IOS(new LogStreamBuf), BALL_OSTREAM(new LogStreamBuf), delete_buffer_(true) { if (associate_stdio == true) { // associate cout to informations and warnings, // cerr to errors by default insert(std::cout, INFORMATION, ERROR - 1); insert(std::cerr, ERROR); } } // remove the streambuffer LogStream::~LogStream() { if (delete_buffer_) { delete rdbuf(); } } void LogStream::insert(ostream& stream, int min_level, int max_level) { // return if no LogStreamBuf is defined! if (rdbuf() == 0) { return; } // first, check whether the stream is already associated (avoid // multiple insertions) using std::list; list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin(); for (; list_it != rdbuf()->stream_list_.end(); ++list_it) { if ((*list_it).stream == &stream) { return; } } // we didn`t find it - create a new entry in the list LogStreamBuf::StreamStruct s_struct; s_struct.min_level = min_level; s_struct.max_level = max_level; s_struct.stream = &stream; rdbuf()->stream_list_.push_back(s_struct); } void LogStream::remove(ostream& stream) { // return if no LogStreamBuf is defined! if (rdbuf() == 0) { return; } // find the stream in the LogStreamBuf's list using std::list; list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin(); for (; list_it != rdbuf()->stream_list_.end(); ++list_it) { if ((*list_it).stream == &stream) { // remove the stream - iterator becomes invalid, so exit rdbuf()->stream_list_.erase(list_it); break; } } // if the stream is not found nothing happens! } void LogStream::insertNotification(const ostream& s, const LogStream::Target& target) { // return if no LogStreamBuf is defined! if (rdbuf() == 0) { return; } // find the stream in the LogStreamBuf's list using std::list; list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin(); for (; list_it != rdbuf()->stream_list_.end(); ++list_it) { if (list_it->stream == &s) { // set the notification target list_it->target = new LogStreamNotifier(const_cast<LogStream::Target&>(target)); break; } } // if the stream is not found nothing happens! } void LogStream::removeNotification(const ostream& s) { // return if no LogStreamBuf is defined! if (rdbuf() == 0) { return; } // find the stream in the LogStreamBuf's list using std::list; list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin(); for (; list_it != rdbuf()->stream_list_.end(); ++list_it) { if (list_it->stream == &s) { // destroy and remove the notification target delete list_it->target; list_it->target = 0; break; } } // if the stream is not found nothing happens! } void LogStream::setMinLevel(const ostream& stream, int level) { // return if no LogStreamBuf is defined! if (rdbuf() == 0) { return; } // find the stream in the LogStreamBuf's list using std::list; list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin(); for (; list_it != rdbuf()->stream_list_.end(); ++list_it) { if ((*list_it).stream == &stream) { // change the streams min_level and exit the loop (*list_it).min_level = level; break; } } } void LogStream::setMaxLevel(const ostream& stream, int level) { // return if no LogStreamBuf is defined! if (rdbuf() == 0) { return; } // find the stream in the LogStreamBuf's list: // iterate over the list until you find the stream`s pointer using std::list; list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin(); for (; list_it != rdbuf()->stream_list_.end(); ++list_it) { if ((*list_it).stream == &stream) { // change the streams max_level and exit the loop (*list_it).max_level = level; break; } } } void LogStream::setPrefix(const ostream& s, const string& prefix) { // return if no LogStreamBuf is defined! if (rdbuf() == 0) { return; } // find the stream in the LogStreamBuf's list: // iterate over the list until you find the stream`s pointer using std::list; list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin(); for (; list_it != rdbuf()->stream_list_.end(); ++list_it) { if ((*list_it).stream == &s) { // change the streams max_level and exit the loop (*list_it).prefix = prefix; return; } } } Size LogStream::getNumberOfLines(int min_level, int max_level) const { // cast this to const, to access non const method rdbuf() which // is usually const, but declared non const LogStream* non_const_this = const_cast<LogStream*>(this); // if rdbuf() is NULL, return if (non_const_this->rdbuf() == 0) { return 0; } // iterate over all loglines and count the lines of interest vector<LogStreamBuf::Logline>::iterator it = non_const_this->rdbuf()->loglines_.begin(); Size count = 0; for (; it != non_const_this->rdbuf()->loglines_.end(); ++it) { if ((*it).level >= min_level && (*it).level <= max_level) { count++; } } return count; } string LogStream::getLineText(Index index) const { if ((signed)getNumberOfLines() < index) { return ""; } LogStream* non_const_this = const_cast<LogStream*>(this); if (non_const_this->rdbuf() == 0) { return ""; } return non_const_this->rdbuf()->loglines_[index].text; } int LogStream::getLineLevel(Index index) const { if ((signed)getNumberOfLines() < index) { return 0; } LogStream* non_const_this = const_cast<LogStream*>(this); if (non_const_this->rdbuf() == 0) { return 0; } return non_const_this->rdbuf()->loglines_[index].level; } time_t LogStream::getLineTime(Index index) const { if ((signed)getNumberOfLines() < index) { return 0; } LogStream* non_const_this = const_cast<LogStream*>(this); if (non_const_this->rdbuf() == 0) { return 0; } return non_const_this->rdbuf()->loglines_[index].time; } // global default logstream LogStream Log(true); # ifdef BALL_NO_INLINE_FUNCTIONS # include <BALL/COMMON/logStream.iC> # endif } // namespace BALL
#include "CachePkgStatic.h" #include "CP_Texture.h" #include "TextureRaw.h" #include "HardRes.h" #include "DTEX_Package.h" #include "DTEX_TextureFormat.h" #include "ResourceAPI.h" #include "RenderAPI.h" #include "DebugDraw.h" #include "CacheAPI.h" #include "AsyncTask.h" #include <logger.h> #include <gimg_pvr.h> #include <gimg_etc2.h> #include <gimg_import.h> #include <gimg_typedef.h> #include <algorithm> #include <assert.h> #include <string.h> namespace dtex { static const int MAX_PRELOAD_COUNT = 512; #if defined(__APPLE__) && !defined(__MACOSX) #define LOCAL_TEX_FMT TEXTURE_PVR4 #elif defined(__ANDROID__) #define LOCAL_TEX_FMT TEXTURE_ETC2 #else #define LOCAL_TEX_FMT TEXTURE_RGBA8 #endif CachePkgStatic::CachePkgStatic(int tex_size, int tex_count) : m_remain(0) { int max_sz = HardRes::GetMaxTexSize(); while (tex_size > max_sz) { tex_size = tex_size >> 1; tex_count = tex_count << 2; } m_tex_edge = tex_size; m_textures.resize(tex_count); for (int i = 0; i < tex_count; ++i) { m_textures[i] = new CP_Texture(tex_size, MAX_PRELOAD_COUNT); } } CachePkgStatic::~CachePkgStatic() { for (int i = 0, n = m_textures.size(); i < n; ++i) { delete m_textures[i]; } } void CachePkgStatic::DebugDraw() const { if (m_textures.empty()) { return; } // DebugDraw::Draw(m_textures[0]->GetTexture()->GetID(), 3); DebugDraw::Draw(m_textures.back()->GetTexture()->GetID(), 3); } void CachePkgStatic::Clear() { for (int i = 0, n = m_textures.size(); i < n; ++i) { m_textures[i]->Clear(); } m_prenodes.clear(); m_pkgs.clear(); m_remain = 0; } void CachePkgStatic::Load(const Package* pkg) { if (m_pkgs.find(pkg->GetID()) != m_pkgs.end()) { return; } const std::vector<Texture*>& textures = pkg->GetTextures(); for (int i = 0, n = textures.size(); i < n; ++i) { assert(textures[i]->Type() == TEX_RAW); TextureRaw* tex = static_cast<TextureRaw*>(textures[i]); if (LOCAL_TEX_FMT != TEXTURE_RGBA8 && tex->GetFormat() != LOCAL_TEX_FMT) { ResourceAPI::LoadTexture(pkg->GetID(), i); continue; } m_prenodes.push_back(CP_Prenode(pkg, i)); } m_pkgs.insert(pkg->GetID()); } void CachePkgStatic::LoadFinish(bool async) { if (m_prenodes.empty()) { return; } m_prenodes.unique(); m_prenodes.sort(); PackPrenodes(); m_prenodes.clear(); LoadTexAndRelocateNodes(async); } void CachePkgStatic::PackPrenodes() { std::list<CP_Prenode>::iterator itr = m_prenodes.begin(); for ( ; itr != m_prenodes.end(); ++itr) { bool succ = false; for (int i = 0, n = m_textures.size(); i < n; ++i) { if (m_textures[i]->PackPrenode(*itr, 1, this)) { succ = true; break; } } if (!succ) { LOGW("%s", "dtex_c4_load_end node insert fail."); ResourceAPI::LoadTexture(itr->GetPackage()->GetID(), itr->GetTexIdx()); } } } void CachePkgStatic::LoadTexAndRelocateNodes(bool async) { int count = 0; for (int i = 0, n = m_textures.size(); i < n; ++i) { count += m_textures[i]->GetNodes().size(); } std::vector<CP_Node*> nodes; nodes.reserve(count); for (int i = 0, n = m_textures.size(); i < n; ++i) { const std::vector<CP_Node*>& src = m_textures[i]->GetNodes(); copy(src.begin(), src.end(), back_inserter(nodes)); } std::sort(nodes.begin(), nodes.end(), NodeTexCmp()); m_remain = nodes.size(); if (async) { for (int i = 0, n = nodes.size(); i < n; ++i) { CP_Node* node = nodes[i]; const std::string& filepath = ResourceAPI::GetTexFilepath(node->GetSrcPkg()->GetID(), node->GetSrcTexIdx(), 0); AsyncTask::Instance()->Load(filepath, LoadTextureCB, node); } } else { for (int i = 0, n = nodes.size(); i < n; ++i) { CP_Node* node = nodes[i]; ResourceAPI::LoadTexture(node->GetSrcPkg()->GetID(), node->GetSrcTexIdx(), LoadTextureCB, node); } } } void CachePkgStatic::CreateTextures() { for (int i = 0, n = m_textures.size(); i < n; ++i) { CP_Texture* tex = m_textures[i]; Texture* tex_impl = tex->GetTexture(); int w = tex_impl->GetWidth(), h = tex_impl->GetHeight(); void* pixels = tex->GetUD(); int id = 0; int fmt = 0; switch (LOCAL_TEX_FMT) { case TEXTURE_PVR4: id = LoadTexturePVR4(w, h, pixels); fmt = TEXTURE_PVR4; break; case TEXTURE_ETC2: id = LoadTextureETC2(w, h, pixels); fmt = TEXTURE_ETC2; break; case TEXTURE_RGBA8: id = RenderAPI::CreateTexture(pixels, w, h, TEXTURE_RGBA8); fmt = TEXTURE_RGBA8; break; default: assert(0); } free(pixels); tex->SetUD(NULL); tex_impl->SetID(id); tex_impl->SetFormat(fmt); } } void CachePkgStatic::RelocateNodes() { for (int i = 0, n = m_textures.size(); i < n; ++i) { const std::vector<CP_Node*>& src = m_textures[i]->GetNodes(); for (int j = 0, m = src.size(); j < m; ++j) { CP_Node* node = src[j]; const Texture* dst_tex = node->GetDstTex()->GetTexture(); const Rect& dst_r = node->GetDstRect(); CacheAPI::RelocatePkg(node->GetSrcPkg()->GetID(), node->GetSrcTexIdx(), dst_tex->GetID(), dst_tex->GetFormat(), dst_tex->GetWidth(), dst_tex->GetHeight(), dst_r.xmin, dst_r.ymin, dst_r.xmax, dst_r.ymax); } } } void CachePkgStatic::LoadTextureCB(int format, int w, int h, const void* data, void* ud) { CP_Node* node = static_cast<CP_Node*>(ud); switch (LOCAL_TEX_FMT) { case TEXTURE_PVR4: assert(format == TEXTURE_PVR4); LoadPartPVR4(w, h, data, node); break; case TEXTURE_ETC2: assert(format == TEXTURE_ETC2); LoadPartETC2(w, h, data, node); break; case TEXTURE_RGBA8: if (!node->GetDstTex()->GetUD()) { uint8_t* ud = BitmapInitBland(node->GetDstTex()->GetTexture()->GetWidth()); node->GetDstTex()->SetUD(ud); } switch (format) { case TEXTURE_RGBA8: LoadPartRGBA8(w, h, data, node); break; case TEXTURE_PVR4: LoadPartRGBA8FromPVR4(w, h, data, node); break; case TEXTURE_ETC2: LoadPartRGBA8FromETC2(w, h, data, node); break; default: assert(0); } break; default: assert(0); } CachePkgStatic* c = static_cast<CachePkgStatic*>(node->GetUD()); if (c->UpRemain()) { c->CreateTextures(); c->RelocateNodes(); } } void CachePkgStatic::LoadTextureCB(const void* data, size_t size, void* ud) { ResourceAPI::LoadTexture(data, size, LoadTextureCB, ud); } void CachePkgStatic::LoadPartPVR4(int w, int h, const void* data, const CP_Node* node) { const Rect& dst_pos = node->GetDstRect(); assert(IS_4TIMES(dst_pos.xmin) && IS_4TIMES(dst_pos.ymin)); CP_Texture* dst_tex = node->GetDstTex(); int tex_w = dst_tex->GetTexture()->GetWidth(), tex_h = dst_tex->GetTexture()->GetHeight(); if (!dst_tex->GetUD()) { void* pixels = gimg_pvr_init_blank(tex_w); dst_tex->SetUD(pixels); } assert(IS_POT(w) && IS_POT(h) && w == dst_pos.xmax - dst_pos.xmin && h == dst_pos.ymax - dst_pos.ymin); int grid_x = dst_pos.xmin >> 2, grid_y = dst_pos.ymin >> 2; int grid_w = w >> 2, grid_h = h >> 2; const uint8_t* src_data = (const uint8_t*)(data); uint8_t* dst_data = (uint8_t*)(dst_tex->GetUD()); for (int y = 0; y < grid_h; ++y) { for (int x = 0; x < grid_w; ++x) { int idx_src = gimg_pvr_get_morton_number(x, y); int idx_dst = gimg_pvr_get_morton_number(grid_x + x, grid_y + y); assert(idx_dst < tex_w * tex_h / 16); int64_t* src = (int64_t*)src_data + idx_src; int64_t* dst = (int64_t*)dst_data + idx_dst; memcpy(dst, src, sizeof(int64_t)); } } } void CachePkgStatic::LoadPartETC2(int w, int h, const void* data, const CP_Node* node) { const Rect& dst_pos = node->GetDstRect(); assert(IS_4TIMES(dst_pos.xmin) && IS_4TIMES(dst_pos.ymin)); CP_Texture* dst_tex = node->GetDstTex(); int tex_w = dst_tex->GetTexture()->GetWidth(), tex_h = dst_tex->GetTexture()->GetHeight(); if (!dst_tex->GetUD()) { void* pixels = gimg_etc2_init_blank(tex_w); dst_tex->SetUD(pixels); } assert(IS_POT(w) && IS_POT(h) && w == dst_pos.xmax - dst_pos.xmin && h == dst_pos.ymax - dst_pos.ymin); int grid_x = dst_pos.xmin >> 2, grid_y = dst_pos.ymin >> 2; int grid_w = w >> 2, grid_h = h >> 2; const uint8_t* src_data = (const uint8_t*)(data); uint8_t* dst_data = (uint8_t*)(dst_tex->GetUD()); const int grid_sz = sizeof(uint8_t) * 8 * 2; const int large_grid_w = tex_w >> 2; for (int y = 0; y < grid_h; ++y) { for (int x = 0; x < grid_w; ++x) { int idx_src = x + grid_w * y; int idx_dst = grid_x + x + large_grid_w * (grid_y + y); assert(idx_dst < tex_w * tex_h / 16); memcpy(dst_data + idx_dst * grid_sz, src_data + idx_src * grid_sz, grid_sz); } } } void CachePkgStatic::LoadPartRGBA8(int w, int h, const void* data, const CP_Node* node) { const Rect& dst_pos = node->GetDstRect(); assert(w == dst_pos.xmax - dst_pos.xmin && h == dst_pos.ymax - dst_pos.ymin); const uint8_t* src_data = (const uint8_t*)(data); uint8_t* dst_data = (uint8_t*)(node->GetDstTex()->GetUD()); const int large_w = node->GetDstTex()->GetTexture()->GetWidth(); for (int y = 0; y < h; ++y) { int idx_src = w * y; int idx_dst = dst_pos.xmin + large_w * (dst_pos.ymin + y); memcpy(dst_data + idx_dst * 4, src_data + idx_src * 4, 4 * w); } } void CachePkgStatic::LoadPartRGBA8FromPVR4(int w, int h, const void* data, const CP_Node* node) { const uint8_t* pixels = (const uint8_t*)(data); uint8_t* uncompressed = gimg_pvr_decode(pixels, w, h); gimg_revert_y(uncompressed, w, h, GPF_RGBA); LoadPartRGBA8(w, h, uncompressed, node); free(uncompressed); } void CachePkgStatic::LoadPartRGBA8FromETC2(int w, int h, const void* data, const CP_Node* node) { const uint8_t* pixels = (const uint8_t*)(data); uint8_t* uncompressed = gimg_etc2_decode(pixels, w, h, ETC2PACKAGE_RGBA_NO_MIPMAPS); LoadPartRGBA8(w, h, uncompressed, node); free(uncompressed); } uint8_t* CachePkgStatic::BitmapInitBland(int edge) { size_t sz = edge * edge * 4; uint8_t* buf = (uint8_t*)malloc(sz); memset(buf, 0, sz); return buf; } int CachePkgStatic::LoadTexturePVR4(int w, int h, const void* data) { int ret = 0; #if defined( __APPLE__ ) && !defined(__MACOSX) // int internal_format = 0; // internal_format = GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; ret = RenderAPI::CreateTexture(data, w, h, TEXTURE_PVR4); #else uint8_t* uncompressed = gimg_pvr_decode(static_cast<const uint8_t*>(data), w, h); gimg_revert_y(uncompressed, w, h, GPF_RGBA); ret = RenderAPI::CreateTexture(uncompressed, w, h, TEXTURE_RGBA8); free(uncompressed); #endif return ret; } int CachePkgStatic::LoadTextureETC2(int w, int h, const void* data) { int ret = 0; #ifdef __ANDROID__ ret = RenderAPI::CreateTexture(data, w, h, TEXTURE_ETC2); #else uint8_t* uncompressed = gimg_etc2_decode(static_cast<const uint8_t*>(data), w, h, ETC2PACKAGE_RGBA_NO_MIPMAPS); ret = RenderAPI::CreateTexture(uncompressed, w, h, TEXTURE_RGBA8); free(uncompressed); #endif // __ANDROID__ return ret; } bool CachePkgStatic::NodeTexCmp::operator () (const CP_Node* n0, const CP_Node* n1) const { int pkg0 = n0->GetSrcPkg()->GetID(), pkg1 = n1->GetSrcPkg()->GetID(); int tex0 = n0->GetSrcTexIdx(), tex1 = n1->GetSrcTexIdx(); if (pkg0 == pkg1) { return tex0 < tex1; } else { return pkg0 < pkg1; } } } [FIXED] loaded texture not same as tex from index #include "CachePkgStatic.h" #include "CP_Texture.h" #include "TextureRaw.h" #include "HardRes.h" #include "DTEX_Package.h" #include "DTEX_TextureFormat.h" #include "ResourceAPI.h" #include "RenderAPI.h" #include "DebugDraw.h" #include "CacheAPI.h" #include "AsyncTask.h" #include <logger.h> #include <gimg_pvr.h> #include <gimg_etc2.h> #include <gimg_import.h> #include <gimg_typedef.h> #include <algorithm> #include <assert.h> #include <string.h> namespace dtex { static const int MAX_PRELOAD_COUNT = 512; #if defined(__APPLE__) && !defined(__MACOSX) #define LOCAL_TEX_FMT TEXTURE_PVR4 #elif defined(__ANDROID__) #define LOCAL_TEX_FMT TEXTURE_ETC2 #else #define LOCAL_TEX_FMT TEXTURE_RGBA8 #endif CachePkgStatic::CachePkgStatic(int tex_size, int tex_count) : m_remain(0) { int max_sz = HardRes::GetMaxTexSize(); while (tex_size > max_sz) { tex_size = tex_size >> 1; tex_count = tex_count << 2; } m_tex_edge = tex_size; m_textures.resize(tex_count); for (int i = 0; i < tex_count; ++i) { m_textures[i] = new CP_Texture(tex_size, MAX_PRELOAD_COUNT); } } CachePkgStatic::~CachePkgStatic() { for (int i = 0, n = m_textures.size(); i < n; ++i) { delete m_textures[i]; } } void CachePkgStatic::DebugDraw() const { if (m_textures.empty()) { return; } // DebugDraw::Draw(m_textures[0]->GetTexture()->GetID(), 3); DebugDraw::Draw(m_textures.back()->GetTexture()->GetID(), 3); } void CachePkgStatic::Clear() { for (int i = 0, n = m_textures.size(); i < n; ++i) { m_textures[i]->Clear(); } m_prenodes.clear(); m_pkgs.clear(); m_remain = 0; } void CachePkgStatic::Load(const Package* pkg) { if (m_pkgs.find(pkg->GetID()) != m_pkgs.end()) { return; } const std::vector<Texture*>& textures = pkg->GetTextures(); for (int i = 0, n = textures.size(); i < n; ++i) { assert(textures[i]->Type() == TEX_RAW); TextureRaw* tex = static_cast<TextureRaw*>(textures[i]); if (LOCAL_TEX_FMT != TEXTURE_RGBA8 && tex->GetFormat() != LOCAL_TEX_FMT) { ResourceAPI::LoadTexture(pkg->GetID(), i); continue; } m_prenodes.push_back(CP_Prenode(pkg, i)); } m_pkgs.insert(pkg->GetID()); } void CachePkgStatic::LoadFinish(bool async) { if (m_prenodes.empty()) { return; } m_prenodes.unique(); m_prenodes.sort(); PackPrenodes(); m_prenodes.clear(); LoadTexAndRelocateNodes(async); } void CachePkgStatic::PackPrenodes() { std::list<CP_Prenode>::iterator itr = m_prenodes.begin(); for ( ; itr != m_prenodes.end(); ++itr) { bool succ = false; for (int i = 0, n = m_textures.size(); i < n; ++i) { if (m_textures[i]->PackPrenode(*itr, 1, this)) { succ = true; break; } } if (!succ) { LOGW("%s", "dtex_c4_load_end node insert fail."); ResourceAPI::LoadTexture(itr->GetPackage()->GetID(), itr->GetTexIdx()); } } } void CachePkgStatic::LoadTexAndRelocateNodes(bool async) { int count = 0; for (int i = 0, n = m_textures.size(); i < n; ++i) { count += m_textures[i]->GetNodes().size(); } std::vector<CP_Node*> nodes; nodes.reserve(count); for (int i = 0, n = m_textures.size(); i < n; ++i) { const std::vector<CP_Node*>& src = m_textures[i]->GetNodes(); copy(src.begin(), src.end(), back_inserter(nodes)); } std::sort(nodes.begin(), nodes.end(), NodeTexCmp()); m_remain = nodes.size(); if (async) { for (int i = 0, n = nodes.size(); i < n; ++i) { CP_Node* node = nodes[i]; const std::string& filepath = ResourceAPI::GetTexFilepath(node->GetSrcPkg()->GetID(), node->GetSrcTexIdx(), 0); AsyncTask::Instance()->Load(filepath, LoadTextureCB, node); } } else { for (int i = 0, n = nodes.size(); i < n; ++i) { CP_Node* node = nodes[i]; ResourceAPI::LoadTexture(node->GetSrcPkg()->GetID(), node->GetSrcTexIdx(), LoadTextureCB, node); } } } void CachePkgStatic::CreateTextures() { for (int i = 0, n = m_textures.size(); i < n; ++i) { CP_Texture* tex = m_textures[i]; Texture* tex_impl = tex->GetTexture(); int w = tex_impl->GetWidth(), h = tex_impl->GetHeight(); void* pixels = tex->GetUD(); int id = 0; int fmt = 0; switch (LOCAL_TEX_FMT) { case TEXTURE_PVR4: id = LoadTexturePVR4(w, h, pixels); fmt = TEXTURE_PVR4; break; case TEXTURE_ETC2: id = LoadTextureETC2(w, h, pixels); fmt = TEXTURE_ETC2; break; case TEXTURE_RGBA8: id = RenderAPI::CreateTexture(pixels, w, h, TEXTURE_RGBA8); fmt = TEXTURE_RGBA8; break; default: assert(0); } free(pixels); tex->SetUD(NULL); tex_impl->SetID(id); tex_impl->SetFormat(fmt); } } void CachePkgStatic::RelocateNodes() { for (int i = 0, n = m_textures.size(); i < n; ++i) { const std::vector<CP_Node*>& src = m_textures[i]->GetNodes(); for (int j = 0, m = src.size(); j < m; ++j) { CP_Node* node = src[j]; const Texture* dst_tex = node->GetDstTex()->GetTexture(); const Rect& dst_r = node->GetDstRect(); CacheAPI::RelocatePkg(node->GetSrcPkg()->GetID(), node->GetSrcTexIdx(), dst_tex->GetID(), dst_tex->GetFormat(), dst_tex->GetWidth(), dst_tex->GetHeight(), dst_r.xmin, dst_r.ymin, dst_r.xmax, dst_r.ymax); } } } void CachePkgStatic::LoadTextureCB(int format, int w, int h, const void* data, void* ud) { CP_Node* node = static_cast<CP_Node*>(ud); switch (LOCAL_TEX_FMT) { case TEXTURE_PVR4: assert(format == TEXTURE_PVR4); LoadPartPVR4(w, h, data, node); break; case TEXTURE_ETC2: assert(format == TEXTURE_ETC2); LoadPartETC2(w, h, data, node); break; case TEXTURE_RGBA8: if (!node->GetDstTex()->GetUD()) { uint8_t* ud = BitmapInitBland(node->GetDstTex()->GetTexture()->GetWidth()); node->GetDstTex()->SetUD(ud); } switch (format) { case TEXTURE_RGBA8: LoadPartRGBA8(w, h, data, node); break; case TEXTURE_PVR4: LoadPartRGBA8FromPVR4(w, h, data, node); break; case TEXTURE_ETC2: LoadPartRGBA8FromETC2(w, h, data, node); break; default: assert(0); } break; default: assert(0); } CachePkgStatic* c = static_cast<CachePkgStatic*>(node->GetUD()); if (c->UpRemain()) { c->CreateTextures(); c->RelocateNodes(); } } void CachePkgStatic::LoadTextureCB(const void* data, size_t size, void* ud) { ResourceAPI::LoadTexture(data, size, LoadTextureCB, ud); } void CachePkgStatic::LoadPartPVR4(int w, int h, const void* data, const CP_Node* node) { assert(IS_POT(w) && IS_POT(h)); const Rect& dst_pos = node->GetDstRect(); if (w != dst_pos.xmax - dst_pos.xmin || h != dst_pos.ymax - dst_pos.ymin) { return; } assert(IS_4TIMES(dst_pos.xmin) && IS_4TIMES(dst_pos.ymin)); CP_Texture* dst_tex = node->GetDstTex(); int tex_w = dst_tex->GetTexture()->GetWidth(), tex_h = dst_tex->GetTexture()->GetHeight(); if (!dst_tex->GetUD()) { void* pixels = gimg_pvr_init_blank(tex_w); dst_tex->SetUD(pixels); } int grid_x = dst_pos.xmin >> 2, grid_y = dst_pos.ymin >> 2; int grid_w = w >> 2, grid_h = h >> 2; const uint8_t* src_data = (const uint8_t*)(data); uint8_t* dst_data = (uint8_t*)(dst_tex->GetUD()); for (int y = 0; y < grid_h; ++y) { for (int x = 0; x < grid_w; ++x) { int idx_src = gimg_pvr_get_morton_number(x, y); int idx_dst = gimg_pvr_get_morton_number(grid_x + x, grid_y + y); assert(idx_dst < tex_w * tex_h / 16); int64_t* src = (int64_t*)src_data + idx_src; int64_t* dst = (int64_t*)dst_data + idx_dst; memcpy(dst, src, sizeof(int64_t)); } } } void CachePkgStatic::LoadPartETC2(int w, int h, const void* data, const CP_Node* node) { assert(IS_POT(w) && IS_POT(h)); const Rect& dst_pos = node->GetDstRect(); if (w != dst_pos.xmax - dst_pos.xmin || h != dst_pos.ymax - dst_pos.ymin) { return; } assert(IS_4TIMES(dst_pos.xmin) && IS_4TIMES(dst_pos.ymin)); CP_Texture* dst_tex = node->GetDstTex(); int tex_w = dst_tex->GetTexture()->GetWidth(), tex_h = dst_tex->GetTexture()->GetHeight(); if (!dst_tex->GetUD()) { void* pixels = gimg_etc2_init_blank(tex_w); dst_tex->SetUD(pixels); } int grid_x = dst_pos.xmin >> 2, grid_y = dst_pos.ymin >> 2; int grid_w = w >> 2, grid_h = h >> 2; const uint8_t* src_data = (const uint8_t*)(data); uint8_t* dst_data = (uint8_t*)(dst_tex->GetUD()); const int grid_sz = sizeof(uint8_t) * 8 * 2; const int large_grid_w = tex_w >> 2; for (int y = 0; y < grid_h; ++y) { for (int x = 0; x < grid_w; ++x) { int idx_src = x + grid_w * y; int idx_dst = grid_x + x + large_grid_w * (grid_y + y); assert(idx_dst < tex_w * tex_h / 16); memcpy(dst_data + idx_dst * grid_sz, src_data + idx_src * grid_sz, grid_sz); } } } void CachePkgStatic::LoadPartRGBA8(int w, int h, const void* data, const CP_Node* node) { const Rect& dst_pos = node->GetDstRect(); if (w != dst_pos.xmax - dst_pos.xmin || h != dst_pos.ymax - dst_pos.ymin) { return; } const uint8_t* src_data = (const uint8_t*)(data); uint8_t* dst_data = (uint8_t*)(node->GetDstTex()->GetUD()); const int large_w = node->GetDstTex()->GetTexture()->GetWidth(); for (int y = 0; y < h; ++y) { int idx_src = w * y; int idx_dst = dst_pos.xmin + large_w * (dst_pos.ymin + y); memcpy(dst_data + idx_dst * 4, src_data + idx_src * 4, 4 * w); } } void CachePkgStatic::LoadPartRGBA8FromPVR4(int w, int h, const void* data, const CP_Node* node) { const uint8_t* pixels = (const uint8_t*)(data); uint8_t* uncompressed = gimg_pvr_decode(pixels, w, h); gimg_revert_y(uncompressed, w, h, GPF_RGBA); LoadPartRGBA8(w, h, uncompressed, node); free(uncompressed); } void CachePkgStatic::LoadPartRGBA8FromETC2(int w, int h, const void* data, const CP_Node* node) { const uint8_t* pixels = (const uint8_t*)(data); uint8_t* uncompressed = gimg_etc2_decode(pixels, w, h, ETC2PACKAGE_RGBA_NO_MIPMAPS); LoadPartRGBA8(w, h, uncompressed, node); free(uncompressed); } uint8_t* CachePkgStatic::BitmapInitBland(int edge) { size_t sz = edge * edge * 4; uint8_t* buf = (uint8_t*)malloc(sz); memset(buf, 0, sz); return buf; } int CachePkgStatic::LoadTexturePVR4(int w, int h, const void* data) { int ret = 0; #if defined( __APPLE__ ) && !defined(__MACOSX) // int internal_format = 0; // internal_format = GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; ret = RenderAPI::CreateTexture(data, w, h, TEXTURE_PVR4); #else uint8_t* uncompressed = gimg_pvr_decode(static_cast<const uint8_t*>(data), w, h); gimg_revert_y(uncompressed, w, h, GPF_RGBA); ret = RenderAPI::CreateTexture(uncompressed, w, h, TEXTURE_RGBA8); free(uncompressed); #endif return ret; } int CachePkgStatic::LoadTextureETC2(int w, int h, const void* data) { int ret = 0; #ifdef __ANDROID__ ret = RenderAPI::CreateTexture(data, w, h, TEXTURE_ETC2); #else uint8_t* uncompressed = gimg_etc2_decode(static_cast<const uint8_t*>(data), w, h, ETC2PACKAGE_RGBA_NO_MIPMAPS); ret = RenderAPI::CreateTexture(uncompressed, w, h, TEXTURE_RGBA8); free(uncompressed); #endif // __ANDROID__ return ret; } bool CachePkgStatic::NodeTexCmp::operator () (const CP_Node* n0, const CP_Node* n1) const { int pkg0 = n0->GetSrcPkg()->GetID(), pkg1 = n1->GetSrcPkg()->GetID(); int tex0 = n0->GetSrcTexIdx(), tex1 = n1->GetSrcTexIdx(); if (pkg0 == pkg1) { return tex0 < tex1; } else { return pkg0 < pkg1; } } }
//===-- IOHandler.cpp -------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Core/IOHandler.h" // C Includes #ifndef LLDB_DISABLE_CURSES #include <curses.h> #include <panel.h> #endif // C++ Includes #if defined(__APPLE__) #include <deque> #endif #include <string> // Other libraries and framework includes // Project includes #include "lldb/Core/Debugger.h" #include "lldb/Core/StreamFile.h" #include "lldb/Host/File.h" // for File #include "lldb/Host/Predicate.h" // for Predicate, ::eBroad... #include "lldb/Utility/Status.h" // for Status #include "lldb/Utility/StreamString.h" // for StreamString #include "lldb/Utility/StringList.h" // for StringList #include "lldb/lldb-forward.h" // for StreamFileSP #ifndef LLDB_DISABLE_LIBEDIT #include "lldb/Host/Editline.h" #endif #include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Interpreter/CommandInterpreter.h" #ifndef LLDB_DISABLE_CURSES #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Core/Module.h" #include "lldb/Core/State.h" #include "lldb/Core/ValueObject.h" #include "lldb/Core/ValueObjectRegister.h" #include "lldb/Symbol/Block.h" #include "lldb/Symbol/Function.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Symbol/VariableList.h" #include "lldb/Target/Process.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/StackFrame.h" #include "lldb/Target/StopInfo.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #endif #include "llvm/ADT/StringRef.h" // for StringRef #ifdef _MSC_VER #include <windows.h> #endif #include <memory> // for shared_ptr #include <mutex> // for recursive_mutex #include <assert.h> // for assert #include <ctype.h> // for isspace #include <errno.h> // for EINTR, errno #include <stdint.h> // for uint32_t, UINT32_MAX #include <stdio.h> // for size_t, fprintf, feof #include <string.h> // for strlen #include <type_traits> // for move using namespace lldb; using namespace lldb_private; IOHandler::IOHandler(Debugger &debugger, IOHandler::Type type) : IOHandler(debugger, type, StreamFileSP(), // Adopt STDIN from top input reader StreamFileSP(), // Adopt STDOUT from top input reader StreamFileSP(), // Adopt STDERR from top input reader 0) // Flags {} IOHandler::IOHandler(Debugger &debugger, IOHandler::Type type, const lldb::StreamFileSP &input_sp, const lldb::StreamFileSP &output_sp, const lldb::StreamFileSP &error_sp, uint32_t flags) : m_debugger(debugger), m_input_sp(input_sp), m_output_sp(output_sp), m_error_sp(error_sp), m_popped(false), m_flags(flags), m_type(type), m_user_data(nullptr), m_done(false), m_active(false) { // If any files are not specified, then adopt them from the top input reader. if (!m_input_sp || !m_output_sp || !m_error_sp) debugger.AdoptTopIOHandlerFilesIfInvalid(m_input_sp, m_output_sp, m_error_sp); } IOHandler::~IOHandler() = default; int IOHandler::GetInputFD() { return (m_input_sp ? m_input_sp->GetFile().GetDescriptor() : -1); } int IOHandler::GetOutputFD() { return (m_output_sp ? m_output_sp->GetFile().GetDescriptor() : -1); } int IOHandler::GetErrorFD() { return (m_error_sp ? m_error_sp->GetFile().GetDescriptor() : -1); } FILE *IOHandler::GetInputFILE() { return (m_input_sp ? m_input_sp->GetFile().GetStream() : nullptr); } FILE *IOHandler::GetOutputFILE() { return (m_output_sp ? m_output_sp->GetFile().GetStream() : nullptr); } FILE *IOHandler::GetErrorFILE() { return (m_error_sp ? m_error_sp->GetFile().GetStream() : nullptr); } StreamFileSP &IOHandler::GetInputStreamFile() { return m_input_sp; } StreamFileSP &IOHandler::GetOutputStreamFile() { return m_output_sp; } StreamFileSP &IOHandler::GetErrorStreamFile() { return m_error_sp; } bool IOHandler::GetIsInteractive() { return GetInputStreamFile()->GetFile().GetIsInteractive(); } bool IOHandler::GetIsRealTerminal() { return GetInputStreamFile()->GetFile().GetIsRealTerminal(); } void IOHandler::SetPopped(bool b) { m_popped.SetValue(b, eBroadcastOnChange); } void IOHandler::WaitForPop() { m_popped.WaitForValueEqualTo(true); } void IOHandlerStack::PrintAsync(Stream *stream, const char *s, size_t len) { if (stream) { std::lock_guard<std::recursive_mutex> guard(m_mutex); if (m_top) m_top->PrintAsync(stream, s, len); } } IOHandlerConfirm::IOHandlerConfirm(Debugger &debugger, llvm::StringRef prompt, bool default_response) : IOHandlerEditline( debugger, IOHandler::Type::Confirm, nullptr, // nullptr editline_name means no history loaded/saved llvm::StringRef(), // No prompt llvm::StringRef(), // No continuation prompt false, // Multi-line false, // Don't colorize the prompt (i.e. the confirm message.) 0, *this), m_default_response(default_response), m_user_response(default_response) { StreamString prompt_stream; prompt_stream.PutCString(prompt); if (m_default_response) prompt_stream.Printf(": [Y/n] "); else prompt_stream.Printf(": [y/N] "); SetPrompt(prompt_stream.GetString()); } IOHandlerConfirm::~IOHandlerConfirm() = default; int IOHandlerConfirm::IOHandlerComplete(IOHandler &io_handler, const char *current_line, const char *cursor, const char *last_char, int skip_first_n_matches, int max_matches, StringList &matches) { if (current_line == cursor) { if (m_default_response) { matches.AppendString("y"); } else { matches.AppendString("n"); } } return matches.GetSize(); } void IOHandlerConfirm::IOHandlerInputComplete(IOHandler &io_handler, std::string &line) { if (line.empty()) { // User just hit enter, set the response to the default m_user_response = m_default_response; io_handler.SetIsDone(true); return; } if (line.size() == 1) { switch (line[0]) { case 'y': case 'Y': m_user_response = true; io_handler.SetIsDone(true); return; case 'n': case 'N': m_user_response = false; io_handler.SetIsDone(true); return; default: break; } } if (line == "yes" || line == "YES" || line == "Yes") { m_user_response = true; io_handler.SetIsDone(true); } else if (line == "no" || line == "NO" || line == "No") { m_user_response = false; io_handler.SetIsDone(true); } } int IOHandlerDelegate::IOHandlerComplete(IOHandler &io_handler, const char *current_line, const char *cursor, const char *last_char, int skip_first_n_matches, int max_matches, StringList &matches) { switch (m_completion) { case Completion::None: break; case Completion::LLDBCommand: return io_handler.GetDebugger().GetCommandInterpreter().HandleCompletion( current_line, cursor, last_char, skip_first_n_matches, max_matches, matches); case Completion::Expression: { bool word_complete = false; const char *word_start = cursor; if (cursor > current_line) --word_start; while (word_start > current_line && !isspace(*word_start)) --word_start; CommandCompletions::InvokeCommonCompletionCallbacks( io_handler.GetDebugger().GetCommandInterpreter(), CommandCompletions::eVariablePathCompletion, word_start, skip_first_n_matches, max_matches, nullptr, word_complete, matches); size_t num_matches = matches.GetSize(); if (num_matches > 0) { std::string common_prefix; matches.LongestCommonPrefix(common_prefix); const size_t partial_name_len = strlen(word_start); // If we matched a unique single command, add a space... // Only do this if the completer told us this was a complete word, // however... if (num_matches == 1 && word_complete) { common_prefix.push_back(' '); } common_prefix.erase(0, partial_name_len); matches.InsertStringAtIndex(0, std::move(common_prefix)); } return num_matches; } break; } return 0; } IOHandlerEditline::IOHandlerEditline( Debugger &debugger, IOHandler::Type type, const char *editline_name, // Used for saving history files llvm::StringRef prompt, llvm::StringRef continuation_prompt, bool multi_line, bool color_prompts, uint32_t line_number_start, IOHandlerDelegate &delegate) : IOHandlerEditline(debugger, type, StreamFileSP(), // Inherit input from top input reader StreamFileSP(), // Inherit output from top input reader StreamFileSP(), // Inherit error from top input reader 0, // Flags editline_name, // Used for saving history files prompt, continuation_prompt, multi_line, color_prompts, line_number_start, delegate) {} IOHandlerEditline::IOHandlerEditline( Debugger &debugger, IOHandler::Type type, const lldb::StreamFileSP &input_sp, const lldb::StreamFileSP &output_sp, const lldb::StreamFileSP &error_sp, uint32_t flags, const char *editline_name, // Used for saving history files llvm::StringRef prompt, llvm::StringRef continuation_prompt, bool multi_line, bool color_prompts, uint32_t line_number_start, IOHandlerDelegate &delegate) : IOHandler(debugger, type, input_sp, output_sp, error_sp, flags), #ifndef LLDB_DISABLE_LIBEDIT m_editline_ap(), #endif m_delegate(delegate), m_prompt(), m_continuation_prompt(), m_current_lines_ptr(nullptr), m_base_line_number(line_number_start), m_curr_line_idx(UINT32_MAX), m_multi_line(multi_line), m_color_prompts(color_prompts), m_interrupt_exits(true), m_editing(false) { SetPrompt(prompt); #ifndef LLDB_DISABLE_LIBEDIT bool use_editline = false; use_editline = m_input_sp->GetFile().GetIsRealTerminal(); if (use_editline) { m_editline_ap.reset(new Editline(editline_name, GetInputFILE(), GetOutputFILE(), GetErrorFILE(), m_color_prompts)); m_editline_ap->SetIsInputCompleteCallback(IsInputCompleteCallback, this); m_editline_ap->SetAutoCompleteCallback(AutoCompleteCallback, this); // See if the delegate supports fixing indentation const char *indent_chars = delegate.IOHandlerGetFixIndentationCharacters(); if (indent_chars) { // The delegate does support indentation, hook it up so when any // indentation // character is typed, the delegate gets a chance to fix it m_editline_ap->SetFixIndentationCallback(FixIndentationCallback, this, indent_chars); } } #endif SetBaseLineNumber(m_base_line_number); SetPrompt(prompt); SetContinuationPrompt(continuation_prompt); } IOHandlerEditline::~IOHandlerEditline() { #ifndef LLDB_DISABLE_LIBEDIT m_editline_ap.reset(); #endif } void IOHandlerEditline::Activate() { IOHandler::Activate(); m_delegate.IOHandlerActivated(*this); } void IOHandlerEditline::Deactivate() { IOHandler::Deactivate(); m_delegate.IOHandlerDeactivated(*this); } bool IOHandlerEditline::GetLine(std::string &line, bool &interrupted) { #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) { return m_editline_ap->GetLine(line, interrupted); } else { #endif line.clear(); FILE *in = GetInputFILE(); if (in) { if (GetIsInteractive()) { const char *prompt = nullptr; if (m_multi_line && m_curr_line_idx > 0) prompt = GetContinuationPrompt(); if (prompt == nullptr) prompt = GetPrompt(); if (prompt && prompt[0]) { FILE *out = GetOutputFILE(); if (out) { ::fprintf(out, "%s", prompt); ::fflush(out); } } } char buffer[256]; bool done = false; bool got_line = false; m_editing = true; while (!done) { if (fgets(buffer, sizeof(buffer), in) == nullptr) { const int saved_errno = errno; if (feof(in)) done = true; else if (ferror(in)) { if (saved_errno != EINTR) done = true; } } else { got_line = true; size_t buffer_len = strlen(buffer); assert(buffer[buffer_len] == '\0'); char last_char = buffer[buffer_len - 1]; if (last_char == '\r' || last_char == '\n') { done = true; // Strip trailing newlines while (last_char == '\r' || last_char == '\n') { --buffer_len; if (buffer_len == 0) break; last_char = buffer[buffer_len - 1]; } } line.append(buffer, buffer_len); } } m_editing = false; // We might have gotten a newline on a line by itself // make sure to return true in this case. return got_line; } else { // No more input file, we are done... SetIsDone(true); } return false; #ifndef LLDB_DISABLE_LIBEDIT } #endif } #ifndef LLDB_DISABLE_LIBEDIT bool IOHandlerEditline::IsInputCompleteCallback(Editline *editline, StringList &lines, void *baton) { IOHandlerEditline *editline_reader = (IOHandlerEditline *)baton; return editline_reader->m_delegate.IOHandlerIsInputComplete(*editline_reader, lines); } int IOHandlerEditline::FixIndentationCallback(Editline *editline, const StringList &lines, int cursor_position, void *baton) { IOHandlerEditline *editline_reader = (IOHandlerEditline *)baton; return editline_reader->m_delegate.IOHandlerFixIndentation( *editline_reader, lines, cursor_position); } int IOHandlerEditline::AutoCompleteCallback(const char *current_line, const char *cursor, const char *last_char, int skip_first_n_matches, int max_matches, StringList &matches, void *baton) { IOHandlerEditline *editline_reader = (IOHandlerEditline *)baton; if (editline_reader) return editline_reader->m_delegate.IOHandlerComplete( *editline_reader, current_line, cursor, last_char, skip_first_n_matches, max_matches, matches); return 0; } #endif const char *IOHandlerEditline::GetPrompt() { #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) { return m_editline_ap->GetPrompt(); } else { #endif if (m_prompt.empty()) return nullptr; #ifndef LLDB_DISABLE_LIBEDIT } #endif return m_prompt.c_str(); } bool IOHandlerEditline::SetPrompt(llvm::StringRef prompt) { m_prompt = prompt; #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) m_editline_ap->SetPrompt(m_prompt.empty() ? nullptr : m_prompt.c_str()); #endif return true; } const char *IOHandlerEditline::GetContinuationPrompt() { return (m_continuation_prompt.empty() ? nullptr : m_continuation_prompt.c_str()); } void IOHandlerEditline::SetContinuationPrompt(llvm::StringRef prompt) { m_continuation_prompt = prompt; #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) m_editline_ap->SetContinuationPrompt(m_continuation_prompt.empty() ? nullptr : m_continuation_prompt.c_str()); #endif } void IOHandlerEditline::SetBaseLineNumber(uint32_t line) { m_base_line_number = line; } uint32_t IOHandlerEditline::GetCurrentLineIndex() const { #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) return m_editline_ap->GetCurrentLine(); #endif return m_curr_line_idx; } bool IOHandlerEditline::GetLines(StringList &lines, bool &interrupted) { m_current_lines_ptr = &lines; bool success = false; #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) { return m_editline_ap->GetLines(m_base_line_number, lines, interrupted); } else { #endif bool done = false; Status error; while (!done) { // Show line numbers if we are asked to std::string line; if (m_base_line_number > 0 && GetIsInteractive()) { FILE *out = GetOutputFILE(); if (out) ::fprintf(out, "%u%s", m_base_line_number + (uint32_t)lines.GetSize(), GetPrompt() == nullptr ? " " : ""); } m_curr_line_idx = lines.GetSize(); bool interrupted = false; if (GetLine(line, interrupted) && !interrupted) { lines.AppendString(line); done = m_delegate.IOHandlerIsInputComplete(*this, lines); } else { done = true; } } success = lines.GetSize() > 0; #ifndef LLDB_DISABLE_LIBEDIT } #endif return success; } // Each IOHandler gets to run until it is done. It should read data // from the "in" and place output into "out" and "err and return // when done. void IOHandlerEditline::Run() { std::string line; while (IsActive()) { bool interrupted = false; if (m_multi_line) { StringList lines; if (GetLines(lines, interrupted)) { if (interrupted) { m_done = m_interrupt_exits; m_delegate.IOHandlerInputInterrupted(*this, line); } else { line = lines.CopyList(); m_delegate.IOHandlerInputComplete(*this, line); } } else { m_done = true; } } else { if (GetLine(line, interrupted)) { if (interrupted) m_delegate.IOHandlerInputInterrupted(*this, line); else m_delegate.IOHandlerInputComplete(*this, line); } else { m_done = true; } } } } void IOHandlerEditline::Cancel() { #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) m_editline_ap->Cancel(); #endif } bool IOHandlerEditline::Interrupt() { // Let the delgate handle it first if (m_delegate.IOHandlerInterrupt(*this)) return true; #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) return m_editline_ap->Interrupt(); #endif return false; } void IOHandlerEditline::GotEOF() { #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) m_editline_ap->Interrupt(); #endif } void IOHandlerEditline::PrintAsync(Stream *stream, const char *s, size_t len) { #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) m_editline_ap->PrintAsync(stream, s, len); else #endif { #ifdef _MSC_VER const char *prompt = GetPrompt(); if (prompt) { // Back up over previous prompt using Windows API CONSOLE_SCREEN_BUFFER_INFO screen_buffer_info; HANDLE console_handle = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfo(console_handle, &screen_buffer_info); COORD coord = screen_buffer_info.dwCursorPosition; coord.X -= strlen(prompt); if (coord.X < 0) coord.X = 0; SetConsoleCursorPosition(console_handle, coord); } #endif IOHandler::PrintAsync(stream, s, len); #ifdef _MSC_VER if (prompt) IOHandler::PrintAsync(GetOutputStreamFile().get(), prompt, strlen(prompt)); #endif } } // we may want curses to be disabled for some builds // for instance, windows #ifndef LLDB_DISABLE_CURSES #define KEY_RETURN 10 #define KEY_ESCAPE 27 namespace curses { class Menu; class MenuDelegate; class Window; class WindowDelegate; typedef std::shared_ptr<Menu> MenuSP; typedef std::shared_ptr<MenuDelegate> MenuDelegateSP; typedef std::shared_ptr<Window> WindowSP; typedef std::shared_ptr<WindowDelegate> WindowDelegateSP; typedef std::vector<MenuSP> Menus; typedef std::vector<WindowSP> Windows; typedef std::vector<WindowDelegateSP> WindowDelegates; #if 0 type summary add -s "x=${var.x}, y=${var.y}" curses::Point type summary add -s "w=${var.width}, h=${var.height}" curses::Size type summary add -s "${var.origin%S} ${var.size%S}" curses::Rect #endif struct Point { int x; int y; Point(int _x = 0, int _y = 0) : x(_x), y(_y) {} void Clear() { x = 0; y = 0; } Point &operator+=(const Point &rhs) { x += rhs.x; y += rhs.y; return *this; } void Dump() { printf("(x=%i, y=%i)\n", x, y); } }; bool operator==(const Point &lhs, const Point &rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } bool operator!=(const Point &lhs, const Point &rhs) { return lhs.x != rhs.x || lhs.y != rhs.y; } struct Size { int width; int height; Size(int w = 0, int h = 0) : width(w), height(h) {} void Clear() { width = 0; height = 0; } void Dump() { printf("(w=%i, h=%i)\n", width, height); } }; bool operator==(const Size &lhs, const Size &rhs) { return lhs.width == rhs.width && lhs.height == rhs.height; } bool operator!=(const Size &lhs, const Size &rhs) { return lhs.width != rhs.width || lhs.height != rhs.height; } struct Rect { Point origin; Size size; Rect() : origin(), size() {} Rect(const Point &p, const Size &s) : origin(p), size(s) {} void Clear() { origin.Clear(); size.Clear(); } void Dump() { printf("(x=%i, y=%i), w=%i, h=%i)\n", origin.x, origin.y, size.width, size.height); } void Inset(int w, int h) { if (size.width > w * 2) size.width -= w * 2; origin.x += w; if (size.height > h * 2) size.height -= h * 2; origin.y += h; } // Return a status bar rectangle which is the last line of // this rectangle. This rectangle will be modified to not // include the status bar area. Rect MakeStatusBar() { Rect status_bar; if (size.height > 1) { status_bar.origin.x = origin.x; status_bar.origin.y = size.height; status_bar.size.width = size.width; status_bar.size.height = 1; --size.height; } return status_bar; } // Return a menubar rectangle which is the first line of // this rectangle. This rectangle will be modified to not // include the menubar area. Rect MakeMenuBar() { Rect menubar; if (size.height > 1) { menubar.origin.x = origin.x; menubar.origin.y = origin.y; menubar.size.width = size.width; menubar.size.height = 1; ++origin.y; --size.height; } return menubar; } void HorizontalSplitPercentage(float top_percentage, Rect &top, Rect &bottom) const { float top_height = top_percentage * size.height; HorizontalSplit(top_height, top, bottom); } void HorizontalSplit(int top_height, Rect &top, Rect &bottom) const { top = *this; if (top_height < size.height) { top.size.height = top_height; bottom.origin.x = origin.x; bottom.origin.y = origin.y + top.size.height; bottom.size.width = size.width; bottom.size.height = size.height - top.size.height; } else { bottom.Clear(); } } void VerticalSplitPercentage(float left_percentage, Rect &left, Rect &right) const { float left_width = left_percentage * size.width; VerticalSplit(left_width, left, right); } void VerticalSplit(int left_width, Rect &left, Rect &right) const { left = *this; if (left_width < size.width) { left.size.width = left_width; right.origin.x = origin.x + left.size.width; right.origin.y = origin.y; right.size.width = size.width - left.size.width; right.size.height = size.height; } else { right.Clear(); } } }; bool operator==(const Rect &lhs, const Rect &rhs) { return lhs.origin == rhs.origin && lhs.size == rhs.size; } bool operator!=(const Rect &lhs, const Rect &rhs) { return lhs.origin != rhs.origin || lhs.size != rhs.size; } enum HandleCharResult { eKeyNotHandled = 0, eKeyHandled = 1, eQuitApplication = 2 }; enum class MenuActionResult { Handled, NotHandled, Quit // Exit all menus and quit }; struct KeyHelp { int ch; const char *description; }; class WindowDelegate { public: virtual ~WindowDelegate() = default; virtual bool WindowDelegateDraw(Window &window, bool force) { return false; // Drawing not handled } virtual HandleCharResult WindowDelegateHandleChar(Window &window, int key) { return eKeyNotHandled; } virtual const char *WindowDelegateGetHelpText() { return nullptr; } virtual KeyHelp *WindowDelegateGetKeyHelp() { return nullptr; } }; class HelpDialogDelegate : public WindowDelegate { public: HelpDialogDelegate(const char *text, KeyHelp *key_help_array); ~HelpDialogDelegate() override; bool WindowDelegateDraw(Window &window, bool force) override; HandleCharResult WindowDelegateHandleChar(Window &window, int key) override; size_t GetNumLines() const { return m_text.GetSize(); } size_t GetMaxLineLength() const { return m_text.GetMaxStringLength(); } protected: StringList m_text; int m_first_visible_line; }; class Window { public: Window(const char *name) : m_name(name), m_window(nullptr), m_panel(nullptr), m_parent(nullptr), m_subwindows(), m_delegate_sp(), m_curr_active_window_idx(UINT32_MAX), m_prev_active_window_idx(UINT32_MAX), m_delete(false), m_needs_update(true), m_can_activate(true), m_is_subwin(false) {} Window(const char *name, WINDOW *w, bool del = true) : m_name(name), m_window(nullptr), m_panel(nullptr), m_parent(nullptr), m_subwindows(), m_delegate_sp(), m_curr_active_window_idx(UINT32_MAX), m_prev_active_window_idx(UINT32_MAX), m_delete(del), m_needs_update(true), m_can_activate(true), m_is_subwin(false) { if (w) Reset(w); } Window(const char *name, const Rect &bounds) : m_name(name), m_window(nullptr), m_parent(nullptr), m_subwindows(), m_delegate_sp(), m_curr_active_window_idx(UINT32_MAX), m_prev_active_window_idx(UINT32_MAX), m_delete(true), m_needs_update(true), m_can_activate(true), m_is_subwin(false) { Reset(::newwin(bounds.size.height, bounds.size.width, bounds.origin.y, bounds.origin.y)); } virtual ~Window() { RemoveSubWindows(); Reset(); } void Reset(WINDOW *w = nullptr, bool del = true) { if (m_window == w) return; if (m_panel) { ::del_panel(m_panel); m_panel = nullptr; } if (m_window && m_delete) { ::delwin(m_window); m_window = nullptr; m_delete = false; } if (w) { m_window = w; m_panel = ::new_panel(m_window); m_delete = del; } } void AttributeOn(attr_t attr) { ::wattron(m_window, attr); } void AttributeOff(attr_t attr) { ::wattroff(m_window, attr); } void Box(chtype v_char = ACS_VLINE, chtype h_char = ACS_HLINE) { ::box(m_window, v_char, h_char); } void Clear() { ::wclear(m_window); } void Erase() { ::werase(m_window); } Rect GetBounds() { return Rect(GetParentOrigin(), GetSize()); } // Get the rectangle in our parent window int GetChar() { return ::wgetch(m_window); } int GetCursorX() { return getcurx(m_window); } int GetCursorY() { return getcury(m_window); } Rect GetFrame() { return Rect(Point(), GetSize()); } // Get our rectangle in our own coordinate system Point GetParentOrigin() { return Point(GetParentX(), GetParentY()); } Size GetSize() { return Size(GetWidth(), GetHeight()); } int GetParentX() { return getparx(m_window); } int GetParentY() { return getpary(m_window); } int GetMaxX() { return getmaxx(m_window); } int GetMaxY() { return getmaxy(m_window); } int GetWidth() { return GetMaxX(); } int GetHeight() { return GetMaxY(); } void MoveCursor(int x, int y) { ::wmove(m_window, y, x); } void MoveWindow(int x, int y) { MoveWindow(Point(x, y)); } void Resize(int w, int h) { ::wresize(m_window, h, w); } void Resize(const Size &size) { ::wresize(m_window, size.height, size.width); } void PutChar(int ch) { ::waddch(m_window, ch); } void PutCString(const char *s, int len = -1) { ::waddnstr(m_window, s, len); } void Refresh() { ::wrefresh(m_window); } void DeferredRefresh() { // We are using panels, so we don't need to call this... //::wnoutrefresh(m_window); } void SetBackground(int color_pair_idx) { ::wbkgd(m_window, COLOR_PAIR(color_pair_idx)); } void UnderlineOn() { AttributeOn(A_UNDERLINE); } void UnderlineOff() { AttributeOff(A_UNDERLINE); } void PutCStringTruncated(const char *s, int right_pad) { int bytes_left = GetWidth() - GetCursorX(); if (bytes_left > right_pad) { bytes_left -= right_pad; ::waddnstr(m_window, s, bytes_left); } } void MoveWindow(const Point &origin) { const bool moving_window = origin != GetParentOrigin(); if (m_is_subwin && moving_window) { // Can't move subwindows, must delete and re-create Size size = GetSize(); Reset(::subwin(m_parent->m_window, size.height, size.width, origin.y, origin.x), true); } else { ::mvwin(m_window, origin.y, origin.x); } } void SetBounds(const Rect &bounds) { const bool moving_window = bounds.origin != GetParentOrigin(); if (m_is_subwin && moving_window) { // Can't move subwindows, must delete and re-create Reset(::subwin(m_parent->m_window, bounds.size.height, bounds.size.width, bounds.origin.y, bounds.origin.x), true); } else { if (moving_window) MoveWindow(bounds.origin); Resize(bounds.size); } } void Printf(const char *format, ...) __attribute__((format(printf, 2, 3))) { va_list args; va_start(args, format); vwprintw(m_window, format, args); va_end(args); } void Touch() { ::touchwin(m_window); if (m_parent) m_parent->Touch(); } WindowSP CreateSubWindow(const char *name, const Rect &bounds, bool make_active) { WindowSP subwindow_sp; if (m_window) { subwindow_sp.reset(new Window( name, ::subwin(m_window, bounds.size.height, bounds.size.width, bounds.origin.y, bounds.origin.x), true)); subwindow_sp->m_is_subwin = true; } else { subwindow_sp.reset( new Window(name, ::newwin(bounds.size.height, bounds.size.width, bounds.origin.y, bounds.origin.x), true)); subwindow_sp->m_is_subwin = false; } subwindow_sp->m_parent = this; if (make_active) { m_prev_active_window_idx = m_curr_active_window_idx; m_curr_active_window_idx = m_subwindows.size(); } m_subwindows.push_back(subwindow_sp); ::top_panel(subwindow_sp->m_panel); m_needs_update = true; return subwindow_sp; } bool RemoveSubWindow(Window *window) { Windows::iterator pos, end = m_subwindows.end(); size_t i = 0; for (pos = m_subwindows.begin(); pos != end; ++pos, ++i) { if ((*pos).get() == window) { if (m_prev_active_window_idx == i) m_prev_active_window_idx = UINT32_MAX; else if (m_prev_active_window_idx != UINT32_MAX && m_prev_active_window_idx > i) --m_prev_active_window_idx; if (m_curr_active_window_idx == i) m_curr_active_window_idx = UINT32_MAX; else if (m_curr_active_window_idx != UINT32_MAX && m_curr_active_window_idx > i) --m_curr_active_window_idx; window->Erase(); m_subwindows.erase(pos); m_needs_update = true; if (m_parent) m_parent->Touch(); else ::touchwin(stdscr); return true; } } return false; } WindowSP FindSubWindow(const char *name) { Windows::iterator pos, end = m_subwindows.end(); size_t i = 0; for (pos = m_subwindows.begin(); pos != end; ++pos, ++i) { if ((*pos)->m_name.compare(name) == 0) return *pos; } return WindowSP(); } void RemoveSubWindows() { m_curr_active_window_idx = UINT32_MAX; m_prev_active_window_idx = UINT32_MAX; for (Windows::iterator pos = m_subwindows.begin(); pos != m_subwindows.end(); pos = m_subwindows.erase(pos)) { (*pos)->Erase(); } if (m_parent) m_parent->Touch(); else ::touchwin(stdscr); } WINDOW *get() { return m_window; } operator WINDOW *() { return m_window; } //---------------------------------------------------------------------- // Window drawing utilities //---------------------------------------------------------------------- void DrawTitleBox(const char *title, const char *bottom_message = nullptr) { attr_t attr = 0; if (IsActive()) attr = A_BOLD | COLOR_PAIR(2); else attr = 0; if (attr) AttributeOn(attr); Box(); MoveCursor(3, 0); if (title && title[0]) { PutChar('<'); PutCString(title); PutChar('>'); } if (bottom_message && bottom_message[0]) { int bottom_message_length = strlen(bottom_message); int x = GetWidth() - 3 - (bottom_message_length + 2); if (x > 0) { MoveCursor(x, GetHeight() - 1); PutChar('['); PutCString(bottom_message); PutChar(']'); } else { MoveCursor(1, GetHeight() - 1); PutChar('['); PutCStringTruncated(bottom_message, 1); } } if (attr) AttributeOff(attr); } virtual void Draw(bool force) { if (m_delegate_sp && m_delegate_sp->WindowDelegateDraw(*this, force)) return; for (auto &subwindow_sp : m_subwindows) subwindow_sp->Draw(force); } bool CreateHelpSubwindow() { if (m_delegate_sp) { const char *text = m_delegate_sp->WindowDelegateGetHelpText(); KeyHelp *key_help = m_delegate_sp->WindowDelegateGetKeyHelp(); if ((text && text[0]) || key_help) { std::auto_ptr<HelpDialogDelegate> help_delegate_ap( new HelpDialogDelegate(text, key_help)); const size_t num_lines = help_delegate_ap->GetNumLines(); const size_t max_length = help_delegate_ap->GetMaxLineLength(); Rect bounds = GetBounds(); bounds.Inset(1, 1); if (max_length + 4 < static_cast<size_t>(bounds.size.width)) { bounds.origin.x += (bounds.size.width - max_length + 4) / 2; bounds.size.width = max_length + 4; } else { if (bounds.size.width > 100) { const int inset_w = bounds.size.width / 4; bounds.origin.x += inset_w; bounds.size.width -= 2 * inset_w; } } if (num_lines + 2 < static_cast<size_t>(bounds.size.height)) { bounds.origin.y += (bounds.size.height - num_lines + 2) / 2; bounds.size.height = num_lines + 2; } else { if (bounds.size.height > 100) { const int inset_h = bounds.size.height / 4; bounds.origin.y += inset_h; bounds.size.height -= 2 * inset_h; } } WindowSP help_window_sp; Window *parent_window = GetParent(); if (parent_window) help_window_sp = parent_window->CreateSubWindow("Help", bounds, true); else help_window_sp = CreateSubWindow("Help", bounds, true); help_window_sp->SetDelegate( WindowDelegateSP(help_delegate_ap.release())); return true; } } return false; } virtual HandleCharResult HandleChar(int key) { // Always check the active window first HandleCharResult result = eKeyNotHandled; WindowSP active_window_sp = GetActiveWindow(); if (active_window_sp) { result = active_window_sp->HandleChar(key); if (result != eKeyNotHandled) return result; } if (m_delegate_sp) { result = m_delegate_sp->WindowDelegateHandleChar(*this, key); if (result != eKeyNotHandled) return result; } // Then check for any windows that want any keys // that weren't handled. This is typically only // for a menubar. // Make a copy of the subwindows in case any HandleChar() // functions muck with the subwindows. If we don't do this, // we can crash when iterating over the subwindows. Windows subwindows(m_subwindows); for (auto subwindow_sp : subwindows) { if (!subwindow_sp->m_can_activate) { HandleCharResult result = subwindow_sp->HandleChar(key); if (result != eKeyNotHandled) return result; } } return eKeyNotHandled; } bool SetActiveWindow(Window *window) { const size_t num_subwindows = m_subwindows.size(); for (size_t i = 0; i < num_subwindows; ++i) { if (m_subwindows[i].get() == window) { m_prev_active_window_idx = m_curr_active_window_idx; ::top_panel(window->m_panel); m_curr_active_window_idx = i; return true; } } return false; } WindowSP GetActiveWindow() { if (!m_subwindows.empty()) { if (m_curr_active_window_idx >= m_subwindows.size()) { if (m_prev_active_window_idx < m_subwindows.size()) { m_curr_active_window_idx = m_prev_active_window_idx; m_prev_active_window_idx = UINT32_MAX; } else if (IsActive()) { m_prev_active_window_idx = UINT32_MAX; m_curr_active_window_idx = UINT32_MAX; // Find first window that wants to be active if this window is active const size_t num_subwindows = m_subwindows.size(); for (size_t i = 0; i < num_subwindows; ++i) { if (m_subwindows[i]->GetCanBeActive()) { m_curr_active_window_idx = i; break; } } } } if (m_curr_active_window_idx < m_subwindows.size()) return m_subwindows[m_curr_active_window_idx]; } return WindowSP(); } bool GetCanBeActive() const { return m_can_activate; } void SetCanBeActive(bool b) { m_can_activate = b; } const WindowDelegateSP &GetDelegate() const { return m_delegate_sp; } void SetDelegate(const WindowDelegateSP &delegate_sp) { m_delegate_sp = delegate_sp; } Window *GetParent() const { return m_parent; } bool IsActive() const { if (m_parent) return m_parent->GetActiveWindow().get() == this; else return true; // Top level window is always active } void SelectNextWindowAsActive() { // Move active focus to next window const size_t num_subwindows = m_subwindows.size(); if (m_curr_active_window_idx == UINT32_MAX) { uint32_t idx = 0; for (auto subwindow_sp : m_subwindows) { if (subwindow_sp->GetCanBeActive()) { m_curr_active_window_idx = idx; break; } ++idx; } } else if (m_curr_active_window_idx + 1 < num_subwindows) { bool handled = false; m_prev_active_window_idx = m_curr_active_window_idx; for (size_t idx = m_curr_active_window_idx + 1; idx < num_subwindows; ++idx) { if (m_subwindows[idx]->GetCanBeActive()) { m_curr_active_window_idx = idx; handled = true; break; } } if (!handled) { for (size_t idx = 0; idx <= m_prev_active_window_idx; ++idx) { if (m_subwindows[idx]->GetCanBeActive()) { m_curr_active_window_idx = idx; break; } } } } else { m_prev_active_window_idx = m_curr_active_window_idx; for (size_t idx = 0; idx < num_subwindows; ++idx) { if (m_subwindows[idx]->GetCanBeActive()) { m_curr_active_window_idx = idx; break; } } } } const char *GetName() const { return m_name.c_str(); } protected: std::string m_name; WINDOW *m_window; PANEL *m_panel; Window *m_parent; Windows m_subwindows; WindowDelegateSP m_delegate_sp; uint32_t m_curr_active_window_idx; uint32_t m_prev_active_window_idx; bool m_delete; bool m_needs_update; bool m_can_activate; bool m_is_subwin; private: DISALLOW_COPY_AND_ASSIGN(Window); }; class MenuDelegate { public: virtual ~MenuDelegate() = default; virtual MenuActionResult MenuDelegateAction(Menu &menu) = 0; }; class Menu : public WindowDelegate { public: enum class Type { Invalid, Bar, Item, Separator }; // Menubar or separator constructor Menu(Type type); // Menuitem constructor Menu(const char *name, const char *key_name, int key_value, uint64_t identifier); ~Menu() override = default; const MenuDelegateSP &GetDelegate() const { return m_delegate_sp; } void SetDelegate(const MenuDelegateSP &delegate_sp) { m_delegate_sp = delegate_sp; } void RecalculateNameLengths(); void AddSubmenu(const MenuSP &menu_sp); int DrawAndRunMenu(Window &window); void DrawMenuTitle(Window &window, bool highlight); bool WindowDelegateDraw(Window &window, bool force) override; HandleCharResult WindowDelegateHandleChar(Window &window, int key) override; MenuActionResult ActionPrivate(Menu &menu) { MenuActionResult result = MenuActionResult::NotHandled; if (m_delegate_sp) { result = m_delegate_sp->MenuDelegateAction(menu); if (result != MenuActionResult::NotHandled) return result; } else if (m_parent) { result = m_parent->ActionPrivate(menu); if (result != MenuActionResult::NotHandled) return result; } return m_canned_result; } MenuActionResult Action() { // Call the recursive action so it can try to handle it // with the menu delegate, and if not, try our parent menu return ActionPrivate(*this); } void SetCannedResult(MenuActionResult result) { m_canned_result = result; } Menus &GetSubmenus() { return m_submenus; } const Menus &GetSubmenus() const { return m_submenus; } int GetSelectedSubmenuIndex() const { return m_selected; } void SetSelectedSubmenuIndex(int idx) { m_selected = idx; } Type GetType() const { return m_type; } int GetStartingColumn() const { return m_start_col; } void SetStartingColumn(int col) { m_start_col = col; } int GetKeyValue() const { return m_key_value; } void SetKeyValue(int key_value) { m_key_value = key_value; } std::string &GetName() { return m_name; } std::string &GetKeyName() { return m_key_name; } int GetDrawWidth() const { return m_max_submenu_name_length + m_max_submenu_key_name_length + 8; } uint64_t GetIdentifier() const { return m_identifier; } void SetIdentifier(uint64_t identifier) { m_identifier = identifier; } protected: std::string m_name; std::string m_key_name; uint64_t m_identifier; Type m_type; int m_key_value; int m_start_col; int m_max_submenu_name_length; int m_max_submenu_key_name_length; int m_selected; Menu *m_parent; Menus m_submenus; WindowSP m_menu_window_sp; MenuActionResult m_canned_result; MenuDelegateSP m_delegate_sp; }; // Menubar or separator constructor Menu::Menu(Type type) : m_name(), m_key_name(), m_identifier(0), m_type(type), m_key_value(0), m_start_col(0), m_max_submenu_name_length(0), m_max_submenu_key_name_length(0), m_selected(0), m_parent(nullptr), m_submenus(), m_canned_result(MenuActionResult::NotHandled), m_delegate_sp() {} // Menuitem constructor Menu::Menu(const char *name, const char *key_name, int key_value, uint64_t identifier) : m_name(), m_key_name(), m_identifier(identifier), m_type(Type::Invalid), m_key_value(key_value), m_start_col(0), m_max_submenu_name_length(0), m_max_submenu_key_name_length(0), m_selected(0), m_parent(nullptr), m_submenus(), m_canned_result(MenuActionResult::NotHandled), m_delegate_sp() { if (name && name[0]) { m_name = name; m_type = Type::Item; if (key_name && key_name[0]) m_key_name = key_name; } else { m_type = Type::Separator; } } void Menu::RecalculateNameLengths() { m_max_submenu_name_length = 0; m_max_submenu_key_name_length = 0; Menus &submenus = GetSubmenus(); const size_t num_submenus = submenus.size(); for (size_t i = 0; i < num_submenus; ++i) { Menu *submenu = submenus[i].get(); if (static_cast<size_t>(m_max_submenu_name_length) < submenu->m_name.size()) m_max_submenu_name_length = submenu->m_name.size(); if (static_cast<size_t>(m_max_submenu_key_name_length) < submenu->m_key_name.size()) m_max_submenu_key_name_length = submenu->m_key_name.size(); } } void Menu::AddSubmenu(const MenuSP &menu_sp) { menu_sp->m_parent = this; if (static_cast<size_t>(m_max_submenu_name_length) < menu_sp->m_name.size()) m_max_submenu_name_length = menu_sp->m_name.size(); if (static_cast<size_t>(m_max_submenu_key_name_length) < menu_sp->m_key_name.size()) m_max_submenu_key_name_length = menu_sp->m_key_name.size(); m_submenus.push_back(menu_sp); } void Menu::DrawMenuTitle(Window &window, bool highlight) { if (m_type == Type::Separator) { window.MoveCursor(0, window.GetCursorY()); window.PutChar(ACS_LTEE); int width = window.GetWidth(); if (width > 2) { width -= 2; for (int i = 0; i < width; ++i) window.PutChar(ACS_HLINE); } window.PutChar(ACS_RTEE); } else { const int shortcut_key = m_key_value; bool underlined_shortcut = false; const attr_t hilgight_attr = A_REVERSE; if (highlight) window.AttributeOn(hilgight_attr); if (isprint(shortcut_key)) { size_t lower_pos = m_name.find(tolower(shortcut_key)); size_t upper_pos = m_name.find(toupper(shortcut_key)); const char *name = m_name.c_str(); size_t pos = std::min<size_t>(lower_pos, upper_pos); if (pos != std::string::npos) { underlined_shortcut = true; if (pos > 0) { window.PutCString(name, pos); name += pos; } const attr_t shortcut_attr = A_UNDERLINE | A_BOLD; window.AttributeOn(shortcut_attr); window.PutChar(name[0]); window.AttributeOff(shortcut_attr); name++; if (name[0]) window.PutCString(name); } } if (!underlined_shortcut) { window.PutCString(m_name.c_str()); } if (highlight) window.AttributeOff(hilgight_attr); if (m_key_name.empty()) { if (!underlined_shortcut && isprint(m_key_value)) { window.AttributeOn(COLOR_PAIR(3)); window.Printf(" (%c)", m_key_value); window.AttributeOff(COLOR_PAIR(3)); } } else { window.AttributeOn(COLOR_PAIR(3)); window.Printf(" (%s)", m_key_name.c_str()); window.AttributeOff(COLOR_PAIR(3)); } } } bool Menu::WindowDelegateDraw(Window &window, bool force) { Menus &submenus = GetSubmenus(); const size_t num_submenus = submenus.size(); const int selected_idx = GetSelectedSubmenuIndex(); Menu::Type menu_type = GetType(); switch (menu_type) { case Menu::Type::Bar: { window.SetBackground(2); window.MoveCursor(0, 0); for (size_t i = 0; i < num_submenus; ++i) { Menu *menu = submenus[i].get(); if (i > 0) window.PutChar(' '); menu->SetStartingColumn(window.GetCursorX()); window.PutCString("| "); menu->DrawMenuTitle(window, false); } window.PutCString(" |"); window.DeferredRefresh(); } break; case Menu::Type::Item: { int y = 1; int x = 3; // Draw the menu int cursor_x = 0; int cursor_y = 0; window.Erase(); window.SetBackground(2); window.Box(); for (size_t i = 0; i < num_submenus; ++i) { const bool is_selected = (i == static_cast<size_t>(selected_idx)); window.MoveCursor(x, y + i); if (is_selected) { // Remember where we want the cursor to be cursor_x = x - 1; cursor_y = y + i; } submenus[i]->DrawMenuTitle(window, is_selected); } window.MoveCursor(cursor_x, cursor_y); window.DeferredRefresh(); } break; default: case Menu::Type::Separator: break; } return true; // Drawing handled... } HandleCharResult Menu::WindowDelegateHandleChar(Window &window, int key) { HandleCharResult result = eKeyNotHandled; Menus &submenus = GetSubmenus(); const size_t num_submenus = submenus.size(); const int selected_idx = GetSelectedSubmenuIndex(); Menu::Type menu_type = GetType(); if (menu_type == Menu::Type::Bar) { MenuSP run_menu_sp; switch (key) { case KEY_DOWN: case KEY_UP: // Show last menu or first menu if (selected_idx < static_cast<int>(num_submenus)) run_menu_sp = submenus[selected_idx]; else if (!submenus.empty()) run_menu_sp = submenus.front(); result = eKeyHandled; break; case KEY_RIGHT: ++m_selected; if (m_selected >= static_cast<int>(num_submenus)) m_selected = 0; if (m_selected < static_cast<int>(num_submenus)) run_menu_sp = submenus[m_selected]; else if (!submenus.empty()) run_menu_sp = submenus.front(); result = eKeyHandled; break; case KEY_LEFT: --m_selected; if (m_selected < 0) m_selected = num_submenus - 1; if (m_selected < static_cast<int>(num_submenus)) run_menu_sp = submenus[m_selected]; else if (!submenus.empty()) run_menu_sp = submenus.front(); result = eKeyHandled; break; default: for (size_t i = 0; i < num_submenus; ++i) { if (submenus[i]->GetKeyValue() == key) { SetSelectedSubmenuIndex(i); run_menu_sp = submenus[i]; result = eKeyHandled; break; } } break; } if (run_menu_sp) { // Run the action on this menu in case we need to populate the // menu with dynamic content and also in case check marks, and // any other menu decorations need to be calculated if (run_menu_sp->Action() == MenuActionResult::Quit) return eQuitApplication; Rect menu_bounds; menu_bounds.origin.x = run_menu_sp->GetStartingColumn(); menu_bounds.origin.y = 1; menu_bounds.size.width = run_menu_sp->GetDrawWidth(); menu_bounds.size.height = run_menu_sp->GetSubmenus().size() + 2; if (m_menu_window_sp) window.GetParent()->RemoveSubWindow(m_menu_window_sp.get()); m_menu_window_sp = window.GetParent()->CreateSubWindow( run_menu_sp->GetName().c_str(), menu_bounds, true); m_menu_window_sp->SetDelegate(run_menu_sp); } } else if (menu_type == Menu::Type::Item) { switch (key) { case KEY_DOWN: if (m_submenus.size() > 1) { const int start_select = m_selected; while (++m_selected != start_select) { if (static_cast<size_t>(m_selected) >= num_submenus) m_selected = 0; if (m_submenus[m_selected]->GetType() == Type::Separator) continue; else break; } return eKeyHandled; } break; case KEY_UP: if (m_submenus.size() > 1) { const int start_select = m_selected; while (--m_selected != start_select) { if (m_selected < static_cast<int>(0)) m_selected = num_submenus - 1; if (m_submenus[m_selected]->GetType() == Type::Separator) continue; else break; } return eKeyHandled; } break; case KEY_RETURN: if (static_cast<size_t>(selected_idx) < num_submenus) { if (submenus[selected_idx]->Action() == MenuActionResult::Quit) return eQuitApplication; window.GetParent()->RemoveSubWindow(&window); return eKeyHandled; } break; case KEY_ESCAPE: // Beware: pressing escape key has 1 to 2 second delay in // case other chars are entered for escaped sequences window.GetParent()->RemoveSubWindow(&window); return eKeyHandled; default: for (size_t i = 0; i < num_submenus; ++i) { Menu *menu = submenus[i].get(); if (menu->GetKeyValue() == key) { SetSelectedSubmenuIndex(i); window.GetParent()->RemoveSubWindow(&window); if (menu->Action() == MenuActionResult::Quit) return eQuitApplication; return eKeyHandled; } } break; } } else if (menu_type == Menu::Type::Separator) { } return result; } class Application { public: Application(FILE *in, FILE *out) : m_window_sp(), m_screen(nullptr), m_in(in), m_out(out) {} ~Application() { m_window_delegates.clear(); m_window_sp.reset(); if (m_screen) { ::delscreen(m_screen); m_screen = nullptr; } } void Initialize() { ::setlocale(LC_ALL, ""); ::setlocale(LC_CTYPE, ""); #if 0 ::initscr(); #else m_screen = ::newterm(nullptr, m_out, m_in); #endif ::start_color(); ::curs_set(0); ::noecho(); ::keypad(stdscr, TRUE); } void Terminate() { ::endwin(); } void Run(Debugger &debugger) { bool done = false; int delay_in_tenths_of_a_second = 1; // Alas the threading model in curses is a bit lame so we need to // resort to polling every 0.5 seconds. We could poll for stdin // ourselves and then pass the keys down but then we need to // translate all of the escape sequences ourselves. So we resort to // polling for input because we need to receive async process events // while in this loop. halfdelay(delay_in_tenths_of_a_second); // Poll using some number of tenths // of seconds seconds when calling // Window::GetChar() ListenerSP listener_sp( Listener::MakeListener("lldb.IOHandler.curses.Application")); ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass()); ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass()); ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass()); debugger.EnableForwardEvents(listener_sp); bool update = true; #if defined(__APPLE__) std::deque<int> escape_chars; #endif while (!done) { if (update) { m_window_sp->Draw(false); // All windows should be calling Window::DeferredRefresh() instead // of Window::Refresh() so we can do a single update and avoid // any screen blinking update_panels(); // Cursor hiding isn't working on MacOSX, so hide it in the top left // corner m_window_sp->MoveCursor(0, 0); doupdate(); update = false; } #if defined(__APPLE__) // Terminal.app doesn't map its function keys correctly, F1-F4 default to: // \033OP, \033OQ, \033OR, \033OS, so lets take care of this here if // possible int ch; if (escape_chars.empty()) ch = m_window_sp->GetChar(); else { ch = escape_chars.front(); escape_chars.pop_front(); } if (ch == KEY_ESCAPE) { int ch2 = m_window_sp->GetChar(); if (ch2 == 'O') { int ch3 = m_window_sp->GetChar(); switch (ch3) { case 'P': ch = KEY_F(1); break; case 'Q': ch = KEY_F(2); break; case 'R': ch = KEY_F(3); break; case 'S': ch = KEY_F(4); break; default: escape_chars.push_back(ch2); if (ch3 != -1) escape_chars.push_back(ch3); break; } } else if (ch2 != -1) escape_chars.push_back(ch2); } #else int ch = m_window_sp->GetChar(); #endif if (ch == -1) { if (feof(m_in) || ferror(m_in)) { done = true; } else { // Just a timeout from using halfdelay(), check for events EventSP event_sp; while (listener_sp->PeekAtNextEvent()) { listener_sp->GetEvent(event_sp, std::chrono::seconds(0)); if (event_sp) { Broadcaster *broadcaster = event_sp->GetBroadcaster(); if (broadcaster) { // uint32_t event_type = event_sp->GetType(); ConstString broadcaster_class( broadcaster->GetBroadcasterClass()); if (broadcaster_class == broadcaster_class_process) { debugger.GetCommandInterpreter().UpdateExecutionContext( nullptr); update = true; continue; // Don't get any key, just update our view } } } } } } else { HandleCharResult key_result = m_window_sp->HandleChar(ch); switch (key_result) { case eKeyHandled: debugger.GetCommandInterpreter().UpdateExecutionContext(nullptr); update = true; break; case eKeyNotHandled: break; case eQuitApplication: done = true; break; } } } debugger.CancelForwardEvents(listener_sp); } WindowSP &GetMainWindow() { if (!m_window_sp) m_window_sp.reset(new Window("main", stdscr, false)); return m_window_sp; } WindowDelegates &GetWindowDelegates() { return m_window_delegates; } protected: WindowSP m_window_sp; WindowDelegates m_window_delegates; SCREEN *m_screen; FILE *m_in; FILE *m_out; }; } // namespace curses using namespace curses; struct Row { ValueObjectManager value; Row *parent; // The process stop ID when the children were calculated. uint32_t children_stop_id; int row_idx; int x; int y; bool might_have_children; bool expanded; bool calculated_children; std::vector<Row> children; Row(const ValueObjectSP &v, Row *p) : value(v, lldb::eDynamicDontRunTarget, true), parent(p), row_idx(0), x(1), y(1), might_have_children(v ? v->MightHaveChildren() : false), expanded(false), calculated_children(false), children() {} size_t GetDepth() const { if (parent) return 1 + parent->GetDepth(); return 0; } void Expand() { expanded = true; } std::vector<Row> &GetChildren() { ProcessSP process_sp = value.GetProcessSP(); auto stop_id = process_sp->GetStopID(); if (process_sp && stop_id != children_stop_id) { children_stop_id = stop_id; calculated_children = false; } if (!calculated_children) { children.clear(); calculated_children = true; ValueObjectSP valobj = value.GetSP(); if (valobj) { const size_t num_children = valobj->GetNumChildren(); for (size_t i = 0; i < num_children; ++i) { children.push_back(Row(valobj->GetChildAtIndex(i, true), this)); } } } return children; } void Unexpand() { expanded = false; calculated_children = false; children.clear(); } void DrawTree(Window &window) { if (parent) parent->DrawTreeForChild(window, this, 0); if (might_have_children) { // It we can get UTF8 characters to work we should try to use the "symbol" // UTF8 string below // const char *symbol = ""; // if (row.expanded) // symbol = "\xe2\x96\xbd "; // else // symbol = "\xe2\x96\xb7 "; // window.PutCString (symbol); // The ACS_DARROW and ACS_RARROW don't look very nice they are just a // 'v' or '>' character... // if (expanded) // window.PutChar (ACS_DARROW); // else // window.PutChar (ACS_RARROW); // Since we can't find any good looking right arrow/down arrow // symbols, just use a diamond... window.PutChar(ACS_DIAMOND); window.PutChar(ACS_HLINE); } } void DrawTreeForChild(Window &window, Row *child, uint32_t reverse_depth) { if (parent) parent->DrawTreeForChild(window, this, reverse_depth + 1); if (&GetChildren().back() == child) { // Last child if (reverse_depth == 0) { window.PutChar(ACS_LLCORNER); window.PutChar(ACS_HLINE); } else { window.PutChar(' '); window.PutChar(' '); } } else { if (reverse_depth == 0) { window.PutChar(ACS_LTEE); window.PutChar(ACS_HLINE); } else { window.PutChar(ACS_VLINE); window.PutChar(' '); } } } }; struct DisplayOptions { bool show_types; }; class TreeItem; class TreeDelegate { public: TreeDelegate() = default; virtual ~TreeDelegate() = default; virtual void TreeDelegateDrawTreeItem(TreeItem &item, Window &window) = 0; virtual void TreeDelegateGenerateChildren(TreeItem &item) = 0; virtual bool TreeDelegateItemSelected( TreeItem &item) = 0; // Return true if we need to update views }; typedef std::shared_ptr<TreeDelegate> TreeDelegateSP; class TreeItem { public: TreeItem(TreeItem *parent, TreeDelegate &delegate, bool might_have_children) : m_parent(parent), m_delegate(delegate), m_user_data(nullptr), m_identifier(0), m_row_idx(-1), m_children(), m_might_have_children(might_have_children), m_is_expanded(false) {} TreeItem &operator=(const TreeItem &rhs) { if (this != &rhs) { m_parent = rhs.m_parent; m_delegate = rhs.m_delegate; m_user_data = rhs.m_user_data; m_identifier = rhs.m_identifier; m_row_idx = rhs.m_row_idx; m_children = rhs.m_children; m_might_have_children = rhs.m_might_have_children; m_is_expanded = rhs.m_is_expanded; } return *this; } size_t GetDepth() const { if (m_parent) return 1 + m_parent->GetDepth(); return 0; } int GetRowIndex() const { return m_row_idx; } void ClearChildren() { m_children.clear(); } void Resize(size_t n, const TreeItem &t) { m_children.resize(n, t); } TreeItem &operator[](size_t i) { return m_children[i]; } void SetRowIndex(int row_idx) { m_row_idx = row_idx; } size_t GetNumChildren() { m_delegate.TreeDelegateGenerateChildren(*this); return m_children.size(); } void ItemWasSelected() { m_delegate.TreeDelegateItemSelected(*this); } void CalculateRowIndexes(int &row_idx) { SetRowIndex(row_idx); ++row_idx; const bool expanded = IsExpanded(); // The root item must calculate its children, // or we must calculate the number of children // if the item is expanded if (m_parent == nullptr || expanded) GetNumChildren(); for (auto &item : m_children) { if (expanded) item.CalculateRowIndexes(row_idx); else item.SetRowIndex(-1); } } TreeItem *GetParent() { return m_parent; } bool IsExpanded() const { return m_is_expanded; } void Expand() { m_is_expanded = true; } void Unexpand() { m_is_expanded = false; } bool Draw(Window &window, const int first_visible_row, const uint32_t selected_row_idx, int &row_idx, int &num_rows_left) { if (num_rows_left <= 0) return false; if (m_row_idx >= first_visible_row) { window.MoveCursor(2, row_idx + 1); if (m_parent) m_parent->DrawTreeForChild(window, this, 0); if (m_might_have_children) { // It we can get UTF8 characters to work we should try to use the // "symbol" // UTF8 string below // const char *symbol = ""; // if (row.expanded) // symbol = "\xe2\x96\xbd "; // else // symbol = "\xe2\x96\xb7 "; // window.PutCString (symbol); // The ACS_DARROW and ACS_RARROW don't look very nice they are just a // 'v' or '>' character... // if (expanded) // window.PutChar (ACS_DARROW); // else // window.PutChar (ACS_RARROW); // Since we can't find any good looking right arrow/down arrow // symbols, just use a diamond... window.PutChar(ACS_DIAMOND); window.PutChar(ACS_HLINE); } bool highlight = (selected_row_idx == static_cast<size_t>(m_row_idx)) && window.IsActive(); if (highlight) window.AttributeOn(A_REVERSE); m_delegate.TreeDelegateDrawTreeItem(*this, window); if (highlight) window.AttributeOff(A_REVERSE); ++row_idx; --num_rows_left; } if (num_rows_left <= 0) return false; // We are done drawing... if (IsExpanded()) { for (auto &item : m_children) { // If we displayed all the rows and item.Draw() returns // false we are done drawing and can exit this for loop if (!item.Draw(window, first_visible_row, selected_row_idx, row_idx, num_rows_left)) break; } } return num_rows_left >= 0; // Return true if not done drawing yet } void DrawTreeForChild(Window &window, TreeItem *child, uint32_t reverse_depth) { if (m_parent) m_parent->DrawTreeForChild(window, this, reverse_depth + 1); if (&m_children.back() == child) { // Last child if (reverse_depth == 0) { window.PutChar(ACS_LLCORNER); window.PutChar(ACS_HLINE); } else { window.PutChar(' '); window.PutChar(' '); } } else { if (reverse_depth == 0) { window.PutChar(ACS_LTEE); window.PutChar(ACS_HLINE); } else { window.PutChar(ACS_VLINE); window.PutChar(' '); } } } TreeItem *GetItemForRowIndex(uint32_t row_idx) { if (static_cast<uint32_t>(m_row_idx) == row_idx) return this; if (m_children.empty()) return nullptr; if (IsExpanded()) { for (auto &item : m_children) { TreeItem *selected_item_ptr = item.GetItemForRowIndex(row_idx); if (selected_item_ptr) return selected_item_ptr; } } return nullptr; } void *GetUserData() const { return m_user_data; } void SetUserData(void *user_data) { m_user_data = user_data; } uint64_t GetIdentifier() const { return m_identifier; } void SetIdentifier(uint64_t identifier) { m_identifier = identifier; } void SetMightHaveChildren(bool b) { m_might_have_children = b; } protected: TreeItem *m_parent; TreeDelegate &m_delegate; void *m_user_data; uint64_t m_identifier; int m_row_idx; // Zero based visible row index, -1 if not visible or for the // root item std::vector<TreeItem> m_children; bool m_might_have_children; bool m_is_expanded; }; class TreeWindowDelegate : public WindowDelegate { public: TreeWindowDelegate(Debugger &debugger, const TreeDelegateSP &delegate_sp) : m_debugger(debugger), m_delegate_sp(delegate_sp), m_root(nullptr, *delegate_sp, true), m_selected_item(nullptr), m_num_rows(0), m_selected_row_idx(0), m_first_visible_row(0), m_min_x(0), m_min_y(0), m_max_x(0), m_max_y(0) {} int NumVisibleRows() const { return m_max_y - m_min_y; } bool WindowDelegateDraw(Window &window, bool force) override { ExecutionContext exe_ctx( m_debugger.GetCommandInterpreter().GetExecutionContext()); Process *process = exe_ctx.GetProcessPtr(); bool display_content = false; if (process) { StateType state = process->GetState(); if (StateIsStoppedState(state, true)) { // We are stopped, so it is ok to display_content = true; } else if (StateIsRunningState(state)) { return true; // Don't do any updating when we are running } } m_min_x = 2; m_min_y = 1; m_max_x = window.GetWidth() - 1; m_max_y = window.GetHeight() - 1; window.Erase(); window.DrawTitleBox(window.GetName()); if (display_content) { const int num_visible_rows = NumVisibleRows(); m_num_rows = 0; m_root.CalculateRowIndexes(m_num_rows); // If we unexpanded while having something selected our // total number of rows is less than the num visible rows, // then make sure we show all the rows by setting the first // visible row accordingly. if (m_first_visible_row > 0 && m_num_rows < num_visible_rows) m_first_visible_row = 0; // Make sure the selected row is always visible if (m_selected_row_idx < m_first_visible_row) m_first_visible_row = m_selected_row_idx; else if (m_first_visible_row + num_visible_rows <= m_selected_row_idx) m_first_visible_row = m_selected_row_idx - num_visible_rows + 1; int row_idx = 0; int num_rows_left = num_visible_rows; m_root.Draw(window, m_first_visible_row, m_selected_row_idx, row_idx, num_rows_left); // Get the selected row m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx); } else { m_selected_item = nullptr; } window.DeferredRefresh(); return true; // Drawing handled } const char *WindowDelegateGetHelpText() override { return "Thread window keyboard shortcuts:"; } KeyHelp *WindowDelegateGetKeyHelp() override { static curses::KeyHelp g_source_view_key_help[] = { {KEY_UP, "Select previous item"}, {KEY_DOWN, "Select next item"}, {KEY_RIGHT, "Expand the selected item"}, {KEY_LEFT, "Unexpand the selected item or select parent if not expanded"}, {KEY_PPAGE, "Page up"}, {KEY_NPAGE, "Page down"}, {'h', "Show help dialog"}, {' ', "Toggle item expansion"}, {',', "Page up"}, {'.', "Page down"}, {'\0', nullptr}}; return g_source_view_key_help; } HandleCharResult WindowDelegateHandleChar(Window &window, int c) override { switch (c) { case ',': case KEY_PPAGE: // Page up key if (m_first_visible_row > 0) { if (m_first_visible_row > m_max_y) m_first_visible_row -= m_max_y; else m_first_visible_row = 0; m_selected_row_idx = m_first_visible_row; m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx); if (m_selected_item) m_selected_item->ItemWasSelected(); } return eKeyHandled; case '.': case KEY_NPAGE: // Page down key if (m_num_rows > m_max_y) { if (m_first_visible_row + m_max_y < m_num_rows) { m_first_visible_row += m_max_y; m_selected_row_idx = m_first_visible_row; m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx); if (m_selected_item) m_selected_item->ItemWasSelected(); } } return eKeyHandled; case KEY_UP: if (m_selected_row_idx > 0) { --m_selected_row_idx; m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx); if (m_selected_item) m_selected_item->ItemWasSelected(); } return eKeyHandled; case KEY_DOWN: if (m_selected_row_idx + 1 < m_num_rows) { ++m_selected_row_idx; m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx); if (m_selected_item) m_selected_item->ItemWasSelected(); } return eKeyHandled; case KEY_RIGHT: if (m_selected_item) { if (!m_selected_item->IsExpanded()) m_selected_item->Expand(); } return eKeyHandled; case KEY_LEFT: if (m_selected_item) { if (m_selected_item->IsExpanded()) m_selected_item->Unexpand(); else if (m_selected_item->GetParent()) { m_selected_row_idx = m_selected_item->GetParent()->GetRowIndex(); m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx); if (m_selected_item) m_selected_item->ItemWasSelected(); } } return eKeyHandled; case ' ': // Toggle expansion state when SPACE is pressed if (m_selected_item) { if (m_selected_item->IsExpanded()) m_selected_item->Unexpand(); else m_selected_item->Expand(); } return eKeyHandled; case 'h': window.CreateHelpSubwindow(); return eKeyHandled; default: break; } return eKeyNotHandled; } protected: Debugger &m_debugger; TreeDelegateSP m_delegate_sp; TreeItem m_root; TreeItem *m_selected_item; int m_num_rows; int m_selected_row_idx; int m_first_visible_row; int m_min_x; int m_min_y; int m_max_x; int m_max_y; }; class FrameTreeDelegate : public TreeDelegate { public: FrameTreeDelegate() : TreeDelegate() { FormatEntity::Parse( "frame #${frame.index}: {${function.name}${function.pc-offset}}}", m_format); } ~FrameTreeDelegate() override = default; void TreeDelegateDrawTreeItem(TreeItem &item, Window &window) override { Thread *thread = (Thread *)item.GetUserData(); if (thread) { const uint64_t frame_idx = item.GetIdentifier(); StackFrameSP frame_sp = thread->GetStackFrameAtIndex(frame_idx); if (frame_sp) { StreamString strm; const SymbolContext &sc = frame_sp->GetSymbolContext(eSymbolContextEverything); ExecutionContext exe_ctx(frame_sp); if (FormatEntity::Format(m_format, strm, &sc, &exe_ctx, nullptr, nullptr, false, false)) { int right_pad = 1; window.PutCStringTruncated(strm.GetString().str().c_str(), right_pad); } } } } void TreeDelegateGenerateChildren(TreeItem &item) override { // No children for frames yet... } bool TreeDelegateItemSelected(TreeItem &item) override { Thread *thread = (Thread *)item.GetUserData(); if (thread) { thread->GetProcess()->GetThreadList().SetSelectedThreadByID( thread->GetID()); const uint64_t frame_idx = item.GetIdentifier(); thread->SetSelectedFrameByIndex(frame_idx); return true; } return false; } protected: FormatEntity::Entry m_format; }; class ThreadTreeDelegate : public TreeDelegate { public: ThreadTreeDelegate(Debugger &debugger) : TreeDelegate(), m_debugger(debugger), m_tid(LLDB_INVALID_THREAD_ID), m_stop_id(UINT32_MAX) { FormatEntity::Parse("thread #${thread.index}: tid = ${thread.id}{, stop " "reason = ${thread.stop-reason}}", m_format); } ~ThreadTreeDelegate() override = default; ProcessSP GetProcess() { return m_debugger.GetCommandInterpreter() .GetExecutionContext() .GetProcessSP(); } ThreadSP GetThread(const TreeItem &item) { ProcessSP process_sp = GetProcess(); if (process_sp) return process_sp->GetThreadList().FindThreadByID(item.GetIdentifier()); return ThreadSP(); } void TreeDelegateDrawTreeItem(TreeItem &item, Window &window) override { ThreadSP thread_sp = GetThread(item); if (thread_sp) { StreamString strm; ExecutionContext exe_ctx(thread_sp); if (FormatEntity::Format(m_format, strm, nullptr, &exe_ctx, nullptr, nullptr, false, false)) { int right_pad = 1; window.PutCStringTruncated(strm.GetString().str().c_str(), right_pad); } } } void TreeDelegateGenerateChildren(TreeItem &item) override { ProcessSP process_sp = GetProcess(); if (process_sp && process_sp->IsAlive()) { StateType state = process_sp->GetState(); if (StateIsStoppedState(state, true)) { ThreadSP thread_sp = GetThread(item); if (thread_sp) { if (m_stop_id == process_sp->GetStopID() && thread_sp->GetID() == m_tid) return; // Children are already up to date if (!m_frame_delegate_sp) { // Always expand the thread item the first time we show it m_frame_delegate_sp.reset(new FrameTreeDelegate()); } m_stop_id = process_sp->GetStopID(); m_tid = thread_sp->GetID(); TreeItem t(&item, *m_frame_delegate_sp, false); size_t num_frames = thread_sp->GetStackFrameCount(); item.Resize(num_frames, t); for (size_t i = 0; i < num_frames; ++i) { item[i].SetUserData(thread_sp.get()); item[i].SetIdentifier(i); } } return; } } item.ClearChildren(); } bool TreeDelegateItemSelected(TreeItem &item) override { ProcessSP process_sp = GetProcess(); if (process_sp && process_sp->IsAlive()) { StateType state = process_sp->GetState(); if (StateIsStoppedState(state, true)) { ThreadSP thread_sp = GetThread(item); if (thread_sp) { ThreadList &thread_list = thread_sp->GetProcess()->GetThreadList(); std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex()); ThreadSP selected_thread_sp = thread_list.GetSelectedThread(); if (selected_thread_sp->GetID() != thread_sp->GetID()) { thread_list.SetSelectedThreadByID(thread_sp->GetID()); return true; } } } } return false; } protected: Debugger &m_debugger; std::shared_ptr<FrameTreeDelegate> m_frame_delegate_sp; lldb::user_id_t m_tid; uint32_t m_stop_id; FormatEntity::Entry m_format; }; class ThreadsTreeDelegate : public TreeDelegate { public: ThreadsTreeDelegate(Debugger &debugger) : TreeDelegate(), m_thread_delegate_sp(), m_debugger(debugger), m_stop_id(UINT32_MAX) { FormatEntity::Parse("process ${process.id}{, name = ${process.name}}", m_format); } ~ThreadsTreeDelegate() override = default; ProcessSP GetProcess() { return m_debugger.GetCommandInterpreter() .GetExecutionContext() .GetProcessSP(); } void TreeDelegateDrawTreeItem(TreeItem &item, Window &window) override { ProcessSP process_sp = GetProcess(); if (process_sp && process_sp->IsAlive()) { StreamString strm; ExecutionContext exe_ctx(process_sp); if (FormatEntity::Format(m_format, strm, nullptr, &exe_ctx, nullptr, nullptr, false, false)) { int right_pad = 1; window.PutCStringTruncated(strm.GetString().str().c_str(), right_pad); } } } void TreeDelegateGenerateChildren(TreeItem &item) override { ProcessSP process_sp = GetProcess(); if (process_sp && process_sp->IsAlive()) { StateType state = process_sp->GetState(); if (StateIsStoppedState(state, true)) { const uint32_t stop_id = process_sp->GetStopID(); if (m_stop_id == stop_id) return; // Children are already up to date m_stop_id = stop_id; if (!m_thread_delegate_sp) { // Always expand the thread item the first time we show it // item.Expand(); m_thread_delegate_sp.reset(new ThreadTreeDelegate(m_debugger)); } TreeItem t(&item, *m_thread_delegate_sp, false); ThreadList &threads = process_sp->GetThreadList(); std::lock_guard<std::recursive_mutex> guard(threads.GetMutex()); size_t num_threads = threads.GetSize(); item.Resize(num_threads, t); for (size_t i = 0; i < num_threads; ++i) { item[i].SetIdentifier(threads.GetThreadAtIndex(i)->GetID()); item[i].SetMightHaveChildren(true); } return; } } item.ClearChildren(); } bool TreeDelegateItemSelected(TreeItem &item) override { return false; } protected: std::shared_ptr<ThreadTreeDelegate> m_thread_delegate_sp; Debugger &m_debugger; uint32_t m_stop_id; FormatEntity::Entry m_format; }; class ValueObjectListDelegate : public WindowDelegate { public: ValueObjectListDelegate() : m_rows(), m_selected_row(nullptr), m_selected_row_idx(0), m_first_visible_row(0), m_num_rows(0), m_max_x(0), m_max_y(0) {} ValueObjectListDelegate(ValueObjectList &valobj_list) : m_rows(), m_selected_row(nullptr), m_selected_row_idx(0), m_first_visible_row(0), m_num_rows(0), m_max_x(0), m_max_y(0) { SetValues(valobj_list); } ~ValueObjectListDelegate() override = default; void SetValues(ValueObjectList &valobj_list) { m_selected_row = nullptr; m_selected_row_idx = 0; m_first_visible_row = 0; m_num_rows = 0; m_rows.clear(); for (auto &valobj_sp : valobj_list.GetObjects()) m_rows.push_back(Row(valobj_sp, nullptr)); } bool WindowDelegateDraw(Window &window, bool force) override { m_num_rows = 0; m_min_x = 2; m_min_y = 1; m_max_x = window.GetWidth() - 1; m_max_y = window.GetHeight() - 1; window.Erase(); window.DrawTitleBox(window.GetName()); const int num_visible_rows = NumVisibleRows(); const int num_rows = CalculateTotalNumberRows(m_rows); // If we unexpanded while having something selected our // total number of rows is less than the num visible rows, // then make sure we show all the rows by setting the first // visible row accordingly. if (m_first_visible_row > 0 && num_rows < num_visible_rows) m_first_visible_row = 0; // Make sure the selected row is always visible if (m_selected_row_idx < m_first_visible_row) m_first_visible_row = m_selected_row_idx; else if (m_first_visible_row + num_visible_rows <= m_selected_row_idx) m_first_visible_row = m_selected_row_idx - num_visible_rows + 1; DisplayRows(window, m_rows, g_options); window.DeferredRefresh(); // Get the selected row m_selected_row = GetRowForRowIndex(m_selected_row_idx); // Keep the cursor on the selected row so the highlight and the cursor // are always on the same line if (m_selected_row) window.MoveCursor(m_selected_row->x, m_selected_row->y); return true; // Drawing handled } KeyHelp *WindowDelegateGetKeyHelp() override { static curses::KeyHelp g_source_view_key_help[] = { {KEY_UP, "Select previous item"}, {KEY_DOWN, "Select next item"}, {KEY_RIGHT, "Expand selected item"}, {KEY_LEFT, "Unexpand selected item or select parent if not expanded"}, {KEY_PPAGE, "Page up"}, {KEY_NPAGE, "Page down"}, {'A', "Format as annotated address"}, {'b', "Format as binary"}, {'B', "Format as hex bytes with ASCII"}, {'c', "Format as character"}, {'d', "Format as a signed integer"}, {'D', "Format selected value using the default format for the type"}, {'f', "Format as float"}, {'h', "Show help dialog"}, {'i', "Format as instructions"}, {'o', "Format as octal"}, {'p', "Format as pointer"}, {'s', "Format as C string"}, {'t', "Toggle showing/hiding type names"}, {'u', "Format as an unsigned integer"}, {'x', "Format as hex"}, {'X', "Format as uppercase hex"}, {' ', "Toggle item expansion"}, {',', "Page up"}, {'.', "Page down"}, {'\0', nullptr}}; return g_source_view_key_help; } HandleCharResult WindowDelegateHandleChar(Window &window, int c) override { switch (c) { case 'x': case 'X': case 'o': case 's': case 'u': case 'd': case 'D': case 'i': case 'A': case 'p': case 'c': case 'b': case 'B': case 'f': // Change the format for the currently selected item if (m_selected_row) { auto valobj_sp = m_selected_row->value.GetSP(); if (valobj_sp) valobj_sp->SetFormat(FormatForChar(c)); } return eKeyHandled; case 't': // Toggle showing type names g_options.show_types = !g_options.show_types; return eKeyHandled; case ',': case KEY_PPAGE: // Page up key if (m_first_visible_row > 0) { if (static_cast<int>(m_first_visible_row) > m_max_y) m_first_visible_row -= m_max_y; else m_first_visible_row = 0; m_selected_row_idx = m_first_visible_row; } return eKeyHandled; case '.': case KEY_NPAGE: // Page down key if (m_num_rows > static_cast<size_t>(m_max_y)) { if (m_first_visible_row + m_max_y < m_num_rows) { m_first_visible_row += m_max_y; m_selected_row_idx = m_first_visible_row; } } return eKeyHandled; case KEY_UP: if (m_selected_row_idx > 0) --m_selected_row_idx; return eKeyHandled; case KEY_DOWN: if (m_selected_row_idx + 1 < m_num_rows) ++m_selected_row_idx; return eKeyHandled; case KEY_RIGHT: if (m_selected_row) { if (!m_selected_row->expanded) m_selected_row->Expand(); } return eKeyHandled; case KEY_LEFT: if (m_selected_row) { if (m_selected_row->expanded) m_selected_row->Unexpand(); else if (m_selected_row->parent) m_selected_row_idx = m_selected_row->parent->row_idx; } return eKeyHandled; case ' ': // Toggle expansion state when SPACE is pressed if (m_selected_row) { if (m_selected_row->expanded) m_selected_row->Unexpand(); else m_selected_row->Expand(); } return eKeyHandled; case 'h': window.CreateHelpSubwindow(); return eKeyHandled; default: break; } return eKeyNotHandled; } protected: std::vector<Row> m_rows; Row *m_selected_row; uint32_t m_selected_row_idx; uint32_t m_first_visible_row; uint32_t m_num_rows; int m_min_x; int m_min_y; int m_max_x; int m_max_y; static Format FormatForChar(int c) { switch (c) { case 'x': return eFormatHex; case 'X': return eFormatHexUppercase; case 'o': return eFormatOctal; case 's': return eFormatCString; case 'u': return eFormatUnsigned; case 'd': return eFormatDecimal; case 'D': return eFormatDefault; case 'i': return eFormatInstruction; case 'A': return eFormatAddressInfo; case 'p': return eFormatPointer; case 'c': return eFormatChar; case 'b': return eFormatBinary; case 'B': return eFormatBytesWithASCII; case 'f': return eFormatFloat; } return eFormatDefault; } bool DisplayRowObject(Window &window, Row &row, DisplayOptions &options, bool highlight, bool last_child) { ValueObject *valobj = row.value.GetSP().get(); if (valobj == nullptr) return false; const char *type_name = options.show_types ? valobj->GetTypeName().GetCString() : nullptr; const char *name = valobj->GetName().GetCString(); const char *value = valobj->GetValueAsCString(); const char *summary = valobj->GetSummaryAsCString(); window.MoveCursor(row.x, row.y); row.DrawTree(window); if (highlight) window.AttributeOn(A_REVERSE); if (type_name && type_name[0]) window.Printf("(%s) ", type_name); if (name && name[0]) window.PutCString(name); attr_t changd_attr = 0; if (valobj->GetValueDidChange()) changd_attr = COLOR_PAIR(5) | A_BOLD; if (value && value[0]) { window.PutCString(" = "); if (changd_attr) window.AttributeOn(changd_attr); window.PutCString(value); if (changd_attr) window.AttributeOff(changd_attr); } if (summary && summary[0]) { window.PutChar(' '); if (changd_attr) window.AttributeOn(changd_attr); window.PutCString(summary); if (changd_attr) window.AttributeOff(changd_attr); } if (highlight) window.AttributeOff(A_REVERSE); return true; } void DisplayRows(Window &window, std::vector<Row> &rows, DisplayOptions &options) { // > 0x25B7 // \/ 0x25BD bool window_is_active = window.IsActive(); for (auto &row : rows) { const bool last_child = row.parent && &rows[rows.size() - 1] == &row; // Save the row index in each Row structure row.row_idx = m_num_rows; if ((m_num_rows >= m_first_visible_row) && ((m_num_rows - m_first_visible_row) < static_cast<size_t>(NumVisibleRows()))) { row.x = m_min_x; row.y = m_num_rows - m_first_visible_row + 1; if (DisplayRowObject(window, row, options, window_is_active && m_num_rows == m_selected_row_idx, last_child)) { ++m_num_rows; } else { row.x = 0; row.y = 0; } } else { row.x = 0; row.y = 0; ++m_num_rows; } auto &children = row.GetChildren(); if (row.expanded && !children.empty()) { DisplayRows(window, children, options); } } } int CalculateTotalNumberRows(std::vector<Row> &rows) { int row_count = 0; for (auto &row : rows) { ++row_count; if (row.expanded) row_count += CalculateTotalNumberRows(row.GetChildren()); } return row_count; } static Row *GetRowForRowIndexImpl(std::vector<Row> &rows, size_t &row_index) { for (auto &row : rows) { if (row_index == 0) return &row; else { --row_index; auto &children = row.GetChildren(); if (row.expanded && !children.empty()) { Row *result = GetRowForRowIndexImpl(children, row_index); if (result) return result; } } } return nullptr; } Row *GetRowForRowIndex(size_t row_index) { return GetRowForRowIndexImpl(m_rows, row_index); } int NumVisibleRows() const { return m_max_y - m_min_y; } static DisplayOptions g_options; }; class FrameVariablesWindowDelegate : public ValueObjectListDelegate { public: FrameVariablesWindowDelegate(Debugger &debugger) : ValueObjectListDelegate(), m_debugger(debugger), m_frame_block(nullptr) {} ~FrameVariablesWindowDelegate() override = default; const char *WindowDelegateGetHelpText() override { return "Frame variable window keyboard shortcuts:"; } bool WindowDelegateDraw(Window &window, bool force) override { ExecutionContext exe_ctx( m_debugger.GetCommandInterpreter().GetExecutionContext()); Process *process = exe_ctx.GetProcessPtr(); Block *frame_block = nullptr; StackFrame *frame = nullptr; if (process) { StateType state = process->GetState(); if (StateIsStoppedState(state, true)) { frame = exe_ctx.GetFramePtr(); if (frame) frame_block = frame->GetFrameBlock(); } else if (StateIsRunningState(state)) { return true; // Don't do any updating when we are running } } ValueObjectList local_values; if (frame_block) { // Only update the variables if they have changed if (m_frame_block != frame_block) { m_frame_block = frame_block; VariableList *locals = frame->GetVariableList(true); if (locals) { const DynamicValueType use_dynamic = eDynamicDontRunTarget; const size_t num_locals = locals->GetSize(); for (size_t i = 0; i < num_locals; ++i) { ValueObjectSP value_sp = frame->GetValueObjectForFrameVariable( locals->GetVariableAtIndex(i), use_dynamic); if (value_sp) { ValueObjectSP synthetic_value_sp = value_sp->GetSyntheticValue(); if (synthetic_value_sp) local_values.Append(synthetic_value_sp); else local_values.Append(value_sp); } } // Update the values SetValues(local_values); } } } else { m_frame_block = nullptr; // Update the values with an empty list if there is no frame SetValues(local_values); } return ValueObjectListDelegate::WindowDelegateDraw(window, force); } protected: Debugger &m_debugger; Block *m_frame_block; }; class RegistersWindowDelegate : public ValueObjectListDelegate { public: RegistersWindowDelegate(Debugger &debugger) : ValueObjectListDelegate(), m_debugger(debugger) {} ~RegistersWindowDelegate() override = default; const char *WindowDelegateGetHelpText() override { return "Register window keyboard shortcuts:"; } bool WindowDelegateDraw(Window &window, bool force) override { ExecutionContext exe_ctx( m_debugger.GetCommandInterpreter().GetExecutionContext()); StackFrame *frame = exe_ctx.GetFramePtr(); ValueObjectList value_list; if (frame) { if (frame->GetStackID() != m_stack_id) { m_stack_id = frame->GetStackID(); RegisterContextSP reg_ctx(frame->GetRegisterContext()); if (reg_ctx) { const uint32_t num_sets = reg_ctx->GetRegisterSetCount(); for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx) { value_list.Append( ValueObjectRegisterSet::Create(frame, reg_ctx, set_idx)); } } SetValues(value_list); } } else { Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive()) return true; // Don't do any updating if we are running else { // Update the values with an empty list if there // is no process or the process isn't alive anymore SetValues(value_list); } } return ValueObjectListDelegate::WindowDelegateDraw(window, force); } protected: Debugger &m_debugger; StackID m_stack_id; }; static const char *CursesKeyToCString(int ch) { static char g_desc[32]; if (ch >= KEY_F0 && ch < KEY_F0 + 64) { snprintf(g_desc, sizeof(g_desc), "F%u", ch - KEY_F0); return g_desc; } switch (ch) { case KEY_DOWN: return "down"; case KEY_UP: return "up"; case KEY_LEFT: return "left"; case KEY_RIGHT: return "right"; case KEY_HOME: return "home"; case KEY_BACKSPACE: return "backspace"; case KEY_DL: return "delete-line"; case KEY_IL: return "insert-line"; case KEY_DC: return "delete-char"; case KEY_IC: return "insert-char"; case KEY_CLEAR: return "clear"; case KEY_EOS: return "clear-to-eos"; case KEY_EOL: return "clear-to-eol"; case KEY_SF: return "scroll-forward"; case KEY_SR: return "scroll-backward"; case KEY_NPAGE: return "page-down"; case KEY_PPAGE: return "page-up"; case KEY_STAB: return "set-tab"; case KEY_CTAB: return "clear-tab"; case KEY_CATAB: return "clear-all-tabs"; case KEY_ENTER: return "enter"; case KEY_PRINT: return "print"; case KEY_LL: return "lower-left key"; case KEY_A1: return "upper left of keypad"; case KEY_A3: return "upper right of keypad"; case KEY_B2: return "center of keypad"; case KEY_C1: return "lower left of keypad"; case KEY_C3: return "lower right of keypad"; case KEY_BTAB: return "back-tab key"; case KEY_BEG: return "begin key"; case KEY_CANCEL: return "cancel key"; case KEY_CLOSE: return "close key"; case KEY_COMMAND: return "command key"; case KEY_COPY: return "copy key"; case KEY_CREATE: return "create key"; case KEY_END: return "end key"; case KEY_EXIT: return "exit key"; case KEY_FIND: return "find key"; case KEY_HELP: return "help key"; case KEY_MARK: return "mark key"; case KEY_MESSAGE: return "message key"; case KEY_MOVE: return "move key"; case KEY_NEXT: return "next key"; case KEY_OPEN: return "open key"; case KEY_OPTIONS: return "options key"; case KEY_PREVIOUS: return "previous key"; case KEY_REDO: return "redo key"; case KEY_REFERENCE: return "reference key"; case KEY_REFRESH: return "refresh key"; case KEY_REPLACE: return "replace key"; case KEY_RESTART: return "restart key"; case KEY_RESUME: return "resume key"; case KEY_SAVE: return "save key"; case KEY_SBEG: return "shifted begin key"; case KEY_SCANCEL: return "shifted cancel key"; case KEY_SCOMMAND: return "shifted command key"; case KEY_SCOPY: return "shifted copy key"; case KEY_SCREATE: return "shifted create key"; case KEY_SDC: return "shifted delete-character key"; case KEY_SDL: return "shifted delete-line key"; case KEY_SELECT: return "select key"; case KEY_SEND: return "shifted end key"; case KEY_SEOL: return "shifted clear-to-end-of-line key"; case KEY_SEXIT: return "shifted exit key"; case KEY_SFIND: return "shifted find key"; case KEY_SHELP: return "shifted help key"; case KEY_SHOME: return "shifted home key"; case KEY_SIC: return "shifted insert-character key"; case KEY_SLEFT: return "shifted left-arrow key"; case KEY_SMESSAGE: return "shifted message key"; case KEY_SMOVE: return "shifted move key"; case KEY_SNEXT: return "shifted next key"; case KEY_SOPTIONS: return "shifted options key"; case KEY_SPREVIOUS: return "shifted previous key"; case KEY_SPRINT: return "shifted print key"; case KEY_SREDO: return "shifted redo key"; case KEY_SREPLACE: return "shifted replace key"; case KEY_SRIGHT: return "shifted right-arrow key"; case KEY_SRSUME: return "shifted resume key"; case KEY_SSAVE: return "shifted save key"; case KEY_SSUSPEND: return "shifted suspend key"; case KEY_SUNDO: return "shifted undo key"; case KEY_SUSPEND: return "suspend key"; case KEY_UNDO: return "undo key"; case KEY_MOUSE: return "Mouse event has occurred"; case KEY_RESIZE: return "Terminal resize event"; #ifdef KEY_EVENT case KEY_EVENT: return "We were interrupted by an event"; #endif case KEY_RETURN: return "return"; case ' ': return "space"; case '\t': return "tab"; case KEY_ESCAPE: return "escape"; default: if (isprint(ch)) snprintf(g_desc, sizeof(g_desc), "%c", ch); else snprintf(g_desc, sizeof(g_desc), "\\x%2.2x", ch); return g_desc; } return nullptr; } HelpDialogDelegate::HelpDialogDelegate(const char *text, KeyHelp *key_help_array) : m_text(), m_first_visible_line(0) { if (text && text[0]) { m_text.SplitIntoLines(text); m_text.AppendString(""); } if (key_help_array) { for (KeyHelp *key = key_help_array; key->ch; ++key) { StreamString key_description; key_description.Printf("%10s - %s", CursesKeyToCString(key->ch), key->description); m_text.AppendString(key_description.GetString()); } } } HelpDialogDelegate::~HelpDialogDelegate() = default; bool HelpDialogDelegate::WindowDelegateDraw(Window &window, bool force) { window.Erase(); const int window_height = window.GetHeight(); int x = 2; int y = 1; const int min_y = y; const int max_y = window_height - 1 - y; const size_t num_visible_lines = max_y - min_y + 1; const size_t num_lines = m_text.GetSize(); const char *bottom_message; if (num_lines <= num_visible_lines) bottom_message = "Press any key to exit"; else bottom_message = "Use arrows to scroll, any other key to exit"; window.DrawTitleBox(window.GetName(), bottom_message); while (y <= max_y) { window.MoveCursor(x, y); window.PutCStringTruncated( m_text.GetStringAtIndex(m_first_visible_line + y - min_y), 1); ++y; } return true; } HandleCharResult HelpDialogDelegate::WindowDelegateHandleChar(Window &window, int key) { bool done = false; const size_t num_lines = m_text.GetSize(); const size_t num_visible_lines = window.GetHeight() - 2; if (num_lines <= num_visible_lines) { done = true; // If we have all lines visible and don't need scrolling, then any // key press will cause us to exit } else { switch (key) { case KEY_UP: if (m_first_visible_line > 0) --m_first_visible_line; break; case KEY_DOWN: if (m_first_visible_line + num_visible_lines < num_lines) ++m_first_visible_line; break; case KEY_PPAGE: case ',': if (m_first_visible_line > 0) { if (static_cast<size_t>(m_first_visible_line) >= num_visible_lines) m_first_visible_line -= num_visible_lines; else m_first_visible_line = 0; } break; case KEY_NPAGE: case '.': if (m_first_visible_line + num_visible_lines < num_lines) { m_first_visible_line += num_visible_lines; if (static_cast<size_t>(m_first_visible_line) > num_lines) m_first_visible_line = num_lines - num_visible_lines; } break; default: done = true; break; } } if (done) window.GetParent()->RemoveSubWindow(&window); return eKeyHandled; } class ApplicationDelegate : public WindowDelegate, public MenuDelegate { public: enum { eMenuID_LLDB = 1, eMenuID_LLDBAbout, eMenuID_LLDBExit, eMenuID_Target, eMenuID_TargetCreate, eMenuID_TargetDelete, eMenuID_Process, eMenuID_ProcessAttach, eMenuID_ProcessDetach, eMenuID_ProcessLaunch, eMenuID_ProcessContinue, eMenuID_ProcessHalt, eMenuID_ProcessKill, eMenuID_Thread, eMenuID_ThreadStepIn, eMenuID_ThreadStepOver, eMenuID_ThreadStepOut, eMenuID_View, eMenuID_ViewBacktrace, eMenuID_ViewRegisters, eMenuID_ViewSource, eMenuID_ViewVariables, eMenuID_Help, eMenuID_HelpGUIHelp }; ApplicationDelegate(Application &app, Debugger &debugger) : WindowDelegate(), MenuDelegate(), m_app(app), m_debugger(debugger) {} ~ApplicationDelegate() override = default; bool WindowDelegateDraw(Window &window, bool force) override { return false; // Drawing not handled, let standard window drawing happen } HandleCharResult WindowDelegateHandleChar(Window &window, int key) override { switch (key) { case '\t': window.SelectNextWindowAsActive(); return eKeyHandled; case 'h': window.CreateHelpSubwindow(); return eKeyHandled; case KEY_ESCAPE: return eQuitApplication; default: break; } return eKeyNotHandled; } const char *WindowDelegateGetHelpText() override { return "Welcome to the LLDB curses GUI.\n\n" "Press the TAB key to change the selected view.\n" "Each view has its own keyboard shortcuts, press 'h' to open a " "dialog to display them.\n\n" "Common key bindings for all views:"; } KeyHelp *WindowDelegateGetKeyHelp() override { static curses::KeyHelp g_source_view_key_help[] = { {'\t', "Select next view"}, {'h', "Show help dialog with view specific key bindings"}, {',', "Page up"}, {'.', "Page down"}, {KEY_UP, "Select previous"}, {KEY_DOWN, "Select next"}, {KEY_LEFT, "Unexpand or select parent"}, {KEY_RIGHT, "Expand"}, {KEY_PPAGE, "Page up"}, {KEY_NPAGE, "Page down"}, {'\0', nullptr}}; return g_source_view_key_help; } MenuActionResult MenuDelegateAction(Menu &menu) override { switch (menu.GetIdentifier()) { case eMenuID_ThreadStepIn: { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasThreadScope()) { Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive() && StateIsStoppedState(process->GetState(), true)) exe_ctx.GetThreadRef().StepIn(true); } } return MenuActionResult::Handled; case eMenuID_ThreadStepOut: { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasThreadScope()) { Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive() && StateIsStoppedState(process->GetState(), true)) exe_ctx.GetThreadRef().StepOut(); } } return MenuActionResult::Handled; case eMenuID_ThreadStepOver: { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasThreadScope()) { Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive() && StateIsStoppedState(process->GetState(), true)) exe_ctx.GetThreadRef().StepOver(true); } } return MenuActionResult::Handled; case eMenuID_ProcessContinue: { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasProcessScope()) { Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive() && StateIsStoppedState(process->GetState(), true)) process->Resume(); } } return MenuActionResult::Handled; case eMenuID_ProcessKill: { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasProcessScope()) { Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive()) process->Destroy(false); } } return MenuActionResult::Handled; case eMenuID_ProcessHalt: { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasProcessScope()) { Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive()) process->Halt(); } } return MenuActionResult::Handled; case eMenuID_ProcessDetach: { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasProcessScope()) { Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive()) process->Detach(false); } } return MenuActionResult::Handled; case eMenuID_Process: { // Populate the menu with all of the threads if the process is stopped // when // the Process menu gets selected and is about to display its submenu. Menus &submenus = menu.GetSubmenus(); ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive() && StateIsStoppedState(process->GetState(), true)) { if (submenus.size() == 7) menu.AddSubmenu(MenuSP(new Menu(Menu::Type::Separator))); else if (submenus.size() > 8) submenus.erase(submenus.begin() + 8, submenus.end()); ThreadList &threads = process->GetThreadList(); std::lock_guard<std::recursive_mutex> guard(threads.GetMutex()); size_t num_threads = threads.GetSize(); for (size_t i = 0; i < num_threads; ++i) { ThreadSP thread_sp = threads.GetThreadAtIndex(i); char menu_char = '\0'; if (i < 9) menu_char = '1' + i; StreamString thread_menu_title; thread_menu_title.Printf("Thread %u", thread_sp->GetIndexID()); const char *thread_name = thread_sp->GetName(); if (thread_name && thread_name[0]) thread_menu_title.Printf(" %s", thread_name); else { const char *queue_name = thread_sp->GetQueueName(); if (queue_name && queue_name[0]) thread_menu_title.Printf(" %s", queue_name); } menu.AddSubmenu( MenuSP(new Menu(thread_menu_title.GetString().str().c_str(), nullptr, menu_char, thread_sp->GetID()))); } } else if (submenus.size() > 7) { // Remove the separator and any other thread submenu items // that were previously added submenus.erase(submenus.begin() + 7, submenus.end()); } // Since we are adding and removing items we need to recalculate the name // lengths menu.RecalculateNameLengths(); } return MenuActionResult::Handled; case eMenuID_ViewVariables: { WindowSP main_window_sp = m_app.GetMainWindow(); WindowSP source_window_sp = main_window_sp->FindSubWindow("Source"); WindowSP variables_window_sp = main_window_sp->FindSubWindow("Variables"); WindowSP registers_window_sp = main_window_sp->FindSubWindow("Registers"); const Rect source_bounds = source_window_sp->GetBounds(); if (variables_window_sp) { const Rect variables_bounds = variables_window_sp->GetBounds(); main_window_sp->RemoveSubWindow(variables_window_sp.get()); if (registers_window_sp) { // We have a registers window, so give all the area back to the // registers window Rect registers_bounds = variables_bounds; registers_bounds.size.width = source_bounds.size.width; registers_window_sp->SetBounds(registers_bounds); } else { // We have no registers window showing so give the bottom // area back to the source view source_window_sp->Resize(source_bounds.size.width, source_bounds.size.height + variables_bounds.size.height); } } else { Rect new_variables_rect; if (registers_window_sp) { // We have a registers window so split the area of the registers // window into two columns where the left hand side will be the // variables and the right hand side will be the registers const Rect variables_bounds = registers_window_sp->GetBounds(); Rect new_registers_rect; variables_bounds.VerticalSplitPercentage(0.50, new_variables_rect, new_registers_rect); registers_window_sp->SetBounds(new_registers_rect); } else { // No variables window, grab the bottom part of the source window Rect new_source_rect; source_bounds.HorizontalSplitPercentage(0.70, new_source_rect, new_variables_rect); source_window_sp->SetBounds(new_source_rect); } WindowSP new_window_sp = main_window_sp->CreateSubWindow( "Variables", new_variables_rect, false); new_window_sp->SetDelegate( WindowDelegateSP(new FrameVariablesWindowDelegate(m_debugger))); } touchwin(stdscr); } return MenuActionResult::Handled; case eMenuID_ViewRegisters: { WindowSP main_window_sp = m_app.GetMainWindow(); WindowSP source_window_sp = main_window_sp->FindSubWindow("Source"); WindowSP variables_window_sp = main_window_sp->FindSubWindow("Variables"); WindowSP registers_window_sp = main_window_sp->FindSubWindow("Registers"); const Rect source_bounds = source_window_sp->GetBounds(); if (registers_window_sp) { if (variables_window_sp) { const Rect variables_bounds = variables_window_sp->GetBounds(); // We have a variables window, so give all the area back to the // variables window variables_window_sp->Resize(variables_bounds.size.width + registers_window_sp->GetWidth(), variables_bounds.size.height); } else { // We have no variables window showing so give the bottom // area back to the source view source_window_sp->Resize(source_bounds.size.width, source_bounds.size.height + registers_window_sp->GetHeight()); } main_window_sp->RemoveSubWindow(registers_window_sp.get()); } else { Rect new_regs_rect; if (variables_window_sp) { // We have a variables window, split it into two columns // where the left hand side will be the variables and the // right hand side will be the registers const Rect variables_bounds = variables_window_sp->GetBounds(); Rect new_vars_rect; variables_bounds.VerticalSplitPercentage(0.50, new_vars_rect, new_regs_rect); variables_window_sp->SetBounds(new_vars_rect); } else { // No registers window, grab the bottom part of the source window Rect new_source_rect; source_bounds.HorizontalSplitPercentage(0.70, new_source_rect, new_regs_rect); source_window_sp->SetBounds(new_source_rect); } WindowSP new_window_sp = main_window_sp->CreateSubWindow("Registers", new_regs_rect, false); new_window_sp->SetDelegate( WindowDelegateSP(new RegistersWindowDelegate(m_debugger))); } touchwin(stdscr); } return MenuActionResult::Handled; case eMenuID_HelpGUIHelp: m_app.GetMainWindow()->CreateHelpSubwindow(); return MenuActionResult::Handled; default: break; } return MenuActionResult::NotHandled; } protected: Application &m_app; Debugger &m_debugger; }; class StatusBarWindowDelegate : public WindowDelegate { public: StatusBarWindowDelegate(Debugger &debugger) : m_debugger(debugger) { FormatEntity::Parse("Thread: ${thread.id%tid}", m_format); } ~StatusBarWindowDelegate() override = default; bool WindowDelegateDraw(Window &window, bool force) override { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); Process *process = exe_ctx.GetProcessPtr(); Thread *thread = exe_ctx.GetThreadPtr(); StackFrame *frame = exe_ctx.GetFramePtr(); window.Erase(); window.SetBackground(2); window.MoveCursor(0, 0); if (process) { const StateType state = process->GetState(); window.Printf("Process: %5" PRIu64 " %10s", process->GetID(), StateAsCString(state)); if (StateIsStoppedState(state, true)) { StreamString strm; if (thread && FormatEntity::Format(m_format, strm, nullptr, &exe_ctx, nullptr, nullptr, false, false)) { window.MoveCursor(40, 0); window.PutCStringTruncated(strm.GetString().str().c_str(), 1); } window.MoveCursor(60, 0); if (frame) window.Printf("Frame: %3u PC = 0x%16.16" PRIx64, frame->GetFrameIndex(), frame->GetFrameCodeAddress().GetOpcodeLoadAddress( exe_ctx.GetTargetPtr())); } else if (state == eStateExited) { const char *exit_desc = process->GetExitDescription(); const int exit_status = process->GetExitStatus(); if (exit_desc && exit_desc[0]) window.Printf(" with status = %i (%s)", exit_status, exit_desc); else window.Printf(" with status = %i", exit_status); } } window.DeferredRefresh(); return true; } protected: Debugger &m_debugger; FormatEntity::Entry m_format; }; class SourceFileWindowDelegate : public WindowDelegate { public: SourceFileWindowDelegate(Debugger &debugger) : WindowDelegate(), m_debugger(debugger), m_sc(), m_file_sp(), m_disassembly_scope(nullptr), m_disassembly_sp(), m_disassembly_range(), m_title(), m_line_width(4), m_selected_line(0), m_pc_line(0), m_stop_id(0), m_frame_idx(UINT32_MAX), m_first_visible_line(0), m_min_x(0), m_min_y(0), m_max_x(0), m_max_y(0) {} ~SourceFileWindowDelegate() override = default; void Update(const SymbolContext &sc) { m_sc = sc; } uint32_t NumVisibleLines() const { return m_max_y - m_min_y; } const char *WindowDelegateGetHelpText() override { return "Source/Disassembly window keyboard shortcuts:"; } KeyHelp *WindowDelegateGetKeyHelp() override { static curses::KeyHelp g_source_view_key_help[] = { {KEY_RETURN, "Run to selected line with one shot breakpoint"}, {KEY_UP, "Select previous source line"}, {KEY_DOWN, "Select next source line"}, {KEY_PPAGE, "Page up"}, {KEY_NPAGE, "Page down"}, {'b', "Set breakpoint on selected source/disassembly line"}, {'c', "Continue process"}, {'d', "Detach and resume process"}, {'D', "Detach with process suspended"}, {'h', "Show help dialog"}, {'k', "Kill process"}, {'n', "Step over (source line)"}, {'N', "Step over (single instruction)"}, {'o', "Step out"}, {'s', "Step in (source line)"}, {'S', "Step in (single instruction)"}, {',', "Page up"}, {'.', "Page down"}, {'\0', nullptr}}; return g_source_view_key_help; } bool WindowDelegateDraw(Window &window, bool force) override { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); Process *process = exe_ctx.GetProcessPtr(); Thread *thread = nullptr; bool update_location = false; if (process) { StateType state = process->GetState(); if (StateIsStoppedState(state, true)) { // We are stopped, so it is ok to update_location = true; } } m_min_x = 1; m_min_y = 2; m_max_x = window.GetMaxX() - 1; m_max_y = window.GetMaxY() - 1; const uint32_t num_visible_lines = NumVisibleLines(); StackFrameSP frame_sp; bool set_selected_line_to_pc = false; if (update_location) { const bool process_alive = process ? process->IsAlive() : false; bool thread_changed = false; if (process_alive) { thread = exe_ctx.GetThreadPtr(); if (thread) { frame_sp = thread->GetSelectedFrame(); auto tid = thread->GetID(); thread_changed = tid != m_tid; m_tid = tid; } else { if (m_tid != LLDB_INVALID_THREAD_ID) { thread_changed = true; m_tid = LLDB_INVALID_THREAD_ID; } } } const uint32_t stop_id = process ? process->GetStopID() : 0; const bool stop_id_changed = stop_id != m_stop_id; bool frame_changed = false; m_stop_id = stop_id; m_title.Clear(); if (frame_sp) { m_sc = frame_sp->GetSymbolContext(eSymbolContextEverything); if (m_sc.module_sp) { m_title.Printf( "%s", m_sc.module_sp->GetFileSpec().GetFilename().GetCString()); ConstString func_name = m_sc.GetFunctionName(); if (func_name) m_title.Printf("`%s", func_name.GetCString()); } const uint32_t frame_idx = frame_sp->GetFrameIndex(); frame_changed = frame_idx != m_frame_idx; m_frame_idx = frame_idx; } else { m_sc.Clear(true); frame_changed = m_frame_idx != UINT32_MAX; m_frame_idx = UINT32_MAX; } const bool context_changed = thread_changed || frame_changed || stop_id_changed; if (process_alive) { if (m_sc.line_entry.IsValid()) { m_pc_line = m_sc.line_entry.line; if (m_pc_line != UINT32_MAX) --m_pc_line; // Convert to zero based line number... // Update the selected line if the stop ID changed... if (context_changed) m_selected_line = m_pc_line; if (m_file_sp && m_file_sp->FileSpecMatches(m_sc.line_entry.file)) { // Same file, nothing to do, we should either have the // lines or not (source file missing) if (m_selected_line >= static_cast<size_t>(m_first_visible_line)) { if (m_selected_line >= m_first_visible_line + num_visible_lines) m_first_visible_line = m_selected_line - 10; } else { if (m_selected_line > 10) m_first_visible_line = m_selected_line - 10; else m_first_visible_line = 0; } } else { // File changed, set selected line to the line with the PC m_selected_line = m_pc_line; m_file_sp = m_debugger.GetSourceManager().GetFile(m_sc.line_entry.file); if (m_file_sp) { const size_t num_lines = m_file_sp->GetNumLines(); int m_line_width = 1; for (size_t n = num_lines; n >= 10; n = n / 10) ++m_line_width; snprintf(m_line_format, sizeof(m_line_format), " %%%iu ", m_line_width); if (num_lines < num_visible_lines || m_selected_line < num_visible_lines) m_first_visible_line = 0; else m_first_visible_line = m_selected_line - 10; } } } else { m_file_sp.reset(); } if (!m_file_sp || m_file_sp->GetNumLines() == 0) { // Show disassembly bool prefer_file_cache = false; if (m_sc.function) { if (m_disassembly_scope != m_sc.function) { m_disassembly_scope = m_sc.function; m_disassembly_sp = m_sc.function->GetInstructions( exe_ctx, nullptr, prefer_file_cache); if (m_disassembly_sp) { set_selected_line_to_pc = true; m_disassembly_range = m_sc.function->GetAddressRange(); } else { m_disassembly_range.Clear(); } } else { set_selected_line_to_pc = context_changed; } } else if (m_sc.symbol) { if (m_disassembly_scope != m_sc.symbol) { m_disassembly_scope = m_sc.symbol; m_disassembly_sp = m_sc.symbol->GetInstructions( exe_ctx, nullptr, prefer_file_cache); if (m_disassembly_sp) { set_selected_line_to_pc = true; m_disassembly_range.GetBaseAddress() = m_sc.symbol->GetAddress(); m_disassembly_range.SetByteSize(m_sc.symbol->GetByteSize()); } else { m_disassembly_range.Clear(); } } else { set_selected_line_to_pc = context_changed; } } } } else { m_pc_line = UINT32_MAX; } } const int window_width = window.GetWidth(); window.Erase(); window.DrawTitleBox("Sources"); if (!m_title.GetString().empty()) { window.AttributeOn(A_REVERSE); window.MoveCursor(1, 1); window.PutChar(' '); window.PutCStringTruncated(m_title.GetString().str().c_str(), 1); int x = window.GetCursorX(); if (x < window_width - 1) { window.Printf("%*s", window_width - x - 1, ""); } window.AttributeOff(A_REVERSE); } Target *target = exe_ctx.GetTargetPtr(); const size_t num_source_lines = GetNumSourceLines(); if (num_source_lines > 0) { // Display source BreakpointLines bp_lines; if (target) { BreakpointList &bp_list = target->GetBreakpointList(); const size_t num_bps = bp_list.GetSize(); for (size_t bp_idx = 0; bp_idx < num_bps; ++bp_idx) { BreakpointSP bp_sp = bp_list.GetBreakpointAtIndex(bp_idx); const size_t num_bps_locs = bp_sp->GetNumLocations(); for (size_t bp_loc_idx = 0; bp_loc_idx < num_bps_locs; ++bp_loc_idx) { BreakpointLocationSP bp_loc_sp = bp_sp->GetLocationAtIndex(bp_loc_idx); LineEntry bp_loc_line_entry; if (bp_loc_sp->GetAddress().CalculateSymbolContextLineEntry( bp_loc_line_entry)) { if (m_file_sp->GetFileSpec() == bp_loc_line_entry.file) { bp_lines.insert(bp_loc_line_entry.line); } } } } } const attr_t selected_highlight_attr = A_REVERSE; const attr_t pc_highlight_attr = COLOR_PAIR(1); for (size_t i = 0; i < num_visible_lines; ++i) { const uint32_t curr_line = m_first_visible_line + i; if (curr_line < num_source_lines) { const int line_y = m_min_y + i; window.MoveCursor(1, line_y); const bool is_pc_line = curr_line == m_pc_line; const bool line_is_selected = m_selected_line == curr_line; // Highlight the line as the PC line first, then if the selected line // isn't the same as the PC line, highlight it differently attr_t highlight_attr = 0; attr_t bp_attr = 0; if (is_pc_line) highlight_attr = pc_highlight_attr; else if (line_is_selected) highlight_attr = selected_highlight_attr; if (bp_lines.find(curr_line + 1) != bp_lines.end()) bp_attr = COLOR_PAIR(2); if (bp_attr) window.AttributeOn(bp_attr); window.Printf(m_line_format, curr_line + 1); if (bp_attr) window.AttributeOff(bp_attr); window.PutChar(ACS_VLINE); // Mark the line with the PC with a diamond if (is_pc_line) window.PutChar(ACS_DIAMOND); else window.PutChar(' '); if (highlight_attr) window.AttributeOn(highlight_attr); const uint32_t line_len = m_file_sp->GetLineLength(curr_line + 1, false); if (line_len > 0) window.PutCString(m_file_sp->PeekLineData(curr_line + 1), line_len); if (is_pc_line && frame_sp && frame_sp->GetConcreteFrameIndex() == 0) { StopInfoSP stop_info_sp; if (thread) stop_info_sp = thread->GetStopInfo(); if (stop_info_sp) { const char *stop_description = stop_info_sp->GetDescription(); if (stop_description && stop_description[0]) { size_t stop_description_len = strlen(stop_description); int desc_x = window_width - stop_description_len - 16; window.Printf("%*s", desc_x - window.GetCursorX(), ""); // window.MoveCursor(window_width - stop_description_len - 15, // line_y); window.Printf("<<< Thread %u: %s ", thread->GetIndexID(), stop_description); } } else { window.Printf("%*s", window_width - window.GetCursorX() - 1, ""); } } if (highlight_attr) window.AttributeOff(highlight_attr); } else { break; } } } else { size_t num_disassembly_lines = GetNumDisassemblyLines(); if (num_disassembly_lines > 0) { // Display disassembly BreakpointAddrs bp_file_addrs; Target *target = exe_ctx.GetTargetPtr(); if (target) { BreakpointList &bp_list = target->GetBreakpointList(); const size_t num_bps = bp_list.GetSize(); for (size_t bp_idx = 0; bp_idx < num_bps; ++bp_idx) { BreakpointSP bp_sp = bp_list.GetBreakpointAtIndex(bp_idx); const size_t num_bps_locs = bp_sp->GetNumLocations(); for (size_t bp_loc_idx = 0; bp_loc_idx < num_bps_locs; ++bp_loc_idx) { BreakpointLocationSP bp_loc_sp = bp_sp->GetLocationAtIndex(bp_loc_idx); LineEntry bp_loc_line_entry; const lldb::addr_t file_addr = bp_loc_sp->GetAddress().GetFileAddress(); if (file_addr != LLDB_INVALID_ADDRESS) { if (m_disassembly_range.ContainsFileAddress(file_addr)) bp_file_addrs.insert(file_addr); } } } } const attr_t selected_highlight_attr = A_REVERSE; const attr_t pc_highlight_attr = COLOR_PAIR(1); StreamString strm; InstructionList &insts = m_disassembly_sp->GetInstructionList(); Address pc_address; if (frame_sp) pc_address = frame_sp->GetFrameCodeAddress(); const uint32_t pc_idx = pc_address.IsValid() ? insts.GetIndexOfInstructionAtAddress(pc_address) : UINT32_MAX; if (set_selected_line_to_pc) { m_selected_line = pc_idx; } const uint32_t non_visible_pc_offset = (num_visible_lines / 5); if (static_cast<size_t>(m_first_visible_line) >= num_disassembly_lines) m_first_visible_line = 0; if (pc_idx < num_disassembly_lines) { if (pc_idx < static_cast<uint32_t>(m_first_visible_line) || pc_idx >= m_first_visible_line + num_visible_lines) m_first_visible_line = pc_idx - non_visible_pc_offset; } for (size_t i = 0; i < num_visible_lines; ++i) { const uint32_t inst_idx = m_first_visible_line + i; Instruction *inst = insts.GetInstructionAtIndex(inst_idx).get(); if (!inst) break; const int line_y = m_min_y + i; window.MoveCursor(1, line_y); const bool is_pc_line = frame_sp && inst_idx == pc_idx; const bool line_is_selected = m_selected_line == inst_idx; // Highlight the line as the PC line first, then if the selected line // isn't the same as the PC line, highlight it differently attr_t highlight_attr = 0; attr_t bp_attr = 0; if (is_pc_line) highlight_attr = pc_highlight_attr; else if (line_is_selected) highlight_attr = selected_highlight_attr; if (bp_file_addrs.find(inst->GetAddress().GetFileAddress()) != bp_file_addrs.end()) bp_attr = COLOR_PAIR(2); if (bp_attr) window.AttributeOn(bp_attr); window.Printf(" 0x%16.16llx ", static_cast<unsigned long long>( inst->GetAddress().GetLoadAddress(target))); if (bp_attr) window.AttributeOff(bp_attr); window.PutChar(ACS_VLINE); // Mark the line with the PC with a diamond if (is_pc_line) window.PutChar(ACS_DIAMOND); else window.PutChar(' '); if (highlight_attr) window.AttributeOn(highlight_attr); const char *mnemonic = inst->GetMnemonic(&exe_ctx); const char *operands = inst->GetOperands(&exe_ctx); const char *comment = inst->GetComment(&exe_ctx); if (mnemonic != nullptr && mnemonic[0] == '\0') mnemonic = nullptr; if (operands != nullptr && operands[0] == '\0') operands = nullptr; if (comment != nullptr && comment[0] == '\0') comment = nullptr; strm.Clear(); if (mnemonic != nullptr && operands != nullptr && comment != nullptr) strm.Printf("%-8s %-25s ; %s", mnemonic, operands, comment); else if (mnemonic != nullptr && operands != nullptr) strm.Printf("%-8s %s", mnemonic, operands); else if (mnemonic != nullptr) strm.Printf("%s", mnemonic); int right_pad = 1; window.PutCStringTruncated(strm.GetData(), right_pad); if (is_pc_line && frame_sp && frame_sp->GetConcreteFrameIndex() == 0) { StopInfoSP stop_info_sp; if (thread) stop_info_sp = thread->GetStopInfo(); if (stop_info_sp) { const char *stop_description = stop_info_sp->GetDescription(); if (stop_description && stop_description[0]) { size_t stop_description_len = strlen(stop_description); int desc_x = window_width - stop_description_len - 16; window.Printf("%*s", desc_x - window.GetCursorX(), ""); // window.MoveCursor(window_width - stop_description_len - 15, // line_y); window.Printf("<<< Thread %u: %s ", thread->GetIndexID(), stop_description); } } else { window.Printf("%*s", window_width - window.GetCursorX() - 1, ""); } } if (highlight_attr) window.AttributeOff(highlight_attr); } } } window.DeferredRefresh(); return true; // Drawing handled } size_t GetNumLines() { size_t num_lines = GetNumSourceLines(); if (num_lines == 0) num_lines = GetNumDisassemblyLines(); return num_lines; } size_t GetNumSourceLines() const { if (m_file_sp) return m_file_sp->GetNumLines(); return 0; } size_t GetNumDisassemblyLines() const { if (m_disassembly_sp) return m_disassembly_sp->GetInstructionList().GetSize(); return 0; } HandleCharResult WindowDelegateHandleChar(Window &window, int c) override { const uint32_t num_visible_lines = NumVisibleLines(); const size_t num_lines = GetNumLines(); switch (c) { case ',': case KEY_PPAGE: // Page up key if (static_cast<uint32_t>(m_first_visible_line) > num_visible_lines) m_first_visible_line -= num_visible_lines; else m_first_visible_line = 0; m_selected_line = m_first_visible_line; return eKeyHandled; case '.': case KEY_NPAGE: // Page down key { if (m_first_visible_line + num_visible_lines < num_lines) m_first_visible_line += num_visible_lines; else if (num_lines < num_visible_lines) m_first_visible_line = 0; else m_first_visible_line = num_lines - num_visible_lines; m_selected_line = m_first_visible_line; } return eKeyHandled; case KEY_UP: if (m_selected_line > 0) { m_selected_line--; if (static_cast<size_t>(m_first_visible_line) > m_selected_line) m_first_visible_line = m_selected_line; } return eKeyHandled; case KEY_DOWN: if (m_selected_line + 1 < num_lines) { m_selected_line++; if (m_first_visible_line + num_visible_lines < m_selected_line) m_first_visible_line++; } return eKeyHandled; case '\r': case '\n': case KEY_ENTER: // Set a breakpoint and run to the line using a one shot breakpoint if (GetNumSourceLines() > 0) { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasProcessScope() && exe_ctx.GetProcessRef().IsAlive()) { BreakpointSP bp_sp = exe_ctx.GetTargetRef().CreateBreakpoint( nullptr, // Don't limit the breakpoint to certain modules m_file_sp->GetFileSpec(), // Source file m_selected_line + 1, // Source line number (m_selected_line is zero based) 0, // No offset eLazyBoolCalculate, // Check inlines using global setting eLazyBoolCalculate, // Skip prologue using global setting, false, // internal false, // request_hardware eLazyBoolCalculate); // move_to_nearest_code // Make breakpoint one shot bp_sp->GetOptions()->SetOneShot(true); exe_ctx.GetProcessRef().Resume(); } } else if (m_selected_line < GetNumDisassemblyLines()) { const Instruction *inst = m_disassembly_sp->GetInstructionList() .GetInstructionAtIndex(m_selected_line) .get(); ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasTargetScope()) { Address addr = inst->GetAddress(); BreakpointSP bp_sp = exe_ctx.GetTargetRef().CreateBreakpoint( addr, // lldb_private::Address false, // internal false); // request_hardware // Make breakpoint one shot bp_sp->GetOptions()->SetOneShot(true); exe_ctx.GetProcessRef().Resume(); } } return eKeyHandled; case 'b': // 'b' == toggle breakpoint on currently selected line if (m_selected_line < GetNumSourceLines()) { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasTargetScope()) { BreakpointSP bp_sp = exe_ctx.GetTargetRef().CreateBreakpoint( nullptr, // Don't limit the breakpoint to certain modules m_file_sp->GetFileSpec(), // Source file m_selected_line + 1, // Source line number (m_selected_line is zero based) 0, // No offset eLazyBoolCalculate, // Check inlines using global setting eLazyBoolCalculate, // Skip prologue using global setting, false, // internal false, // request_hardware eLazyBoolCalculate); // move_to_nearest_code } } else if (m_selected_line < GetNumDisassemblyLines()) { const Instruction *inst = m_disassembly_sp->GetInstructionList() .GetInstructionAtIndex(m_selected_line) .get(); ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasTargetScope()) { Address addr = inst->GetAddress(); BreakpointSP bp_sp = exe_ctx.GetTargetRef().CreateBreakpoint( addr, // lldb_private::Address false, // internal false); // request_hardware } } return eKeyHandled; case 'd': // 'd' == detach and let run case 'D': // 'D' == detach and keep stopped { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasProcessScope()) exe_ctx.GetProcessRef().Detach(c == 'D'); } return eKeyHandled; case 'k': // 'k' == kill { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasProcessScope()) exe_ctx.GetProcessRef().Destroy(false); } return eKeyHandled; case 'c': // 'c' == continue { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasProcessScope()) exe_ctx.GetProcessRef().Resume(); } return eKeyHandled; case 'o': // 'o' == step out { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasThreadScope() && StateIsStoppedState(exe_ctx.GetProcessRef().GetState(), true)) { exe_ctx.GetThreadRef().StepOut(); } } return eKeyHandled; case 'n': // 'n' == step over case 'N': // 'N' == step over instruction { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasThreadScope() && StateIsStoppedState(exe_ctx.GetProcessRef().GetState(), true)) { bool source_step = (c == 'n'); exe_ctx.GetThreadRef().StepOver(source_step); } } return eKeyHandled; case 's': // 's' == step into case 'S': // 'S' == step into instruction { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasThreadScope() && StateIsStoppedState(exe_ctx.GetProcessRef().GetState(), true)) { bool source_step = (c == 's'); exe_ctx.GetThreadRef().StepIn(source_step); } } return eKeyHandled; case 'h': window.CreateHelpSubwindow(); return eKeyHandled; default: break; } return eKeyNotHandled; } protected: typedef std::set<uint32_t> BreakpointLines; typedef std::set<lldb::addr_t> BreakpointAddrs; Debugger &m_debugger; SymbolContext m_sc; SourceManager::FileSP m_file_sp; SymbolContextScope *m_disassembly_scope; lldb::DisassemblerSP m_disassembly_sp; AddressRange m_disassembly_range; StreamString m_title; lldb::user_id_t m_tid; char m_line_format[8]; int m_line_width; uint32_t m_selected_line; // The selected line uint32_t m_pc_line; // The line with the PC uint32_t m_stop_id; uint32_t m_frame_idx; int m_first_visible_line; int m_min_x; int m_min_y; int m_max_x; int m_max_y; }; DisplayOptions ValueObjectListDelegate::g_options = {true}; IOHandlerCursesGUI::IOHandlerCursesGUI(Debugger &debugger) : IOHandler(debugger, IOHandler::Type::Curses) {} void IOHandlerCursesGUI::Activate() { IOHandler::Activate(); if (!m_app_ap) { m_app_ap.reset(new Application(GetInputFILE(), GetOutputFILE())); // This is both a window and a menu delegate std::shared_ptr<ApplicationDelegate> app_delegate_sp( new ApplicationDelegate(*m_app_ap, m_debugger)); MenuDelegateSP app_menu_delegate_sp = std::static_pointer_cast<MenuDelegate>(app_delegate_sp); MenuSP lldb_menu_sp( new Menu("LLDB", "F1", KEY_F(1), ApplicationDelegate::eMenuID_LLDB)); MenuSP exit_menuitem_sp( new Menu("Exit", nullptr, 'x', ApplicationDelegate::eMenuID_LLDBExit)); exit_menuitem_sp->SetCannedResult(MenuActionResult::Quit); lldb_menu_sp->AddSubmenu(MenuSP(new Menu( "About LLDB", nullptr, 'a', ApplicationDelegate::eMenuID_LLDBAbout))); lldb_menu_sp->AddSubmenu(MenuSP(new Menu(Menu::Type::Separator))); lldb_menu_sp->AddSubmenu(exit_menuitem_sp); MenuSP target_menu_sp(new Menu("Target", "F2", KEY_F(2), ApplicationDelegate::eMenuID_Target)); target_menu_sp->AddSubmenu(MenuSP(new Menu( "Create", nullptr, 'c', ApplicationDelegate::eMenuID_TargetCreate))); target_menu_sp->AddSubmenu(MenuSP(new Menu( "Delete", nullptr, 'd', ApplicationDelegate::eMenuID_TargetDelete))); MenuSP process_menu_sp(new Menu("Process", "F3", KEY_F(3), ApplicationDelegate::eMenuID_Process)); process_menu_sp->AddSubmenu(MenuSP(new Menu( "Attach", nullptr, 'a', ApplicationDelegate::eMenuID_ProcessAttach))); process_menu_sp->AddSubmenu(MenuSP(new Menu( "Detach", nullptr, 'd', ApplicationDelegate::eMenuID_ProcessDetach))); process_menu_sp->AddSubmenu(MenuSP(new Menu( "Launch", nullptr, 'l', ApplicationDelegate::eMenuID_ProcessLaunch))); process_menu_sp->AddSubmenu(MenuSP(new Menu(Menu::Type::Separator))); process_menu_sp->AddSubmenu( MenuSP(new Menu("Continue", nullptr, 'c', ApplicationDelegate::eMenuID_ProcessContinue))); process_menu_sp->AddSubmenu(MenuSP(new Menu( "Halt", nullptr, 'h', ApplicationDelegate::eMenuID_ProcessHalt))); process_menu_sp->AddSubmenu(MenuSP(new Menu( "Kill", nullptr, 'k', ApplicationDelegate::eMenuID_ProcessKill))); MenuSP thread_menu_sp(new Menu("Thread", "F4", KEY_F(4), ApplicationDelegate::eMenuID_Thread)); thread_menu_sp->AddSubmenu(MenuSP(new Menu( "Step In", nullptr, 'i', ApplicationDelegate::eMenuID_ThreadStepIn))); thread_menu_sp->AddSubmenu( MenuSP(new Menu("Step Over", nullptr, 'v', ApplicationDelegate::eMenuID_ThreadStepOver))); thread_menu_sp->AddSubmenu(MenuSP(new Menu( "Step Out", nullptr, 'o', ApplicationDelegate::eMenuID_ThreadStepOut))); MenuSP view_menu_sp( new Menu("View", "F5", KEY_F(5), ApplicationDelegate::eMenuID_View)); view_menu_sp->AddSubmenu( MenuSP(new Menu("Backtrace", nullptr, 'b', ApplicationDelegate::eMenuID_ViewBacktrace))); view_menu_sp->AddSubmenu( MenuSP(new Menu("Registers", nullptr, 'r', ApplicationDelegate::eMenuID_ViewRegisters))); view_menu_sp->AddSubmenu(MenuSP(new Menu( "Source", nullptr, 's', ApplicationDelegate::eMenuID_ViewSource))); view_menu_sp->AddSubmenu( MenuSP(new Menu("Variables", nullptr, 'v', ApplicationDelegate::eMenuID_ViewVariables))); MenuSP help_menu_sp( new Menu("Help", "F6", KEY_F(6), ApplicationDelegate::eMenuID_Help)); help_menu_sp->AddSubmenu(MenuSP(new Menu( "GUI Help", nullptr, 'g', ApplicationDelegate::eMenuID_HelpGUIHelp))); m_app_ap->Initialize(); WindowSP &main_window_sp = m_app_ap->GetMainWindow(); MenuSP menubar_sp(new Menu(Menu::Type::Bar)); menubar_sp->AddSubmenu(lldb_menu_sp); menubar_sp->AddSubmenu(target_menu_sp); menubar_sp->AddSubmenu(process_menu_sp); menubar_sp->AddSubmenu(thread_menu_sp); menubar_sp->AddSubmenu(view_menu_sp); menubar_sp->AddSubmenu(help_menu_sp); menubar_sp->SetDelegate(app_menu_delegate_sp); Rect content_bounds = main_window_sp->GetFrame(); Rect menubar_bounds = content_bounds.MakeMenuBar(); Rect status_bounds = content_bounds.MakeStatusBar(); Rect source_bounds; Rect variables_bounds; Rect threads_bounds; Rect source_variables_bounds; content_bounds.VerticalSplitPercentage(0.80, source_variables_bounds, threads_bounds); source_variables_bounds.HorizontalSplitPercentage(0.70, source_bounds, variables_bounds); WindowSP menubar_window_sp = main_window_sp->CreateSubWindow("Menubar", menubar_bounds, false); // Let the menubar get keys if the active window doesn't handle the // keys that are typed so it can respond to menubar key presses. menubar_window_sp->SetCanBeActive( false); // Don't let the menubar become the active window menubar_window_sp->SetDelegate(menubar_sp); WindowSP source_window_sp( main_window_sp->CreateSubWindow("Source", source_bounds, true)); WindowSP variables_window_sp( main_window_sp->CreateSubWindow("Variables", variables_bounds, false)); WindowSP threads_window_sp( main_window_sp->CreateSubWindow("Threads", threads_bounds, false)); WindowSP status_window_sp( main_window_sp->CreateSubWindow("Error", status_bounds, false)); status_window_sp->SetCanBeActive( false); // Don't let the status bar become the active window main_window_sp->SetDelegate( std::static_pointer_cast<WindowDelegate>(app_delegate_sp)); source_window_sp->SetDelegate( WindowDelegateSP(new SourceFileWindowDelegate(m_debugger))); variables_window_sp->SetDelegate( WindowDelegateSP(new FrameVariablesWindowDelegate(m_debugger))); TreeDelegateSP thread_delegate_sp(new ThreadsTreeDelegate(m_debugger)); threads_window_sp->SetDelegate(WindowDelegateSP( new TreeWindowDelegate(m_debugger, thread_delegate_sp))); status_window_sp->SetDelegate( WindowDelegateSP(new StatusBarWindowDelegate(m_debugger))); // Show the main help window once the first time the curses GUI is launched static bool g_showed_help = false; if (!g_showed_help) { g_showed_help = true; main_window_sp->CreateHelpSubwindow(); } init_pair(1, COLOR_WHITE, COLOR_BLUE); init_pair(2, COLOR_BLACK, COLOR_WHITE); init_pair(3, COLOR_MAGENTA, COLOR_WHITE); init_pair(4, COLOR_MAGENTA, COLOR_BLACK); init_pair(5, COLOR_RED, COLOR_BLACK); } } void IOHandlerCursesGUI::Deactivate() { m_app_ap->Terminate(); } void IOHandlerCursesGUI::Run() { m_app_ap->Run(m_debugger); SetIsDone(true); } IOHandlerCursesGUI::~IOHandlerCursesGUI() = default; void IOHandlerCursesGUI::Cancel() {} bool IOHandlerCursesGUI::Interrupt() { return false; } void IOHandlerCursesGUI::GotEOF() {} #endif // LLDB_DISABLE_CURSES Fix incorrect Status -> Error rename in IOHandler Change 302872 was a massive rename of the Error class to Status. The change included an incorrect rename of the "Status" window in the LLDB GUI from "Status to "Error". This patch undoes this incorrect rename and restores the status window's correct name. Differential Revision: https://reviews.llvm.org/D33241 Patch by Brian Gianforcaro. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@303553 91177308-0d34-0410-b5e6-96231b3b80d8 //===-- IOHandler.cpp -------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Core/IOHandler.h" // C Includes #ifndef LLDB_DISABLE_CURSES #include <curses.h> #include <panel.h> #endif // C++ Includes #if defined(__APPLE__) #include <deque> #endif #include <string> // Other libraries and framework includes // Project includes #include "lldb/Core/Debugger.h" #include "lldb/Core/StreamFile.h" #include "lldb/Host/File.h" // for File #include "lldb/Host/Predicate.h" // for Predicate, ::eBroad... #include "lldb/Utility/Status.h" // for Status #include "lldb/Utility/StreamString.h" // for StreamString #include "lldb/Utility/StringList.h" // for StringList #include "lldb/lldb-forward.h" // for StreamFileSP #ifndef LLDB_DISABLE_LIBEDIT #include "lldb/Host/Editline.h" #endif #include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Interpreter/CommandInterpreter.h" #ifndef LLDB_DISABLE_CURSES #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Core/Module.h" #include "lldb/Core/State.h" #include "lldb/Core/ValueObject.h" #include "lldb/Core/ValueObjectRegister.h" #include "lldb/Symbol/Block.h" #include "lldb/Symbol/Function.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Symbol/VariableList.h" #include "lldb/Target/Process.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/StackFrame.h" #include "lldb/Target/StopInfo.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #endif #include "llvm/ADT/StringRef.h" // for StringRef #ifdef _MSC_VER #include <windows.h> #endif #include <memory> // for shared_ptr #include <mutex> // for recursive_mutex #include <assert.h> // for assert #include <ctype.h> // for isspace #include <errno.h> // for EINTR, errno #include <stdint.h> // for uint32_t, UINT32_MAX #include <stdio.h> // for size_t, fprintf, feof #include <string.h> // for strlen #include <type_traits> // for move using namespace lldb; using namespace lldb_private; IOHandler::IOHandler(Debugger &debugger, IOHandler::Type type) : IOHandler(debugger, type, StreamFileSP(), // Adopt STDIN from top input reader StreamFileSP(), // Adopt STDOUT from top input reader StreamFileSP(), // Adopt STDERR from top input reader 0) // Flags {} IOHandler::IOHandler(Debugger &debugger, IOHandler::Type type, const lldb::StreamFileSP &input_sp, const lldb::StreamFileSP &output_sp, const lldb::StreamFileSP &error_sp, uint32_t flags) : m_debugger(debugger), m_input_sp(input_sp), m_output_sp(output_sp), m_error_sp(error_sp), m_popped(false), m_flags(flags), m_type(type), m_user_data(nullptr), m_done(false), m_active(false) { // If any files are not specified, then adopt them from the top input reader. if (!m_input_sp || !m_output_sp || !m_error_sp) debugger.AdoptTopIOHandlerFilesIfInvalid(m_input_sp, m_output_sp, m_error_sp); } IOHandler::~IOHandler() = default; int IOHandler::GetInputFD() { return (m_input_sp ? m_input_sp->GetFile().GetDescriptor() : -1); } int IOHandler::GetOutputFD() { return (m_output_sp ? m_output_sp->GetFile().GetDescriptor() : -1); } int IOHandler::GetErrorFD() { return (m_error_sp ? m_error_sp->GetFile().GetDescriptor() : -1); } FILE *IOHandler::GetInputFILE() { return (m_input_sp ? m_input_sp->GetFile().GetStream() : nullptr); } FILE *IOHandler::GetOutputFILE() { return (m_output_sp ? m_output_sp->GetFile().GetStream() : nullptr); } FILE *IOHandler::GetErrorFILE() { return (m_error_sp ? m_error_sp->GetFile().GetStream() : nullptr); } StreamFileSP &IOHandler::GetInputStreamFile() { return m_input_sp; } StreamFileSP &IOHandler::GetOutputStreamFile() { return m_output_sp; } StreamFileSP &IOHandler::GetErrorStreamFile() { return m_error_sp; } bool IOHandler::GetIsInteractive() { return GetInputStreamFile()->GetFile().GetIsInteractive(); } bool IOHandler::GetIsRealTerminal() { return GetInputStreamFile()->GetFile().GetIsRealTerminal(); } void IOHandler::SetPopped(bool b) { m_popped.SetValue(b, eBroadcastOnChange); } void IOHandler::WaitForPop() { m_popped.WaitForValueEqualTo(true); } void IOHandlerStack::PrintAsync(Stream *stream, const char *s, size_t len) { if (stream) { std::lock_guard<std::recursive_mutex> guard(m_mutex); if (m_top) m_top->PrintAsync(stream, s, len); } } IOHandlerConfirm::IOHandlerConfirm(Debugger &debugger, llvm::StringRef prompt, bool default_response) : IOHandlerEditline( debugger, IOHandler::Type::Confirm, nullptr, // nullptr editline_name means no history loaded/saved llvm::StringRef(), // No prompt llvm::StringRef(), // No continuation prompt false, // Multi-line false, // Don't colorize the prompt (i.e. the confirm message.) 0, *this), m_default_response(default_response), m_user_response(default_response) { StreamString prompt_stream; prompt_stream.PutCString(prompt); if (m_default_response) prompt_stream.Printf(": [Y/n] "); else prompt_stream.Printf(": [y/N] "); SetPrompt(prompt_stream.GetString()); } IOHandlerConfirm::~IOHandlerConfirm() = default; int IOHandlerConfirm::IOHandlerComplete(IOHandler &io_handler, const char *current_line, const char *cursor, const char *last_char, int skip_first_n_matches, int max_matches, StringList &matches) { if (current_line == cursor) { if (m_default_response) { matches.AppendString("y"); } else { matches.AppendString("n"); } } return matches.GetSize(); } void IOHandlerConfirm::IOHandlerInputComplete(IOHandler &io_handler, std::string &line) { if (line.empty()) { // User just hit enter, set the response to the default m_user_response = m_default_response; io_handler.SetIsDone(true); return; } if (line.size() == 1) { switch (line[0]) { case 'y': case 'Y': m_user_response = true; io_handler.SetIsDone(true); return; case 'n': case 'N': m_user_response = false; io_handler.SetIsDone(true); return; default: break; } } if (line == "yes" || line == "YES" || line == "Yes") { m_user_response = true; io_handler.SetIsDone(true); } else if (line == "no" || line == "NO" || line == "No") { m_user_response = false; io_handler.SetIsDone(true); } } int IOHandlerDelegate::IOHandlerComplete(IOHandler &io_handler, const char *current_line, const char *cursor, const char *last_char, int skip_first_n_matches, int max_matches, StringList &matches) { switch (m_completion) { case Completion::None: break; case Completion::LLDBCommand: return io_handler.GetDebugger().GetCommandInterpreter().HandleCompletion( current_line, cursor, last_char, skip_first_n_matches, max_matches, matches); case Completion::Expression: { bool word_complete = false; const char *word_start = cursor; if (cursor > current_line) --word_start; while (word_start > current_line && !isspace(*word_start)) --word_start; CommandCompletions::InvokeCommonCompletionCallbacks( io_handler.GetDebugger().GetCommandInterpreter(), CommandCompletions::eVariablePathCompletion, word_start, skip_first_n_matches, max_matches, nullptr, word_complete, matches); size_t num_matches = matches.GetSize(); if (num_matches > 0) { std::string common_prefix; matches.LongestCommonPrefix(common_prefix); const size_t partial_name_len = strlen(word_start); // If we matched a unique single command, add a space... // Only do this if the completer told us this was a complete word, // however... if (num_matches == 1 && word_complete) { common_prefix.push_back(' '); } common_prefix.erase(0, partial_name_len); matches.InsertStringAtIndex(0, std::move(common_prefix)); } return num_matches; } break; } return 0; } IOHandlerEditline::IOHandlerEditline( Debugger &debugger, IOHandler::Type type, const char *editline_name, // Used for saving history files llvm::StringRef prompt, llvm::StringRef continuation_prompt, bool multi_line, bool color_prompts, uint32_t line_number_start, IOHandlerDelegate &delegate) : IOHandlerEditline(debugger, type, StreamFileSP(), // Inherit input from top input reader StreamFileSP(), // Inherit output from top input reader StreamFileSP(), // Inherit error from top input reader 0, // Flags editline_name, // Used for saving history files prompt, continuation_prompt, multi_line, color_prompts, line_number_start, delegate) {} IOHandlerEditline::IOHandlerEditline( Debugger &debugger, IOHandler::Type type, const lldb::StreamFileSP &input_sp, const lldb::StreamFileSP &output_sp, const lldb::StreamFileSP &error_sp, uint32_t flags, const char *editline_name, // Used for saving history files llvm::StringRef prompt, llvm::StringRef continuation_prompt, bool multi_line, bool color_prompts, uint32_t line_number_start, IOHandlerDelegate &delegate) : IOHandler(debugger, type, input_sp, output_sp, error_sp, flags), #ifndef LLDB_DISABLE_LIBEDIT m_editline_ap(), #endif m_delegate(delegate), m_prompt(), m_continuation_prompt(), m_current_lines_ptr(nullptr), m_base_line_number(line_number_start), m_curr_line_idx(UINT32_MAX), m_multi_line(multi_line), m_color_prompts(color_prompts), m_interrupt_exits(true), m_editing(false) { SetPrompt(prompt); #ifndef LLDB_DISABLE_LIBEDIT bool use_editline = false; use_editline = m_input_sp->GetFile().GetIsRealTerminal(); if (use_editline) { m_editline_ap.reset(new Editline(editline_name, GetInputFILE(), GetOutputFILE(), GetErrorFILE(), m_color_prompts)); m_editline_ap->SetIsInputCompleteCallback(IsInputCompleteCallback, this); m_editline_ap->SetAutoCompleteCallback(AutoCompleteCallback, this); // See if the delegate supports fixing indentation const char *indent_chars = delegate.IOHandlerGetFixIndentationCharacters(); if (indent_chars) { // The delegate does support indentation, hook it up so when any // indentation // character is typed, the delegate gets a chance to fix it m_editline_ap->SetFixIndentationCallback(FixIndentationCallback, this, indent_chars); } } #endif SetBaseLineNumber(m_base_line_number); SetPrompt(prompt); SetContinuationPrompt(continuation_prompt); } IOHandlerEditline::~IOHandlerEditline() { #ifndef LLDB_DISABLE_LIBEDIT m_editline_ap.reset(); #endif } void IOHandlerEditline::Activate() { IOHandler::Activate(); m_delegate.IOHandlerActivated(*this); } void IOHandlerEditline::Deactivate() { IOHandler::Deactivate(); m_delegate.IOHandlerDeactivated(*this); } bool IOHandlerEditline::GetLine(std::string &line, bool &interrupted) { #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) { return m_editline_ap->GetLine(line, interrupted); } else { #endif line.clear(); FILE *in = GetInputFILE(); if (in) { if (GetIsInteractive()) { const char *prompt = nullptr; if (m_multi_line && m_curr_line_idx > 0) prompt = GetContinuationPrompt(); if (prompt == nullptr) prompt = GetPrompt(); if (prompt && prompt[0]) { FILE *out = GetOutputFILE(); if (out) { ::fprintf(out, "%s", prompt); ::fflush(out); } } } char buffer[256]; bool done = false; bool got_line = false; m_editing = true; while (!done) { if (fgets(buffer, sizeof(buffer), in) == nullptr) { const int saved_errno = errno; if (feof(in)) done = true; else if (ferror(in)) { if (saved_errno != EINTR) done = true; } } else { got_line = true; size_t buffer_len = strlen(buffer); assert(buffer[buffer_len] == '\0'); char last_char = buffer[buffer_len - 1]; if (last_char == '\r' || last_char == '\n') { done = true; // Strip trailing newlines while (last_char == '\r' || last_char == '\n') { --buffer_len; if (buffer_len == 0) break; last_char = buffer[buffer_len - 1]; } } line.append(buffer, buffer_len); } } m_editing = false; // We might have gotten a newline on a line by itself // make sure to return true in this case. return got_line; } else { // No more input file, we are done... SetIsDone(true); } return false; #ifndef LLDB_DISABLE_LIBEDIT } #endif } #ifndef LLDB_DISABLE_LIBEDIT bool IOHandlerEditline::IsInputCompleteCallback(Editline *editline, StringList &lines, void *baton) { IOHandlerEditline *editline_reader = (IOHandlerEditline *)baton; return editline_reader->m_delegate.IOHandlerIsInputComplete(*editline_reader, lines); } int IOHandlerEditline::FixIndentationCallback(Editline *editline, const StringList &lines, int cursor_position, void *baton) { IOHandlerEditline *editline_reader = (IOHandlerEditline *)baton; return editline_reader->m_delegate.IOHandlerFixIndentation( *editline_reader, lines, cursor_position); } int IOHandlerEditline::AutoCompleteCallback(const char *current_line, const char *cursor, const char *last_char, int skip_first_n_matches, int max_matches, StringList &matches, void *baton) { IOHandlerEditline *editline_reader = (IOHandlerEditline *)baton; if (editline_reader) return editline_reader->m_delegate.IOHandlerComplete( *editline_reader, current_line, cursor, last_char, skip_first_n_matches, max_matches, matches); return 0; } #endif const char *IOHandlerEditline::GetPrompt() { #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) { return m_editline_ap->GetPrompt(); } else { #endif if (m_prompt.empty()) return nullptr; #ifndef LLDB_DISABLE_LIBEDIT } #endif return m_prompt.c_str(); } bool IOHandlerEditline::SetPrompt(llvm::StringRef prompt) { m_prompt = prompt; #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) m_editline_ap->SetPrompt(m_prompt.empty() ? nullptr : m_prompt.c_str()); #endif return true; } const char *IOHandlerEditline::GetContinuationPrompt() { return (m_continuation_prompt.empty() ? nullptr : m_continuation_prompt.c_str()); } void IOHandlerEditline::SetContinuationPrompt(llvm::StringRef prompt) { m_continuation_prompt = prompt; #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) m_editline_ap->SetContinuationPrompt(m_continuation_prompt.empty() ? nullptr : m_continuation_prompt.c_str()); #endif } void IOHandlerEditline::SetBaseLineNumber(uint32_t line) { m_base_line_number = line; } uint32_t IOHandlerEditline::GetCurrentLineIndex() const { #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) return m_editline_ap->GetCurrentLine(); #endif return m_curr_line_idx; } bool IOHandlerEditline::GetLines(StringList &lines, bool &interrupted) { m_current_lines_ptr = &lines; bool success = false; #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) { return m_editline_ap->GetLines(m_base_line_number, lines, interrupted); } else { #endif bool done = false; Status error; while (!done) { // Show line numbers if we are asked to std::string line; if (m_base_line_number > 0 && GetIsInteractive()) { FILE *out = GetOutputFILE(); if (out) ::fprintf(out, "%u%s", m_base_line_number + (uint32_t)lines.GetSize(), GetPrompt() == nullptr ? " " : ""); } m_curr_line_idx = lines.GetSize(); bool interrupted = false; if (GetLine(line, interrupted) && !interrupted) { lines.AppendString(line); done = m_delegate.IOHandlerIsInputComplete(*this, lines); } else { done = true; } } success = lines.GetSize() > 0; #ifndef LLDB_DISABLE_LIBEDIT } #endif return success; } // Each IOHandler gets to run until it is done. It should read data // from the "in" and place output into "out" and "err and return // when done. void IOHandlerEditline::Run() { std::string line; while (IsActive()) { bool interrupted = false; if (m_multi_line) { StringList lines; if (GetLines(lines, interrupted)) { if (interrupted) { m_done = m_interrupt_exits; m_delegate.IOHandlerInputInterrupted(*this, line); } else { line = lines.CopyList(); m_delegate.IOHandlerInputComplete(*this, line); } } else { m_done = true; } } else { if (GetLine(line, interrupted)) { if (interrupted) m_delegate.IOHandlerInputInterrupted(*this, line); else m_delegate.IOHandlerInputComplete(*this, line); } else { m_done = true; } } } } void IOHandlerEditline::Cancel() { #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) m_editline_ap->Cancel(); #endif } bool IOHandlerEditline::Interrupt() { // Let the delgate handle it first if (m_delegate.IOHandlerInterrupt(*this)) return true; #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) return m_editline_ap->Interrupt(); #endif return false; } void IOHandlerEditline::GotEOF() { #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) m_editline_ap->Interrupt(); #endif } void IOHandlerEditline::PrintAsync(Stream *stream, const char *s, size_t len) { #ifndef LLDB_DISABLE_LIBEDIT if (m_editline_ap) m_editline_ap->PrintAsync(stream, s, len); else #endif { #ifdef _MSC_VER const char *prompt = GetPrompt(); if (prompt) { // Back up over previous prompt using Windows API CONSOLE_SCREEN_BUFFER_INFO screen_buffer_info; HANDLE console_handle = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfo(console_handle, &screen_buffer_info); COORD coord = screen_buffer_info.dwCursorPosition; coord.X -= strlen(prompt); if (coord.X < 0) coord.X = 0; SetConsoleCursorPosition(console_handle, coord); } #endif IOHandler::PrintAsync(stream, s, len); #ifdef _MSC_VER if (prompt) IOHandler::PrintAsync(GetOutputStreamFile().get(), prompt, strlen(prompt)); #endif } } // we may want curses to be disabled for some builds // for instance, windows #ifndef LLDB_DISABLE_CURSES #define KEY_RETURN 10 #define KEY_ESCAPE 27 namespace curses { class Menu; class MenuDelegate; class Window; class WindowDelegate; typedef std::shared_ptr<Menu> MenuSP; typedef std::shared_ptr<MenuDelegate> MenuDelegateSP; typedef std::shared_ptr<Window> WindowSP; typedef std::shared_ptr<WindowDelegate> WindowDelegateSP; typedef std::vector<MenuSP> Menus; typedef std::vector<WindowSP> Windows; typedef std::vector<WindowDelegateSP> WindowDelegates; #if 0 type summary add -s "x=${var.x}, y=${var.y}" curses::Point type summary add -s "w=${var.width}, h=${var.height}" curses::Size type summary add -s "${var.origin%S} ${var.size%S}" curses::Rect #endif struct Point { int x; int y; Point(int _x = 0, int _y = 0) : x(_x), y(_y) {} void Clear() { x = 0; y = 0; } Point &operator+=(const Point &rhs) { x += rhs.x; y += rhs.y; return *this; } void Dump() { printf("(x=%i, y=%i)\n", x, y); } }; bool operator==(const Point &lhs, const Point &rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } bool operator!=(const Point &lhs, const Point &rhs) { return lhs.x != rhs.x || lhs.y != rhs.y; } struct Size { int width; int height; Size(int w = 0, int h = 0) : width(w), height(h) {} void Clear() { width = 0; height = 0; } void Dump() { printf("(w=%i, h=%i)\n", width, height); } }; bool operator==(const Size &lhs, const Size &rhs) { return lhs.width == rhs.width && lhs.height == rhs.height; } bool operator!=(const Size &lhs, const Size &rhs) { return lhs.width != rhs.width || lhs.height != rhs.height; } struct Rect { Point origin; Size size; Rect() : origin(), size() {} Rect(const Point &p, const Size &s) : origin(p), size(s) {} void Clear() { origin.Clear(); size.Clear(); } void Dump() { printf("(x=%i, y=%i), w=%i, h=%i)\n", origin.x, origin.y, size.width, size.height); } void Inset(int w, int h) { if (size.width > w * 2) size.width -= w * 2; origin.x += w; if (size.height > h * 2) size.height -= h * 2; origin.y += h; } // Return a status bar rectangle which is the last line of // this rectangle. This rectangle will be modified to not // include the status bar area. Rect MakeStatusBar() { Rect status_bar; if (size.height > 1) { status_bar.origin.x = origin.x; status_bar.origin.y = size.height; status_bar.size.width = size.width; status_bar.size.height = 1; --size.height; } return status_bar; } // Return a menubar rectangle which is the first line of // this rectangle. This rectangle will be modified to not // include the menubar area. Rect MakeMenuBar() { Rect menubar; if (size.height > 1) { menubar.origin.x = origin.x; menubar.origin.y = origin.y; menubar.size.width = size.width; menubar.size.height = 1; ++origin.y; --size.height; } return menubar; } void HorizontalSplitPercentage(float top_percentage, Rect &top, Rect &bottom) const { float top_height = top_percentage * size.height; HorizontalSplit(top_height, top, bottom); } void HorizontalSplit(int top_height, Rect &top, Rect &bottom) const { top = *this; if (top_height < size.height) { top.size.height = top_height; bottom.origin.x = origin.x; bottom.origin.y = origin.y + top.size.height; bottom.size.width = size.width; bottom.size.height = size.height - top.size.height; } else { bottom.Clear(); } } void VerticalSplitPercentage(float left_percentage, Rect &left, Rect &right) const { float left_width = left_percentage * size.width; VerticalSplit(left_width, left, right); } void VerticalSplit(int left_width, Rect &left, Rect &right) const { left = *this; if (left_width < size.width) { left.size.width = left_width; right.origin.x = origin.x + left.size.width; right.origin.y = origin.y; right.size.width = size.width - left.size.width; right.size.height = size.height; } else { right.Clear(); } } }; bool operator==(const Rect &lhs, const Rect &rhs) { return lhs.origin == rhs.origin && lhs.size == rhs.size; } bool operator!=(const Rect &lhs, const Rect &rhs) { return lhs.origin != rhs.origin || lhs.size != rhs.size; } enum HandleCharResult { eKeyNotHandled = 0, eKeyHandled = 1, eQuitApplication = 2 }; enum class MenuActionResult { Handled, NotHandled, Quit // Exit all menus and quit }; struct KeyHelp { int ch; const char *description; }; class WindowDelegate { public: virtual ~WindowDelegate() = default; virtual bool WindowDelegateDraw(Window &window, bool force) { return false; // Drawing not handled } virtual HandleCharResult WindowDelegateHandleChar(Window &window, int key) { return eKeyNotHandled; } virtual const char *WindowDelegateGetHelpText() { return nullptr; } virtual KeyHelp *WindowDelegateGetKeyHelp() { return nullptr; } }; class HelpDialogDelegate : public WindowDelegate { public: HelpDialogDelegate(const char *text, KeyHelp *key_help_array); ~HelpDialogDelegate() override; bool WindowDelegateDraw(Window &window, bool force) override; HandleCharResult WindowDelegateHandleChar(Window &window, int key) override; size_t GetNumLines() const { return m_text.GetSize(); } size_t GetMaxLineLength() const { return m_text.GetMaxStringLength(); } protected: StringList m_text; int m_first_visible_line; }; class Window { public: Window(const char *name) : m_name(name), m_window(nullptr), m_panel(nullptr), m_parent(nullptr), m_subwindows(), m_delegate_sp(), m_curr_active_window_idx(UINT32_MAX), m_prev_active_window_idx(UINT32_MAX), m_delete(false), m_needs_update(true), m_can_activate(true), m_is_subwin(false) {} Window(const char *name, WINDOW *w, bool del = true) : m_name(name), m_window(nullptr), m_panel(nullptr), m_parent(nullptr), m_subwindows(), m_delegate_sp(), m_curr_active_window_idx(UINT32_MAX), m_prev_active_window_idx(UINT32_MAX), m_delete(del), m_needs_update(true), m_can_activate(true), m_is_subwin(false) { if (w) Reset(w); } Window(const char *name, const Rect &bounds) : m_name(name), m_window(nullptr), m_parent(nullptr), m_subwindows(), m_delegate_sp(), m_curr_active_window_idx(UINT32_MAX), m_prev_active_window_idx(UINT32_MAX), m_delete(true), m_needs_update(true), m_can_activate(true), m_is_subwin(false) { Reset(::newwin(bounds.size.height, bounds.size.width, bounds.origin.y, bounds.origin.y)); } virtual ~Window() { RemoveSubWindows(); Reset(); } void Reset(WINDOW *w = nullptr, bool del = true) { if (m_window == w) return; if (m_panel) { ::del_panel(m_panel); m_panel = nullptr; } if (m_window && m_delete) { ::delwin(m_window); m_window = nullptr; m_delete = false; } if (w) { m_window = w; m_panel = ::new_panel(m_window); m_delete = del; } } void AttributeOn(attr_t attr) { ::wattron(m_window, attr); } void AttributeOff(attr_t attr) { ::wattroff(m_window, attr); } void Box(chtype v_char = ACS_VLINE, chtype h_char = ACS_HLINE) { ::box(m_window, v_char, h_char); } void Clear() { ::wclear(m_window); } void Erase() { ::werase(m_window); } Rect GetBounds() { return Rect(GetParentOrigin(), GetSize()); } // Get the rectangle in our parent window int GetChar() { return ::wgetch(m_window); } int GetCursorX() { return getcurx(m_window); } int GetCursorY() { return getcury(m_window); } Rect GetFrame() { return Rect(Point(), GetSize()); } // Get our rectangle in our own coordinate system Point GetParentOrigin() { return Point(GetParentX(), GetParentY()); } Size GetSize() { return Size(GetWidth(), GetHeight()); } int GetParentX() { return getparx(m_window); } int GetParentY() { return getpary(m_window); } int GetMaxX() { return getmaxx(m_window); } int GetMaxY() { return getmaxy(m_window); } int GetWidth() { return GetMaxX(); } int GetHeight() { return GetMaxY(); } void MoveCursor(int x, int y) { ::wmove(m_window, y, x); } void MoveWindow(int x, int y) { MoveWindow(Point(x, y)); } void Resize(int w, int h) { ::wresize(m_window, h, w); } void Resize(const Size &size) { ::wresize(m_window, size.height, size.width); } void PutChar(int ch) { ::waddch(m_window, ch); } void PutCString(const char *s, int len = -1) { ::waddnstr(m_window, s, len); } void Refresh() { ::wrefresh(m_window); } void DeferredRefresh() { // We are using panels, so we don't need to call this... //::wnoutrefresh(m_window); } void SetBackground(int color_pair_idx) { ::wbkgd(m_window, COLOR_PAIR(color_pair_idx)); } void UnderlineOn() { AttributeOn(A_UNDERLINE); } void UnderlineOff() { AttributeOff(A_UNDERLINE); } void PutCStringTruncated(const char *s, int right_pad) { int bytes_left = GetWidth() - GetCursorX(); if (bytes_left > right_pad) { bytes_left -= right_pad; ::waddnstr(m_window, s, bytes_left); } } void MoveWindow(const Point &origin) { const bool moving_window = origin != GetParentOrigin(); if (m_is_subwin && moving_window) { // Can't move subwindows, must delete and re-create Size size = GetSize(); Reset(::subwin(m_parent->m_window, size.height, size.width, origin.y, origin.x), true); } else { ::mvwin(m_window, origin.y, origin.x); } } void SetBounds(const Rect &bounds) { const bool moving_window = bounds.origin != GetParentOrigin(); if (m_is_subwin && moving_window) { // Can't move subwindows, must delete and re-create Reset(::subwin(m_parent->m_window, bounds.size.height, bounds.size.width, bounds.origin.y, bounds.origin.x), true); } else { if (moving_window) MoveWindow(bounds.origin); Resize(bounds.size); } } void Printf(const char *format, ...) __attribute__((format(printf, 2, 3))) { va_list args; va_start(args, format); vwprintw(m_window, format, args); va_end(args); } void Touch() { ::touchwin(m_window); if (m_parent) m_parent->Touch(); } WindowSP CreateSubWindow(const char *name, const Rect &bounds, bool make_active) { WindowSP subwindow_sp; if (m_window) { subwindow_sp.reset(new Window( name, ::subwin(m_window, bounds.size.height, bounds.size.width, bounds.origin.y, bounds.origin.x), true)); subwindow_sp->m_is_subwin = true; } else { subwindow_sp.reset( new Window(name, ::newwin(bounds.size.height, bounds.size.width, bounds.origin.y, bounds.origin.x), true)); subwindow_sp->m_is_subwin = false; } subwindow_sp->m_parent = this; if (make_active) { m_prev_active_window_idx = m_curr_active_window_idx; m_curr_active_window_idx = m_subwindows.size(); } m_subwindows.push_back(subwindow_sp); ::top_panel(subwindow_sp->m_panel); m_needs_update = true; return subwindow_sp; } bool RemoveSubWindow(Window *window) { Windows::iterator pos, end = m_subwindows.end(); size_t i = 0; for (pos = m_subwindows.begin(); pos != end; ++pos, ++i) { if ((*pos).get() == window) { if (m_prev_active_window_idx == i) m_prev_active_window_idx = UINT32_MAX; else if (m_prev_active_window_idx != UINT32_MAX && m_prev_active_window_idx > i) --m_prev_active_window_idx; if (m_curr_active_window_idx == i) m_curr_active_window_idx = UINT32_MAX; else if (m_curr_active_window_idx != UINT32_MAX && m_curr_active_window_idx > i) --m_curr_active_window_idx; window->Erase(); m_subwindows.erase(pos); m_needs_update = true; if (m_parent) m_parent->Touch(); else ::touchwin(stdscr); return true; } } return false; } WindowSP FindSubWindow(const char *name) { Windows::iterator pos, end = m_subwindows.end(); size_t i = 0; for (pos = m_subwindows.begin(); pos != end; ++pos, ++i) { if ((*pos)->m_name.compare(name) == 0) return *pos; } return WindowSP(); } void RemoveSubWindows() { m_curr_active_window_idx = UINT32_MAX; m_prev_active_window_idx = UINT32_MAX; for (Windows::iterator pos = m_subwindows.begin(); pos != m_subwindows.end(); pos = m_subwindows.erase(pos)) { (*pos)->Erase(); } if (m_parent) m_parent->Touch(); else ::touchwin(stdscr); } WINDOW *get() { return m_window; } operator WINDOW *() { return m_window; } //---------------------------------------------------------------------- // Window drawing utilities //---------------------------------------------------------------------- void DrawTitleBox(const char *title, const char *bottom_message = nullptr) { attr_t attr = 0; if (IsActive()) attr = A_BOLD | COLOR_PAIR(2); else attr = 0; if (attr) AttributeOn(attr); Box(); MoveCursor(3, 0); if (title && title[0]) { PutChar('<'); PutCString(title); PutChar('>'); } if (bottom_message && bottom_message[0]) { int bottom_message_length = strlen(bottom_message); int x = GetWidth() - 3 - (bottom_message_length + 2); if (x > 0) { MoveCursor(x, GetHeight() - 1); PutChar('['); PutCString(bottom_message); PutChar(']'); } else { MoveCursor(1, GetHeight() - 1); PutChar('['); PutCStringTruncated(bottom_message, 1); } } if (attr) AttributeOff(attr); } virtual void Draw(bool force) { if (m_delegate_sp && m_delegate_sp->WindowDelegateDraw(*this, force)) return; for (auto &subwindow_sp : m_subwindows) subwindow_sp->Draw(force); } bool CreateHelpSubwindow() { if (m_delegate_sp) { const char *text = m_delegate_sp->WindowDelegateGetHelpText(); KeyHelp *key_help = m_delegate_sp->WindowDelegateGetKeyHelp(); if ((text && text[0]) || key_help) { std::auto_ptr<HelpDialogDelegate> help_delegate_ap( new HelpDialogDelegate(text, key_help)); const size_t num_lines = help_delegate_ap->GetNumLines(); const size_t max_length = help_delegate_ap->GetMaxLineLength(); Rect bounds = GetBounds(); bounds.Inset(1, 1); if (max_length + 4 < static_cast<size_t>(bounds.size.width)) { bounds.origin.x += (bounds.size.width - max_length + 4) / 2; bounds.size.width = max_length + 4; } else { if (bounds.size.width > 100) { const int inset_w = bounds.size.width / 4; bounds.origin.x += inset_w; bounds.size.width -= 2 * inset_w; } } if (num_lines + 2 < static_cast<size_t>(bounds.size.height)) { bounds.origin.y += (bounds.size.height - num_lines + 2) / 2; bounds.size.height = num_lines + 2; } else { if (bounds.size.height > 100) { const int inset_h = bounds.size.height / 4; bounds.origin.y += inset_h; bounds.size.height -= 2 * inset_h; } } WindowSP help_window_sp; Window *parent_window = GetParent(); if (parent_window) help_window_sp = parent_window->CreateSubWindow("Help", bounds, true); else help_window_sp = CreateSubWindow("Help", bounds, true); help_window_sp->SetDelegate( WindowDelegateSP(help_delegate_ap.release())); return true; } } return false; } virtual HandleCharResult HandleChar(int key) { // Always check the active window first HandleCharResult result = eKeyNotHandled; WindowSP active_window_sp = GetActiveWindow(); if (active_window_sp) { result = active_window_sp->HandleChar(key); if (result != eKeyNotHandled) return result; } if (m_delegate_sp) { result = m_delegate_sp->WindowDelegateHandleChar(*this, key); if (result != eKeyNotHandled) return result; } // Then check for any windows that want any keys // that weren't handled. This is typically only // for a menubar. // Make a copy of the subwindows in case any HandleChar() // functions muck with the subwindows. If we don't do this, // we can crash when iterating over the subwindows. Windows subwindows(m_subwindows); for (auto subwindow_sp : subwindows) { if (!subwindow_sp->m_can_activate) { HandleCharResult result = subwindow_sp->HandleChar(key); if (result != eKeyNotHandled) return result; } } return eKeyNotHandled; } bool SetActiveWindow(Window *window) { const size_t num_subwindows = m_subwindows.size(); for (size_t i = 0; i < num_subwindows; ++i) { if (m_subwindows[i].get() == window) { m_prev_active_window_idx = m_curr_active_window_idx; ::top_panel(window->m_panel); m_curr_active_window_idx = i; return true; } } return false; } WindowSP GetActiveWindow() { if (!m_subwindows.empty()) { if (m_curr_active_window_idx >= m_subwindows.size()) { if (m_prev_active_window_idx < m_subwindows.size()) { m_curr_active_window_idx = m_prev_active_window_idx; m_prev_active_window_idx = UINT32_MAX; } else if (IsActive()) { m_prev_active_window_idx = UINT32_MAX; m_curr_active_window_idx = UINT32_MAX; // Find first window that wants to be active if this window is active const size_t num_subwindows = m_subwindows.size(); for (size_t i = 0; i < num_subwindows; ++i) { if (m_subwindows[i]->GetCanBeActive()) { m_curr_active_window_idx = i; break; } } } } if (m_curr_active_window_idx < m_subwindows.size()) return m_subwindows[m_curr_active_window_idx]; } return WindowSP(); } bool GetCanBeActive() const { return m_can_activate; } void SetCanBeActive(bool b) { m_can_activate = b; } const WindowDelegateSP &GetDelegate() const { return m_delegate_sp; } void SetDelegate(const WindowDelegateSP &delegate_sp) { m_delegate_sp = delegate_sp; } Window *GetParent() const { return m_parent; } bool IsActive() const { if (m_parent) return m_parent->GetActiveWindow().get() == this; else return true; // Top level window is always active } void SelectNextWindowAsActive() { // Move active focus to next window const size_t num_subwindows = m_subwindows.size(); if (m_curr_active_window_idx == UINT32_MAX) { uint32_t idx = 0; for (auto subwindow_sp : m_subwindows) { if (subwindow_sp->GetCanBeActive()) { m_curr_active_window_idx = idx; break; } ++idx; } } else if (m_curr_active_window_idx + 1 < num_subwindows) { bool handled = false; m_prev_active_window_idx = m_curr_active_window_idx; for (size_t idx = m_curr_active_window_idx + 1; idx < num_subwindows; ++idx) { if (m_subwindows[idx]->GetCanBeActive()) { m_curr_active_window_idx = idx; handled = true; break; } } if (!handled) { for (size_t idx = 0; idx <= m_prev_active_window_idx; ++idx) { if (m_subwindows[idx]->GetCanBeActive()) { m_curr_active_window_idx = idx; break; } } } } else { m_prev_active_window_idx = m_curr_active_window_idx; for (size_t idx = 0; idx < num_subwindows; ++idx) { if (m_subwindows[idx]->GetCanBeActive()) { m_curr_active_window_idx = idx; break; } } } } const char *GetName() const { return m_name.c_str(); } protected: std::string m_name; WINDOW *m_window; PANEL *m_panel; Window *m_parent; Windows m_subwindows; WindowDelegateSP m_delegate_sp; uint32_t m_curr_active_window_idx; uint32_t m_prev_active_window_idx; bool m_delete; bool m_needs_update; bool m_can_activate; bool m_is_subwin; private: DISALLOW_COPY_AND_ASSIGN(Window); }; class MenuDelegate { public: virtual ~MenuDelegate() = default; virtual MenuActionResult MenuDelegateAction(Menu &menu) = 0; }; class Menu : public WindowDelegate { public: enum class Type { Invalid, Bar, Item, Separator }; // Menubar or separator constructor Menu(Type type); // Menuitem constructor Menu(const char *name, const char *key_name, int key_value, uint64_t identifier); ~Menu() override = default; const MenuDelegateSP &GetDelegate() const { return m_delegate_sp; } void SetDelegate(const MenuDelegateSP &delegate_sp) { m_delegate_sp = delegate_sp; } void RecalculateNameLengths(); void AddSubmenu(const MenuSP &menu_sp); int DrawAndRunMenu(Window &window); void DrawMenuTitle(Window &window, bool highlight); bool WindowDelegateDraw(Window &window, bool force) override; HandleCharResult WindowDelegateHandleChar(Window &window, int key) override; MenuActionResult ActionPrivate(Menu &menu) { MenuActionResult result = MenuActionResult::NotHandled; if (m_delegate_sp) { result = m_delegate_sp->MenuDelegateAction(menu); if (result != MenuActionResult::NotHandled) return result; } else if (m_parent) { result = m_parent->ActionPrivate(menu); if (result != MenuActionResult::NotHandled) return result; } return m_canned_result; } MenuActionResult Action() { // Call the recursive action so it can try to handle it // with the menu delegate, and if not, try our parent menu return ActionPrivate(*this); } void SetCannedResult(MenuActionResult result) { m_canned_result = result; } Menus &GetSubmenus() { return m_submenus; } const Menus &GetSubmenus() const { return m_submenus; } int GetSelectedSubmenuIndex() const { return m_selected; } void SetSelectedSubmenuIndex(int idx) { m_selected = idx; } Type GetType() const { return m_type; } int GetStartingColumn() const { return m_start_col; } void SetStartingColumn(int col) { m_start_col = col; } int GetKeyValue() const { return m_key_value; } void SetKeyValue(int key_value) { m_key_value = key_value; } std::string &GetName() { return m_name; } std::string &GetKeyName() { return m_key_name; } int GetDrawWidth() const { return m_max_submenu_name_length + m_max_submenu_key_name_length + 8; } uint64_t GetIdentifier() const { return m_identifier; } void SetIdentifier(uint64_t identifier) { m_identifier = identifier; } protected: std::string m_name; std::string m_key_name; uint64_t m_identifier; Type m_type; int m_key_value; int m_start_col; int m_max_submenu_name_length; int m_max_submenu_key_name_length; int m_selected; Menu *m_parent; Menus m_submenus; WindowSP m_menu_window_sp; MenuActionResult m_canned_result; MenuDelegateSP m_delegate_sp; }; // Menubar or separator constructor Menu::Menu(Type type) : m_name(), m_key_name(), m_identifier(0), m_type(type), m_key_value(0), m_start_col(0), m_max_submenu_name_length(0), m_max_submenu_key_name_length(0), m_selected(0), m_parent(nullptr), m_submenus(), m_canned_result(MenuActionResult::NotHandled), m_delegate_sp() {} // Menuitem constructor Menu::Menu(const char *name, const char *key_name, int key_value, uint64_t identifier) : m_name(), m_key_name(), m_identifier(identifier), m_type(Type::Invalid), m_key_value(key_value), m_start_col(0), m_max_submenu_name_length(0), m_max_submenu_key_name_length(0), m_selected(0), m_parent(nullptr), m_submenus(), m_canned_result(MenuActionResult::NotHandled), m_delegate_sp() { if (name && name[0]) { m_name = name; m_type = Type::Item; if (key_name && key_name[0]) m_key_name = key_name; } else { m_type = Type::Separator; } } void Menu::RecalculateNameLengths() { m_max_submenu_name_length = 0; m_max_submenu_key_name_length = 0; Menus &submenus = GetSubmenus(); const size_t num_submenus = submenus.size(); for (size_t i = 0; i < num_submenus; ++i) { Menu *submenu = submenus[i].get(); if (static_cast<size_t>(m_max_submenu_name_length) < submenu->m_name.size()) m_max_submenu_name_length = submenu->m_name.size(); if (static_cast<size_t>(m_max_submenu_key_name_length) < submenu->m_key_name.size()) m_max_submenu_key_name_length = submenu->m_key_name.size(); } } void Menu::AddSubmenu(const MenuSP &menu_sp) { menu_sp->m_parent = this; if (static_cast<size_t>(m_max_submenu_name_length) < menu_sp->m_name.size()) m_max_submenu_name_length = menu_sp->m_name.size(); if (static_cast<size_t>(m_max_submenu_key_name_length) < menu_sp->m_key_name.size()) m_max_submenu_key_name_length = menu_sp->m_key_name.size(); m_submenus.push_back(menu_sp); } void Menu::DrawMenuTitle(Window &window, bool highlight) { if (m_type == Type::Separator) { window.MoveCursor(0, window.GetCursorY()); window.PutChar(ACS_LTEE); int width = window.GetWidth(); if (width > 2) { width -= 2; for (int i = 0; i < width; ++i) window.PutChar(ACS_HLINE); } window.PutChar(ACS_RTEE); } else { const int shortcut_key = m_key_value; bool underlined_shortcut = false; const attr_t hilgight_attr = A_REVERSE; if (highlight) window.AttributeOn(hilgight_attr); if (isprint(shortcut_key)) { size_t lower_pos = m_name.find(tolower(shortcut_key)); size_t upper_pos = m_name.find(toupper(shortcut_key)); const char *name = m_name.c_str(); size_t pos = std::min<size_t>(lower_pos, upper_pos); if (pos != std::string::npos) { underlined_shortcut = true; if (pos > 0) { window.PutCString(name, pos); name += pos; } const attr_t shortcut_attr = A_UNDERLINE | A_BOLD; window.AttributeOn(shortcut_attr); window.PutChar(name[0]); window.AttributeOff(shortcut_attr); name++; if (name[0]) window.PutCString(name); } } if (!underlined_shortcut) { window.PutCString(m_name.c_str()); } if (highlight) window.AttributeOff(hilgight_attr); if (m_key_name.empty()) { if (!underlined_shortcut && isprint(m_key_value)) { window.AttributeOn(COLOR_PAIR(3)); window.Printf(" (%c)", m_key_value); window.AttributeOff(COLOR_PAIR(3)); } } else { window.AttributeOn(COLOR_PAIR(3)); window.Printf(" (%s)", m_key_name.c_str()); window.AttributeOff(COLOR_PAIR(3)); } } } bool Menu::WindowDelegateDraw(Window &window, bool force) { Menus &submenus = GetSubmenus(); const size_t num_submenus = submenus.size(); const int selected_idx = GetSelectedSubmenuIndex(); Menu::Type menu_type = GetType(); switch (menu_type) { case Menu::Type::Bar: { window.SetBackground(2); window.MoveCursor(0, 0); for (size_t i = 0; i < num_submenus; ++i) { Menu *menu = submenus[i].get(); if (i > 0) window.PutChar(' '); menu->SetStartingColumn(window.GetCursorX()); window.PutCString("| "); menu->DrawMenuTitle(window, false); } window.PutCString(" |"); window.DeferredRefresh(); } break; case Menu::Type::Item: { int y = 1; int x = 3; // Draw the menu int cursor_x = 0; int cursor_y = 0; window.Erase(); window.SetBackground(2); window.Box(); for (size_t i = 0; i < num_submenus; ++i) { const bool is_selected = (i == static_cast<size_t>(selected_idx)); window.MoveCursor(x, y + i); if (is_selected) { // Remember where we want the cursor to be cursor_x = x - 1; cursor_y = y + i; } submenus[i]->DrawMenuTitle(window, is_selected); } window.MoveCursor(cursor_x, cursor_y); window.DeferredRefresh(); } break; default: case Menu::Type::Separator: break; } return true; // Drawing handled... } HandleCharResult Menu::WindowDelegateHandleChar(Window &window, int key) { HandleCharResult result = eKeyNotHandled; Menus &submenus = GetSubmenus(); const size_t num_submenus = submenus.size(); const int selected_idx = GetSelectedSubmenuIndex(); Menu::Type menu_type = GetType(); if (menu_type == Menu::Type::Bar) { MenuSP run_menu_sp; switch (key) { case KEY_DOWN: case KEY_UP: // Show last menu or first menu if (selected_idx < static_cast<int>(num_submenus)) run_menu_sp = submenus[selected_idx]; else if (!submenus.empty()) run_menu_sp = submenus.front(); result = eKeyHandled; break; case KEY_RIGHT: ++m_selected; if (m_selected >= static_cast<int>(num_submenus)) m_selected = 0; if (m_selected < static_cast<int>(num_submenus)) run_menu_sp = submenus[m_selected]; else if (!submenus.empty()) run_menu_sp = submenus.front(); result = eKeyHandled; break; case KEY_LEFT: --m_selected; if (m_selected < 0) m_selected = num_submenus - 1; if (m_selected < static_cast<int>(num_submenus)) run_menu_sp = submenus[m_selected]; else if (!submenus.empty()) run_menu_sp = submenus.front(); result = eKeyHandled; break; default: for (size_t i = 0; i < num_submenus; ++i) { if (submenus[i]->GetKeyValue() == key) { SetSelectedSubmenuIndex(i); run_menu_sp = submenus[i]; result = eKeyHandled; break; } } break; } if (run_menu_sp) { // Run the action on this menu in case we need to populate the // menu with dynamic content and also in case check marks, and // any other menu decorations need to be calculated if (run_menu_sp->Action() == MenuActionResult::Quit) return eQuitApplication; Rect menu_bounds; menu_bounds.origin.x = run_menu_sp->GetStartingColumn(); menu_bounds.origin.y = 1; menu_bounds.size.width = run_menu_sp->GetDrawWidth(); menu_bounds.size.height = run_menu_sp->GetSubmenus().size() + 2; if (m_menu_window_sp) window.GetParent()->RemoveSubWindow(m_menu_window_sp.get()); m_menu_window_sp = window.GetParent()->CreateSubWindow( run_menu_sp->GetName().c_str(), menu_bounds, true); m_menu_window_sp->SetDelegate(run_menu_sp); } } else if (menu_type == Menu::Type::Item) { switch (key) { case KEY_DOWN: if (m_submenus.size() > 1) { const int start_select = m_selected; while (++m_selected != start_select) { if (static_cast<size_t>(m_selected) >= num_submenus) m_selected = 0; if (m_submenus[m_selected]->GetType() == Type::Separator) continue; else break; } return eKeyHandled; } break; case KEY_UP: if (m_submenus.size() > 1) { const int start_select = m_selected; while (--m_selected != start_select) { if (m_selected < static_cast<int>(0)) m_selected = num_submenus - 1; if (m_submenus[m_selected]->GetType() == Type::Separator) continue; else break; } return eKeyHandled; } break; case KEY_RETURN: if (static_cast<size_t>(selected_idx) < num_submenus) { if (submenus[selected_idx]->Action() == MenuActionResult::Quit) return eQuitApplication; window.GetParent()->RemoveSubWindow(&window); return eKeyHandled; } break; case KEY_ESCAPE: // Beware: pressing escape key has 1 to 2 second delay in // case other chars are entered for escaped sequences window.GetParent()->RemoveSubWindow(&window); return eKeyHandled; default: for (size_t i = 0; i < num_submenus; ++i) { Menu *menu = submenus[i].get(); if (menu->GetKeyValue() == key) { SetSelectedSubmenuIndex(i); window.GetParent()->RemoveSubWindow(&window); if (menu->Action() == MenuActionResult::Quit) return eQuitApplication; return eKeyHandled; } } break; } } else if (menu_type == Menu::Type::Separator) { } return result; } class Application { public: Application(FILE *in, FILE *out) : m_window_sp(), m_screen(nullptr), m_in(in), m_out(out) {} ~Application() { m_window_delegates.clear(); m_window_sp.reset(); if (m_screen) { ::delscreen(m_screen); m_screen = nullptr; } } void Initialize() { ::setlocale(LC_ALL, ""); ::setlocale(LC_CTYPE, ""); #if 0 ::initscr(); #else m_screen = ::newterm(nullptr, m_out, m_in); #endif ::start_color(); ::curs_set(0); ::noecho(); ::keypad(stdscr, TRUE); } void Terminate() { ::endwin(); } void Run(Debugger &debugger) { bool done = false; int delay_in_tenths_of_a_second = 1; // Alas the threading model in curses is a bit lame so we need to // resort to polling every 0.5 seconds. We could poll for stdin // ourselves and then pass the keys down but then we need to // translate all of the escape sequences ourselves. So we resort to // polling for input because we need to receive async process events // while in this loop. halfdelay(delay_in_tenths_of_a_second); // Poll using some number of tenths // of seconds seconds when calling // Window::GetChar() ListenerSP listener_sp( Listener::MakeListener("lldb.IOHandler.curses.Application")); ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass()); ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass()); ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass()); debugger.EnableForwardEvents(listener_sp); bool update = true; #if defined(__APPLE__) std::deque<int> escape_chars; #endif while (!done) { if (update) { m_window_sp->Draw(false); // All windows should be calling Window::DeferredRefresh() instead // of Window::Refresh() so we can do a single update and avoid // any screen blinking update_panels(); // Cursor hiding isn't working on MacOSX, so hide it in the top left // corner m_window_sp->MoveCursor(0, 0); doupdate(); update = false; } #if defined(__APPLE__) // Terminal.app doesn't map its function keys correctly, F1-F4 default to: // \033OP, \033OQ, \033OR, \033OS, so lets take care of this here if // possible int ch; if (escape_chars.empty()) ch = m_window_sp->GetChar(); else { ch = escape_chars.front(); escape_chars.pop_front(); } if (ch == KEY_ESCAPE) { int ch2 = m_window_sp->GetChar(); if (ch2 == 'O') { int ch3 = m_window_sp->GetChar(); switch (ch3) { case 'P': ch = KEY_F(1); break; case 'Q': ch = KEY_F(2); break; case 'R': ch = KEY_F(3); break; case 'S': ch = KEY_F(4); break; default: escape_chars.push_back(ch2); if (ch3 != -1) escape_chars.push_back(ch3); break; } } else if (ch2 != -1) escape_chars.push_back(ch2); } #else int ch = m_window_sp->GetChar(); #endif if (ch == -1) { if (feof(m_in) || ferror(m_in)) { done = true; } else { // Just a timeout from using halfdelay(), check for events EventSP event_sp; while (listener_sp->PeekAtNextEvent()) { listener_sp->GetEvent(event_sp, std::chrono::seconds(0)); if (event_sp) { Broadcaster *broadcaster = event_sp->GetBroadcaster(); if (broadcaster) { // uint32_t event_type = event_sp->GetType(); ConstString broadcaster_class( broadcaster->GetBroadcasterClass()); if (broadcaster_class == broadcaster_class_process) { debugger.GetCommandInterpreter().UpdateExecutionContext( nullptr); update = true; continue; // Don't get any key, just update our view } } } } } } else { HandleCharResult key_result = m_window_sp->HandleChar(ch); switch (key_result) { case eKeyHandled: debugger.GetCommandInterpreter().UpdateExecutionContext(nullptr); update = true; break; case eKeyNotHandled: break; case eQuitApplication: done = true; break; } } } debugger.CancelForwardEvents(listener_sp); } WindowSP &GetMainWindow() { if (!m_window_sp) m_window_sp.reset(new Window("main", stdscr, false)); return m_window_sp; } WindowDelegates &GetWindowDelegates() { return m_window_delegates; } protected: WindowSP m_window_sp; WindowDelegates m_window_delegates; SCREEN *m_screen; FILE *m_in; FILE *m_out; }; } // namespace curses using namespace curses; struct Row { ValueObjectManager value; Row *parent; // The process stop ID when the children were calculated. uint32_t children_stop_id; int row_idx; int x; int y; bool might_have_children; bool expanded; bool calculated_children; std::vector<Row> children; Row(const ValueObjectSP &v, Row *p) : value(v, lldb::eDynamicDontRunTarget, true), parent(p), row_idx(0), x(1), y(1), might_have_children(v ? v->MightHaveChildren() : false), expanded(false), calculated_children(false), children() {} size_t GetDepth() const { if (parent) return 1 + parent->GetDepth(); return 0; } void Expand() { expanded = true; } std::vector<Row> &GetChildren() { ProcessSP process_sp = value.GetProcessSP(); auto stop_id = process_sp->GetStopID(); if (process_sp && stop_id != children_stop_id) { children_stop_id = stop_id; calculated_children = false; } if (!calculated_children) { children.clear(); calculated_children = true; ValueObjectSP valobj = value.GetSP(); if (valobj) { const size_t num_children = valobj->GetNumChildren(); for (size_t i = 0; i < num_children; ++i) { children.push_back(Row(valobj->GetChildAtIndex(i, true), this)); } } } return children; } void Unexpand() { expanded = false; calculated_children = false; children.clear(); } void DrawTree(Window &window) { if (parent) parent->DrawTreeForChild(window, this, 0); if (might_have_children) { // It we can get UTF8 characters to work we should try to use the "symbol" // UTF8 string below // const char *symbol = ""; // if (row.expanded) // symbol = "\xe2\x96\xbd "; // else // symbol = "\xe2\x96\xb7 "; // window.PutCString (symbol); // The ACS_DARROW and ACS_RARROW don't look very nice they are just a // 'v' or '>' character... // if (expanded) // window.PutChar (ACS_DARROW); // else // window.PutChar (ACS_RARROW); // Since we can't find any good looking right arrow/down arrow // symbols, just use a diamond... window.PutChar(ACS_DIAMOND); window.PutChar(ACS_HLINE); } } void DrawTreeForChild(Window &window, Row *child, uint32_t reverse_depth) { if (parent) parent->DrawTreeForChild(window, this, reverse_depth + 1); if (&GetChildren().back() == child) { // Last child if (reverse_depth == 0) { window.PutChar(ACS_LLCORNER); window.PutChar(ACS_HLINE); } else { window.PutChar(' '); window.PutChar(' '); } } else { if (reverse_depth == 0) { window.PutChar(ACS_LTEE); window.PutChar(ACS_HLINE); } else { window.PutChar(ACS_VLINE); window.PutChar(' '); } } } }; struct DisplayOptions { bool show_types; }; class TreeItem; class TreeDelegate { public: TreeDelegate() = default; virtual ~TreeDelegate() = default; virtual void TreeDelegateDrawTreeItem(TreeItem &item, Window &window) = 0; virtual void TreeDelegateGenerateChildren(TreeItem &item) = 0; virtual bool TreeDelegateItemSelected( TreeItem &item) = 0; // Return true if we need to update views }; typedef std::shared_ptr<TreeDelegate> TreeDelegateSP; class TreeItem { public: TreeItem(TreeItem *parent, TreeDelegate &delegate, bool might_have_children) : m_parent(parent), m_delegate(delegate), m_user_data(nullptr), m_identifier(0), m_row_idx(-1), m_children(), m_might_have_children(might_have_children), m_is_expanded(false) {} TreeItem &operator=(const TreeItem &rhs) { if (this != &rhs) { m_parent = rhs.m_parent; m_delegate = rhs.m_delegate; m_user_data = rhs.m_user_data; m_identifier = rhs.m_identifier; m_row_idx = rhs.m_row_idx; m_children = rhs.m_children; m_might_have_children = rhs.m_might_have_children; m_is_expanded = rhs.m_is_expanded; } return *this; } size_t GetDepth() const { if (m_parent) return 1 + m_parent->GetDepth(); return 0; } int GetRowIndex() const { return m_row_idx; } void ClearChildren() { m_children.clear(); } void Resize(size_t n, const TreeItem &t) { m_children.resize(n, t); } TreeItem &operator[](size_t i) { return m_children[i]; } void SetRowIndex(int row_idx) { m_row_idx = row_idx; } size_t GetNumChildren() { m_delegate.TreeDelegateGenerateChildren(*this); return m_children.size(); } void ItemWasSelected() { m_delegate.TreeDelegateItemSelected(*this); } void CalculateRowIndexes(int &row_idx) { SetRowIndex(row_idx); ++row_idx; const bool expanded = IsExpanded(); // The root item must calculate its children, // or we must calculate the number of children // if the item is expanded if (m_parent == nullptr || expanded) GetNumChildren(); for (auto &item : m_children) { if (expanded) item.CalculateRowIndexes(row_idx); else item.SetRowIndex(-1); } } TreeItem *GetParent() { return m_parent; } bool IsExpanded() const { return m_is_expanded; } void Expand() { m_is_expanded = true; } void Unexpand() { m_is_expanded = false; } bool Draw(Window &window, const int first_visible_row, const uint32_t selected_row_idx, int &row_idx, int &num_rows_left) { if (num_rows_left <= 0) return false; if (m_row_idx >= first_visible_row) { window.MoveCursor(2, row_idx + 1); if (m_parent) m_parent->DrawTreeForChild(window, this, 0); if (m_might_have_children) { // It we can get UTF8 characters to work we should try to use the // "symbol" // UTF8 string below // const char *symbol = ""; // if (row.expanded) // symbol = "\xe2\x96\xbd "; // else // symbol = "\xe2\x96\xb7 "; // window.PutCString (symbol); // The ACS_DARROW and ACS_RARROW don't look very nice they are just a // 'v' or '>' character... // if (expanded) // window.PutChar (ACS_DARROW); // else // window.PutChar (ACS_RARROW); // Since we can't find any good looking right arrow/down arrow // symbols, just use a diamond... window.PutChar(ACS_DIAMOND); window.PutChar(ACS_HLINE); } bool highlight = (selected_row_idx == static_cast<size_t>(m_row_idx)) && window.IsActive(); if (highlight) window.AttributeOn(A_REVERSE); m_delegate.TreeDelegateDrawTreeItem(*this, window); if (highlight) window.AttributeOff(A_REVERSE); ++row_idx; --num_rows_left; } if (num_rows_left <= 0) return false; // We are done drawing... if (IsExpanded()) { for (auto &item : m_children) { // If we displayed all the rows and item.Draw() returns // false we are done drawing and can exit this for loop if (!item.Draw(window, first_visible_row, selected_row_idx, row_idx, num_rows_left)) break; } } return num_rows_left >= 0; // Return true if not done drawing yet } void DrawTreeForChild(Window &window, TreeItem *child, uint32_t reverse_depth) { if (m_parent) m_parent->DrawTreeForChild(window, this, reverse_depth + 1); if (&m_children.back() == child) { // Last child if (reverse_depth == 0) { window.PutChar(ACS_LLCORNER); window.PutChar(ACS_HLINE); } else { window.PutChar(' '); window.PutChar(' '); } } else { if (reverse_depth == 0) { window.PutChar(ACS_LTEE); window.PutChar(ACS_HLINE); } else { window.PutChar(ACS_VLINE); window.PutChar(' '); } } } TreeItem *GetItemForRowIndex(uint32_t row_idx) { if (static_cast<uint32_t>(m_row_idx) == row_idx) return this; if (m_children.empty()) return nullptr; if (IsExpanded()) { for (auto &item : m_children) { TreeItem *selected_item_ptr = item.GetItemForRowIndex(row_idx); if (selected_item_ptr) return selected_item_ptr; } } return nullptr; } void *GetUserData() const { return m_user_data; } void SetUserData(void *user_data) { m_user_data = user_data; } uint64_t GetIdentifier() const { return m_identifier; } void SetIdentifier(uint64_t identifier) { m_identifier = identifier; } void SetMightHaveChildren(bool b) { m_might_have_children = b; } protected: TreeItem *m_parent; TreeDelegate &m_delegate; void *m_user_data; uint64_t m_identifier; int m_row_idx; // Zero based visible row index, -1 if not visible or for the // root item std::vector<TreeItem> m_children; bool m_might_have_children; bool m_is_expanded; }; class TreeWindowDelegate : public WindowDelegate { public: TreeWindowDelegate(Debugger &debugger, const TreeDelegateSP &delegate_sp) : m_debugger(debugger), m_delegate_sp(delegate_sp), m_root(nullptr, *delegate_sp, true), m_selected_item(nullptr), m_num_rows(0), m_selected_row_idx(0), m_first_visible_row(0), m_min_x(0), m_min_y(0), m_max_x(0), m_max_y(0) {} int NumVisibleRows() const { return m_max_y - m_min_y; } bool WindowDelegateDraw(Window &window, bool force) override { ExecutionContext exe_ctx( m_debugger.GetCommandInterpreter().GetExecutionContext()); Process *process = exe_ctx.GetProcessPtr(); bool display_content = false; if (process) { StateType state = process->GetState(); if (StateIsStoppedState(state, true)) { // We are stopped, so it is ok to display_content = true; } else if (StateIsRunningState(state)) { return true; // Don't do any updating when we are running } } m_min_x = 2; m_min_y = 1; m_max_x = window.GetWidth() - 1; m_max_y = window.GetHeight() - 1; window.Erase(); window.DrawTitleBox(window.GetName()); if (display_content) { const int num_visible_rows = NumVisibleRows(); m_num_rows = 0; m_root.CalculateRowIndexes(m_num_rows); // If we unexpanded while having something selected our // total number of rows is less than the num visible rows, // then make sure we show all the rows by setting the first // visible row accordingly. if (m_first_visible_row > 0 && m_num_rows < num_visible_rows) m_first_visible_row = 0; // Make sure the selected row is always visible if (m_selected_row_idx < m_first_visible_row) m_first_visible_row = m_selected_row_idx; else if (m_first_visible_row + num_visible_rows <= m_selected_row_idx) m_first_visible_row = m_selected_row_idx - num_visible_rows + 1; int row_idx = 0; int num_rows_left = num_visible_rows; m_root.Draw(window, m_first_visible_row, m_selected_row_idx, row_idx, num_rows_left); // Get the selected row m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx); } else { m_selected_item = nullptr; } window.DeferredRefresh(); return true; // Drawing handled } const char *WindowDelegateGetHelpText() override { return "Thread window keyboard shortcuts:"; } KeyHelp *WindowDelegateGetKeyHelp() override { static curses::KeyHelp g_source_view_key_help[] = { {KEY_UP, "Select previous item"}, {KEY_DOWN, "Select next item"}, {KEY_RIGHT, "Expand the selected item"}, {KEY_LEFT, "Unexpand the selected item or select parent if not expanded"}, {KEY_PPAGE, "Page up"}, {KEY_NPAGE, "Page down"}, {'h', "Show help dialog"}, {' ', "Toggle item expansion"}, {',', "Page up"}, {'.', "Page down"}, {'\0', nullptr}}; return g_source_view_key_help; } HandleCharResult WindowDelegateHandleChar(Window &window, int c) override { switch (c) { case ',': case KEY_PPAGE: // Page up key if (m_first_visible_row > 0) { if (m_first_visible_row > m_max_y) m_first_visible_row -= m_max_y; else m_first_visible_row = 0; m_selected_row_idx = m_first_visible_row; m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx); if (m_selected_item) m_selected_item->ItemWasSelected(); } return eKeyHandled; case '.': case KEY_NPAGE: // Page down key if (m_num_rows > m_max_y) { if (m_first_visible_row + m_max_y < m_num_rows) { m_first_visible_row += m_max_y; m_selected_row_idx = m_first_visible_row; m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx); if (m_selected_item) m_selected_item->ItemWasSelected(); } } return eKeyHandled; case KEY_UP: if (m_selected_row_idx > 0) { --m_selected_row_idx; m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx); if (m_selected_item) m_selected_item->ItemWasSelected(); } return eKeyHandled; case KEY_DOWN: if (m_selected_row_idx + 1 < m_num_rows) { ++m_selected_row_idx; m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx); if (m_selected_item) m_selected_item->ItemWasSelected(); } return eKeyHandled; case KEY_RIGHT: if (m_selected_item) { if (!m_selected_item->IsExpanded()) m_selected_item->Expand(); } return eKeyHandled; case KEY_LEFT: if (m_selected_item) { if (m_selected_item->IsExpanded()) m_selected_item->Unexpand(); else if (m_selected_item->GetParent()) { m_selected_row_idx = m_selected_item->GetParent()->GetRowIndex(); m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx); if (m_selected_item) m_selected_item->ItemWasSelected(); } } return eKeyHandled; case ' ': // Toggle expansion state when SPACE is pressed if (m_selected_item) { if (m_selected_item->IsExpanded()) m_selected_item->Unexpand(); else m_selected_item->Expand(); } return eKeyHandled; case 'h': window.CreateHelpSubwindow(); return eKeyHandled; default: break; } return eKeyNotHandled; } protected: Debugger &m_debugger; TreeDelegateSP m_delegate_sp; TreeItem m_root; TreeItem *m_selected_item; int m_num_rows; int m_selected_row_idx; int m_first_visible_row; int m_min_x; int m_min_y; int m_max_x; int m_max_y; }; class FrameTreeDelegate : public TreeDelegate { public: FrameTreeDelegate() : TreeDelegate() { FormatEntity::Parse( "frame #${frame.index}: {${function.name}${function.pc-offset}}}", m_format); } ~FrameTreeDelegate() override = default; void TreeDelegateDrawTreeItem(TreeItem &item, Window &window) override { Thread *thread = (Thread *)item.GetUserData(); if (thread) { const uint64_t frame_idx = item.GetIdentifier(); StackFrameSP frame_sp = thread->GetStackFrameAtIndex(frame_idx); if (frame_sp) { StreamString strm; const SymbolContext &sc = frame_sp->GetSymbolContext(eSymbolContextEverything); ExecutionContext exe_ctx(frame_sp); if (FormatEntity::Format(m_format, strm, &sc, &exe_ctx, nullptr, nullptr, false, false)) { int right_pad = 1; window.PutCStringTruncated(strm.GetString().str().c_str(), right_pad); } } } } void TreeDelegateGenerateChildren(TreeItem &item) override { // No children for frames yet... } bool TreeDelegateItemSelected(TreeItem &item) override { Thread *thread = (Thread *)item.GetUserData(); if (thread) { thread->GetProcess()->GetThreadList().SetSelectedThreadByID( thread->GetID()); const uint64_t frame_idx = item.GetIdentifier(); thread->SetSelectedFrameByIndex(frame_idx); return true; } return false; } protected: FormatEntity::Entry m_format; }; class ThreadTreeDelegate : public TreeDelegate { public: ThreadTreeDelegate(Debugger &debugger) : TreeDelegate(), m_debugger(debugger), m_tid(LLDB_INVALID_THREAD_ID), m_stop_id(UINT32_MAX) { FormatEntity::Parse("thread #${thread.index}: tid = ${thread.id}{, stop " "reason = ${thread.stop-reason}}", m_format); } ~ThreadTreeDelegate() override = default; ProcessSP GetProcess() { return m_debugger.GetCommandInterpreter() .GetExecutionContext() .GetProcessSP(); } ThreadSP GetThread(const TreeItem &item) { ProcessSP process_sp = GetProcess(); if (process_sp) return process_sp->GetThreadList().FindThreadByID(item.GetIdentifier()); return ThreadSP(); } void TreeDelegateDrawTreeItem(TreeItem &item, Window &window) override { ThreadSP thread_sp = GetThread(item); if (thread_sp) { StreamString strm; ExecutionContext exe_ctx(thread_sp); if (FormatEntity::Format(m_format, strm, nullptr, &exe_ctx, nullptr, nullptr, false, false)) { int right_pad = 1; window.PutCStringTruncated(strm.GetString().str().c_str(), right_pad); } } } void TreeDelegateGenerateChildren(TreeItem &item) override { ProcessSP process_sp = GetProcess(); if (process_sp && process_sp->IsAlive()) { StateType state = process_sp->GetState(); if (StateIsStoppedState(state, true)) { ThreadSP thread_sp = GetThread(item); if (thread_sp) { if (m_stop_id == process_sp->GetStopID() && thread_sp->GetID() == m_tid) return; // Children are already up to date if (!m_frame_delegate_sp) { // Always expand the thread item the first time we show it m_frame_delegate_sp.reset(new FrameTreeDelegate()); } m_stop_id = process_sp->GetStopID(); m_tid = thread_sp->GetID(); TreeItem t(&item, *m_frame_delegate_sp, false); size_t num_frames = thread_sp->GetStackFrameCount(); item.Resize(num_frames, t); for (size_t i = 0; i < num_frames; ++i) { item[i].SetUserData(thread_sp.get()); item[i].SetIdentifier(i); } } return; } } item.ClearChildren(); } bool TreeDelegateItemSelected(TreeItem &item) override { ProcessSP process_sp = GetProcess(); if (process_sp && process_sp->IsAlive()) { StateType state = process_sp->GetState(); if (StateIsStoppedState(state, true)) { ThreadSP thread_sp = GetThread(item); if (thread_sp) { ThreadList &thread_list = thread_sp->GetProcess()->GetThreadList(); std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex()); ThreadSP selected_thread_sp = thread_list.GetSelectedThread(); if (selected_thread_sp->GetID() != thread_sp->GetID()) { thread_list.SetSelectedThreadByID(thread_sp->GetID()); return true; } } } } return false; } protected: Debugger &m_debugger; std::shared_ptr<FrameTreeDelegate> m_frame_delegate_sp; lldb::user_id_t m_tid; uint32_t m_stop_id; FormatEntity::Entry m_format; }; class ThreadsTreeDelegate : public TreeDelegate { public: ThreadsTreeDelegate(Debugger &debugger) : TreeDelegate(), m_thread_delegate_sp(), m_debugger(debugger), m_stop_id(UINT32_MAX) { FormatEntity::Parse("process ${process.id}{, name = ${process.name}}", m_format); } ~ThreadsTreeDelegate() override = default; ProcessSP GetProcess() { return m_debugger.GetCommandInterpreter() .GetExecutionContext() .GetProcessSP(); } void TreeDelegateDrawTreeItem(TreeItem &item, Window &window) override { ProcessSP process_sp = GetProcess(); if (process_sp && process_sp->IsAlive()) { StreamString strm; ExecutionContext exe_ctx(process_sp); if (FormatEntity::Format(m_format, strm, nullptr, &exe_ctx, nullptr, nullptr, false, false)) { int right_pad = 1; window.PutCStringTruncated(strm.GetString().str().c_str(), right_pad); } } } void TreeDelegateGenerateChildren(TreeItem &item) override { ProcessSP process_sp = GetProcess(); if (process_sp && process_sp->IsAlive()) { StateType state = process_sp->GetState(); if (StateIsStoppedState(state, true)) { const uint32_t stop_id = process_sp->GetStopID(); if (m_stop_id == stop_id) return; // Children are already up to date m_stop_id = stop_id; if (!m_thread_delegate_sp) { // Always expand the thread item the first time we show it // item.Expand(); m_thread_delegate_sp.reset(new ThreadTreeDelegate(m_debugger)); } TreeItem t(&item, *m_thread_delegate_sp, false); ThreadList &threads = process_sp->GetThreadList(); std::lock_guard<std::recursive_mutex> guard(threads.GetMutex()); size_t num_threads = threads.GetSize(); item.Resize(num_threads, t); for (size_t i = 0; i < num_threads; ++i) { item[i].SetIdentifier(threads.GetThreadAtIndex(i)->GetID()); item[i].SetMightHaveChildren(true); } return; } } item.ClearChildren(); } bool TreeDelegateItemSelected(TreeItem &item) override { return false; } protected: std::shared_ptr<ThreadTreeDelegate> m_thread_delegate_sp; Debugger &m_debugger; uint32_t m_stop_id; FormatEntity::Entry m_format; }; class ValueObjectListDelegate : public WindowDelegate { public: ValueObjectListDelegate() : m_rows(), m_selected_row(nullptr), m_selected_row_idx(0), m_first_visible_row(0), m_num_rows(0), m_max_x(0), m_max_y(0) {} ValueObjectListDelegate(ValueObjectList &valobj_list) : m_rows(), m_selected_row(nullptr), m_selected_row_idx(0), m_first_visible_row(0), m_num_rows(0), m_max_x(0), m_max_y(0) { SetValues(valobj_list); } ~ValueObjectListDelegate() override = default; void SetValues(ValueObjectList &valobj_list) { m_selected_row = nullptr; m_selected_row_idx = 0; m_first_visible_row = 0; m_num_rows = 0; m_rows.clear(); for (auto &valobj_sp : valobj_list.GetObjects()) m_rows.push_back(Row(valobj_sp, nullptr)); } bool WindowDelegateDraw(Window &window, bool force) override { m_num_rows = 0; m_min_x = 2; m_min_y = 1; m_max_x = window.GetWidth() - 1; m_max_y = window.GetHeight() - 1; window.Erase(); window.DrawTitleBox(window.GetName()); const int num_visible_rows = NumVisibleRows(); const int num_rows = CalculateTotalNumberRows(m_rows); // If we unexpanded while having something selected our // total number of rows is less than the num visible rows, // then make sure we show all the rows by setting the first // visible row accordingly. if (m_first_visible_row > 0 && num_rows < num_visible_rows) m_first_visible_row = 0; // Make sure the selected row is always visible if (m_selected_row_idx < m_first_visible_row) m_first_visible_row = m_selected_row_idx; else if (m_first_visible_row + num_visible_rows <= m_selected_row_idx) m_first_visible_row = m_selected_row_idx - num_visible_rows + 1; DisplayRows(window, m_rows, g_options); window.DeferredRefresh(); // Get the selected row m_selected_row = GetRowForRowIndex(m_selected_row_idx); // Keep the cursor on the selected row so the highlight and the cursor // are always on the same line if (m_selected_row) window.MoveCursor(m_selected_row->x, m_selected_row->y); return true; // Drawing handled } KeyHelp *WindowDelegateGetKeyHelp() override { static curses::KeyHelp g_source_view_key_help[] = { {KEY_UP, "Select previous item"}, {KEY_DOWN, "Select next item"}, {KEY_RIGHT, "Expand selected item"}, {KEY_LEFT, "Unexpand selected item or select parent if not expanded"}, {KEY_PPAGE, "Page up"}, {KEY_NPAGE, "Page down"}, {'A', "Format as annotated address"}, {'b', "Format as binary"}, {'B', "Format as hex bytes with ASCII"}, {'c', "Format as character"}, {'d', "Format as a signed integer"}, {'D', "Format selected value using the default format for the type"}, {'f', "Format as float"}, {'h', "Show help dialog"}, {'i', "Format as instructions"}, {'o', "Format as octal"}, {'p', "Format as pointer"}, {'s', "Format as C string"}, {'t', "Toggle showing/hiding type names"}, {'u', "Format as an unsigned integer"}, {'x', "Format as hex"}, {'X', "Format as uppercase hex"}, {' ', "Toggle item expansion"}, {',', "Page up"}, {'.', "Page down"}, {'\0', nullptr}}; return g_source_view_key_help; } HandleCharResult WindowDelegateHandleChar(Window &window, int c) override { switch (c) { case 'x': case 'X': case 'o': case 's': case 'u': case 'd': case 'D': case 'i': case 'A': case 'p': case 'c': case 'b': case 'B': case 'f': // Change the format for the currently selected item if (m_selected_row) { auto valobj_sp = m_selected_row->value.GetSP(); if (valobj_sp) valobj_sp->SetFormat(FormatForChar(c)); } return eKeyHandled; case 't': // Toggle showing type names g_options.show_types = !g_options.show_types; return eKeyHandled; case ',': case KEY_PPAGE: // Page up key if (m_first_visible_row > 0) { if (static_cast<int>(m_first_visible_row) > m_max_y) m_first_visible_row -= m_max_y; else m_first_visible_row = 0; m_selected_row_idx = m_first_visible_row; } return eKeyHandled; case '.': case KEY_NPAGE: // Page down key if (m_num_rows > static_cast<size_t>(m_max_y)) { if (m_first_visible_row + m_max_y < m_num_rows) { m_first_visible_row += m_max_y; m_selected_row_idx = m_first_visible_row; } } return eKeyHandled; case KEY_UP: if (m_selected_row_idx > 0) --m_selected_row_idx; return eKeyHandled; case KEY_DOWN: if (m_selected_row_idx + 1 < m_num_rows) ++m_selected_row_idx; return eKeyHandled; case KEY_RIGHT: if (m_selected_row) { if (!m_selected_row->expanded) m_selected_row->Expand(); } return eKeyHandled; case KEY_LEFT: if (m_selected_row) { if (m_selected_row->expanded) m_selected_row->Unexpand(); else if (m_selected_row->parent) m_selected_row_idx = m_selected_row->parent->row_idx; } return eKeyHandled; case ' ': // Toggle expansion state when SPACE is pressed if (m_selected_row) { if (m_selected_row->expanded) m_selected_row->Unexpand(); else m_selected_row->Expand(); } return eKeyHandled; case 'h': window.CreateHelpSubwindow(); return eKeyHandled; default: break; } return eKeyNotHandled; } protected: std::vector<Row> m_rows; Row *m_selected_row; uint32_t m_selected_row_idx; uint32_t m_first_visible_row; uint32_t m_num_rows; int m_min_x; int m_min_y; int m_max_x; int m_max_y; static Format FormatForChar(int c) { switch (c) { case 'x': return eFormatHex; case 'X': return eFormatHexUppercase; case 'o': return eFormatOctal; case 's': return eFormatCString; case 'u': return eFormatUnsigned; case 'd': return eFormatDecimal; case 'D': return eFormatDefault; case 'i': return eFormatInstruction; case 'A': return eFormatAddressInfo; case 'p': return eFormatPointer; case 'c': return eFormatChar; case 'b': return eFormatBinary; case 'B': return eFormatBytesWithASCII; case 'f': return eFormatFloat; } return eFormatDefault; } bool DisplayRowObject(Window &window, Row &row, DisplayOptions &options, bool highlight, bool last_child) { ValueObject *valobj = row.value.GetSP().get(); if (valobj == nullptr) return false; const char *type_name = options.show_types ? valobj->GetTypeName().GetCString() : nullptr; const char *name = valobj->GetName().GetCString(); const char *value = valobj->GetValueAsCString(); const char *summary = valobj->GetSummaryAsCString(); window.MoveCursor(row.x, row.y); row.DrawTree(window); if (highlight) window.AttributeOn(A_REVERSE); if (type_name && type_name[0]) window.Printf("(%s) ", type_name); if (name && name[0]) window.PutCString(name); attr_t changd_attr = 0; if (valobj->GetValueDidChange()) changd_attr = COLOR_PAIR(5) | A_BOLD; if (value && value[0]) { window.PutCString(" = "); if (changd_attr) window.AttributeOn(changd_attr); window.PutCString(value); if (changd_attr) window.AttributeOff(changd_attr); } if (summary && summary[0]) { window.PutChar(' '); if (changd_attr) window.AttributeOn(changd_attr); window.PutCString(summary); if (changd_attr) window.AttributeOff(changd_attr); } if (highlight) window.AttributeOff(A_REVERSE); return true; } void DisplayRows(Window &window, std::vector<Row> &rows, DisplayOptions &options) { // > 0x25B7 // \/ 0x25BD bool window_is_active = window.IsActive(); for (auto &row : rows) { const bool last_child = row.parent && &rows[rows.size() - 1] == &row; // Save the row index in each Row structure row.row_idx = m_num_rows; if ((m_num_rows >= m_first_visible_row) && ((m_num_rows - m_first_visible_row) < static_cast<size_t>(NumVisibleRows()))) { row.x = m_min_x; row.y = m_num_rows - m_first_visible_row + 1; if (DisplayRowObject(window, row, options, window_is_active && m_num_rows == m_selected_row_idx, last_child)) { ++m_num_rows; } else { row.x = 0; row.y = 0; } } else { row.x = 0; row.y = 0; ++m_num_rows; } auto &children = row.GetChildren(); if (row.expanded && !children.empty()) { DisplayRows(window, children, options); } } } int CalculateTotalNumberRows(std::vector<Row> &rows) { int row_count = 0; for (auto &row : rows) { ++row_count; if (row.expanded) row_count += CalculateTotalNumberRows(row.GetChildren()); } return row_count; } static Row *GetRowForRowIndexImpl(std::vector<Row> &rows, size_t &row_index) { for (auto &row : rows) { if (row_index == 0) return &row; else { --row_index; auto &children = row.GetChildren(); if (row.expanded && !children.empty()) { Row *result = GetRowForRowIndexImpl(children, row_index); if (result) return result; } } } return nullptr; } Row *GetRowForRowIndex(size_t row_index) { return GetRowForRowIndexImpl(m_rows, row_index); } int NumVisibleRows() const { return m_max_y - m_min_y; } static DisplayOptions g_options; }; class FrameVariablesWindowDelegate : public ValueObjectListDelegate { public: FrameVariablesWindowDelegate(Debugger &debugger) : ValueObjectListDelegate(), m_debugger(debugger), m_frame_block(nullptr) {} ~FrameVariablesWindowDelegate() override = default; const char *WindowDelegateGetHelpText() override { return "Frame variable window keyboard shortcuts:"; } bool WindowDelegateDraw(Window &window, bool force) override { ExecutionContext exe_ctx( m_debugger.GetCommandInterpreter().GetExecutionContext()); Process *process = exe_ctx.GetProcessPtr(); Block *frame_block = nullptr; StackFrame *frame = nullptr; if (process) { StateType state = process->GetState(); if (StateIsStoppedState(state, true)) { frame = exe_ctx.GetFramePtr(); if (frame) frame_block = frame->GetFrameBlock(); } else if (StateIsRunningState(state)) { return true; // Don't do any updating when we are running } } ValueObjectList local_values; if (frame_block) { // Only update the variables if they have changed if (m_frame_block != frame_block) { m_frame_block = frame_block; VariableList *locals = frame->GetVariableList(true); if (locals) { const DynamicValueType use_dynamic = eDynamicDontRunTarget; const size_t num_locals = locals->GetSize(); for (size_t i = 0; i < num_locals; ++i) { ValueObjectSP value_sp = frame->GetValueObjectForFrameVariable( locals->GetVariableAtIndex(i), use_dynamic); if (value_sp) { ValueObjectSP synthetic_value_sp = value_sp->GetSyntheticValue(); if (synthetic_value_sp) local_values.Append(synthetic_value_sp); else local_values.Append(value_sp); } } // Update the values SetValues(local_values); } } } else { m_frame_block = nullptr; // Update the values with an empty list if there is no frame SetValues(local_values); } return ValueObjectListDelegate::WindowDelegateDraw(window, force); } protected: Debugger &m_debugger; Block *m_frame_block; }; class RegistersWindowDelegate : public ValueObjectListDelegate { public: RegistersWindowDelegate(Debugger &debugger) : ValueObjectListDelegate(), m_debugger(debugger) {} ~RegistersWindowDelegate() override = default; const char *WindowDelegateGetHelpText() override { return "Register window keyboard shortcuts:"; } bool WindowDelegateDraw(Window &window, bool force) override { ExecutionContext exe_ctx( m_debugger.GetCommandInterpreter().GetExecutionContext()); StackFrame *frame = exe_ctx.GetFramePtr(); ValueObjectList value_list; if (frame) { if (frame->GetStackID() != m_stack_id) { m_stack_id = frame->GetStackID(); RegisterContextSP reg_ctx(frame->GetRegisterContext()); if (reg_ctx) { const uint32_t num_sets = reg_ctx->GetRegisterSetCount(); for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx) { value_list.Append( ValueObjectRegisterSet::Create(frame, reg_ctx, set_idx)); } } SetValues(value_list); } } else { Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive()) return true; // Don't do any updating if we are running else { // Update the values with an empty list if there // is no process or the process isn't alive anymore SetValues(value_list); } } return ValueObjectListDelegate::WindowDelegateDraw(window, force); } protected: Debugger &m_debugger; StackID m_stack_id; }; static const char *CursesKeyToCString(int ch) { static char g_desc[32]; if (ch >= KEY_F0 && ch < KEY_F0 + 64) { snprintf(g_desc, sizeof(g_desc), "F%u", ch - KEY_F0); return g_desc; } switch (ch) { case KEY_DOWN: return "down"; case KEY_UP: return "up"; case KEY_LEFT: return "left"; case KEY_RIGHT: return "right"; case KEY_HOME: return "home"; case KEY_BACKSPACE: return "backspace"; case KEY_DL: return "delete-line"; case KEY_IL: return "insert-line"; case KEY_DC: return "delete-char"; case KEY_IC: return "insert-char"; case KEY_CLEAR: return "clear"; case KEY_EOS: return "clear-to-eos"; case KEY_EOL: return "clear-to-eol"; case KEY_SF: return "scroll-forward"; case KEY_SR: return "scroll-backward"; case KEY_NPAGE: return "page-down"; case KEY_PPAGE: return "page-up"; case KEY_STAB: return "set-tab"; case KEY_CTAB: return "clear-tab"; case KEY_CATAB: return "clear-all-tabs"; case KEY_ENTER: return "enter"; case KEY_PRINT: return "print"; case KEY_LL: return "lower-left key"; case KEY_A1: return "upper left of keypad"; case KEY_A3: return "upper right of keypad"; case KEY_B2: return "center of keypad"; case KEY_C1: return "lower left of keypad"; case KEY_C3: return "lower right of keypad"; case KEY_BTAB: return "back-tab key"; case KEY_BEG: return "begin key"; case KEY_CANCEL: return "cancel key"; case KEY_CLOSE: return "close key"; case KEY_COMMAND: return "command key"; case KEY_COPY: return "copy key"; case KEY_CREATE: return "create key"; case KEY_END: return "end key"; case KEY_EXIT: return "exit key"; case KEY_FIND: return "find key"; case KEY_HELP: return "help key"; case KEY_MARK: return "mark key"; case KEY_MESSAGE: return "message key"; case KEY_MOVE: return "move key"; case KEY_NEXT: return "next key"; case KEY_OPEN: return "open key"; case KEY_OPTIONS: return "options key"; case KEY_PREVIOUS: return "previous key"; case KEY_REDO: return "redo key"; case KEY_REFERENCE: return "reference key"; case KEY_REFRESH: return "refresh key"; case KEY_REPLACE: return "replace key"; case KEY_RESTART: return "restart key"; case KEY_RESUME: return "resume key"; case KEY_SAVE: return "save key"; case KEY_SBEG: return "shifted begin key"; case KEY_SCANCEL: return "shifted cancel key"; case KEY_SCOMMAND: return "shifted command key"; case KEY_SCOPY: return "shifted copy key"; case KEY_SCREATE: return "shifted create key"; case KEY_SDC: return "shifted delete-character key"; case KEY_SDL: return "shifted delete-line key"; case KEY_SELECT: return "select key"; case KEY_SEND: return "shifted end key"; case KEY_SEOL: return "shifted clear-to-end-of-line key"; case KEY_SEXIT: return "shifted exit key"; case KEY_SFIND: return "shifted find key"; case KEY_SHELP: return "shifted help key"; case KEY_SHOME: return "shifted home key"; case KEY_SIC: return "shifted insert-character key"; case KEY_SLEFT: return "shifted left-arrow key"; case KEY_SMESSAGE: return "shifted message key"; case KEY_SMOVE: return "shifted move key"; case KEY_SNEXT: return "shifted next key"; case KEY_SOPTIONS: return "shifted options key"; case KEY_SPREVIOUS: return "shifted previous key"; case KEY_SPRINT: return "shifted print key"; case KEY_SREDO: return "shifted redo key"; case KEY_SREPLACE: return "shifted replace key"; case KEY_SRIGHT: return "shifted right-arrow key"; case KEY_SRSUME: return "shifted resume key"; case KEY_SSAVE: return "shifted save key"; case KEY_SSUSPEND: return "shifted suspend key"; case KEY_SUNDO: return "shifted undo key"; case KEY_SUSPEND: return "suspend key"; case KEY_UNDO: return "undo key"; case KEY_MOUSE: return "Mouse event has occurred"; case KEY_RESIZE: return "Terminal resize event"; #ifdef KEY_EVENT case KEY_EVENT: return "We were interrupted by an event"; #endif case KEY_RETURN: return "return"; case ' ': return "space"; case '\t': return "tab"; case KEY_ESCAPE: return "escape"; default: if (isprint(ch)) snprintf(g_desc, sizeof(g_desc), "%c", ch); else snprintf(g_desc, sizeof(g_desc), "\\x%2.2x", ch); return g_desc; } return nullptr; } HelpDialogDelegate::HelpDialogDelegate(const char *text, KeyHelp *key_help_array) : m_text(), m_first_visible_line(0) { if (text && text[0]) { m_text.SplitIntoLines(text); m_text.AppendString(""); } if (key_help_array) { for (KeyHelp *key = key_help_array; key->ch; ++key) { StreamString key_description; key_description.Printf("%10s - %s", CursesKeyToCString(key->ch), key->description); m_text.AppendString(key_description.GetString()); } } } HelpDialogDelegate::~HelpDialogDelegate() = default; bool HelpDialogDelegate::WindowDelegateDraw(Window &window, bool force) { window.Erase(); const int window_height = window.GetHeight(); int x = 2; int y = 1; const int min_y = y; const int max_y = window_height - 1 - y; const size_t num_visible_lines = max_y - min_y + 1; const size_t num_lines = m_text.GetSize(); const char *bottom_message; if (num_lines <= num_visible_lines) bottom_message = "Press any key to exit"; else bottom_message = "Use arrows to scroll, any other key to exit"; window.DrawTitleBox(window.GetName(), bottom_message); while (y <= max_y) { window.MoveCursor(x, y); window.PutCStringTruncated( m_text.GetStringAtIndex(m_first_visible_line + y - min_y), 1); ++y; } return true; } HandleCharResult HelpDialogDelegate::WindowDelegateHandleChar(Window &window, int key) { bool done = false; const size_t num_lines = m_text.GetSize(); const size_t num_visible_lines = window.GetHeight() - 2; if (num_lines <= num_visible_lines) { done = true; // If we have all lines visible and don't need scrolling, then any // key press will cause us to exit } else { switch (key) { case KEY_UP: if (m_first_visible_line > 0) --m_first_visible_line; break; case KEY_DOWN: if (m_first_visible_line + num_visible_lines < num_lines) ++m_first_visible_line; break; case KEY_PPAGE: case ',': if (m_first_visible_line > 0) { if (static_cast<size_t>(m_first_visible_line) >= num_visible_lines) m_first_visible_line -= num_visible_lines; else m_first_visible_line = 0; } break; case KEY_NPAGE: case '.': if (m_first_visible_line + num_visible_lines < num_lines) { m_first_visible_line += num_visible_lines; if (static_cast<size_t>(m_first_visible_line) > num_lines) m_first_visible_line = num_lines - num_visible_lines; } break; default: done = true; break; } } if (done) window.GetParent()->RemoveSubWindow(&window); return eKeyHandled; } class ApplicationDelegate : public WindowDelegate, public MenuDelegate { public: enum { eMenuID_LLDB = 1, eMenuID_LLDBAbout, eMenuID_LLDBExit, eMenuID_Target, eMenuID_TargetCreate, eMenuID_TargetDelete, eMenuID_Process, eMenuID_ProcessAttach, eMenuID_ProcessDetach, eMenuID_ProcessLaunch, eMenuID_ProcessContinue, eMenuID_ProcessHalt, eMenuID_ProcessKill, eMenuID_Thread, eMenuID_ThreadStepIn, eMenuID_ThreadStepOver, eMenuID_ThreadStepOut, eMenuID_View, eMenuID_ViewBacktrace, eMenuID_ViewRegisters, eMenuID_ViewSource, eMenuID_ViewVariables, eMenuID_Help, eMenuID_HelpGUIHelp }; ApplicationDelegate(Application &app, Debugger &debugger) : WindowDelegate(), MenuDelegate(), m_app(app), m_debugger(debugger) {} ~ApplicationDelegate() override = default; bool WindowDelegateDraw(Window &window, bool force) override { return false; // Drawing not handled, let standard window drawing happen } HandleCharResult WindowDelegateHandleChar(Window &window, int key) override { switch (key) { case '\t': window.SelectNextWindowAsActive(); return eKeyHandled; case 'h': window.CreateHelpSubwindow(); return eKeyHandled; case KEY_ESCAPE: return eQuitApplication; default: break; } return eKeyNotHandled; } const char *WindowDelegateGetHelpText() override { return "Welcome to the LLDB curses GUI.\n\n" "Press the TAB key to change the selected view.\n" "Each view has its own keyboard shortcuts, press 'h' to open a " "dialog to display them.\n\n" "Common key bindings for all views:"; } KeyHelp *WindowDelegateGetKeyHelp() override { static curses::KeyHelp g_source_view_key_help[] = { {'\t', "Select next view"}, {'h', "Show help dialog with view specific key bindings"}, {',', "Page up"}, {'.', "Page down"}, {KEY_UP, "Select previous"}, {KEY_DOWN, "Select next"}, {KEY_LEFT, "Unexpand or select parent"}, {KEY_RIGHT, "Expand"}, {KEY_PPAGE, "Page up"}, {KEY_NPAGE, "Page down"}, {'\0', nullptr}}; return g_source_view_key_help; } MenuActionResult MenuDelegateAction(Menu &menu) override { switch (menu.GetIdentifier()) { case eMenuID_ThreadStepIn: { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasThreadScope()) { Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive() && StateIsStoppedState(process->GetState(), true)) exe_ctx.GetThreadRef().StepIn(true); } } return MenuActionResult::Handled; case eMenuID_ThreadStepOut: { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasThreadScope()) { Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive() && StateIsStoppedState(process->GetState(), true)) exe_ctx.GetThreadRef().StepOut(); } } return MenuActionResult::Handled; case eMenuID_ThreadStepOver: { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasThreadScope()) { Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive() && StateIsStoppedState(process->GetState(), true)) exe_ctx.GetThreadRef().StepOver(true); } } return MenuActionResult::Handled; case eMenuID_ProcessContinue: { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasProcessScope()) { Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive() && StateIsStoppedState(process->GetState(), true)) process->Resume(); } } return MenuActionResult::Handled; case eMenuID_ProcessKill: { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasProcessScope()) { Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive()) process->Destroy(false); } } return MenuActionResult::Handled; case eMenuID_ProcessHalt: { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasProcessScope()) { Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive()) process->Halt(); } } return MenuActionResult::Handled; case eMenuID_ProcessDetach: { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasProcessScope()) { Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive()) process->Detach(false); } } return MenuActionResult::Handled; case eMenuID_Process: { // Populate the menu with all of the threads if the process is stopped // when // the Process menu gets selected and is about to display its submenu. Menus &submenus = menu.GetSubmenus(); ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); Process *process = exe_ctx.GetProcessPtr(); if (process && process->IsAlive() && StateIsStoppedState(process->GetState(), true)) { if (submenus.size() == 7) menu.AddSubmenu(MenuSP(new Menu(Menu::Type::Separator))); else if (submenus.size() > 8) submenus.erase(submenus.begin() + 8, submenus.end()); ThreadList &threads = process->GetThreadList(); std::lock_guard<std::recursive_mutex> guard(threads.GetMutex()); size_t num_threads = threads.GetSize(); for (size_t i = 0; i < num_threads; ++i) { ThreadSP thread_sp = threads.GetThreadAtIndex(i); char menu_char = '\0'; if (i < 9) menu_char = '1' + i; StreamString thread_menu_title; thread_menu_title.Printf("Thread %u", thread_sp->GetIndexID()); const char *thread_name = thread_sp->GetName(); if (thread_name && thread_name[0]) thread_menu_title.Printf(" %s", thread_name); else { const char *queue_name = thread_sp->GetQueueName(); if (queue_name && queue_name[0]) thread_menu_title.Printf(" %s", queue_name); } menu.AddSubmenu( MenuSP(new Menu(thread_menu_title.GetString().str().c_str(), nullptr, menu_char, thread_sp->GetID()))); } } else if (submenus.size() > 7) { // Remove the separator and any other thread submenu items // that were previously added submenus.erase(submenus.begin() + 7, submenus.end()); } // Since we are adding and removing items we need to recalculate the name // lengths menu.RecalculateNameLengths(); } return MenuActionResult::Handled; case eMenuID_ViewVariables: { WindowSP main_window_sp = m_app.GetMainWindow(); WindowSP source_window_sp = main_window_sp->FindSubWindow("Source"); WindowSP variables_window_sp = main_window_sp->FindSubWindow("Variables"); WindowSP registers_window_sp = main_window_sp->FindSubWindow("Registers"); const Rect source_bounds = source_window_sp->GetBounds(); if (variables_window_sp) { const Rect variables_bounds = variables_window_sp->GetBounds(); main_window_sp->RemoveSubWindow(variables_window_sp.get()); if (registers_window_sp) { // We have a registers window, so give all the area back to the // registers window Rect registers_bounds = variables_bounds; registers_bounds.size.width = source_bounds.size.width; registers_window_sp->SetBounds(registers_bounds); } else { // We have no registers window showing so give the bottom // area back to the source view source_window_sp->Resize(source_bounds.size.width, source_bounds.size.height + variables_bounds.size.height); } } else { Rect new_variables_rect; if (registers_window_sp) { // We have a registers window so split the area of the registers // window into two columns where the left hand side will be the // variables and the right hand side will be the registers const Rect variables_bounds = registers_window_sp->GetBounds(); Rect new_registers_rect; variables_bounds.VerticalSplitPercentage(0.50, new_variables_rect, new_registers_rect); registers_window_sp->SetBounds(new_registers_rect); } else { // No variables window, grab the bottom part of the source window Rect new_source_rect; source_bounds.HorizontalSplitPercentage(0.70, new_source_rect, new_variables_rect); source_window_sp->SetBounds(new_source_rect); } WindowSP new_window_sp = main_window_sp->CreateSubWindow( "Variables", new_variables_rect, false); new_window_sp->SetDelegate( WindowDelegateSP(new FrameVariablesWindowDelegate(m_debugger))); } touchwin(stdscr); } return MenuActionResult::Handled; case eMenuID_ViewRegisters: { WindowSP main_window_sp = m_app.GetMainWindow(); WindowSP source_window_sp = main_window_sp->FindSubWindow("Source"); WindowSP variables_window_sp = main_window_sp->FindSubWindow("Variables"); WindowSP registers_window_sp = main_window_sp->FindSubWindow("Registers"); const Rect source_bounds = source_window_sp->GetBounds(); if (registers_window_sp) { if (variables_window_sp) { const Rect variables_bounds = variables_window_sp->GetBounds(); // We have a variables window, so give all the area back to the // variables window variables_window_sp->Resize(variables_bounds.size.width + registers_window_sp->GetWidth(), variables_bounds.size.height); } else { // We have no variables window showing so give the bottom // area back to the source view source_window_sp->Resize(source_bounds.size.width, source_bounds.size.height + registers_window_sp->GetHeight()); } main_window_sp->RemoveSubWindow(registers_window_sp.get()); } else { Rect new_regs_rect; if (variables_window_sp) { // We have a variables window, split it into two columns // where the left hand side will be the variables and the // right hand side will be the registers const Rect variables_bounds = variables_window_sp->GetBounds(); Rect new_vars_rect; variables_bounds.VerticalSplitPercentage(0.50, new_vars_rect, new_regs_rect); variables_window_sp->SetBounds(new_vars_rect); } else { // No registers window, grab the bottom part of the source window Rect new_source_rect; source_bounds.HorizontalSplitPercentage(0.70, new_source_rect, new_regs_rect); source_window_sp->SetBounds(new_source_rect); } WindowSP new_window_sp = main_window_sp->CreateSubWindow("Registers", new_regs_rect, false); new_window_sp->SetDelegate( WindowDelegateSP(new RegistersWindowDelegate(m_debugger))); } touchwin(stdscr); } return MenuActionResult::Handled; case eMenuID_HelpGUIHelp: m_app.GetMainWindow()->CreateHelpSubwindow(); return MenuActionResult::Handled; default: break; } return MenuActionResult::NotHandled; } protected: Application &m_app; Debugger &m_debugger; }; class StatusBarWindowDelegate : public WindowDelegate { public: StatusBarWindowDelegate(Debugger &debugger) : m_debugger(debugger) { FormatEntity::Parse("Thread: ${thread.id%tid}", m_format); } ~StatusBarWindowDelegate() override = default; bool WindowDelegateDraw(Window &window, bool force) override { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); Process *process = exe_ctx.GetProcessPtr(); Thread *thread = exe_ctx.GetThreadPtr(); StackFrame *frame = exe_ctx.GetFramePtr(); window.Erase(); window.SetBackground(2); window.MoveCursor(0, 0); if (process) { const StateType state = process->GetState(); window.Printf("Process: %5" PRIu64 " %10s", process->GetID(), StateAsCString(state)); if (StateIsStoppedState(state, true)) { StreamString strm; if (thread && FormatEntity::Format(m_format, strm, nullptr, &exe_ctx, nullptr, nullptr, false, false)) { window.MoveCursor(40, 0); window.PutCStringTruncated(strm.GetString().str().c_str(), 1); } window.MoveCursor(60, 0); if (frame) window.Printf("Frame: %3u PC = 0x%16.16" PRIx64, frame->GetFrameIndex(), frame->GetFrameCodeAddress().GetOpcodeLoadAddress( exe_ctx.GetTargetPtr())); } else if (state == eStateExited) { const char *exit_desc = process->GetExitDescription(); const int exit_status = process->GetExitStatus(); if (exit_desc && exit_desc[0]) window.Printf(" with status = %i (%s)", exit_status, exit_desc); else window.Printf(" with status = %i", exit_status); } } window.DeferredRefresh(); return true; } protected: Debugger &m_debugger; FormatEntity::Entry m_format; }; class SourceFileWindowDelegate : public WindowDelegate { public: SourceFileWindowDelegate(Debugger &debugger) : WindowDelegate(), m_debugger(debugger), m_sc(), m_file_sp(), m_disassembly_scope(nullptr), m_disassembly_sp(), m_disassembly_range(), m_title(), m_line_width(4), m_selected_line(0), m_pc_line(0), m_stop_id(0), m_frame_idx(UINT32_MAX), m_first_visible_line(0), m_min_x(0), m_min_y(0), m_max_x(0), m_max_y(0) {} ~SourceFileWindowDelegate() override = default; void Update(const SymbolContext &sc) { m_sc = sc; } uint32_t NumVisibleLines() const { return m_max_y - m_min_y; } const char *WindowDelegateGetHelpText() override { return "Source/Disassembly window keyboard shortcuts:"; } KeyHelp *WindowDelegateGetKeyHelp() override { static curses::KeyHelp g_source_view_key_help[] = { {KEY_RETURN, "Run to selected line with one shot breakpoint"}, {KEY_UP, "Select previous source line"}, {KEY_DOWN, "Select next source line"}, {KEY_PPAGE, "Page up"}, {KEY_NPAGE, "Page down"}, {'b', "Set breakpoint on selected source/disassembly line"}, {'c', "Continue process"}, {'d', "Detach and resume process"}, {'D', "Detach with process suspended"}, {'h', "Show help dialog"}, {'k', "Kill process"}, {'n', "Step over (source line)"}, {'N', "Step over (single instruction)"}, {'o', "Step out"}, {'s', "Step in (source line)"}, {'S', "Step in (single instruction)"}, {',', "Page up"}, {'.', "Page down"}, {'\0', nullptr}}; return g_source_view_key_help; } bool WindowDelegateDraw(Window &window, bool force) override { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); Process *process = exe_ctx.GetProcessPtr(); Thread *thread = nullptr; bool update_location = false; if (process) { StateType state = process->GetState(); if (StateIsStoppedState(state, true)) { // We are stopped, so it is ok to update_location = true; } } m_min_x = 1; m_min_y = 2; m_max_x = window.GetMaxX() - 1; m_max_y = window.GetMaxY() - 1; const uint32_t num_visible_lines = NumVisibleLines(); StackFrameSP frame_sp; bool set_selected_line_to_pc = false; if (update_location) { const bool process_alive = process ? process->IsAlive() : false; bool thread_changed = false; if (process_alive) { thread = exe_ctx.GetThreadPtr(); if (thread) { frame_sp = thread->GetSelectedFrame(); auto tid = thread->GetID(); thread_changed = tid != m_tid; m_tid = tid; } else { if (m_tid != LLDB_INVALID_THREAD_ID) { thread_changed = true; m_tid = LLDB_INVALID_THREAD_ID; } } } const uint32_t stop_id = process ? process->GetStopID() : 0; const bool stop_id_changed = stop_id != m_stop_id; bool frame_changed = false; m_stop_id = stop_id; m_title.Clear(); if (frame_sp) { m_sc = frame_sp->GetSymbolContext(eSymbolContextEverything); if (m_sc.module_sp) { m_title.Printf( "%s", m_sc.module_sp->GetFileSpec().GetFilename().GetCString()); ConstString func_name = m_sc.GetFunctionName(); if (func_name) m_title.Printf("`%s", func_name.GetCString()); } const uint32_t frame_idx = frame_sp->GetFrameIndex(); frame_changed = frame_idx != m_frame_idx; m_frame_idx = frame_idx; } else { m_sc.Clear(true); frame_changed = m_frame_idx != UINT32_MAX; m_frame_idx = UINT32_MAX; } const bool context_changed = thread_changed || frame_changed || stop_id_changed; if (process_alive) { if (m_sc.line_entry.IsValid()) { m_pc_line = m_sc.line_entry.line; if (m_pc_line != UINT32_MAX) --m_pc_line; // Convert to zero based line number... // Update the selected line if the stop ID changed... if (context_changed) m_selected_line = m_pc_line; if (m_file_sp && m_file_sp->FileSpecMatches(m_sc.line_entry.file)) { // Same file, nothing to do, we should either have the // lines or not (source file missing) if (m_selected_line >= static_cast<size_t>(m_first_visible_line)) { if (m_selected_line >= m_first_visible_line + num_visible_lines) m_first_visible_line = m_selected_line - 10; } else { if (m_selected_line > 10) m_first_visible_line = m_selected_line - 10; else m_first_visible_line = 0; } } else { // File changed, set selected line to the line with the PC m_selected_line = m_pc_line; m_file_sp = m_debugger.GetSourceManager().GetFile(m_sc.line_entry.file); if (m_file_sp) { const size_t num_lines = m_file_sp->GetNumLines(); int m_line_width = 1; for (size_t n = num_lines; n >= 10; n = n / 10) ++m_line_width; snprintf(m_line_format, sizeof(m_line_format), " %%%iu ", m_line_width); if (num_lines < num_visible_lines || m_selected_line < num_visible_lines) m_first_visible_line = 0; else m_first_visible_line = m_selected_line - 10; } } } else { m_file_sp.reset(); } if (!m_file_sp || m_file_sp->GetNumLines() == 0) { // Show disassembly bool prefer_file_cache = false; if (m_sc.function) { if (m_disassembly_scope != m_sc.function) { m_disassembly_scope = m_sc.function; m_disassembly_sp = m_sc.function->GetInstructions( exe_ctx, nullptr, prefer_file_cache); if (m_disassembly_sp) { set_selected_line_to_pc = true; m_disassembly_range = m_sc.function->GetAddressRange(); } else { m_disassembly_range.Clear(); } } else { set_selected_line_to_pc = context_changed; } } else if (m_sc.symbol) { if (m_disassembly_scope != m_sc.symbol) { m_disassembly_scope = m_sc.symbol; m_disassembly_sp = m_sc.symbol->GetInstructions( exe_ctx, nullptr, prefer_file_cache); if (m_disassembly_sp) { set_selected_line_to_pc = true; m_disassembly_range.GetBaseAddress() = m_sc.symbol->GetAddress(); m_disassembly_range.SetByteSize(m_sc.symbol->GetByteSize()); } else { m_disassembly_range.Clear(); } } else { set_selected_line_to_pc = context_changed; } } } } else { m_pc_line = UINT32_MAX; } } const int window_width = window.GetWidth(); window.Erase(); window.DrawTitleBox("Sources"); if (!m_title.GetString().empty()) { window.AttributeOn(A_REVERSE); window.MoveCursor(1, 1); window.PutChar(' '); window.PutCStringTruncated(m_title.GetString().str().c_str(), 1); int x = window.GetCursorX(); if (x < window_width - 1) { window.Printf("%*s", window_width - x - 1, ""); } window.AttributeOff(A_REVERSE); } Target *target = exe_ctx.GetTargetPtr(); const size_t num_source_lines = GetNumSourceLines(); if (num_source_lines > 0) { // Display source BreakpointLines bp_lines; if (target) { BreakpointList &bp_list = target->GetBreakpointList(); const size_t num_bps = bp_list.GetSize(); for (size_t bp_idx = 0; bp_idx < num_bps; ++bp_idx) { BreakpointSP bp_sp = bp_list.GetBreakpointAtIndex(bp_idx); const size_t num_bps_locs = bp_sp->GetNumLocations(); for (size_t bp_loc_idx = 0; bp_loc_idx < num_bps_locs; ++bp_loc_idx) { BreakpointLocationSP bp_loc_sp = bp_sp->GetLocationAtIndex(bp_loc_idx); LineEntry bp_loc_line_entry; if (bp_loc_sp->GetAddress().CalculateSymbolContextLineEntry( bp_loc_line_entry)) { if (m_file_sp->GetFileSpec() == bp_loc_line_entry.file) { bp_lines.insert(bp_loc_line_entry.line); } } } } } const attr_t selected_highlight_attr = A_REVERSE; const attr_t pc_highlight_attr = COLOR_PAIR(1); for (size_t i = 0; i < num_visible_lines; ++i) { const uint32_t curr_line = m_first_visible_line + i; if (curr_line < num_source_lines) { const int line_y = m_min_y + i; window.MoveCursor(1, line_y); const bool is_pc_line = curr_line == m_pc_line; const bool line_is_selected = m_selected_line == curr_line; // Highlight the line as the PC line first, then if the selected line // isn't the same as the PC line, highlight it differently attr_t highlight_attr = 0; attr_t bp_attr = 0; if (is_pc_line) highlight_attr = pc_highlight_attr; else if (line_is_selected) highlight_attr = selected_highlight_attr; if (bp_lines.find(curr_line + 1) != bp_lines.end()) bp_attr = COLOR_PAIR(2); if (bp_attr) window.AttributeOn(bp_attr); window.Printf(m_line_format, curr_line + 1); if (bp_attr) window.AttributeOff(bp_attr); window.PutChar(ACS_VLINE); // Mark the line with the PC with a diamond if (is_pc_line) window.PutChar(ACS_DIAMOND); else window.PutChar(' '); if (highlight_attr) window.AttributeOn(highlight_attr); const uint32_t line_len = m_file_sp->GetLineLength(curr_line + 1, false); if (line_len > 0) window.PutCString(m_file_sp->PeekLineData(curr_line + 1), line_len); if (is_pc_line && frame_sp && frame_sp->GetConcreteFrameIndex() == 0) { StopInfoSP stop_info_sp; if (thread) stop_info_sp = thread->GetStopInfo(); if (stop_info_sp) { const char *stop_description = stop_info_sp->GetDescription(); if (stop_description && stop_description[0]) { size_t stop_description_len = strlen(stop_description); int desc_x = window_width - stop_description_len - 16; window.Printf("%*s", desc_x - window.GetCursorX(), ""); // window.MoveCursor(window_width - stop_description_len - 15, // line_y); window.Printf("<<< Thread %u: %s ", thread->GetIndexID(), stop_description); } } else { window.Printf("%*s", window_width - window.GetCursorX() - 1, ""); } } if (highlight_attr) window.AttributeOff(highlight_attr); } else { break; } } } else { size_t num_disassembly_lines = GetNumDisassemblyLines(); if (num_disassembly_lines > 0) { // Display disassembly BreakpointAddrs bp_file_addrs; Target *target = exe_ctx.GetTargetPtr(); if (target) { BreakpointList &bp_list = target->GetBreakpointList(); const size_t num_bps = bp_list.GetSize(); for (size_t bp_idx = 0; bp_idx < num_bps; ++bp_idx) { BreakpointSP bp_sp = bp_list.GetBreakpointAtIndex(bp_idx); const size_t num_bps_locs = bp_sp->GetNumLocations(); for (size_t bp_loc_idx = 0; bp_loc_idx < num_bps_locs; ++bp_loc_idx) { BreakpointLocationSP bp_loc_sp = bp_sp->GetLocationAtIndex(bp_loc_idx); LineEntry bp_loc_line_entry; const lldb::addr_t file_addr = bp_loc_sp->GetAddress().GetFileAddress(); if (file_addr != LLDB_INVALID_ADDRESS) { if (m_disassembly_range.ContainsFileAddress(file_addr)) bp_file_addrs.insert(file_addr); } } } } const attr_t selected_highlight_attr = A_REVERSE; const attr_t pc_highlight_attr = COLOR_PAIR(1); StreamString strm; InstructionList &insts = m_disassembly_sp->GetInstructionList(); Address pc_address; if (frame_sp) pc_address = frame_sp->GetFrameCodeAddress(); const uint32_t pc_idx = pc_address.IsValid() ? insts.GetIndexOfInstructionAtAddress(pc_address) : UINT32_MAX; if (set_selected_line_to_pc) { m_selected_line = pc_idx; } const uint32_t non_visible_pc_offset = (num_visible_lines / 5); if (static_cast<size_t>(m_first_visible_line) >= num_disassembly_lines) m_first_visible_line = 0; if (pc_idx < num_disassembly_lines) { if (pc_idx < static_cast<uint32_t>(m_first_visible_line) || pc_idx >= m_first_visible_line + num_visible_lines) m_first_visible_line = pc_idx - non_visible_pc_offset; } for (size_t i = 0; i < num_visible_lines; ++i) { const uint32_t inst_idx = m_first_visible_line + i; Instruction *inst = insts.GetInstructionAtIndex(inst_idx).get(); if (!inst) break; const int line_y = m_min_y + i; window.MoveCursor(1, line_y); const bool is_pc_line = frame_sp && inst_idx == pc_idx; const bool line_is_selected = m_selected_line == inst_idx; // Highlight the line as the PC line first, then if the selected line // isn't the same as the PC line, highlight it differently attr_t highlight_attr = 0; attr_t bp_attr = 0; if (is_pc_line) highlight_attr = pc_highlight_attr; else if (line_is_selected) highlight_attr = selected_highlight_attr; if (bp_file_addrs.find(inst->GetAddress().GetFileAddress()) != bp_file_addrs.end()) bp_attr = COLOR_PAIR(2); if (bp_attr) window.AttributeOn(bp_attr); window.Printf(" 0x%16.16llx ", static_cast<unsigned long long>( inst->GetAddress().GetLoadAddress(target))); if (bp_attr) window.AttributeOff(bp_attr); window.PutChar(ACS_VLINE); // Mark the line with the PC with a diamond if (is_pc_line) window.PutChar(ACS_DIAMOND); else window.PutChar(' '); if (highlight_attr) window.AttributeOn(highlight_attr); const char *mnemonic = inst->GetMnemonic(&exe_ctx); const char *operands = inst->GetOperands(&exe_ctx); const char *comment = inst->GetComment(&exe_ctx); if (mnemonic != nullptr && mnemonic[0] == '\0') mnemonic = nullptr; if (operands != nullptr && operands[0] == '\0') operands = nullptr; if (comment != nullptr && comment[0] == '\0') comment = nullptr; strm.Clear(); if (mnemonic != nullptr && operands != nullptr && comment != nullptr) strm.Printf("%-8s %-25s ; %s", mnemonic, operands, comment); else if (mnemonic != nullptr && operands != nullptr) strm.Printf("%-8s %s", mnemonic, operands); else if (mnemonic != nullptr) strm.Printf("%s", mnemonic); int right_pad = 1; window.PutCStringTruncated(strm.GetData(), right_pad); if (is_pc_line && frame_sp && frame_sp->GetConcreteFrameIndex() == 0) { StopInfoSP stop_info_sp; if (thread) stop_info_sp = thread->GetStopInfo(); if (stop_info_sp) { const char *stop_description = stop_info_sp->GetDescription(); if (stop_description && stop_description[0]) { size_t stop_description_len = strlen(stop_description); int desc_x = window_width - stop_description_len - 16; window.Printf("%*s", desc_x - window.GetCursorX(), ""); // window.MoveCursor(window_width - stop_description_len - 15, // line_y); window.Printf("<<< Thread %u: %s ", thread->GetIndexID(), stop_description); } } else { window.Printf("%*s", window_width - window.GetCursorX() - 1, ""); } } if (highlight_attr) window.AttributeOff(highlight_attr); } } } window.DeferredRefresh(); return true; // Drawing handled } size_t GetNumLines() { size_t num_lines = GetNumSourceLines(); if (num_lines == 0) num_lines = GetNumDisassemblyLines(); return num_lines; } size_t GetNumSourceLines() const { if (m_file_sp) return m_file_sp->GetNumLines(); return 0; } size_t GetNumDisassemblyLines() const { if (m_disassembly_sp) return m_disassembly_sp->GetInstructionList().GetSize(); return 0; } HandleCharResult WindowDelegateHandleChar(Window &window, int c) override { const uint32_t num_visible_lines = NumVisibleLines(); const size_t num_lines = GetNumLines(); switch (c) { case ',': case KEY_PPAGE: // Page up key if (static_cast<uint32_t>(m_first_visible_line) > num_visible_lines) m_first_visible_line -= num_visible_lines; else m_first_visible_line = 0; m_selected_line = m_first_visible_line; return eKeyHandled; case '.': case KEY_NPAGE: // Page down key { if (m_first_visible_line + num_visible_lines < num_lines) m_first_visible_line += num_visible_lines; else if (num_lines < num_visible_lines) m_first_visible_line = 0; else m_first_visible_line = num_lines - num_visible_lines; m_selected_line = m_first_visible_line; } return eKeyHandled; case KEY_UP: if (m_selected_line > 0) { m_selected_line--; if (static_cast<size_t>(m_first_visible_line) > m_selected_line) m_first_visible_line = m_selected_line; } return eKeyHandled; case KEY_DOWN: if (m_selected_line + 1 < num_lines) { m_selected_line++; if (m_first_visible_line + num_visible_lines < m_selected_line) m_first_visible_line++; } return eKeyHandled; case '\r': case '\n': case KEY_ENTER: // Set a breakpoint and run to the line using a one shot breakpoint if (GetNumSourceLines() > 0) { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasProcessScope() && exe_ctx.GetProcessRef().IsAlive()) { BreakpointSP bp_sp = exe_ctx.GetTargetRef().CreateBreakpoint( nullptr, // Don't limit the breakpoint to certain modules m_file_sp->GetFileSpec(), // Source file m_selected_line + 1, // Source line number (m_selected_line is zero based) 0, // No offset eLazyBoolCalculate, // Check inlines using global setting eLazyBoolCalculate, // Skip prologue using global setting, false, // internal false, // request_hardware eLazyBoolCalculate); // move_to_nearest_code // Make breakpoint one shot bp_sp->GetOptions()->SetOneShot(true); exe_ctx.GetProcessRef().Resume(); } } else if (m_selected_line < GetNumDisassemblyLines()) { const Instruction *inst = m_disassembly_sp->GetInstructionList() .GetInstructionAtIndex(m_selected_line) .get(); ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasTargetScope()) { Address addr = inst->GetAddress(); BreakpointSP bp_sp = exe_ctx.GetTargetRef().CreateBreakpoint( addr, // lldb_private::Address false, // internal false); // request_hardware // Make breakpoint one shot bp_sp->GetOptions()->SetOneShot(true); exe_ctx.GetProcessRef().Resume(); } } return eKeyHandled; case 'b': // 'b' == toggle breakpoint on currently selected line if (m_selected_line < GetNumSourceLines()) { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasTargetScope()) { BreakpointSP bp_sp = exe_ctx.GetTargetRef().CreateBreakpoint( nullptr, // Don't limit the breakpoint to certain modules m_file_sp->GetFileSpec(), // Source file m_selected_line + 1, // Source line number (m_selected_line is zero based) 0, // No offset eLazyBoolCalculate, // Check inlines using global setting eLazyBoolCalculate, // Skip prologue using global setting, false, // internal false, // request_hardware eLazyBoolCalculate); // move_to_nearest_code } } else if (m_selected_line < GetNumDisassemblyLines()) { const Instruction *inst = m_disassembly_sp->GetInstructionList() .GetInstructionAtIndex(m_selected_line) .get(); ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasTargetScope()) { Address addr = inst->GetAddress(); BreakpointSP bp_sp = exe_ctx.GetTargetRef().CreateBreakpoint( addr, // lldb_private::Address false, // internal false); // request_hardware } } return eKeyHandled; case 'd': // 'd' == detach and let run case 'D': // 'D' == detach and keep stopped { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasProcessScope()) exe_ctx.GetProcessRef().Detach(c == 'D'); } return eKeyHandled; case 'k': // 'k' == kill { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasProcessScope()) exe_ctx.GetProcessRef().Destroy(false); } return eKeyHandled; case 'c': // 'c' == continue { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasProcessScope()) exe_ctx.GetProcessRef().Resume(); } return eKeyHandled; case 'o': // 'o' == step out { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasThreadScope() && StateIsStoppedState(exe_ctx.GetProcessRef().GetState(), true)) { exe_ctx.GetThreadRef().StepOut(); } } return eKeyHandled; case 'n': // 'n' == step over case 'N': // 'N' == step over instruction { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasThreadScope() && StateIsStoppedState(exe_ctx.GetProcessRef().GetState(), true)) { bool source_step = (c == 'n'); exe_ctx.GetThreadRef().StepOver(source_step); } } return eKeyHandled; case 's': // 's' == step into case 'S': // 'S' == step into instruction { ExecutionContext exe_ctx = m_debugger.GetCommandInterpreter().GetExecutionContext(); if (exe_ctx.HasThreadScope() && StateIsStoppedState(exe_ctx.GetProcessRef().GetState(), true)) { bool source_step = (c == 's'); exe_ctx.GetThreadRef().StepIn(source_step); } } return eKeyHandled; case 'h': window.CreateHelpSubwindow(); return eKeyHandled; default: break; } return eKeyNotHandled; } protected: typedef std::set<uint32_t> BreakpointLines; typedef std::set<lldb::addr_t> BreakpointAddrs; Debugger &m_debugger; SymbolContext m_sc; SourceManager::FileSP m_file_sp; SymbolContextScope *m_disassembly_scope; lldb::DisassemblerSP m_disassembly_sp; AddressRange m_disassembly_range; StreamString m_title; lldb::user_id_t m_tid; char m_line_format[8]; int m_line_width; uint32_t m_selected_line; // The selected line uint32_t m_pc_line; // The line with the PC uint32_t m_stop_id; uint32_t m_frame_idx; int m_first_visible_line; int m_min_x; int m_min_y; int m_max_x; int m_max_y; }; DisplayOptions ValueObjectListDelegate::g_options = {true}; IOHandlerCursesGUI::IOHandlerCursesGUI(Debugger &debugger) : IOHandler(debugger, IOHandler::Type::Curses) {} void IOHandlerCursesGUI::Activate() { IOHandler::Activate(); if (!m_app_ap) { m_app_ap.reset(new Application(GetInputFILE(), GetOutputFILE())); // This is both a window and a menu delegate std::shared_ptr<ApplicationDelegate> app_delegate_sp( new ApplicationDelegate(*m_app_ap, m_debugger)); MenuDelegateSP app_menu_delegate_sp = std::static_pointer_cast<MenuDelegate>(app_delegate_sp); MenuSP lldb_menu_sp( new Menu("LLDB", "F1", KEY_F(1), ApplicationDelegate::eMenuID_LLDB)); MenuSP exit_menuitem_sp( new Menu("Exit", nullptr, 'x', ApplicationDelegate::eMenuID_LLDBExit)); exit_menuitem_sp->SetCannedResult(MenuActionResult::Quit); lldb_menu_sp->AddSubmenu(MenuSP(new Menu( "About LLDB", nullptr, 'a', ApplicationDelegate::eMenuID_LLDBAbout))); lldb_menu_sp->AddSubmenu(MenuSP(new Menu(Menu::Type::Separator))); lldb_menu_sp->AddSubmenu(exit_menuitem_sp); MenuSP target_menu_sp(new Menu("Target", "F2", KEY_F(2), ApplicationDelegate::eMenuID_Target)); target_menu_sp->AddSubmenu(MenuSP(new Menu( "Create", nullptr, 'c', ApplicationDelegate::eMenuID_TargetCreate))); target_menu_sp->AddSubmenu(MenuSP(new Menu( "Delete", nullptr, 'd', ApplicationDelegate::eMenuID_TargetDelete))); MenuSP process_menu_sp(new Menu("Process", "F3", KEY_F(3), ApplicationDelegate::eMenuID_Process)); process_menu_sp->AddSubmenu(MenuSP(new Menu( "Attach", nullptr, 'a', ApplicationDelegate::eMenuID_ProcessAttach))); process_menu_sp->AddSubmenu(MenuSP(new Menu( "Detach", nullptr, 'd', ApplicationDelegate::eMenuID_ProcessDetach))); process_menu_sp->AddSubmenu(MenuSP(new Menu( "Launch", nullptr, 'l', ApplicationDelegate::eMenuID_ProcessLaunch))); process_menu_sp->AddSubmenu(MenuSP(new Menu(Menu::Type::Separator))); process_menu_sp->AddSubmenu( MenuSP(new Menu("Continue", nullptr, 'c', ApplicationDelegate::eMenuID_ProcessContinue))); process_menu_sp->AddSubmenu(MenuSP(new Menu( "Halt", nullptr, 'h', ApplicationDelegate::eMenuID_ProcessHalt))); process_menu_sp->AddSubmenu(MenuSP(new Menu( "Kill", nullptr, 'k', ApplicationDelegate::eMenuID_ProcessKill))); MenuSP thread_menu_sp(new Menu("Thread", "F4", KEY_F(4), ApplicationDelegate::eMenuID_Thread)); thread_menu_sp->AddSubmenu(MenuSP(new Menu( "Step In", nullptr, 'i', ApplicationDelegate::eMenuID_ThreadStepIn))); thread_menu_sp->AddSubmenu( MenuSP(new Menu("Step Over", nullptr, 'v', ApplicationDelegate::eMenuID_ThreadStepOver))); thread_menu_sp->AddSubmenu(MenuSP(new Menu( "Step Out", nullptr, 'o', ApplicationDelegate::eMenuID_ThreadStepOut))); MenuSP view_menu_sp( new Menu("View", "F5", KEY_F(5), ApplicationDelegate::eMenuID_View)); view_menu_sp->AddSubmenu( MenuSP(new Menu("Backtrace", nullptr, 'b', ApplicationDelegate::eMenuID_ViewBacktrace))); view_menu_sp->AddSubmenu( MenuSP(new Menu("Registers", nullptr, 'r', ApplicationDelegate::eMenuID_ViewRegisters))); view_menu_sp->AddSubmenu(MenuSP(new Menu( "Source", nullptr, 's', ApplicationDelegate::eMenuID_ViewSource))); view_menu_sp->AddSubmenu( MenuSP(new Menu("Variables", nullptr, 'v', ApplicationDelegate::eMenuID_ViewVariables))); MenuSP help_menu_sp( new Menu("Help", "F6", KEY_F(6), ApplicationDelegate::eMenuID_Help)); help_menu_sp->AddSubmenu(MenuSP(new Menu( "GUI Help", nullptr, 'g', ApplicationDelegate::eMenuID_HelpGUIHelp))); m_app_ap->Initialize(); WindowSP &main_window_sp = m_app_ap->GetMainWindow(); MenuSP menubar_sp(new Menu(Menu::Type::Bar)); menubar_sp->AddSubmenu(lldb_menu_sp); menubar_sp->AddSubmenu(target_menu_sp); menubar_sp->AddSubmenu(process_menu_sp); menubar_sp->AddSubmenu(thread_menu_sp); menubar_sp->AddSubmenu(view_menu_sp); menubar_sp->AddSubmenu(help_menu_sp); menubar_sp->SetDelegate(app_menu_delegate_sp); Rect content_bounds = main_window_sp->GetFrame(); Rect menubar_bounds = content_bounds.MakeMenuBar(); Rect status_bounds = content_bounds.MakeStatusBar(); Rect source_bounds; Rect variables_bounds; Rect threads_bounds; Rect source_variables_bounds; content_bounds.VerticalSplitPercentage(0.80, source_variables_bounds, threads_bounds); source_variables_bounds.HorizontalSplitPercentage(0.70, source_bounds, variables_bounds); WindowSP menubar_window_sp = main_window_sp->CreateSubWindow("Menubar", menubar_bounds, false); // Let the menubar get keys if the active window doesn't handle the // keys that are typed so it can respond to menubar key presses. menubar_window_sp->SetCanBeActive( false); // Don't let the menubar become the active window menubar_window_sp->SetDelegate(menubar_sp); WindowSP source_window_sp( main_window_sp->CreateSubWindow("Source", source_bounds, true)); WindowSP variables_window_sp( main_window_sp->CreateSubWindow("Variables", variables_bounds, false)); WindowSP threads_window_sp( main_window_sp->CreateSubWindow("Threads", threads_bounds, false)); WindowSP status_window_sp( main_window_sp->CreateSubWindow("Status", status_bounds, false)); status_window_sp->SetCanBeActive( false); // Don't let the status bar become the active window main_window_sp->SetDelegate( std::static_pointer_cast<WindowDelegate>(app_delegate_sp)); source_window_sp->SetDelegate( WindowDelegateSP(new SourceFileWindowDelegate(m_debugger))); variables_window_sp->SetDelegate( WindowDelegateSP(new FrameVariablesWindowDelegate(m_debugger))); TreeDelegateSP thread_delegate_sp(new ThreadsTreeDelegate(m_debugger)); threads_window_sp->SetDelegate(WindowDelegateSP( new TreeWindowDelegate(m_debugger, thread_delegate_sp))); status_window_sp->SetDelegate( WindowDelegateSP(new StatusBarWindowDelegate(m_debugger))); // Show the main help window once the first time the curses GUI is launched static bool g_showed_help = false; if (!g_showed_help) { g_showed_help = true; main_window_sp->CreateHelpSubwindow(); } init_pair(1, COLOR_WHITE, COLOR_BLUE); init_pair(2, COLOR_BLACK, COLOR_WHITE); init_pair(3, COLOR_MAGENTA, COLOR_WHITE); init_pair(4, COLOR_MAGENTA, COLOR_BLACK); init_pair(5, COLOR_RED, COLOR_BLACK); } } void IOHandlerCursesGUI::Deactivate() { m_app_ap->Terminate(); } void IOHandlerCursesGUI::Run() { m_app_ap->Run(m_debugger); SetIsDone(true); } IOHandlerCursesGUI::~IOHandlerCursesGUI() = default; void IOHandlerCursesGUI::Cancel() {} bool IOHandlerCursesGUI::Interrupt() { return false; } void IOHandlerCursesGUI::GotEOF() {} #endif // LLDB_DISABLE_CURSES
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. // Copyright (C) 2014, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ /* //////////////////////////////////////////////////////////////////// // // Mat basic operations: Copy, Set // // */ #include "precomp.hpp" #include "opencl_kernels_core.hpp" namespace cv { template<typename T> static void copyMask_(const uchar* _src, size_t sstep, const uchar* mask, size_t mstep, uchar* _dst, size_t dstep, Size size) { for( ; size.height--; mask += mstep, _src += sstep, _dst += dstep ) { const T* src = (const T*)_src; T* dst = (T*)_dst; int x = 0; #if CV_ENABLE_UNROLLED for( ; x <= size.width - 4; x += 4 ) { if( mask[x] ) dst[x] = src[x]; if( mask[x+1] ) dst[x+1] = src[x+1]; if( mask[x+2] ) dst[x+2] = src[x+2]; if( mask[x+3] ) dst[x+3] = src[x+3]; } #endif for( ; x < size.width; x++ ) if( mask[x] ) dst[x] = src[x]; } } template<> void copyMask_<uchar>(const uchar* _src, size_t sstep, const uchar* mask, size_t mstep, uchar* _dst, size_t dstep, Size size) { CV_IPP_RUN_FAST(CV_INSTRUMENT_FUN_IPP(ippiCopy_8u_C1MR, _src, (int)sstep, _dst, (int)dstep, ippiSize(size), mask, (int)mstep) >= 0) for( ; size.height--; mask += mstep, _src += sstep, _dst += dstep ) { const uchar* src = (const uchar*)_src; uchar* dst = (uchar*)_dst; int x = 0; #if CV_SIMD { v_uint8 v_zero = vx_setzero_u8(); for( ; x <= size.width - v_uint8::nlanes; x += v_uint8::nlanes ) { v_uint8 v_src = vx_load(src + x), v_dst = vx_load(dst + x), v_nmask = vx_load(mask + x) == v_zero; v_dst = v_select(v_nmask, v_dst, v_src); v_store(dst + x, v_dst); } } vx_cleanup(); #endif for( ; x < size.width; x++ ) if( mask[x] ) dst[x] = src[x]; } } template<> void copyMask_<ushort>(const uchar* _src, size_t sstep, const uchar* mask, size_t mstep, uchar* _dst, size_t dstep, Size size) { CV_IPP_RUN_FAST(CV_INSTRUMENT_FUN_IPP(ippiCopy_16u_C1MR, (const Ipp16u *)_src, (int)sstep, (Ipp16u *)_dst, (int)dstep, ippiSize(size), mask, (int)mstep) >= 0) for( ; size.height--; mask += mstep, _src += sstep, _dst += dstep ) { const ushort* src = (const ushort*)_src; ushort* dst = (ushort*)_dst; int x = 0; #if CV_SIMD { v_uint8 v_zero = vx_setzero_u8(); for( ; x <= size.width - v_uint8::nlanes; x += v_uint8::nlanes ) { v_uint16 v_src1 = vx_load(src + x), v_src2 = vx_load(src + x + v_uint16::nlanes), v_dst1 = vx_load(dst + x), v_dst2 = vx_load(dst + x + v_uint16::nlanes); v_uint8 v_nmask1, v_nmask2; v_uint8 v_nmask = vx_load(mask + x) == v_zero; v_zip(v_nmask, v_nmask, v_nmask1, v_nmask2); v_dst1 = v_select(v_reinterpret_as_u16(v_nmask1), v_dst1, v_src1); v_dst2 = v_select(v_reinterpret_as_u16(v_nmask2), v_dst2, v_src2); v_store(dst + x, v_dst1); v_store(dst + x + v_uint16::nlanes, v_dst2); } } vx_cleanup(); #endif for( ; x < size.width; x++ ) if( mask[x] ) dst[x] = src[x]; } } static void copyMaskGeneric(const uchar* _src, size_t sstep, const uchar* mask, size_t mstep, uchar* _dst, size_t dstep, Size size, void* _esz) { size_t k, esz = *(size_t*)_esz; for( ; size.height--; mask += mstep, _src += sstep, _dst += dstep ) { const uchar* src = _src; uchar* dst = _dst; int x = 0; for( ; x < size.width; x++, src += esz, dst += esz ) { if( !mask[x] ) continue; for( k = 0; k < esz; k++ ) dst[k] = src[k]; } } } #define DEF_COPY_MASK(suffix, type) \ static void copyMask##suffix(const uchar* src, size_t sstep, const uchar* mask, size_t mstep, \ uchar* dst, size_t dstep, Size size, void*) \ { \ copyMask_<type>(src, sstep, mask, mstep, dst, dstep, size); \ } #if defined HAVE_IPP #define DEF_COPY_MASK_F(suffix, type, ippfavor, ipptype) \ static void copyMask##suffix(const uchar* src, size_t sstep, const uchar* mask, size_t mstep, \ uchar* dst, size_t dstep, Size size, void*) \ { \ CV_IPP_RUN_FAST(CV_INSTRUMENT_FUN_IPP(ippiCopy_##ippfavor, (const ipptype *)src, (int)sstep, (ipptype *)dst, (int)dstep, ippiSize(size), (const Ipp8u *)mask, (int)mstep) >= 0)\ copyMask_<type>(src, sstep, mask, mstep, dst, dstep, size); \ } #else #define DEF_COPY_MASK_F(suffix, type, ippfavor, ipptype) \ static void copyMask##suffix(const uchar* src, size_t sstep, const uchar* mask, size_t mstep, \ uchar* dst, size_t dstep, Size size, void*) \ { \ copyMask_<type>(src, sstep, mask, mstep, dst, dstep, size); \ } #endif #if IPP_VERSION_X100 == 901 // bug in IPP 9.0.1 DEF_COPY_MASK(32sC3, Vec3i) DEF_COPY_MASK(8uC3, Vec3b) #else DEF_COPY_MASK_F(8uC3, Vec3b, 8u_C3MR, Ipp8u) DEF_COPY_MASK_F(32sC3, Vec3i, 32s_C3MR, Ipp32s) #endif DEF_COPY_MASK(8u, uchar) DEF_COPY_MASK(16u, ushort) DEF_COPY_MASK_F(32s, int, 32s_C1MR, Ipp32s) DEF_COPY_MASK_F(16uC3, Vec3s, 16u_C3MR, Ipp16u) DEF_COPY_MASK(32sC2, Vec2i) DEF_COPY_MASK_F(32sC4, Vec4i, 32s_C4MR, Ipp32s) DEF_COPY_MASK(32sC6, Vec6i) DEF_COPY_MASK(32sC8, Vec8i) BinaryFunc copyMaskTab[] = { 0, copyMask8u, copyMask16u, copyMask8uC3, copyMask32s, 0, copyMask16uC3, 0, copyMask32sC2, 0, 0, 0, copyMask32sC3, 0, 0, 0, copyMask32sC4, 0, 0, 0, 0, 0, 0, 0, copyMask32sC6, 0, 0, 0, 0, 0, 0, 0, copyMask32sC8 }; BinaryFunc getCopyMaskFunc(size_t esz) { return esz <= 32 && copyMaskTab[esz] ? copyMaskTab[esz] : copyMaskGeneric; } /* dst = src */ void Mat::copyTo( OutputArray _dst ) const { CV_INSTRUMENT_REGION(); #ifdef HAVE_CUDA if (_dst.isGpuMat()) { _dst.getGpuMat().upload(*this); return; } #endif int dtype = _dst.type(); if( _dst.fixedType() && dtype != type() ) { CV_Assert( channels() == CV_MAT_CN(dtype) ); convertTo( _dst, dtype ); return; } if( empty() ) { _dst.release(); return; } if( _dst.isUMat() ) { _dst.create( dims, size.p, type() ); UMat dst = _dst.getUMat(); CV_Assert(dst.u != NULL); size_t i, sz[CV_MAX_DIM] = {0}, dstofs[CV_MAX_DIM], esz = elemSize(); CV_Assert(dims > 0 && dims < CV_MAX_DIM); for( i = 0; i < (size_t)dims; i++ ) sz[i] = size.p[i]; sz[dims-1] *= esz; dst.ndoffset(dstofs); dstofs[dims-1] *= esz; dst.u->currAllocator->upload(dst.u, data, dims, sz, dstofs, dst.step.p, step.p); return; } if( dims <= 2 ) { _dst.create( rows, cols, type() ); Mat dst = _dst.getMat(); if( data == dst.data ) return; if( rows > 0 && cols > 0 ) { Mat src = *this; Size sz = getContinuousSize2D(src, dst, (int)elemSize()); CV_CheckGE(sz.width, 0, ""); const uchar* sptr = src.data; uchar* dptr = dst.data; #if IPP_VERSION_X100 >= 201700 CV_IPP_RUN_FAST(CV_INSTRUMENT_FUN_IPP(ippiCopy_8u_C1R_L, sptr, (int)src.step, dptr, (int)dst.step, ippiSizeL(sz.width, sz.height)) >= 0) #endif for (; sz.height--; sptr += src.step, dptr += dst.step) memcpy(dptr, sptr, sz.width); } return; } _dst.create( dims, size, type() ); Mat dst = _dst.getMat(); if( data == dst.data ) return; if( total() != 0 ) { const Mat* arrays[] = { this, &dst }; uchar* ptrs[2] = {}; NAryMatIterator it(arrays, ptrs, 2); size_t sz = it.size*elemSize(); for( size_t i = 0; i < it.nplanes; i++, ++it ) memcpy(ptrs[1], ptrs[0], sz); } } #ifdef HAVE_IPP static bool ipp_copyTo(const Mat &src, Mat &dst, const Mat &mask) { #ifdef HAVE_IPP_IW_LL CV_INSTRUMENT_REGION_IPP(); if(mask.channels() > 1 || mask.depth() != CV_8U) return false; if (src.dims <= 2) { IppiSize size = ippiSize(src.size()); return CV_INSTRUMENT_FUN_IPP(llwiCopyMask, src.ptr(), (int)src.step, dst.ptr(), (int)dst.step, size, (int)src.elemSize1(), src.channels(), mask.ptr(), (int)mask.step) >= 0; } else { const Mat *arrays[] = {&src, &dst, &mask, NULL}; uchar *ptrs[3] = {NULL}; NAryMatIterator it(arrays, ptrs); IppiSize size = ippiSize(it.size, 1); for (size_t i = 0; i < it.nplanes; i++, ++it) { if(CV_INSTRUMENT_FUN_IPP(llwiCopyMask, ptrs[0], 0, ptrs[1], 0, size, (int)src.elemSize1(), src.channels(), ptrs[2], 0) < 0) return false; } return true; } #else CV_UNUSED(src); CV_UNUSED(dst); CV_UNUSED(mask); return false; #endif } #endif void Mat::copyTo( OutputArray _dst, InputArray _mask ) const { CV_INSTRUMENT_REGION(); Mat mask = _mask.getMat(); if( !mask.data ) { copyTo(_dst); return; } int cn = channels(), mcn = mask.channels(); CV_Assert( mask.depth() == CV_8U && (mcn == 1 || mcn == cn) ); bool colorMask = mcn > 1; if( dims <= 2 ) { CV_Assert( size() == mask.size() ); } Mat dst; { Mat dst0 = _dst.getMat(); _dst.create(dims, size, type()); // TODO Prohibit 'dst' re-creation, user should pass it explicitly with correct size/type or empty dst = _dst.getMat(); if (dst.data != dst0.data) // re-allocation happened { #ifdef OPENCV_FUTURE CV_Assert(dst0.empty() && "copyTo(): dst size/type mismatch (looks like a bug) - use dst.release() before copyTo() call to suppress this message"); #endif dst = Scalar(0); // do not leave dst uninitialized } } CV_IPP_RUN_FAST(ipp_copyTo(*this, dst, mask)) size_t esz = colorMask ? elemSize1() : elemSize(); BinaryFunc copymask = getCopyMaskFunc(esz); if( dims <= 2 ) { Mat src = *this; Size sz = getContinuousSize2D(src, dst, mask, mcn); copymask(src.data, src.step, mask.data, mask.step, dst.data, dst.step, sz, &esz); return; } const Mat* arrays[] = { this, &dst, &mask, 0 }; uchar* ptrs[3] = {}; NAryMatIterator it(arrays, ptrs); Size sz((int)(it.size*mcn), 1); for( size_t i = 0; i < it.nplanes; i++, ++it ) copymask(ptrs[0], 0, ptrs[2], 0, ptrs[1], 0, sz, &esz); } Mat& Mat::operator = (const Scalar& s) { CV_INSTRUMENT_REGION(); if (this->empty()) return *this; const Mat* arrays[] = { this }; uchar* dptr; NAryMatIterator it(arrays, &dptr, 1); size_t elsize = it.size*elemSize(); const int64* is = (const int64*)&s.val[0]; if( is[0] == 0 && is[1] == 0 && is[2] == 0 && is[3] == 0 ) { for( size_t i = 0; i < it.nplanes; i++, ++it ) memset( dptr, 0, elsize ); } else { if( it.nplanes > 0 ) { double scalar[12]; scalarToRawData(s, scalar, type(), 12); size_t blockSize = 12*elemSize1(); for( size_t j = 0; j < elsize; j += blockSize ) { size_t sz = MIN(blockSize, elsize - j); CV_Assert(sz <= sizeof(scalar)); memcpy( dptr + j, scalar, sz ); } } for( size_t i = 1; i < it.nplanes; i++ ) { ++it; memcpy( dptr, data, elsize ); } } return *this; } #ifdef HAVE_IPP static bool ipp_Mat_setTo_Mat(Mat &dst, Mat &_val, Mat &mask) { #ifdef HAVE_IPP_IW_LL CV_INSTRUMENT_REGION_IPP(); if(mask.empty()) return false; if(mask.depth() != CV_8U || mask.channels() > 1) return false; if(dst.channels() > 4) return false; if (dst.depth() == CV_32F) { for (int i = 0; i < (int)(_val.total()); i++) { float v = (float)(_val.at<double>(i)); // cast to float if (cvIsNaN(v) || cvIsInf(v)) // accept finite numbers only return false; } } if(dst.dims <= 2) { IppiSize size = ippiSize(dst.size()); IppDataType dataType = ippiGetDataType(dst.depth()); ::ipp::IwValueFloat s; convertAndUnrollScalar(_val, CV_MAKETYPE(CV_64F, dst.channels()), (uchar*)((Ipp64f*)s), 1); return CV_INSTRUMENT_FUN_IPP(llwiSetMask, s, dst.ptr(), (int)dst.step, size, dataType, dst.channels(), mask.ptr(), (int)mask.step) >= 0; } else { const Mat *arrays[] = {&dst, mask.empty()?NULL:&mask, NULL}; uchar *ptrs[2] = {NULL}; NAryMatIterator it(arrays, ptrs); IppiSize size = {(int)it.size, 1}; IppDataType dataType = ippiGetDataType(dst.depth()); ::ipp::IwValueFloat s; convertAndUnrollScalar(_val, CV_MAKETYPE(CV_64F, dst.channels()), (uchar*)((Ipp64f*)s), 1); for( size_t i = 0; i < it.nplanes; i++, ++it) { if(CV_INSTRUMENT_FUN_IPP(llwiSetMask, s, ptrs[0], 0, size, dataType, dst.channels(), ptrs[1], 0) < 0) return false; } return true; } #else CV_UNUSED(dst); CV_UNUSED(_val); CV_UNUSED(mask); return false; #endif } #endif Mat& Mat::setTo(InputArray _value, InputArray _mask) { CV_INSTRUMENT_REGION(); if( empty() ) return *this; Mat value = _value.getMat(), mask = _mask.getMat(); CV_Assert( checkScalar(value, type(), _value.kind(), _InputArray::MAT )); int cn = channels(), mcn = mask.channels(); CV_Assert( mask.empty() || (mask.depth() == CV_8U && (mcn == 1 || mcn == cn) && size == mask.size) ); CV_IPP_RUN_FAST(ipp_Mat_setTo_Mat(*this, value, mask), *this) size_t esz = mcn > 1 ? elemSize1() : elemSize(); BinaryFunc copymask = getCopyMaskFunc(esz); const Mat* arrays[] = { this, !mask.empty() ? &mask : 0, 0 }; uchar* ptrs[2]={0,0}; NAryMatIterator it(arrays, ptrs); int totalsz = (int)it.size*mcn; int blockSize0 = std::min(totalsz, (int)((BLOCK_SIZE + esz-1)/esz)); blockSize0 -= blockSize0 % mcn; // must be divisible without remainder for unrolling and advancing AutoBuffer<uchar> _scbuf(blockSize0*esz + 32); uchar* scbuf = alignPtr((uchar*)_scbuf.data(), (int)sizeof(double)); convertAndUnrollScalar( value, type(), scbuf, blockSize0/mcn ); for( size_t i = 0; i < it.nplanes; i++, ++it ) { for( int j = 0; j < totalsz; j += blockSize0 ) { Size sz(std::min(blockSize0, totalsz - j), 1); size_t blockSize = sz.width*esz; if( ptrs[1] ) { copymask(scbuf, 0, ptrs[1], 0, ptrs[0], 0, sz, &esz); ptrs[1] += sz.width; } else memcpy(ptrs[0], scbuf, blockSize); ptrs[0] += blockSize; } } return *this; } static void flipHoriz( const uchar* src, size_t sstep, uchar* dst, size_t dstep, Size size, size_t esz ) { int i, j, limit = (int)(((size.width + 1)/2)*esz); AutoBuffer<int> _tab(size.width*esz); int* tab = _tab.data(); for( i = 0; i < size.width; i++ ) for( size_t k = 0; k < esz; k++ ) tab[i*esz + k] = (int)((size.width - i - 1)*esz + k); for( ; size.height--; src += sstep, dst += dstep ) { for( i = 0; i < limit; i++ ) { j = tab[i]; uchar t0 = src[i], t1 = src[j]; dst[i] = t1; dst[j] = t0; } } } static void flipVert( const uchar* src0, size_t sstep, uchar* dst0, size_t dstep, Size size, size_t esz ) { const uchar* src1 = src0 + (size.height - 1)*sstep; uchar* dst1 = dst0 + (size.height - 1)*dstep; size.width *= (int)esz; for( int y = 0; y < (size.height + 1)/2; y++, src0 += sstep, src1 -= sstep, dst0 += dstep, dst1 -= dstep ) { int i = 0; if( ((size_t)src0|(size_t)dst0|(size_t)src1|(size_t)dst1) % sizeof(int) == 0 ) { for( ; i <= size.width - 16; i += 16 ) { int t0 = ((int*)(src0 + i))[0]; int t1 = ((int*)(src1 + i))[0]; ((int*)(dst0 + i))[0] = t1; ((int*)(dst1 + i))[0] = t0; t0 = ((int*)(src0 + i))[1]; t1 = ((int*)(src1 + i))[1]; ((int*)(dst0 + i))[1] = t1; ((int*)(dst1 + i))[1] = t0; t0 = ((int*)(src0 + i))[2]; t1 = ((int*)(src1 + i))[2]; ((int*)(dst0 + i))[2] = t1; ((int*)(dst1 + i))[2] = t0; t0 = ((int*)(src0 + i))[3]; t1 = ((int*)(src1 + i))[3]; ((int*)(dst0 + i))[3] = t1; ((int*)(dst1 + i))[3] = t0; } for( ; i <= size.width - 4; i += 4 ) { int t0 = ((int*)(src0 + i))[0]; int t1 = ((int*)(src1 + i))[0]; ((int*)(dst0 + i))[0] = t1; ((int*)(dst1 + i))[0] = t0; } } for( ; i < size.width; i++ ) { uchar t0 = src0[i]; uchar t1 = src1[i]; dst0[i] = t1; dst1[i] = t0; } } } #ifdef HAVE_OPENCL enum { FLIP_COLS = 1 << 0, FLIP_ROWS = 1 << 1, FLIP_BOTH = FLIP_ROWS | FLIP_COLS }; static bool ocl_flip(InputArray _src, OutputArray _dst, int flipCode ) { CV_Assert(flipCode >= -1 && flipCode <= 1); const ocl::Device & dev = ocl::Device::getDefault(); int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type), flipType, kercn = std::min(ocl::predictOptimalVectorWidth(_src, _dst), 4); bool doubleSupport = dev.doubleFPConfig() > 0; if (!doubleSupport && depth == CV_64F) kercn = cn; if (cn > 4) return false; const char * kernelName; if (flipCode == 0) kernelName = "arithm_flip_rows", flipType = FLIP_ROWS; else if (flipCode > 0) kernelName = "arithm_flip_cols", flipType = FLIP_COLS; else kernelName = "arithm_flip_rows_cols", flipType = FLIP_BOTH; int pxPerWIy = (dev.isIntel() && (dev.type() & ocl::Device::TYPE_GPU)) ? 4 : 1; kercn = (cn!=3 || flipType == FLIP_ROWS) ? std::max(kercn, cn) : cn; ocl::Kernel k(kernelName, ocl::core::flip_oclsrc, format( "-D T=%s -D T1=%s -D cn=%d -D PIX_PER_WI_Y=%d -D kercn=%d", kercn != cn ? ocl::typeToStr(CV_MAKE_TYPE(depth, kercn)) : ocl::vecopTypeToStr(CV_MAKE_TYPE(depth, kercn)), kercn != cn ? ocl::typeToStr(depth) : ocl::vecopTypeToStr(depth), cn, pxPerWIy, kercn)); if (k.empty()) return false; Size size = _src.size(); _dst.create(size, type); UMat src = _src.getUMat(), dst = _dst.getUMat(); int cols = size.width * cn / kercn, rows = size.height; cols = flipType == FLIP_COLS ? (cols + 1) >> 1 : cols; rows = flipType & FLIP_ROWS ? (rows + 1) >> 1 : rows; k.args(ocl::KernelArg::ReadOnlyNoSize(src), ocl::KernelArg::WriteOnly(dst, cn, kercn), rows, cols); size_t maxWorkGroupSize = dev.maxWorkGroupSize(); CV_Assert(maxWorkGroupSize % 4 == 0); size_t globalsize[2] = { (size_t)cols, ((size_t)rows + pxPerWIy - 1) / pxPerWIy }, localsize[2] = { maxWorkGroupSize / 4, 4 }; return k.run(2, globalsize, (flipType == FLIP_COLS) && !dev.isIntel() ? localsize : NULL, false); } #endif #if defined HAVE_IPP static bool ipp_flip(Mat &src, Mat &dst, int flip_mode) { #ifdef HAVE_IPP_IW CV_INSTRUMENT_REGION_IPP(); IppiAxis ippMode; if(flip_mode < 0) ippMode = ippAxsBoth; else if(flip_mode == 0) ippMode = ippAxsHorizontal; else ippMode = ippAxsVertical; try { ::ipp::IwiImage iwSrc = ippiGetImage(src); ::ipp::IwiImage iwDst = ippiGetImage(dst); CV_INSTRUMENT_FUN_IPP(::ipp::iwiMirror, iwSrc, iwDst, ippMode); } catch(const ::ipp::IwException &) { return false; } return true; #else CV_UNUSED(src); CV_UNUSED(dst); CV_UNUSED(flip_mode); return false; #endif } #endif void flip( InputArray _src, OutputArray _dst, int flip_mode ) { CV_INSTRUMENT_REGION(); CV_Assert( _src.dims() <= 2 ); Size size = _src.size(); if (flip_mode < 0) { if (size.width == 1) flip_mode = 0; if (size.height == 1) flip_mode = 1; } if ((size.width == 1 && flip_mode > 0) || (size.height == 1 && flip_mode == 0) || (size.height == 1 && size.width == 1 && flip_mode < 0)) { return _src.copyTo(_dst); } CV_OCL_RUN( _dst.isUMat(), ocl_flip(_src, _dst, flip_mode)) Mat src = _src.getMat(); int type = src.type(); _dst.create( size, type ); Mat dst = _dst.getMat(); CV_IPP_RUN_FAST(ipp_flip(src, dst, flip_mode)); size_t esz = CV_ELEM_SIZE(type); if( flip_mode <= 0 ) flipVert( src.ptr(), src.step, dst.ptr(), dst.step, src.size(), esz ); else flipHoriz( src.ptr(), src.step, dst.ptr(), dst.step, src.size(), esz ); if( flip_mode < 0 ) flipHoriz( dst.ptr(), dst.step, dst.ptr(), dst.step, dst.size(), esz ); } #ifdef HAVE_OPENCL static bool ocl_rotate(InputArray _src, OutputArray _dst, int rotateMode) { switch (rotateMode) { case ROTATE_90_CLOCKWISE: transpose(_src, _dst); flip(_dst, _dst, 1); break; case ROTATE_180: flip(_src, _dst, -1); break; case ROTATE_90_COUNTERCLOCKWISE: transpose(_src, _dst); flip(_dst, _dst, 0); break; default: break; } return true; } #endif void rotate(InputArray _src, OutputArray _dst, int rotateMode) { CV_Assert(_src.dims() <= 2); CV_OCL_RUN(_dst.isUMat(), ocl_rotate(_src, _dst, rotateMode)) switch (rotateMode) { case ROTATE_90_CLOCKWISE: transpose(_src, _dst); flip(_dst, _dst, 1); break; case ROTATE_180: flip(_src, _dst, -1); break; case ROTATE_90_COUNTERCLOCKWISE: transpose(_src, _dst); flip(_dst, _dst, 0); break; default: break; } } #if defined HAVE_OPENCL && !defined __APPLE__ static bool ocl_repeat(InputArray _src, int ny, int nx, OutputArray _dst) { if (ny == 1 && nx == 1) { _src.copyTo(_dst); return true; } int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type), rowsPerWI = ocl::Device::getDefault().isIntel() ? 4 : 1, kercn = ocl::predictOptimalVectorWidth(_src, _dst); ocl::Kernel k("repeat", ocl::core::repeat_oclsrc, format("-D T=%s -D nx=%d -D ny=%d -D rowsPerWI=%d -D cn=%d", ocl::memopTypeToStr(CV_MAKE_TYPE(depth, kercn)), nx, ny, rowsPerWI, kercn)); if (k.empty()) return false; UMat src = _src.getUMat(), dst = _dst.getUMat(); k.args(ocl::KernelArg::ReadOnly(src, cn, kercn), ocl::KernelArg::WriteOnlyNoSize(dst)); size_t globalsize[] = { (size_t)src.cols * cn / kercn, ((size_t)src.rows + rowsPerWI - 1) / rowsPerWI }; return k.run(2, globalsize, NULL, false); } #endif void repeat(InputArray _src, int ny, int nx, OutputArray _dst) { CV_INSTRUMENT_REGION(); CV_Assert(_src.getObj() != _dst.getObj()); CV_Assert( _src.dims() <= 2 ); CV_Assert( ny > 0 && nx > 0 ); Size ssize = _src.size(); _dst.create(ssize.height*ny, ssize.width*nx, _src.type()); #if !defined __APPLE__ CV_OCL_RUN(_dst.isUMat(), ocl_repeat(_src, ny, nx, _dst)) #endif Mat src = _src.getMat(), dst = _dst.getMat(); Size dsize = dst.size(); int esz = (int)src.elemSize(); int x, y; ssize.width *= esz; dsize.width *= esz; for( y = 0; y < ssize.height; y++ ) { for( x = 0; x < dsize.width; x += ssize.width ) memcpy( dst.ptr(y) + x, src.ptr(y), ssize.width ); } for( ; y < dsize.height; y++ ) memcpy( dst.ptr(y), dst.ptr(y - ssize.height), dsize.width ); } Mat repeat(const Mat& src, int ny, int nx) { if( nx == 1 && ny == 1 ) return src; Mat dst; repeat(src, ny, nx, dst); return dst; } } // cv /* Various border types, image boundaries are denoted with '|' * BORDER_REPLICATE: aaaaaa|abcdefgh|hhhhhhh * BORDER_REFLECT: fedcba|abcdefgh|hgfedcb * BORDER_REFLECT_101: gfedcb|abcdefgh|gfedcba * BORDER_WRAP: cdefgh|abcdefgh|abcdefg * BORDER_CONSTANT: iiiiii|abcdefgh|iiiiiii with some specified 'i' */ int cv::borderInterpolate( int p, int len, int borderType ) { CV_TRACE_FUNCTION_VERBOSE(); CV_DbgAssert(len > 0); #ifdef CV_STATIC_ANALYSIS if(p >= 0 && p < len) #else if( (unsigned)p < (unsigned)len ) #endif ; else if( borderType == BORDER_REPLICATE ) p = p < 0 ? 0 : len - 1; else if( borderType == BORDER_REFLECT || borderType == BORDER_REFLECT_101 ) { int delta = borderType == BORDER_REFLECT_101; if( len == 1 ) return 0; do { if( p < 0 ) p = -p - 1 + delta; else p = len - 1 - (p - len) - delta; } #ifdef CV_STATIC_ANALYSIS while(p < 0 || p >= len); #else while( (unsigned)p >= (unsigned)len ); #endif } else if( borderType == BORDER_WRAP ) { CV_Assert(len > 0); if( p < 0 ) p -= ((p-len+1)/len)*len; if( p >= len ) p %= len; } else if( borderType == BORDER_CONSTANT ) p = -1; else CV_Error( CV_StsBadArg, "Unknown/unsupported border type" ); return p; } namespace { void copyMakeBorder_8u( const uchar* src, size_t srcstep, cv::Size srcroi, uchar* dst, size_t dststep, cv::Size dstroi, int top, int left, int cn, int borderType ) { const int isz = (int)sizeof(int); int i, j, k, elemSize = 1; bool intMode = false; if( (cn | srcstep | dststep | (size_t)src | (size_t)dst) % isz == 0 ) { cn /= isz; elemSize = isz; intMode = true; } cv::AutoBuffer<int> _tab((dstroi.width - srcroi.width)*cn); int* tab = _tab.data(); int right = dstroi.width - srcroi.width - left; int bottom = dstroi.height - srcroi.height - top; for( i = 0; i < left; i++ ) { j = cv::borderInterpolate(i - left, srcroi.width, borderType)*cn; for( k = 0; k < cn; k++ ) tab[i*cn + k] = j + k; } for( i = 0; i < right; i++ ) { j = cv::borderInterpolate(srcroi.width + i, srcroi.width, borderType)*cn; for( k = 0; k < cn; k++ ) tab[(i+left)*cn + k] = j + k; } srcroi.width *= cn; dstroi.width *= cn; left *= cn; right *= cn; uchar* dstInner = dst + dststep*top + left*elemSize; for( i = 0; i < srcroi.height; i++, dstInner += dststep, src += srcstep ) { if( dstInner != src ) memcpy(dstInner, src, srcroi.width*elemSize); if( intMode ) { const int* isrc = (int*)src; int* idstInner = (int*)dstInner; for( j = 0; j < left; j++ ) idstInner[j - left] = isrc[tab[j]]; for( j = 0; j < right; j++ ) idstInner[j + srcroi.width] = isrc[tab[j + left]]; } else { for( j = 0; j < left; j++ ) dstInner[j - left] = src[tab[j]]; for( j = 0; j < right; j++ ) dstInner[j + srcroi.width] = src[tab[j + left]]; } } dstroi.width *= elemSize; dst += dststep*top; for( i = 0; i < top; i++ ) { j = cv::borderInterpolate(i - top, srcroi.height, borderType); memcpy(dst + (i - top)*dststep, dst + j*dststep, dstroi.width); } for( i = 0; i < bottom; i++ ) { j = cv::borderInterpolate(i + srcroi.height, srcroi.height, borderType); memcpy(dst + (i + srcroi.height)*dststep, dst + j*dststep, dstroi.width); } } void copyMakeConstBorder_8u( const uchar* src, size_t srcstep, cv::Size srcroi, uchar* dst, size_t dststep, cv::Size dstroi, int top, int left, int cn, const uchar* value ) { int i, j; cv::AutoBuffer<uchar> _constBuf(dstroi.width*cn); uchar* constBuf = _constBuf.data(); int right = dstroi.width - srcroi.width - left; int bottom = dstroi.height - srcroi.height - top; for( i = 0; i < dstroi.width; i++ ) { for( j = 0; j < cn; j++ ) constBuf[i*cn + j] = value[j]; } srcroi.width *= cn; dstroi.width *= cn; left *= cn; right *= cn; uchar* dstInner = dst + dststep*top + left; for( i = 0; i < srcroi.height; i++, dstInner += dststep, src += srcstep ) { if( dstInner != src ) memcpy( dstInner, src, srcroi.width ); memcpy( dstInner - left, constBuf, left ); memcpy( dstInner + srcroi.width, constBuf, right ); } dst += dststep*top; for( i = 0; i < top; i++ ) memcpy(dst + (i - top)*dststep, constBuf, dstroi.width); for( i = 0; i < bottom; i++ ) memcpy(dst + (i + srcroi.height)*dststep, constBuf, dstroi.width); } } #ifdef HAVE_OPENCL namespace cv { static bool ocl_copyMakeBorder( InputArray _src, OutputArray _dst, int top, int bottom, int left, int right, int borderType, const Scalar& value ) { int type = _src.type(), cn = CV_MAT_CN(type), depth = CV_MAT_DEPTH(type), rowsPerWI = ocl::Device::getDefault().isIntel() ? 4 : 1; bool isolated = (borderType & BORDER_ISOLATED) != 0; borderType &= ~cv::BORDER_ISOLATED; if ( !(borderType == BORDER_CONSTANT || borderType == BORDER_REPLICATE || borderType == BORDER_REFLECT || borderType == BORDER_WRAP || borderType == BORDER_REFLECT_101) || cn > 4) return false; const char * const borderMap[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", "BORDER_WRAP", "BORDER_REFLECT_101" }; int scalarcn = cn == 3 ? 4 : cn; int sctype = CV_MAKETYPE(depth, scalarcn); String buildOptions = format("-D T=%s -D %s -D T1=%s -D cn=%d -D ST=%s -D rowsPerWI=%d", ocl::memopTypeToStr(type), borderMap[borderType], ocl::memopTypeToStr(depth), cn, ocl::memopTypeToStr(sctype), rowsPerWI); ocl::Kernel k("copyMakeBorder", ocl::core::copymakeborder_oclsrc, buildOptions); if (k.empty()) return false; UMat src = _src.getUMat(); if( src.isSubmatrix() && !isolated ) { Size wholeSize; Point ofs; src.locateROI(wholeSize, ofs); int dtop = std::min(ofs.y, top); int dbottom = std::min(wholeSize.height - src.rows - ofs.y, bottom); int dleft = std::min(ofs.x, left); int dright = std::min(wholeSize.width - src.cols - ofs.x, right); src.adjustROI(dtop, dbottom, dleft, dright); top -= dtop; left -= dleft; bottom -= dbottom; right -= dright; } _dst.create(src.rows + top + bottom, src.cols + left + right, type); UMat dst = _dst.getUMat(); if (top == 0 && left == 0 && bottom == 0 && right == 0) { if(src.u != dst.u || src.step != dst.step) src.copyTo(dst); return true; } k.args(ocl::KernelArg::ReadOnly(src), ocl::KernelArg::WriteOnly(dst), top, left, ocl::KernelArg::Constant(Mat(1, 1, sctype, value))); size_t globalsize[2] = { (size_t)dst.cols, ((size_t)dst.rows + rowsPerWI - 1) / rowsPerWI }; return k.run(2, globalsize, NULL, false); } } #endif #ifdef HAVE_IPP namespace cv { static bool ipp_copyMakeBorder( Mat &_src, Mat &_dst, int top, int bottom, int left, int right, int _borderType, const Scalar& value ) { #if defined HAVE_IPP_IW_LL && !IPP_DISABLE_PERF_COPYMAKE CV_INSTRUMENT_REGION_IPP(); ::ipp::IwiBorderSize borderSize(left, top, right, bottom); ::ipp::IwiSize size(_src.cols, _src.rows); IppDataType dataType = ippiGetDataType(_src.depth()); IppiBorderType borderType = ippiGetBorderType(_borderType); if((int)borderType == -1) return false; if(_src.dims > 2) return false; Rect dstRect(borderSize.left, borderSize.top, _dst.cols - borderSize.right - borderSize.left, _dst.rows - borderSize.bottom - borderSize.top); Mat subDst = Mat(_dst, dstRect); Mat *pSrc = &_src; return CV_INSTRUMENT_FUN_IPP(llwiCopyMakeBorder, pSrc->ptr(), pSrc->step, subDst.ptr(), subDst.step, size, dataType, _src.channels(), borderSize, borderType, &value[0]) >= 0; #else CV_UNUSED(_src); CV_UNUSED(_dst); CV_UNUSED(top); CV_UNUSED(bottom); CV_UNUSED(left); CV_UNUSED(right); CV_UNUSED(_borderType); CV_UNUSED(value); return false; #endif } } #endif void cv::copyMakeBorder( InputArray _src, OutputArray _dst, int top, int bottom, int left, int right, int borderType, const Scalar& value ) { CV_INSTRUMENT_REGION(); CV_Assert( top >= 0 && bottom >= 0 && left >= 0 && right >= 0 && _src.dims() <= 2); CV_OCL_RUN(_dst.isUMat(), ocl_copyMakeBorder(_src, _dst, top, bottom, left, right, borderType, value)) Mat src = _src.getMat(); int type = src.type(); if( src.isSubmatrix() && (borderType & BORDER_ISOLATED) == 0 ) { Size wholeSize; Point ofs; src.locateROI(wholeSize, ofs); int dtop = std::min(ofs.y, top); int dbottom = std::min(wholeSize.height - src.rows - ofs.y, bottom); int dleft = std::min(ofs.x, left); int dright = std::min(wholeSize.width - src.cols - ofs.x, right); src.adjustROI(dtop, dbottom, dleft, dright); top -= dtop; left -= dleft; bottom -= dbottom; right -= dright; } _dst.create( src.rows + top + bottom, src.cols + left + right, type ); Mat dst = _dst.getMat(); if(top == 0 && left == 0 && bottom == 0 && right == 0) { if(src.data != dst.data || src.step != dst.step) src.copyTo(dst); return; } borderType &= ~BORDER_ISOLATED; CV_IPP_RUN_FAST(ipp_copyMakeBorder(src, dst, top, bottom, left, right, borderType, value)) if( borderType != BORDER_CONSTANT ) copyMakeBorder_8u( src.ptr(), src.step, src.size(), dst.ptr(), dst.step, dst.size(), top, left, (int)src.elemSize(), borderType ); else { int cn = src.channels(), cn1 = cn; AutoBuffer<double> buf(cn); if( cn > 4 ) { CV_Assert( value[0] == value[1] && value[0] == value[2] && value[0] == value[3] ); cn1 = 1; } scalarToRawData(value, buf.data(), CV_MAKETYPE(src.depth(), cn1), cn); copyMakeConstBorder_8u( src.ptr(), src.step, src.size(), dst.ptr(), dst.step, dst.size(), top, left, (int)src.elemSize(), (uchar*)buf.data() ); } } /* dst = src */ CV_IMPL void cvCopy( const void* srcarr, void* dstarr, const void* maskarr ) { if( CV_IS_SPARSE_MAT(srcarr) && CV_IS_SPARSE_MAT(dstarr)) { CV_Assert( maskarr == 0 ); CvSparseMat* src1 = (CvSparseMat*)srcarr; CvSparseMat* dst1 = (CvSparseMat*)dstarr; CvSparseMatIterator iterator; CvSparseNode* node; dst1->dims = src1->dims; memcpy( dst1->size, src1->size, src1->dims*sizeof(src1->size[0])); dst1->valoffset = src1->valoffset; dst1->idxoffset = src1->idxoffset; cvClearSet( dst1->heap ); if( src1->heap->active_count >= dst1->hashsize*CV_SPARSE_HASH_RATIO ) { cvFree( &dst1->hashtable ); dst1->hashsize = src1->hashsize; dst1->hashtable = (void**)cvAlloc( dst1->hashsize*sizeof(dst1->hashtable[0])); } memset( dst1->hashtable, 0, dst1->hashsize*sizeof(dst1->hashtable[0])); for( node = cvInitSparseMatIterator( src1, &iterator ); node != 0; node = cvGetNextSparseNode( &iterator )) { CvSparseNode* node_copy = (CvSparseNode*)cvSetNew( dst1->heap ); int tabidx = node->hashval & (dst1->hashsize - 1); memcpy( node_copy, node, dst1->heap->elem_size ); node_copy->next = (CvSparseNode*)dst1->hashtable[tabidx]; dst1->hashtable[tabidx] = node_copy; } return; } cv::Mat src = cv::cvarrToMat(srcarr, false, true, 1), dst = cv::cvarrToMat(dstarr, false, true, 1); CV_Assert( src.depth() == dst.depth() && src.size == dst.size ); int coi1 = 0, coi2 = 0; if( CV_IS_IMAGE(srcarr) ) coi1 = cvGetImageCOI((const IplImage*)srcarr); if( CV_IS_IMAGE(dstarr) ) coi2 = cvGetImageCOI((const IplImage*)dstarr); if( coi1 || coi2 ) { CV_Assert( (coi1 != 0 || src.channels() == 1) && (coi2 != 0 || dst.channels() == 1) ); int pair[] = { std::max(coi1-1, 0), std::max(coi2-1, 0) }; cv::mixChannels( &src, 1, &dst, 1, pair, 1 ); return; } else CV_Assert( src.channels() == dst.channels() ); if( !maskarr ) src.copyTo(dst); else src.copyTo(dst, cv::cvarrToMat(maskarr)); } CV_IMPL void cvSet( void* arr, CvScalar value, const void* maskarr ) { cv::Mat m = cv::cvarrToMat(arr); if( !maskarr ) m = value; else m.setTo(cv::Scalar(value), cv::cvarrToMat(maskarr)); } CV_IMPL void cvSetZero( CvArr* arr ) { if( CV_IS_SPARSE_MAT(arr) ) { CvSparseMat* mat1 = (CvSparseMat*)arr; cvClearSet( mat1->heap ); if( mat1->hashtable ) memset( mat1->hashtable, 0, mat1->hashsize*sizeof(mat1->hashtable[0])); return; } cv::Mat m = cv::cvarrToMat(arr); m = cv::Scalar(0); } CV_IMPL void cvFlip( const CvArr* srcarr, CvArr* dstarr, int flip_mode ) { cv::Mat src = cv::cvarrToMat(srcarr); cv::Mat dst; if (!dstarr) dst = src; else dst = cv::cvarrToMat(dstarr); CV_Assert( src.type() == dst.type() && src.size() == dst.size() ); cv::flip( src, dst, flip_mode ); } CV_IMPL void cvRepeat( const CvArr* srcarr, CvArr* dstarr ) { cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); CV_Assert( src.type() == dst.type() && dst.rows % src.rows == 0 && dst.cols % src.cols == 0 ); cv::repeat(src, dst.rows/src.rows, dst.cols/src.cols, dst); } /* End of file. */ Update copy.cpp /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. // Copyright (C) 2014, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ /* //////////////////////////////////////////////////////////////////// // // Mat basic operations: Copy, Set // // */ #include "precomp.hpp" #include "opencl_kernels_core.hpp" namespace cv { template<typename T> static void copyMask_(const uchar* _src, size_t sstep, const uchar* mask, size_t mstep, uchar* _dst, size_t dstep, Size size) { for( ; size.height--; mask += mstep, _src += sstep, _dst += dstep ) { const T* src = (const T*)_src; T* dst = (T*)_dst; int x = 0; #if CV_ENABLE_UNROLLED for( ; x <= size.width - 4; x += 4 ) { if( mask[x] ) dst[x] = src[x]; if( mask[x+1] ) dst[x+1] = src[x+1]; if( mask[x+2] ) dst[x+2] = src[x+2]; if( mask[x+3] ) dst[x+3] = src[x+3]; } #endif for( ; x < size.width; x++ ) if( mask[x] ) dst[x] = src[x]; } } template<> void copyMask_<uchar>(const uchar* _src, size_t sstep, const uchar* mask, size_t mstep, uchar* _dst, size_t dstep, Size size) { CV_IPP_RUN_FAST(CV_INSTRUMENT_FUN_IPP(ippiCopy_8u_C1MR, _src, (int)sstep, _dst, (int)dstep, ippiSize(size), mask, (int)mstep) >= 0) for( ; size.height--; mask += mstep, _src += sstep, _dst += dstep ) { const uchar* src = (const uchar*)_src; uchar* dst = (uchar*)_dst; int x = 0; #if CV_SIMD { v_uint8 v_zero = vx_setzero_u8(); for( ; x <= size.width - v_uint8::nlanes; x += v_uint8::nlanes ) { v_uint8 v_src = vx_load(src + x), v_dst = vx_load(dst + x), v_nmask = vx_load(mask + x) == v_zero; v_dst = v_select(v_nmask, v_dst, v_src); v_store(dst + x, v_dst); } } vx_cleanup(); #endif for( ; x < size.width; x++ ) if( mask[x] ) dst[x] = src[x]; } } template<> void copyMask_<ushort>(const uchar* _src, size_t sstep, const uchar* mask, size_t mstep, uchar* _dst, size_t dstep, Size size) { CV_IPP_RUN_FAST(CV_INSTRUMENT_FUN_IPP(ippiCopy_16u_C1MR, (const Ipp16u *)_src, (int)sstep, (Ipp16u *)_dst, (int)dstep, ippiSize(size), mask, (int)mstep) >= 0) for( ; size.height--; mask += mstep, _src += sstep, _dst += dstep ) { const ushort* src = (const ushort*)_src; ushort* dst = (ushort*)_dst; int x = 0; #if CV_SIMD { v_uint8 v_zero = vx_setzero_u8(); for( ; x <= size.width - v_uint8::nlanes; x += v_uint8::nlanes ) { v_uint16 v_src1 = vx_load(src + x), v_src2 = vx_load(src + x + v_uint16::nlanes), v_dst1 = vx_load(dst + x), v_dst2 = vx_load(dst + x + v_uint16::nlanes); v_uint8 v_nmask1, v_nmask2; v_uint8 v_nmask = vx_load(mask + x) == v_zero; v_zip(v_nmask, v_nmask, v_nmask1, v_nmask2); v_dst1 = v_select(v_reinterpret_as_u16(v_nmask1), v_dst1, v_src1); v_dst2 = v_select(v_reinterpret_as_u16(v_nmask2), v_dst2, v_src2); v_store(dst + x, v_dst1); v_store(dst + x + v_uint16::nlanes, v_dst2); } } vx_cleanup(); #endif for( ; x < size.width; x++ ) if( mask[x] ) dst[x] = src[x]; } } static void copyMaskGeneric(const uchar* _src, size_t sstep, const uchar* mask, size_t mstep, uchar* _dst, size_t dstep, Size size, void* _esz) { size_t k, esz = *(size_t*)_esz; for( ; size.height--; mask += mstep, _src += sstep, _dst += dstep ) { const uchar* src = _src; uchar* dst = _dst; int x = 0; for( ; x < size.width; x++, src += esz, dst += esz ) { if( !mask[x] ) continue; for( k = 0; k < esz; k++ ) dst[k] = src[k]; } } } #define DEF_COPY_MASK(suffix, type) \ static void copyMask##suffix(const uchar* src, size_t sstep, const uchar* mask, size_t mstep, \ uchar* dst, size_t dstep, Size size, void*) \ { \ copyMask_<type>(src, sstep, mask, mstep, dst, dstep, size); \ } #if defined HAVE_IPP #define DEF_COPY_MASK_F(suffix, type, ippfavor, ipptype) \ static void copyMask##suffix(const uchar* src, size_t sstep, const uchar* mask, size_t mstep, \ uchar* dst, size_t dstep, Size size, void*) \ { \ CV_IPP_RUN_FAST(CV_INSTRUMENT_FUN_IPP(ippiCopy_##ippfavor, (const ipptype *)src, (int)sstep, (ipptype *)dst, (int)dstep, ippiSize(size), (const Ipp8u *)mask, (int)mstep) >= 0)\ copyMask_<type>(src, sstep, mask, mstep, dst, dstep, size); \ } #else #define DEF_COPY_MASK_F(suffix, type, ippfavor, ipptype) \ static void copyMask##suffix(const uchar* src, size_t sstep, const uchar* mask, size_t mstep, \ uchar* dst, size_t dstep, Size size, void*) \ { \ copyMask_<type>(src, sstep, mask, mstep, dst, dstep, size); \ } #endif #if IPP_VERSION_X100 == 901 // bug in IPP 9.0.1 DEF_COPY_MASK(32sC3, Vec3i) DEF_COPY_MASK(8uC3, Vec3b) #else DEF_COPY_MASK_F(8uC3, Vec3b, 8u_C3MR, Ipp8u) DEF_COPY_MASK_F(32sC3, Vec3i, 32s_C3MR, Ipp32s) #endif DEF_COPY_MASK(8u, uchar) DEF_COPY_MASK(16u, ushort) DEF_COPY_MASK_F(32s, int, 32s_C1MR, Ipp32s) DEF_COPY_MASK_F(16uC3, Vec3s, 16u_C3MR, Ipp16u) DEF_COPY_MASK(32sC2, Vec2i) DEF_COPY_MASK_F(32sC4, Vec4i, 32s_C4MR, Ipp32s) DEF_COPY_MASK(32sC6, Vec6i) DEF_COPY_MASK(32sC8, Vec8i) BinaryFunc copyMaskTab[] = { 0, copyMask8u, copyMask16u, copyMask8uC3, copyMask32s, 0, copyMask16uC3, 0, copyMask32sC2, 0, 0, 0, copyMask32sC3, 0, 0, 0, copyMask32sC4, 0, 0, 0, 0, 0, 0, 0, copyMask32sC6, 0, 0, 0, 0, 0, 0, 0, copyMask32sC8 }; BinaryFunc getCopyMaskFunc(size_t esz) { return esz <= 32 && copyMaskTab[esz] ? copyMaskTab[esz] : copyMaskGeneric; } /* dst = src */ void Mat::copyTo( OutputArray _dst ) const { CV_INSTRUMENT_REGION(); #ifdef HAVE_CUDA if (_dst.isGpuMat()) { _dst.getGpuMat().upload(*this); return; } #endif int dtype = _dst.type(); if( _dst.fixedType() && dtype != type() ) { CV_Assert( channels() == CV_MAT_CN(dtype) ); convertTo( _dst, dtype ); return; } if( empty() ) { _dst.release(); return; } if( _dst.isUMat() ) { _dst.create( dims, size.p, type() ); UMat dst = _dst.getUMat(); CV_Assert(dst.u != NULL); size_t i, sz[CV_MAX_DIM] = {0}, dstofs[CV_MAX_DIM], esz = elemSize(); CV_Assert(dims > 0 && dims < CV_MAX_DIM); for( i = 0; i < (size_t)dims; i++ ) sz[i] = size.p[i]; sz[dims-1] *= esz; dst.ndoffset(dstofs); dstofs[dims-1] *= esz; dst.u->currAllocator->upload(dst.u, data, dims, sz, dstofs, dst.step.p, step.p); return; } if( dims <= 2 ) { _dst.create( rows, cols, type() ); Mat dst = _dst.getMat(); if( data == dst.data ) return; if( rows > 0 && cols > 0 ) { Mat src = *this; Size sz = getContinuousSize2D(src, dst, (int)elemSize()); CV_CheckGE(sz.width, 0, ""); const uchar* sptr = src.data; uchar* dptr = dst.data; #if IPP_VERSION_X100 >= 201700 CV_IPP_RUN_FAST(CV_INSTRUMENT_FUN_IPP(ippiCopy_8u_C1R_L, sptr, (int)src.step, dptr, (int)dst.step, ippiSizeL(sz.width, sz.height)) >= 0) #endif for (; sz.height--; sptr += src.step, dptr += dst.step) memcpy(dptr, sptr, sz.width); } return; } _dst.create( dims, size, type() ); Mat dst = _dst.getMat(); if( data == dst.data ) return; if( total() != 0 ) { const Mat* arrays[] = { this, &dst }; uchar* ptrs[2] = {}; NAryMatIterator it(arrays, ptrs, 2); size_t sz = it.size*elemSize(); for( size_t i = 0; i < it.nplanes; i++, ++it ) memcpy(ptrs[1], ptrs[0], sz); } } #ifdef HAVE_IPP static bool ipp_copyTo(const Mat &src, Mat &dst, const Mat &mask) { #ifdef HAVE_IPP_IW_LL CV_INSTRUMENT_REGION_IPP(); if(mask.channels() > 1 || mask.depth() != CV_8U) return false; if (src.dims <= 2) { IppiSize size = ippiSize(src.size()); return CV_INSTRUMENT_FUN_IPP(llwiCopyMask, src.ptr(), (int)src.step, dst.ptr(), (int)dst.step, size, (int)src.elemSize1(), src.channels(), mask.ptr(), (int)mask.step) >= 0; } else { const Mat *arrays[] = {&src, &dst, &mask, NULL}; uchar *ptrs[3] = {NULL}; NAryMatIterator it(arrays, ptrs); IppiSize size = ippiSize(it.size, 1); for (size_t i = 0; i < it.nplanes; i++, ++it) { if(CV_INSTRUMENT_FUN_IPP(llwiCopyMask, ptrs[0], 0, ptrs[1], 0, size, (int)src.elemSize1(), src.channels(), ptrs[2], 0) < 0) return false; } return true; } #else CV_UNUSED(src); CV_UNUSED(dst); CV_UNUSED(mask); return false; #endif } #endif void Mat::copyTo( OutputArray _dst, InputArray _mask ) const { CV_INSTRUMENT_REGION(); Mat mask = _mask.getMat(); if( !mask.data ) { copyTo(_dst); return; } int cn = channels(), mcn = mask.channels(); CV_Assert( mask.depth() == CV_8U && (mcn == 1 || mcn == cn) ); bool colorMask = mcn > 1; if( dims <= 2 ) { CV_Assert( size() == mask.size() ); } Mat dst; { Mat dst0 = _dst.getMat(); _dst.create(dims, size, type()); // TODO Prohibit 'dst' re-creation, user should pass it explicitly with correct size/type or empty dst = _dst.getMat(); if (dst.data != dst0.data) // re-allocation happened { #ifdef OPENCV_FUTURE CV_Assert(dst0.empty() && "copyTo(): dst size/type mismatch (looks like a bug) - use dst.release() before copyTo() call to suppress this message"); #endif dst = Scalar(0); // do not leave dst uninitialized } } CV_IPP_RUN_FAST(ipp_copyTo(*this, dst, mask)) size_t esz = colorMask ? elemSize1() : elemSize(); BinaryFunc copymask = getCopyMaskFunc(esz); if( dims <= 2 ) { Mat src = *this; Size sz = getContinuousSize2D(src, dst, mask, mcn); copymask(src.data, src.step, mask.data, mask.step, dst.data, dst.step, sz, &esz); return; } const Mat* arrays[] = { this, &dst, &mask, 0 }; uchar* ptrs[3] = {}; NAryMatIterator it(arrays, ptrs); Size sz((int)(it.size*mcn), 1); for( size_t i = 0; i < it.nplanes; i++, ++it ) copymask(ptrs[0], 0, ptrs[2], 0, ptrs[1], 0, sz, &esz); } Mat& Mat::operator = (const Scalar& s) { CV_INSTRUMENT_REGION(); if (this->empty()) return *this; const Mat* arrays[] = { this }; uchar* dptr; NAryMatIterator it(arrays, &dptr, 1); size_t elsize = it.size*elemSize(); const int64* is = (const int64*)&s.val[0]; if( is[0] == 0 && is[1] == 0 && is[2] == 0 && is[3] == 0 ) { for( size_t i = 0; i < it.nplanes; i++, ++it ) memset( dptr, 0, elsize ); } else { if( it.nplanes > 0 ) { double scalar[12]; scalarToRawData(s, scalar, type(), 12); size_t blockSize = 12*elemSize1(); for( size_t j = 0; j < elsize; j += blockSize ) { size_t sz = MIN(blockSize, elsize - j); CV_Assert(sz <= sizeof(scalar)); memcpy( dptr + j, scalar, sz ); } } for( size_t i = 1; i < it.nplanes; i++ ) { ++it; memcpy( dptr, data, elsize ); } } return *this; } #ifdef HAVE_IPP static bool ipp_Mat_setTo_Mat(Mat &dst, Mat &_val, Mat &mask) { #ifdef HAVE_IPP_IW_LL CV_INSTRUMENT_REGION_IPP(); if(mask.empty()) return false; if(mask.depth() != CV_8U || mask.channels() > 1) return false; if(dst.channels() > 4) return false; if (dst.depth() == CV_32F) { for (int i = 0; i < (int)(_val.total()); i++) { float v = (float)(_val.at<double>(i)); // cast to float if (cvIsNaN(v) || cvIsInf(v)) // accept finite numbers only return false; } } if(dst.dims <= 2) { IppiSize size = ippiSize(dst.size()); IppDataType dataType = ippiGetDataType(dst.depth()); ::ipp::IwValueFloat s; convertAndUnrollScalar(_val, CV_MAKETYPE(CV_64F, dst.channels()), (uchar*)((Ipp64f*)s), 1); return CV_INSTRUMENT_FUN_IPP(llwiSetMask, s, dst.ptr(), (int)dst.step, size, dataType, dst.channels(), mask.ptr(), (int)mask.step) >= 0; } else { const Mat *arrays[] = {&dst, mask.empty()?NULL:&mask, NULL}; uchar *ptrs[2] = {NULL}; NAryMatIterator it(arrays, ptrs); IppiSize size = {(int)it.size, 1}; IppDataType dataType = ippiGetDataType(dst.depth()); ::ipp::IwValueFloat s; convertAndUnrollScalar(_val, CV_MAKETYPE(CV_64F, dst.channels()), (uchar*)((Ipp64f*)s), 1); for( size_t i = 0; i < it.nplanes; i++, ++it) { if(CV_INSTRUMENT_FUN_IPP(llwiSetMask, s, ptrs[0], 0, size, dataType, dst.channels(), ptrs[1], 0) < 0) return false; } return true; } #else CV_UNUSED(dst); CV_UNUSED(_val); CV_UNUSED(mask); return false; #endif } #endif Mat& Mat::setTo(InputArray _value, InputArray _mask) { CV_INSTRUMENT_REGION(); if( empty() ) return *this; Mat value = _value.getMat(), mask = _mask.getMat(); CV_Assert( checkScalar(value, type(), _value.kind(), _InputArray::MAT )); int cn = channels(), mcn = mask.channels(); CV_Assert( mask.empty() || (mask.depth() == CV_8U && (mcn == 1 || mcn == cn) && size == mask.size) ); CV_IPP_RUN_FAST(ipp_Mat_setTo_Mat(*this, value, mask), *this) size_t esz = mcn > 1 ? elemSize1() : elemSize(); BinaryFunc copymask = getCopyMaskFunc(esz); const Mat* arrays[] = { this, !mask.empty() ? &mask : 0, 0 }; uchar* ptrs[2]={0,0}; NAryMatIterator it(arrays, ptrs); int totalsz = (int)it.size*mcn; int blockSize0 = std::min(totalsz, (int)((BLOCK_SIZE + esz-1)/esz)); blockSize0 -= blockSize0 % mcn; // must be divisible without remainder for unrolling and advancing AutoBuffer<uchar> _scbuf(blockSize0*esz + 32); uchar* scbuf = alignPtr((uchar*)_scbuf.data(), (int)sizeof(double)); convertAndUnrollScalar( value, type(), scbuf, blockSize0/mcn ); for( size_t i = 0; i < it.nplanes; i++, ++it ) { for( int j = 0; j < totalsz; j += blockSize0 ) { Size sz(std::min(blockSize0, totalsz - j), 1); size_t blockSize = sz.width*esz; if( ptrs[1] ) { copymask(scbuf, 0, ptrs[1], 0, ptrs[0], 0, sz, &esz); ptrs[1] += sz.width; } else memcpy(ptrs[0], scbuf, blockSize); ptrs[0] += blockSize; } } return *this; } static void flipHoriz( const uchar* src, size_t sstep, uchar* dst, size_t dstep, Size size, size_t esz ) { int i, j, limit = (int)(((size.width + 1)/2)*esz); AutoBuffer<int> _tab(size.width*esz); int* tab = _tab.data(); for( i = 0; i < size.width; i++ ) for( size_t k = 0; k < esz; k++ ) tab[i*esz + k] = (int)((size.width - i - 1)*esz + k); for( ; size.height--; src += sstep, dst += dstep ) { for( i = 0; i < limit; i++ ) { j = tab[i]; uchar t0 = src[i], t1 = src[j]; dst[i] = t1; dst[j] = t0; } } } static void flipVert( const uchar* src0, size_t sstep, uchar* dst0, size_t dstep, Size size, size_t esz ) { const uchar* src1 = src0 + (size.height - 1)*sstep; uchar* dst1 = dst0 + (size.height - 1)*dstep; size.width *= (int)esz; for( int y = 0; y < (size.height + 1)/2; y++, src0 += sstep, src1 -= sstep, dst0 += dstep, dst1 -= dstep ) { int i = 0; if( ((size_t)src0|(size_t)dst0|(size_t)src1|(size_t)dst1) % sizeof(int) == 0 ) { for( ; i <= size.width - 16; i += 16 ) { int t0 = ((int*)(src0 + i))[0]; int t1 = ((int*)(src1 + i))[0]; ((int*)(dst0 + i))[0] = t1; ((int*)(dst1 + i))[0] = t0; t0 = ((int*)(src0 + i))[1]; t1 = ((int*)(src1 + i))[1]; ((int*)(dst0 + i))[1] = t1; ((int*)(dst1 + i))[1] = t0; t0 = ((int*)(src0 + i))[2]; t1 = ((int*)(src1 + i))[2]; ((int*)(dst0 + i))[2] = t1; ((int*)(dst1 + i))[2] = t0; t0 = ((int*)(src0 + i))[3]; t1 = ((int*)(src1 + i))[3]; ((int*)(dst0 + i))[3] = t1; ((int*)(dst1 + i))[3] = t0; } for( ; i <= size.width - 4; i += 4 ) { int t0 = ((int*)(src0 + i))[0]; int t1 = ((int*)(src1 + i))[0]; ((int*)(dst0 + i))[0] = t1; ((int*)(dst1 + i))[0] = t0; } } for( ; i < size.width; i++ ) { uchar t0 = src0[i]; uchar t1 = src1[i]; dst0[i] = t1; dst1[i] = t0; } } } #ifdef HAVE_OPENCL enum { FLIP_COLS = 1 << 0, FLIP_ROWS = 1 << 1, FLIP_BOTH = FLIP_ROWS | FLIP_COLS }; static bool ocl_flip(InputArray _src, OutputArray _dst, int flipCode ) { CV_Assert(flipCode >= -1 && flipCode <= 1); const ocl::Device & dev = ocl::Device::getDefault(); int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type), flipType, kercn = std::min(ocl::predictOptimalVectorWidth(_src, _dst), 4); bool doubleSupport = dev.doubleFPConfig() > 0; if (!doubleSupport && depth == CV_64F) kercn = cn; if (cn > 4) return false; const char * kernelName; if (flipCode == 0) kernelName = "arithm_flip_rows", flipType = FLIP_ROWS; else if (flipCode > 0) kernelName = "arithm_flip_cols", flipType = FLIP_COLS; else kernelName = "arithm_flip_rows_cols", flipType = FLIP_BOTH; int pxPerWIy = (dev.isIntel() && (dev.type() & ocl::Device::TYPE_GPU)) ? 4 : 1; kercn = (cn!=3 || flipType == FLIP_ROWS) ? std::max(kercn, cn) : cn; ocl::Kernel k(kernelName, ocl::core::flip_oclsrc, format( "-D T=%s -D T1=%s -D cn=%d -D PIX_PER_WI_Y=%d -D kercn=%d", kercn != cn ? ocl::typeToStr(CV_MAKE_TYPE(depth, kercn)) : ocl::vecopTypeToStr(CV_MAKE_TYPE(depth, kercn)), kercn != cn ? ocl::typeToStr(depth) : ocl::vecopTypeToStr(depth), cn, pxPerWIy, kercn)); if (k.empty()) return false; Size size = _src.size(); _dst.create(size, type); UMat src = _src.getUMat(), dst = _dst.getUMat(); int cols = size.width * cn / kercn, rows = size.height; cols = flipType == FLIP_COLS ? (cols + 1) >> 1 : cols; rows = flipType & FLIP_ROWS ? (rows + 1) >> 1 : rows; k.args(ocl::KernelArg::ReadOnlyNoSize(src), ocl::KernelArg::WriteOnly(dst, cn, kercn), rows, cols); size_t maxWorkGroupSize = dev.maxWorkGroupSize(); CV_Assert(maxWorkGroupSize % 4 == 0); size_t globalsize[2] = { (size_t)cols, ((size_t)rows + pxPerWIy - 1) / pxPerWIy }, localsize[2] = { maxWorkGroupSize / 4, 4 }; return k.run(2, globalsize, (flipType == FLIP_COLS) && !dev.isIntel() ? localsize : NULL, false); } #endif #if defined HAVE_IPP static bool ipp_flip(Mat &src, Mat &dst, int flip_mode) { #ifdef HAVE_IPP_IW CV_INSTRUMENT_REGION_IPP(); IppiAxis ippMode; if(flip_mode < 0) ippMode = ippAxsBoth; else if(flip_mode == 0) ippMode = ippAxsHorizontal; else ippMode = ippAxsVertical; try { ::ipp::IwiImage iwSrc = ippiGetImage(src); ::ipp::IwiImage iwDst = ippiGetImage(dst); CV_INSTRUMENT_FUN_IPP(::ipp::iwiMirror, iwSrc, iwDst, ippMode); } catch(const ::ipp::IwException &) { return false; } return true; #else CV_UNUSED(src); CV_UNUSED(dst); CV_UNUSED(flip_mode); return false; #endif } #endif void flip( InputArray _src, OutputArray _dst, int flip_mode ) { CV_INSTRUMENT_REGION(); CV_Assert( _src.dims() <= 2 ); Size size = _src.size(); if (flip_mode < 0) { if (size.width == 1) flip_mode = 0; if (size.height == 1) flip_mode = 1; } if ((size.width == 1 && flip_mode > 0) || (size.height == 1 && flip_mode == 0) || (size.height == 1 && size.width == 1 && flip_mode < 0)) { return _src.copyTo(_dst); } CV_OCL_RUN( _dst.isUMat(), ocl_flip(_src, _dst, flip_mode)) Mat src = _src.getMat(); int type = src.type(); _dst.create( size, type ); Mat dst = _dst.getMat(); CV_IPP_RUN_FAST(ipp_flip(src, dst, flip_mode)); size_t esz = CV_ELEM_SIZE(type); if( flip_mode <= 0 ) flipVert( src.ptr(), src.step, dst.ptr(), dst.step, src.size(), esz ); else flipHoriz( src.ptr(), src.step, dst.ptr(), dst.step, src.size(), esz ); if( flip_mode < 0 ) flipHoriz( dst.ptr(), dst.step, dst.ptr(), dst.step, dst.size(), esz ); } void rotate(InputArray _src, OutputArray _dst, int rotateMode) { CV_Assert(_src.dims() <= 2); switch (rotateMode) { case ROTATE_90_CLOCKWISE: transpose(_src, _dst); flip(_dst, _dst, 1); break; case ROTATE_180: flip(_src, _dst, -1); break; case ROTATE_90_COUNTERCLOCKWISE: transpose(_src, _dst); flip(_dst, _dst, 0); break; default: break; } } #if defined HAVE_OPENCL && !defined __APPLE__ static bool ocl_repeat(InputArray _src, int ny, int nx, OutputArray _dst) { if (ny == 1 && nx == 1) { _src.copyTo(_dst); return true; } int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type), rowsPerWI = ocl::Device::getDefault().isIntel() ? 4 : 1, kercn = ocl::predictOptimalVectorWidth(_src, _dst); ocl::Kernel k("repeat", ocl::core::repeat_oclsrc, format("-D T=%s -D nx=%d -D ny=%d -D rowsPerWI=%d -D cn=%d", ocl::memopTypeToStr(CV_MAKE_TYPE(depth, kercn)), nx, ny, rowsPerWI, kercn)); if (k.empty()) return false; UMat src = _src.getUMat(), dst = _dst.getUMat(); k.args(ocl::KernelArg::ReadOnly(src, cn, kercn), ocl::KernelArg::WriteOnlyNoSize(dst)); size_t globalsize[] = { (size_t)src.cols * cn / kercn, ((size_t)src.rows + rowsPerWI - 1) / rowsPerWI }; return k.run(2, globalsize, NULL, false); } #endif void repeat(InputArray _src, int ny, int nx, OutputArray _dst) { CV_INSTRUMENT_REGION(); CV_Assert(_src.getObj() != _dst.getObj()); CV_Assert( _src.dims() <= 2 ); CV_Assert( ny > 0 && nx > 0 ); Size ssize = _src.size(); _dst.create(ssize.height*ny, ssize.width*nx, _src.type()); #if !defined __APPLE__ CV_OCL_RUN(_dst.isUMat(), ocl_repeat(_src, ny, nx, _dst)) #endif Mat src = _src.getMat(), dst = _dst.getMat(); Size dsize = dst.size(); int esz = (int)src.elemSize(); int x, y; ssize.width *= esz; dsize.width *= esz; for( y = 0; y < ssize.height; y++ ) { for( x = 0; x < dsize.width; x += ssize.width ) memcpy( dst.ptr(y) + x, src.ptr(y), ssize.width ); } for( ; y < dsize.height; y++ ) memcpy( dst.ptr(y), dst.ptr(y - ssize.height), dsize.width ); } Mat repeat(const Mat& src, int ny, int nx) { if( nx == 1 && ny == 1 ) return src; Mat dst; repeat(src, ny, nx, dst); return dst; } } // cv /* Various border types, image boundaries are denoted with '|' * BORDER_REPLICATE: aaaaaa|abcdefgh|hhhhhhh * BORDER_REFLECT: fedcba|abcdefgh|hgfedcb * BORDER_REFLECT_101: gfedcb|abcdefgh|gfedcba * BORDER_WRAP: cdefgh|abcdefgh|abcdefg * BORDER_CONSTANT: iiiiii|abcdefgh|iiiiiii with some specified 'i' */ int cv::borderInterpolate( int p, int len, int borderType ) { CV_TRACE_FUNCTION_VERBOSE(); CV_DbgAssert(len > 0); #ifdef CV_STATIC_ANALYSIS if(p >= 0 && p < len) #else if( (unsigned)p < (unsigned)len ) #endif ; else if( borderType == BORDER_REPLICATE ) p = p < 0 ? 0 : len - 1; else if( borderType == BORDER_REFLECT || borderType == BORDER_REFLECT_101 ) { int delta = borderType == BORDER_REFLECT_101; if( len == 1 ) return 0; do { if( p < 0 ) p = -p - 1 + delta; else p = len - 1 - (p - len) - delta; } #ifdef CV_STATIC_ANALYSIS while(p < 0 || p >= len); #else while( (unsigned)p >= (unsigned)len ); #endif } else if( borderType == BORDER_WRAP ) { CV_Assert(len > 0); if( p < 0 ) p -= ((p-len+1)/len)*len; if( p >= len ) p %= len; } else if( borderType == BORDER_CONSTANT ) p = -1; else CV_Error( CV_StsBadArg, "Unknown/unsupported border type" ); return p; } namespace { void copyMakeBorder_8u( const uchar* src, size_t srcstep, cv::Size srcroi, uchar* dst, size_t dststep, cv::Size dstroi, int top, int left, int cn, int borderType ) { const int isz = (int)sizeof(int); int i, j, k, elemSize = 1; bool intMode = false; if( (cn | srcstep | dststep | (size_t)src | (size_t)dst) % isz == 0 ) { cn /= isz; elemSize = isz; intMode = true; } cv::AutoBuffer<int> _tab((dstroi.width - srcroi.width)*cn); int* tab = _tab.data(); int right = dstroi.width - srcroi.width - left; int bottom = dstroi.height - srcroi.height - top; for( i = 0; i < left; i++ ) { j = cv::borderInterpolate(i - left, srcroi.width, borderType)*cn; for( k = 0; k < cn; k++ ) tab[i*cn + k] = j + k; } for( i = 0; i < right; i++ ) { j = cv::borderInterpolate(srcroi.width + i, srcroi.width, borderType)*cn; for( k = 0; k < cn; k++ ) tab[(i+left)*cn + k] = j + k; } srcroi.width *= cn; dstroi.width *= cn; left *= cn; right *= cn; uchar* dstInner = dst + dststep*top + left*elemSize; for( i = 0; i < srcroi.height; i++, dstInner += dststep, src += srcstep ) { if( dstInner != src ) memcpy(dstInner, src, srcroi.width*elemSize); if( intMode ) { const int* isrc = (int*)src; int* idstInner = (int*)dstInner; for( j = 0; j < left; j++ ) idstInner[j - left] = isrc[tab[j]]; for( j = 0; j < right; j++ ) idstInner[j + srcroi.width] = isrc[tab[j + left]]; } else { for( j = 0; j < left; j++ ) dstInner[j - left] = src[tab[j]]; for( j = 0; j < right; j++ ) dstInner[j + srcroi.width] = src[tab[j + left]]; } } dstroi.width *= elemSize; dst += dststep*top; for( i = 0; i < top; i++ ) { j = cv::borderInterpolate(i - top, srcroi.height, borderType); memcpy(dst + (i - top)*dststep, dst + j*dststep, dstroi.width); } for( i = 0; i < bottom; i++ ) { j = cv::borderInterpolate(i + srcroi.height, srcroi.height, borderType); memcpy(dst + (i + srcroi.height)*dststep, dst + j*dststep, dstroi.width); } } void copyMakeConstBorder_8u( const uchar* src, size_t srcstep, cv::Size srcroi, uchar* dst, size_t dststep, cv::Size dstroi, int top, int left, int cn, const uchar* value ) { int i, j; cv::AutoBuffer<uchar> _constBuf(dstroi.width*cn); uchar* constBuf = _constBuf.data(); int right = dstroi.width - srcroi.width - left; int bottom = dstroi.height - srcroi.height - top; for( i = 0; i < dstroi.width; i++ ) { for( j = 0; j < cn; j++ ) constBuf[i*cn + j] = value[j]; } srcroi.width *= cn; dstroi.width *= cn; left *= cn; right *= cn; uchar* dstInner = dst + dststep*top + left; for( i = 0; i < srcroi.height; i++, dstInner += dststep, src += srcstep ) { if( dstInner != src ) memcpy( dstInner, src, srcroi.width ); memcpy( dstInner - left, constBuf, left ); memcpy( dstInner + srcroi.width, constBuf, right ); } dst += dststep*top; for( i = 0; i < top; i++ ) memcpy(dst + (i - top)*dststep, constBuf, dstroi.width); for( i = 0; i < bottom; i++ ) memcpy(dst + (i + srcroi.height)*dststep, constBuf, dstroi.width); } } #ifdef HAVE_OPENCL namespace cv { static bool ocl_copyMakeBorder( InputArray _src, OutputArray _dst, int top, int bottom, int left, int right, int borderType, const Scalar& value ) { int type = _src.type(), cn = CV_MAT_CN(type), depth = CV_MAT_DEPTH(type), rowsPerWI = ocl::Device::getDefault().isIntel() ? 4 : 1; bool isolated = (borderType & BORDER_ISOLATED) != 0; borderType &= ~cv::BORDER_ISOLATED; if ( !(borderType == BORDER_CONSTANT || borderType == BORDER_REPLICATE || borderType == BORDER_REFLECT || borderType == BORDER_WRAP || borderType == BORDER_REFLECT_101) || cn > 4) return false; const char * const borderMap[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", "BORDER_WRAP", "BORDER_REFLECT_101" }; int scalarcn = cn == 3 ? 4 : cn; int sctype = CV_MAKETYPE(depth, scalarcn); String buildOptions = format("-D T=%s -D %s -D T1=%s -D cn=%d -D ST=%s -D rowsPerWI=%d", ocl::memopTypeToStr(type), borderMap[borderType], ocl::memopTypeToStr(depth), cn, ocl::memopTypeToStr(sctype), rowsPerWI); ocl::Kernel k("copyMakeBorder", ocl::core::copymakeborder_oclsrc, buildOptions); if (k.empty()) return false; UMat src = _src.getUMat(); if( src.isSubmatrix() && !isolated ) { Size wholeSize; Point ofs; src.locateROI(wholeSize, ofs); int dtop = std::min(ofs.y, top); int dbottom = std::min(wholeSize.height - src.rows - ofs.y, bottom); int dleft = std::min(ofs.x, left); int dright = std::min(wholeSize.width - src.cols - ofs.x, right); src.adjustROI(dtop, dbottom, dleft, dright); top -= dtop; left -= dleft; bottom -= dbottom; right -= dright; } _dst.create(src.rows + top + bottom, src.cols + left + right, type); UMat dst = _dst.getUMat(); if (top == 0 && left == 0 && bottom == 0 && right == 0) { if(src.u != dst.u || src.step != dst.step) src.copyTo(dst); return true; } k.args(ocl::KernelArg::ReadOnly(src), ocl::KernelArg::WriteOnly(dst), top, left, ocl::KernelArg::Constant(Mat(1, 1, sctype, value))); size_t globalsize[2] = { (size_t)dst.cols, ((size_t)dst.rows + rowsPerWI - 1) / rowsPerWI }; return k.run(2, globalsize, NULL, false); } } #endif #ifdef HAVE_IPP namespace cv { static bool ipp_copyMakeBorder( Mat &_src, Mat &_dst, int top, int bottom, int left, int right, int _borderType, const Scalar& value ) { #if defined HAVE_IPP_IW_LL && !IPP_DISABLE_PERF_COPYMAKE CV_INSTRUMENT_REGION_IPP(); ::ipp::IwiBorderSize borderSize(left, top, right, bottom); ::ipp::IwiSize size(_src.cols, _src.rows); IppDataType dataType = ippiGetDataType(_src.depth()); IppiBorderType borderType = ippiGetBorderType(_borderType); if((int)borderType == -1) return false; if(_src.dims > 2) return false; Rect dstRect(borderSize.left, borderSize.top, _dst.cols - borderSize.right - borderSize.left, _dst.rows - borderSize.bottom - borderSize.top); Mat subDst = Mat(_dst, dstRect); Mat *pSrc = &_src; return CV_INSTRUMENT_FUN_IPP(llwiCopyMakeBorder, pSrc->ptr(), pSrc->step, subDst.ptr(), subDst.step, size, dataType, _src.channels(), borderSize, borderType, &value[0]) >= 0; #else CV_UNUSED(_src); CV_UNUSED(_dst); CV_UNUSED(top); CV_UNUSED(bottom); CV_UNUSED(left); CV_UNUSED(right); CV_UNUSED(_borderType); CV_UNUSED(value); return false; #endif } } #endif void cv::copyMakeBorder( InputArray _src, OutputArray _dst, int top, int bottom, int left, int right, int borderType, const Scalar& value ) { CV_INSTRUMENT_REGION(); CV_Assert( top >= 0 && bottom >= 0 && left >= 0 && right >= 0 && _src.dims() <= 2); CV_OCL_RUN(_dst.isUMat(), ocl_copyMakeBorder(_src, _dst, top, bottom, left, right, borderType, value)) Mat src = _src.getMat(); int type = src.type(); if( src.isSubmatrix() && (borderType & BORDER_ISOLATED) == 0 ) { Size wholeSize; Point ofs; src.locateROI(wholeSize, ofs); int dtop = std::min(ofs.y, top); int dbottom = std::min(wholeSize.height - src.rows - ofs.y, bottom); int dleft = std::min(ofs.x, left); int dright = std::min(wholeSize.width - src.cols - ofs.x, right); src.adjustROI(dtop, dbottom, dleft, dright); top -= dtop; left -= dleft; bottom -= dbottom; right -= dright; } _dst.create( src.rows + top + bottom, src.cols + left + right, type ); Mat dst = _dst.getMat(); if(top == 0 && left == 0 && bottom == 0 && right == 0) { if(src.data != dst.data || src.step != dst.step) src.copyTo(dst); return; } borderType &= ~BORDER_ISOLATED; CV_IPP_RUN_FAST(ipp_copyMakeBorder(src, dst, top, bottom, left, right, borderType, value)) if( borderType != BORDER_CONSTANT ) copyMakeBorder_8u( src.ptr(), src.step, src.size(), dst.ptr(), dst.step, dst.size(), top, left, (int)src.elemSize(), borderType ); else { int cn = src.channels(), cn1 = cn; AutoBuffer<double> buf(cn); if( cn > 4 ) { CV_Assert( value[0] == value[1] && value[0] == value[2] && value[0] == value[3] ); cn1 = 1; } scalarToRawData(value, buf.data(), CV_MAKETYPE(src.depth(), cn1), cn); copyMakeConstBorder_8u( src.ptr(), src.step, src.size(), dst.ptr(), dst.step, dst.size(), top, left, (int)src.elemSize(), (uchar*)buf.data() ); } } /* dst = src */ CV_IMPL void cvCopy( const void* srcarr, void* dstarr, const void* maskarr ) { if( CV_IS_SPARSE_MAT(srcarr) && CV_IS_SPARSE_MAT(dstarr)) { CV_Assert( maskarr == 0 ); CvSparseMat* src1 = (CvSparseMat*)srcarr; CvSparseMat* dst1 = (CvSparseMat*)dstarr; CvSparseMatIterator iterator; CvSparseNode* node; dst1->dims = src1->dims; memcpy( dst1->size, src1->size, src1->dims*sizeof(src1->size[0])); dst1->valoffset = src1->valoffset; dst1->idxoffset = src1->idxoffset; cvClearSet( dst1->heap ); if( src1->heap->active_count >= dst1->hashsize*CV_SPARSE_HASH_RATIO ) { cvFree( &dst1->hashtable ); dst1->hashsize = src1->hashsize; dst1->hashtable = (void**)cvAlloc( dst1->hashsize*sizeof(dst1->hashtable[0])); } memset( dst1->hashtable, 0, dst1->hashsize*sizeof(dst1->hashtable[0])); for( node = cvInitSparseMatIterator( src1, &iterator ); node != 0; node = cvGetNextSparseNode( &iterator )) { CvSparseNode* node_copy = (CvSparseNode*)cvSetNew( dst1->heap ); int tabidx = node->hashval & (dst1->hashsize - 1); memcpy( node_copy, node, dst1->heap->elem_size ); node_copy->next = (CvSparseNode*)dst1->hashtable[tabidx]; dst1->hashtable[tabidx] = node_copy; } return; } cv::Mat src = cv::cvarrToMat(srcarr, false, true, 1), dst = cv::cvarrToMat(dstarr, false, true, 1); CV_Assert( src.depth() == dst.depth() && src.size == dst.size ); int coi1 = 0, coi2 = 0; if( CV_IS_IMAGE(srcarr) ) coi1 = cvGetImageCOI((const IplImage*)srcarr); if( CV_IS_IMAGE(dstarr) ) coi2 = cvGetImageCOI((const IplImage*)dstarr); if( coi1 || coi2 ) { CV_Assert( (coi1 != 0 || src.channels() == 1) && (coi2 != 0 || dst.channels() == 1) ); int pair[] = { std::max(coi1-1, 0), std::max(coi2-1, 0) }; cv::mixChannels( &src, 1, &dst, 1, pair, 1 ); return; } else CV_Assert( src.channels() == dst.channels() ); if( !maskarr ) src.copyTo(dst); else src.copyTo(dst, cv::cvarrToMat(maskarr)); } CV_IMPL void cvSet( void* arr, CvScalar value, const void* maskarr ) { cv::Mat m = cv::cvarrToMat(arr); if( !maskarr ) m = value; else m.setTo(cv::Scalar(value), cv::cvarrToMat(maskarr)); } CV_IMPL void cvSetZero( CvArr* arr ) { if( CV_IS_SPARSE_MAT(arr) ) { CvSparseMat* mat1 = (CvSparseMat*)arr; cvClearSet( mat1->heap ); if( mat1->hashtable ) memset( mat1->hashtable, 0, mat1->hashsize*sizeof(mat1->hashtable[0])); return; } cv::Mat m = cv::cvarrToMat(arr); m = cv::Scalar(0); } CV_IMPL void cvFlip( const CvArr* srcarr, CvArr* dstarr, int flip_mode ) { cv::Mat src = cv::cvarrToMat(srcarr); cv::Mat dst; if (!dstarr) dst = src; else dst = cv::cvarrToMat(dstarr); CV_Assert( src.type() == dst.type() && src.size() == dst.size() ); cv::flip( src, dst, flip_mode ); } CV_IMPL void cvRepeat( const CvArr* srcarr, CvArr* dstarr ) { cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); CV_Assert( src.type() == dst.type() && dst.rows % src.rows == 0 && dst.cols % src.cols == 0 ); cv::repeat(src, dst.rows/src.rows, dst.cols/src.cols, dst); } /* End of file. */
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "ManualBindings.h" #include "tolua++.h" #include "Root.h" #include "World.h" #include "Plugin.h" #include "Plugin_NewLua.h" #include "PluginManager.h" #include "Player.h" #include "WebAdmin.h" #include "StringMap.h" #include "ClientHandle.h" #include "BlockEntities/ChestEntity.h" #include "BlockEntities/DispenserEntity.h" #include "BlockEntities/DropperEntity.h" #include "BlockEntities/FurnaceEntity.h" #include "md5/md5.h" #include "LuaWindow.h" #include "LuaState.h" /**************************** * Better error reporting for Lua **/ int tolua_do_error(lua_State* L, const char * a_pMsg, tolua_Error * a_pToLuaError) { // Retrieve current function name lua_Debug entry; VERIFY(lua_getstack(L, 0, &entry)); VERIFY(lua_getinfo(L, "n", &entry)); // Insert function name into error msg AString msg(a_pMsg); ReplaceString(msg, "#funcname#", entry.name?entry.name:"?"); // Send the error to Lua tolua_error(L, msg.c_str(), a_pToLuaError); return 0; } int lua_do_error(lua_State* L, const char * a_pFormat, ...) { // Retrieve current function name lua_Debug entry; VERIFY(lua_getstack(L, 0, &entry)); VERIFY(lua_getinfo(L, "n", &entry)); // Insert function name into error msg AString msg(a_pFormat); ReplaceString(msg, "#funcname#", entry.name?entry.name:"?"); // Copied from luaL_error and modified va_list argp; va_start(argp, a_pFormat); luaL_where(L, 1); lua_pushvfstring(L, msg.c_str(), argp); va_end(argp); lua_concat(L, 2); return lua_error(L); } /**************************** * Lua bound functions with special return types **/ static int tolua_StringSplit(lua_State * tolua_S) { cLuaState LuaState(tolua_S); std::string str = (std::string)tolua_tocppstring(LuaState, 1, 0); std::string delim = (std::string)tolua_tocppstring(LuaState, 2, 0); AStringVector Split = StringSplit(str, delim); LuaState.PushStringVector(Split); return 1; } static int tolua_LOG(lua_State* tolua_S) { const char* str = tolua_tocppstring(tolua_S,1,0); cMCLogger::GetInstance()->LogSimple( str, 0 ); return 0; } static int tolua_LOGINFO(lua_State* tolua_S) { const char* str = tolua_tocppstring(tolua_S,1,0); cMCLogger::GetInstance()->LogSimple( str, 1 ); return 0; } static int tolua_LOGWARN(lua_State* tolua_S) { const char* str = tolua_tocppstring(tolua_S,1,0); cMCLogger::GetInstance()->LogSimple( str, 2 ); return 0; } static int tolua_LOGERROR(lua_State* tolua_S) { const char* str = tolua_tocppstring(tolua_S,1,0); cMCLogger::GetInstance()->LogSimple( str, 3 ); return 0; } cPlugin_NewLua * GetLuaPlugin(lua_State * L) { // Get the plugin identification out of LuaState: lua_getglobal(L, LUA_PLUGIN_INSTANCE_VAR_NAME); if (!lua_islightuserdata(L, -1)) { LOGWARNING("%s: cannot get plugin instance, what have you done to my Lua state?", __FUNCTION__); lua_pop(L); return NULL; } cPlugin_NewLua * Plugin = (cPlugin_NewLua *)lua_topointer(L, -1); lua_pop(L, 1); return Plugin; } template< class Ty1, class Ty2, bool (Ty1::*Func1)(const AString &, cItemCallback<Ty2> &) > static int tolua_DoWith(lua_State* tolua_S) { int NumArgs = lua_gettop(tolua_S) - 1; /* This includes 'self' */ if ((NumArgs != 2) && (NumArgs != 3)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 2 or 3 arguments, got %i", NumArgs); } Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, 0); const char * ItemName = tolua_tocppstring(tolua_S, 2, ""); if ((ItemName == NULL) || (ItemName[0] == 0)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a non-empty string for parameter #1", NumArgs); } if (!lua_isfunction( tolua_S, 3)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a function for parameter #2", NumArgs); } /* luaL_ref gets reference to value on top of the stack, the table is the last argument and therefore on the top */ int TableRef = LUA_REFNIL; if (NumArgs == 3) { TableRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (TableRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get value reference of parameter #3", NumArgs); } } /* table value is popped, and now function is on top of the stack */ int FuncRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (FuncRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get function reference of parameter #2", NumArgs); } class cLuaCallback : public cItemCallback<Ty2> { public: cLuaCallback(lua_State* a_LuaState, int a_FuncRef, int a_TableRef) : LuaState( a_LuaState ) , FuncRef( a_FuncRef ) , TableRef( a_TableRef ) {} private: virtual bool Item(Ty2 * a_Item) override { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, FuncRef); /* Push function reference */ tolua_pushusertype(LuaState, a_Item, Ty2::GetClassStatic()); if (TableRef != LUA_REFNIL) { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, TableRef); /* Push table reference */ } int s = lua_pcall(LuaState, (TableRef == LUA_REFNIL ? 1 : 2), 1, 0); if (cLuaState::ReportErrors(LuaState, s)) { return true; // Abort enumeration } if (lua_isboolean(LuaState, -1)) { return (tolua_toboolean(LuaState, -1, 0) > 0); } return false; /* Continue enumeration */ } lua_State * LuaState; int FuncRef; int TableRef; } Callback(tolua_S, FuncRef, TableRef); bool bRetVal = (self->*Func1)(ItemName, Callback); /* Unreference the values again, so the LUA_REGISTRYINDEX can make place for other references */ luaL_unref(tolua_S, LUA_REGISTRYINDEX, TableRef); luaL_unref(tolua_S, LUA_REGISTRYINDEX, FuncRef); /* Push return value on stack */ tolua_pushboolean(tolua_S, bRetVal ); return 1; } template< class Ty1, class Ty2, bool (Ty1::*Func1)(int, cItemCallback<Ty2> &) > static int tolua_DoWithID(lua_State* tolua_S) { int NumArgs = lua_gettop(tolua_S) - 1; /* This includes 'self' */ if ((NumArgs != 2) && (NumArgs != 3)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 2 or 3 arguments, got %i", NumArgs); } Ty1 * self = (Ty1 *)tolua_tousertype(tolua_S, 1, 0); int ItemID = (int)tolua_tonumber(tolua_S, 2, 0); if (!lua_isfunction(tolua_S, 3)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a function for parameter #2", NumArgs); } /* luaL_ref gets reference to value on top of the stack, the table is the last argument and therefore on the top */ int TableRef = LUA_REFNIL; if (NumArgs == 3) { TableRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (TableRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get value reference of parameter #3", NumArgs); } } /* table value is popped, and now function is on top of the stack */ int FuncRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (FuncRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get function reference of parameter #2", NumArgs); } class cLuaCallback : public cItemCallback<Ty2> { public: cLuaCallback(lua_State * a_LuaState, int a_FuncRef, int a_TableRef) : LuaState(a_LuaState), FuncRef(a_FuncRef), TableRef(a_TableRef) {} private: virtual bool Item(Ty2 * a_Item) override { lua_rawgeti(LuaState, LUA_REGISTRYINDEX, FuncRef); // Push function to call tolua_pushusertype(LuaState, a_Item, Ty2::GetClassStatic()); // Push the item if (TableRef != LUA_REFNIL) { lua_rawgeti(LuaState, LUA_REGISTRYINDEX, TableRef); // Push the optional callbackdata param } int s = lua_pcall(LuaState, (TableRef == LUA_REFNIL ? 1 : 2), 1, 0); if (cLuaState::ReportErrors(LuaState, s)) { return true; // Abort enumeration } if (lua_isboolean(LuaState, -1)) { return (tolua_toboolean(LuaState, -1, 0) > 0); } return false; /* Continue enumeration */ } lua_State * LuaState; int FuncRef; int TableRef; } Callback(tolua_S, FuncRef, TableRef); bool bRetVal = (self->*Func1)(ItemID, Callback); /* Unreference the values again, so the LUA_REGISTRYINDEX can make place for other references */ luaL_unref(tolua_S, LUA_REGISTRYINDEX, TableRef); luaL_unref(tolua_S, LUA_REGISTRYINDEX, FuncRef); /* Push return value on stack */ tolua_pushboolean(tolua_S, bRetVal ); return 1; } template< class Ty1, class Ty2, bool (Ty1::*Func1)(int, int, int, cItemCallback<Ty2> &) > static int tolua_DoWithXYZ(lua_State* tolua_S) { int NumArgs = lua_gettop(tolua_S) - 1; /* This includes 'self' */ if ((NumArgs != 4) && (NumArgs != 5)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 4 or 5 arguments, got %i", NumArgs); } Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, 0); if (!lua_isnumber(tolua_S, 2) || !lua_isnumber(tolua_S, 3) || !lua_isnumber(tolua_S, 4)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a number for parameters #1, #2 and #3"); } int ItemX = ((int)tolua_tonumber(tolua_S, 2, 0)); int ItemY = ((int)tolua_tonumber(tolua_S, 3, 0)); int ItemZ = ((int)tolua_tonumber(tolua_S, 4, 0)); LOG("x %i y %i z %i", ItemX, ItemY, ItemZ ); if (!lua_isfunction( tolua_S, 5)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a function for parameter #4"); } /* luaL_ref gets reference to value on top of the stack, the table is the last argument and therefore on the top */ int TableRef = LUA_REFNIL; if (NumArgs == 5) { TableRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (TableRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get value reference of parameter #5"); } } /* table value is popped, and now function is on top of the stack */ int FuncRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (FuncRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get function reference of parameter #4"); } class cLuaCallback : public cItemCallback<Ty2> { public: cLuaCallback(lua_State* a_LuaState, int a_FuncRef, int a_TableRef) : LuaState( a_LuaState ) , FuncRef( a_FuncRef ) , TableRef( a_TableRef ) {} private: virtual bool Item(Ty2 * a_Item) override { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, FuncRef); /* Push function reference */ tolua_pushusertype(LuaState, a_Item, Ty2::GetClassStatic()); if (TableRef != LUA_REFNIL) { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, TableRef); /* Push table reference */ } int s = lua_pcall(LuaState, (TableRef == LUA_REFNIL ? 1 : 2), 1, 0); if (cLuaState::ReportErrors(LuaState, s)) { return true; // Abort enumeration } if (lua_isboolean(LuaState, -1)) { return (tolua_toboolean(LuaState, -1, 0) > 0); } return false; /* Continue enumeration */ } lua_State * LuaState; int FuncRef; int TableRef; } Callback(tolua_S, FuncRef, TableRef); bool bRetVal = (self->*Func1)(ItemX, ItemY, ItemZ, Callback); /* Unreference the values again, so the LUA_REGISTRYINDEX can make place for other references */ luaL_unref(tolua_S, LUA_REGISTRYINDEX, TableRef); luaL_unref(tolua_S, LUA_REGISTRYINDEX, FuncRef); /* Push return value on stack */ tolua_pushboolean(tolua_S, bRetVal ); return 1; } template< class Ty1, class Ty2, bool (Ty1::*Func1)(int, int, cItemCallback<Ty2> &) > static int tolua_ForEachInChunk(lua_State* tolua_S) { int NumArgs = lua_gettop(tolua_S) - 1; /* This includes 'self' */ if ((NumArgs != 3) && (NumArgs != 4)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 3 or 4 arguments, got %i", NumArgs); } Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, 0); if (!lua_isnumber(tolua_S, 2) || !lua_isnumber(tolua_S, 3)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a number for parameters #1 and #2"); } int ChunkX = ((int)tolua_tonumber(tolua_S, 2, 0)); int ChunkZ = ((int)tolua_tonumber(tolua_S, 3, 0)); if (!lua_isfunction( tolua_S, 4)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a function for parameter #3"); } /* luaL_ref gets reference to value on top of the stack, the table is the last argument and therefore on the top */ int TableRef = LUA_REFNIL; if (NumArgs == 4) { TableRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (TableRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get value reference of parameter #4"); } } /* table value is popped, and now function is on top of the stack */ int FuncRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (FuncRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get function reference of parameter #3"); } class cLuaCallback : public cItemCallback<Ty2> { public: cLuaCallback(lua_State* a_LuaState, int a_FuncRef, int a_TableRef) : LuaState( a_LuaState ) , FuncRef( a_FuncRef ) , TableRef( a_TableRef ) {} private: virtual bool Item(Ty2 * a_Item) override { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, FuncRef); /* Push function reference */ tolua_pushusertype(LuaState, a_Item, Ty2::GetClassStatic()); if (TableRef != LUA_REFNIL) { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, TableRef); /* Push table reference */ } int s = lua_pcall(LuaState, (TableRef == LUA_REFNIL ? 1 : 2), 1, 0); if (cLuaState::ReportErrors(LuaState, s)) { return true; /* Abort enumeration */ } if (lua_isboolean(LuaState, -1)) { return (tolua_toboolean(LuaState, -1, 0) > 0); } return false; /* Continue enumeration */ } lua_State * LuaState; int FuncRef; int TableRef; } Callback(tolua_S, FuncRef, TableRef); bool bRetVal = (self->*Func1)(ChunkX, ChunkZ, Callback); /* Unreference the values again, so the LUA_REGISTRYINDEX can make place for other references */ luaL_unref(tolua_S, LUA_REGISTRYINDEX, TableRef); luaL_unref(tolua_S, LUA_REGISTRYINDEX, FuncRef); /* Push return value on stack */ tolua_pushboolean(tolua_S, bRetVal ); return 1; } template< class Ty1, class Ty2, bool (Ty1::*Func1)(cItemCallback<Ty2> &) > static int tolua_ForEach(lua_State * tolua_S) { int NumArgs = lua_gettop(tolua_S) - 1; /* This includes 'self' */ if( NumArgs != 1 && NumArgs != 2) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 1 or 2 arguments, got %i", NumArgs); } Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, 0); if (self == NULL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Not called on an object instance"); } if (!lua_isfunction( tolua_S, 2)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a function for parameter #1"); } /* luaL_ref gets reference to value on top of the stack, the table is the last argument and therefore on the top */ int TableRef = LUA_REFNIL; if (NumArgs == 2) { TableRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (TableRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get value reference of parameter #2"); } } /* table value is popped, and now function is on top of the stack */ int FuncRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (FuncRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get function reference of parameter #1"); } class cLuaCallback : public cItemCallback<Ty2> { public: cLuaCallback(lua_State* a_LuaState, int a_FuncRef, int a_TableRef) : LuaState( a_LuaState ) , FuncRef( a_FuncRef ) , TableRef( a_TableRef ) {} private: virtual bool Item(Ty2 * a_Item) override { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, FuncRef); /* Push function reference */ tolua_pushusertype( LuaState, a_Item, Ty2::GetClassStatic() ); if (TableRef != LUA_REFNIL) { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, TableRef); /* Push table reference */ } int s = lua_pcall(LuaState, (TableRef == LUA_REFNIL ? 1 : 2), 1, 0); if (cLuaState::ReportErrors(LuaState, s)) { return true; /* Abort enumeration */ } if (lua_isboolean(LuaState, -1)) { return (tolua_toboolean( LuaState, -1, 0) > 0); } return false; /* Continue enumeration */ } lua_State * LuaState; int FuncRef; int TableRef; } Callback(tolua_S, FuncRef, TableRef); bool bRetVal = (self->*Func1)(Callback); /* Unreference the values again, so the LUA_REGISTRYINDEX can make place for other references */ luaL_unref(tolua_S, LUA_REGISTRYINDEX, TableRef); luaL_unref(tolua_S, LUA_REGISTRYINDEX, FuncRef); /* Push return value on stack */ tolua_pushboolean(tolua_S, bRetVal ); return 1; } static int tolua_cWorld_SetSignLines(lua_State * tolua_S) { // Exported manually, because tolua would generate useless additional return values (a_Line1 .. a_Line4) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype (tolua_S, 1, "cWorld", 0, &tolua_err) || !tolua_isnumber (tolua_S, 2, 0, &tolua_err) || !tolua_isnumber (tolua_S, 3, 0, &tolua_err) || !tolua_isnumber (tolua_S, 4, 0, &tolua_err) || !tolua_iscppstring(tolua_S, 5, 0, &tolua_err) || !tolua_iscppstring(tolua_S, 6, 0, &tolua_err) || !tolua_iscppstring(tolua_S, 7, 0, &tolua_err) || !tolua_iscppstring(tolua_S, 8, 0, &tolua_err) || !tolua_isusertype (tolua_S, 9, "cPlayer", 1, &tolua_err) || !tolua_isnoobj (tolua_S, 10, &tolua_err) ) goto tolua_lerror; else #endif { cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, 0); int BlockX = (int) tolua_tonumber (tolua_S, 2, 0); int BlockY = (int) tolua_tonumber (tolua_S, 3, 0); int BlockZ = (int) tolua_tonumber (tolua_S, 4, 0); const AString Line1 = tolua_tocppstring(tolua_S, 5, 0); const AString Line2 = tolua_tocppstring(tolua_S, 6, 0); const AString Line3 = tolua_tocppstring(tolua_S, 7, 0); const AString Line4 = tolua_tocppstring(tolua_S, 8, 0); cPlayer * Player = (cPlayer *)tolua_tousertype (tolua_S, 9, NULL); #ifndef TOLUA_RELEASE if (self == NULL) { tolua_error(tolua_S, "invalid 'self' in function 'SetSignLines' / 'UpdateSign'", NULL); } #endif { bool res = self->UpdateSign(BlockX, BlockY, BlockZ, Line1, Line2, Line3, Line4, Player); tolua_pushboolean(tolua_S, res ? 1 : 0); } } return 1; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S, "#ferror in function 'SetSignLines' / 'UpdateSign'.", &tolua_err); return 0; #endif } static int tolua_cWorld_TryGetHeight(lua_State * tolua_S) { // Exported manually, because tolua would require the out-only param a_Height to be used when calling // Takes (a_World,) a_BlockX, a_BlockZ // Returns Height, IsValid #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype (tolua_S, 1, "cWorld", 0, &tolua_err) || !tolua_isnumber (tolua_S, 2, 0, &tolua_err) || !tolua_isnumber (tolua_S, 3, 0, &tolua_err) || !tolua_isnoobj (tolua_S, 4, &tolua_err) ) goto tolua_lerror; else #endif { cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, 0); int BlockX = (int) tolua_tonumber (tolua_S, 2, 0); int BlockZ = (int) tolua_tonumber (tolua_S, 3, 0); #ifndef TOLUA_RELEASE if (self == NULL) { tolua_error(tolua_S, "Invalid 'self' in function 'TryGetHeight'", NULL); } #endif { int Height = 0; bool res = self->TryGetHeight(BlockX, BlockZ, Height); tolua_pushnumber(tolua_S, Height); tolua_pushboolean(tolua_S, res ? 1 : 0); } } return 1; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S, "#ferror in function 'TryGetHeight'.", &tolua_err); return 0; #endif } static int tolua_cPluginManager_GetAllPlugins(lua_State * tolua_S) { cPluginManager* self = (cPluginManager*) tolua_tousertype(tolua_S,1,0); const cPluginManager::PluginMap & AllPlugins = self->GetAllPlugins(); lua_newtable(tolua_S); //lua_createtable(tolua_S, AllPlugins.size(), 0); int newTable = lua_gettop(tolua_S); int index = 1; cPluginManager::PluginMap::const_iterator iter = AllPlugins.begin(); while(iter != AllPlugins.end()) { const cPlugin* Plugin = iter->second; tolua_pushstring( tolua_S, iter->first.c_str() ); if( Plugin != NULL ) { tolua_pushusertype( tolua_S, (void*)Plugin, "const cPlugin" ); } else { tolua_pushboolean(tolua_S, 0); } //lua_rawseti(tolua_S, newTable, index); lua_rawset(tolua_S, -3); ++iter; ++index; } return 1; } static int tolua_cPluginManager_ForEachCommand(lua_State * tolua_S) { int NumArgs = lua_gettop(tolua_S) - 1; /* This includes 'self' */ if( NumArgs != 1) { LOGWARN("Error in function call 'ForEachCommand': Requires 1 argument, got %i", NumArgs); return 0; } cPluginManager * self = (cPluginManager *)tolua_tousertype(tolua_S, 1, 0); if (self == NULL) { LOGWARN("Error in function call 'ForEachCommand': Not called on an object instance"); return 0; } if (!lua_isfunction(tolua_S, 2)) { LOGWARN("Error in function call 'ForEachCommand': Expected a function for parameter #1"); return 0; } int FuncRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (FuncRef == LUA_REFNIL) { LOGWARN("Error in function call 'ForEachCommand': Could not get function reference of parameter #1"); return 0; } class cLuaCallback : public cPluginManager::cCommandEnumCallback { public: cLuaCallback(lua_State * a_LuaState, int a_FuncRef) : LuaState( a_LuaState ) , FuncRef( a_FuncRef ) {} private: virtual bool Command(const AString & a_Command, const cPlugin * a_Plugin, const AString & a_Permission, const AString & a_HelpString) override { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, FuncRef); /* Push function reference */ tolua_pushcppstring(LuaState, a_Command); tolua_pushcppstring(LuaState, a_Permission); tolua_pushcppstring(LuaState, a_HelpString); int s = lua_pcall(LuaState, 3, 1, 0); if (cLuaState::ReportErrors(LuaState, s)) { return true; /* Abort enumeration */ } if (lua_isboolean(LuaState, -1)) { return (tolua_toboolean( LuaState, -1, 0) > 0); } return false; /* Continue enumeration */ } lua_State * LuaState; int FuncRef; } Callback(tolua_S, FuncRef); bool bRetVal = self->ForEachCommand(Callback); /* Unreference the values again, so the LUA_REGISTRYINDEX can make place for other references */ luaL_unref(tolua_S, LUA_REGISTRYINDEX, FuncRef); /* Push return value on stack */ tolua_pushboolean(tolua_S, bRetVal); return 1; } static int tolua_cPluginManager_ForEachConsoleCommand(lua_State * tolua_S) { int NumArgs = lua_gettop(tolua_S) - 1; /* This includes 'self' */ if( NumArgs != 1) { LOGWARN("Error in function call 'ForEachConsoleCommand': Requires 1 argument, got %i", NumArgs); return 0; } cPluginManager * self = (cPluginManager *)tolua_tousertype(tolua_S, 1, 0); if (self == NULL) { LOGWARN("Error in function call 'ForEachConsoleCommand': Not called on an object instance"); return 0; } if (!lua_isfunction(tolua_S, 2)) { LOGWARN("Error in function call 'ForEachConsoleCommand': Expected a function for parameter #1"); return 0; } int FuncRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (FuncRef == LUA_REFNIL) { LOGWARN("Error in function call 'ForEachConsoleCommand': Could not get function reference of parameter #1"); return 0; } class cLuaCallback : public cPluginManager::cCommandEnumCallback { public: cLuaCallback(lua_State * a_LuaState, int a_FuncRef) : LuaState( a_LuaState ) , FuncRef( a_FuncRef ) {} private: virtual bool Command(const AString & a_Command, const cPlugin * a_Plugin, const AString & a_Permission, const AString & a_HelpString) override { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, FuncRef); /* Push function reference */ tolua_pushcppstring(LuaState, a_Command); tolua_pushcppstring(LuaState, a_HelpString); int s = lua_pcall(LuaState, 2, 1, 0); if (cLuaState::ReportErrors(LuaState, s)) { return true; /* Abort enumeration */ } if (lua_isboolean(LuaState, -1)) { return (tolua_toboolean( LuaState, -1, 0) > 0); } return false; /* Continue enumeration */ } lua_State * LuaState; int FuncRef; } Callback(tolua_S, FuncRef); bool bRetVal = self->ForEachConsoleCommand(Callback); /* Unreference the values again, so the LUA_REGISTRYINDEX can make place for other references */ luaL_unref(tolua_S, LUA_REGISTRYINDEX, FuncRef); /* Push return value on stack */ tolua_pushboolean(tolua_S, bRetVal); return 1; } static int tolua_cPluginManager_BindCommand(lua_State * L) { // Function signature: cPluginManager:BindCommand(Command, Permission, Function, HelpString) cPlugin_NewLua * Plugin = GetLuaPlugin(L); if (Plugin == NULL) { return 0; } // Read the arguments to this API call: tolua_Error tolua_err; if ( !tolua_isusertype (L, 1, "cPluginManager", 0, &tolua_err) || !tolua_iscppstring(L, 2, 0, &tolua_err) || !tolua_iscppstring(L, 3, 0, &tolua_err) || !tolua_iscppstring(L, 5, 0, &tolua_err) || !tolua_isnoobj (L, 6, &tolua_err) ) { tolua_error(L, "#ferror in function 'BindCommand'.", &tolua_err); return 0; } if (!lua_isfunction(L, 4)) { luaL_error(L, "\"BindCommand\" function expects a function as its 3rd parameter. Command-binding aborted."); return 0; } cPluginManager * self = (cPluginManager *)tolua_tousertype(L, 1, 0); AString Command (tolua_tocppstring(L, 2, "")); AString Permission(tolua_tocppstring(L, 3, "")); AString HelpString(tolua_tocppstring(L, 5, "")); // Store the function reference: lua_pop(L, 1); // Pop the help string off the stack int FnRef = luaL_ref(L, LUA_REGISTRYINDEX); // Store function reference if (FnRef == LUA_REFNIL) { LOGERROR("\"BindCommand\": Cannot create a function reference. Command \"%s\" not bound.", Command.c_str()); return 0; } if (!self->BindCommand(Command, Plugin, Permission, HelpString)) { // Refused. Possibly already bound. Error message has been given, bail out silently. return 0; } Plugin->BindCommand(Command, FnRef); return 0; } static int tolua_cPluginManager_BindConsoleCommand(lua_State * L) { // Function signature: cPluginManager:BindConsoleCommand(Command, Function, HelpString) // Get the plugin identification out of LuaState: lua_getglobal(L, LUA_PLUGIN_INSTANCE_VAR_NAME); if (!lua_islightuserdata(L, -1)) { LOGERROR("cPluginManager:BindConsoleCommand() cannot get plugin instance, what have you done to my Lua state? Command-binding aborted."); } cPlugin_NewLua * Plugin = (cPlugin_NewLua *)lua_topointer(L, -1); lua_pop(L, 1); // Read the arguments to this API call: tolua_Error tolua_err; if ( !tolua_isusertype (L, 1, "cPluginManager", 0, &tolua_err) || // self !tolua_iscppstring(L, 2, 0, &tolua_err) || // Command !tolua_iscppstring(L, 4, 0, &tolua_err) || // HelpString !tolua_isnoobj (L, 5, &tolua_err) ) { tolua_error(L, "#ferror in function 'BindConsoleCommand'.", &tolua_err); return 0; } if (!lua_isfunction(L, 3)) { luaL_error(L, "\"BindConsoleCommand\" function expects a function as its 2nd parameter. Command-binding aborted."); return 0; } cPluginManager * self = (cPluginManager *)tolua_tousertype(L, 1, 0); AString Command (tolua_tocppstring(L, 2, "")); AString HelpString(tolua_tocppstring(L, 4, "")); // Store the function reference: lua_pop(L, 1); // Pop the help string off the stack int FnRef = luaL_ref(L, LUA_REGISTRYINDEX); // Store function reference if (FnRef == LUA_REFNIL) { LOGERROR("\"BindConsoleCommand\": Cannot create a function reference. Console Command \"%s\" not bound.", Command.c_str()); return 0; } if (!self->BindConsoleCommand(Command, Plugin, HelpString)) { // Refused. Possibly already bound. Error message has been given, bail out silently. return 0; } Plugin->BindConsoleCommand(Command, FnRef); return 0; } static int tolua_cPlayer_GetGroups(lua_State* tolua_S) { cPlayer* self = (cPlayer*) tolua_tousertype(tolua_S,1,0); const cPlayer::GroupList & AllGroups = self->GetGroups(); lua_createtable(tolua_S, AllGroups.size(), 0); int newTable = lua_gettop(tolua_S); int index = 1; cPlayer::GroupList::const_iterator iter = AllGroups.begin(); while(iter != AllGroups.end()) { const cGroup* Group = *iter; tolua_pushusertype( tolua_S, (void*)Group, "const cGroup" ); lua_rawseti(tolua_S, newTable, index); ++iter; ++index; } return 1; } static int tolua_cPlayer_GetResolvedPermissions(lua_State* tolua_S) { cPlayer* self = (cPlayer*) tolua_tousertype(tolua_S,1,0); cPlayer::StringList AllPermissions = self->GetResolvedPermissions(); lua_createtable(tolua_S, AllPermissions.size(), 0); int newTable = lua_gettop(tolua_S); int index = 1; cPlayer::StringList::iterator iter = AllPermissions.begin(); while(iter != AllPermissions.end()) { std::string& Permission = *iter; tolua_pushstring( tolua_S, Permission.c_str() ); lua_rawseti(tolua_S, newTable, index); ++iter; ++index; } return 1; } static int tolua_cPlayer_OpenWindow(lua_State * tolua_S) { // Function signature: cPlayer:OpenWindow(Window) // Retrieve the plugin instance from the Lua state cPlugin_NewLua * Plugin = GetLuaPlugin(tolua_S); if (Plugin == NULL) { return 0; } // Get the parameters: cPlayer * self = (cPlayer *)tolua_tousertype(tolua_S, 1, NULL); cWindow * wnd = (cWindow *)tolua_tousertype(tolua_S, 2, NULL); if ((self == NULL) || (wnd == NULL)) { LOGWARNING("%s: invalid self (%p) or wnd (%p)", __FUNCTION__, self, wnd); return 0; } // If cLuaWindow, add a reference, so that Lua won't delete the cLuaWindow object mid-processing tolua_Error err; if (tolua_isusertype(tolua_S, 2, "cLuaWindow", 0, &err)) { cLuaWindow * LuaWnd = (cLuaWindow *)wnd; // Only if not already referenced if (!LuaWnd->IsLuaReferenced()) { int LuaRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (LuaRef == LUA_REFNIL) { LOGWARNING("%s: Cannot create a window reference. Cannot open window \"%s\".", __FUNCTION__, wnd->GetWindowTitle().c_str() ); return 0; } LuaWnd->SetLuaRef(Plugin, LuaRef); } } // Open the window self->OpenWindow(wnd); return 0; } template < class OBJTYPE, void (OBJTYPE::*SetCallback)(cPlugin_NewLua * a_Plugin, int a_FnRef) > static int tolua_SetObjectCallback(lua_State * tolua_S) { // Function signature: OBJTYPE:SetWhateverCallback(CallbackFunction) // Retrieve the plugin instance from the Lua state cPlugin_NewLua * Plugin = GetLuaPlugin(tolua_S); if (Plugin == NULL) { // Warning message has already been printed by GetLuaPlugin(), bail out silently return 0; } // Get the parameters - self and the function reference: OBJTYPE * self = (OBJTYPE *)tolua_tousertype(tolua_S, 1, NULL); if (self == NULL) { LOGWARNING("%s: invalid self (%p)", __FUNCTION__, self); return 0; } int FnRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); // Store function reference for later retrieval if (FnRef == LUA_REFNIL) { LOGERROR("%s: Cannot create a function reference. Callback not set.", __FUNCTION__); return 0; } // Set the callback (self->*SetCallback)(Plugin, FnRef); return 0; } static int tolua_cPlugin_NewLua_AddWebTab(lua_State * tolua_S) { cPlugin_NewLua * self = (cPlugin_NewLua*)tolua_tousertype(tolua_S,1,0); tolua_Error tolua_err; tolua_err.array = 0; tolua_err.index = 0; tolua_err.type = 0; std::string Title = ""; int Reference = LUA_REFNIL; if( tolua_isstring( tolua_S, 2, 0, &tolua_err ) && lua_isfunction( tolua_S, 3 ) ) { Reference = luaL_ref(tolua_S, LUA_REGISTRYINDEX); Title = ((std::string) tolua_tocppstring(tolua_S,2,0)); } else { return tolua_do_error(tolua_S, "#ferror calling function '#funcname#'", &tolua_err); } if( Reference != LUA_REFNIL ) { if( !self->AddWebTab( Title.c_str(), tolua_S, Reference ) ) { luaL_unref( tolua_S, LUA_REGISTRYINDEX, Reference ); } } else { LOGERROR("ERROR: cPlugin_NewLua:AddWebTab invalid function reference in 2nd argument (Title: \"%s\")", Title.c_str() ); } return 0; } static int tolua_cPlugin_NewLua_AddTab(lua_State* tolua_S) { cPlugin_NewLua * self = (cPlugin_NewLua *) tolua_tousertype(tolua_S, 1, 0); LOGWARN("WARNING: Using deprecated function AddTab()! Use AddWebTab() instead. (plugin \"%s\" in folder \"%s\")", self->GetName().c_str(), self->GetDirectory().c_str() ); return tolua_cPlugin_NewLua_AddWebTab( tolua_S ); } // Perhaps use this as well for copying tables https://github.com/keplerproject/rings/pull/1 static int copy_lua_values(lua_State * a_Source, lua_State * a_Destination, int i, int top) { for(; i <= top; ++i ) { int t = lua_type(a_Source, i); switch (t) { case LUA_TSTRING: /* strings */ { const char * s = lua_tostring(a_Source, i); LOGD("%i push string: %s", i, s); tolua_pushstring(a_Destination, s); } break; case LUA_TBOOLEAN: /* booleans */ { int b = tolua_toboolean(a_Source, i, false); LOGD("%i push bool: %i", i, b); tolua_pushboolean(a_Destination, b ); } break; case LUA_TNUMBER: /* numbers */ { lua_Number d = tolua_tonumber(a_Source, i, 0); LOGD("%i push number: %0.2f", i, d); tolua_pushnumber(a_Destination, d ); } break; case LUA_TUSERDATA: { const char * type = 0; if (lua_getmetatable(a_Source,i)) { lua_rawget(a_Source, LUA_REGISTRYINDEX); type = lua_tostring(a_Source, -1); lua_pop(a_Source, 1); // Pop.. something?! I don't knooow~~ T_T } // don't need tolua_tousertype we already have the type void * ud = tolua_touserdata(a_Source, i, 0); LOGD("%i push usertype: %p of type '%s'", i, ud, type); if( type == 0 ) { LOGERROR("Call(): Something went wrong when trying to get usertype name!"); return 0; } tolua_pushusertype(a_Destination, ud, type); } break; default: /* other values */ LOGERROR("Call(): Unsupported value: '%s'. Can only use numbers and strings!", lua_typename(a_Source, t)); return 0; } } return 1; } static int tolua_cPlugin_Call(lua_State* tolua_S) { cPlugin_NewLua * self = (cPlugin_NewLua *) tolua_tousertype(tolua_S, 1, 0); lua_State* targetState = self->GetLuaState(); int targetTop = lua_gettop(targetState); int top = lua_gettop(tolua_S); LOGD("total in stack: %i", top ); std::string funcName = tolua_tostring(tolua_S, 2, ""); LOGD("Func name: %s", funcName.c_str() ); lua_getglobal(targetState, funcName.c_str()); if(!lua_isfunction(targetState,-1)) { LOGWARN("Error could not find function '%s' in plugin '%s'", funcName.c_str(), self->GetName().c_str() ); lua_pop(targetState,1); return 0; } if( copy_lua_values(tolua_S, targetState, 3, top) == 0 ) // Start at 3 because 1 and 2 are the plugin and function name respectively { // something went wrong, exit return 0; } int s = lua_pcall(targetState, top - 2, LUA_MULTRET, 0); if (cLuaState::ReportErrors(targetState, s)) { LOGWARN("Error while calling function '%s' in plugin '%s'", funcName.c_str(), self->GetName().c_str() ); return 0; } int nresults = lua_gettop(targetState) - targetTop; LOGD("num results: %i", nresults); int ttop = lua_gettop(targetState); if( copy_lua_values(targetState, tolua_S, targetTop+1, ttop) == 0 ) // Start at targetTop+1 and I have no idea why xD { // something went wrong, exit return 0; } lua_pop(targetState, nresults); // I have no idea what I'm doing, but it works return nresults; } static int tolua_md5(lua_State* tolua_S) { std::string SourceString = tolua_tostring(tolua_S, 1, 0); std::string CryptedString = md5( SourceString ); tolua_pushstring( tolua_S, CryptedString.c_str() ); return 1; } static int tolua_push_StringStringMap(lua_State* tolua_S, std::map< std::string, std::string >& a_StringStringMap ) { lua_newtable(tolua_S); int top = lua_gettop(tolua_S); for( std::map< std::string, std::string >::iterator it = a_StringStringMap.begin(); it != a_StringStringMap.end(); ++it ) { const char* key = it->first.c_str(); const char* value = it->second.c_str(); lua_pushstring(tolua_S, key); lua_pushstring(tolua_S, value); lua_settable(tolua_S, top); } return 1; } static int tolua_get_HTTPRequest_Params(lua_State* tolua_S) { HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S,1,0); return tolua_push_StringStringMap(tolua_S, self->Params); } static int tolua_get_HTTPRequest_PostParams(lua_State* tolua_S) { HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S,1,0); return tolua_push_StringStringMap(tolua_S, self->PostParams); } static int tolua_get_HTTPRequest_FormData(lua_State* tolua_S) { HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S,1,0); std::map< std::string, HTTPFormData >& FormData = self->FormData; lua_newtable(tolua_S); int top = lua_gettop(tolua_S); for( std::map< std::string, HTTPFormData >::iterator it = FormData.begin(); it != FormData.end(); ++it ) { lua_pushstring(tolua_S, it->first.c_str() ); tolua_pushusertype(tolua_S, &(it->second), "HTTPFormData" ); //lua_pushlstring(tolua_S, it->second.Value.c_str(), it->second.Value.size() ); // Might contain binary data lua_settable(tolua_S, top); } return 1; } static int tolua_cWebAdmin_GetPlugins(lua_State * tolua_S) { cWebAdmin* self = (cWebAdmin*) tolua_tousertype(tolua_S,1,0); const cWebAdmin::PluginList & AllPlugins = self->GetPlugins(); lua_createtable(tolua_S, AllPlugins.size(), 0); int newTable = lua_gettop(tolua_S); int index = 1; cWebAdmin::PluginList::const_iterator iter = AllPlugins.begin(); while(iter != AllPlugins.end()) { const cWebPlugin* Plugin = *iter; tolua_pushusertype( tolua_S, (void*)Plugin, "const cWebPlugin" ); lua_rawseti(tolua_S, newTable, index); ++iter; ++index; } return 1; } static int tolua_cWebPlugin_GetTabNames(lua_State * tolua_S) { cWebPlugin* self = (cWebPlugin*) tolua_tousertype(tolua_S,1,0); const cWebPlugin::TabNameList & TabNames = self->GetTabNames(); lua_newtable(tolua_S); int newTable = lua_gettop(tolua_S); int index = 1; cWebPlugin::TabNameList::const_iterator iter = TabNames.begin(); while(iter != TabNames.end()) { const AString & FancyName = iter->first; const AString & WebName = iter->second; tolua_pushstring( tolua_S, WebName.c_str() ); // Because the WebName is supposed to be unique, use it as key tolua_pushstring( tolua_S, FancyName.c_str() ); // lua_rawset(tolua_S, -3); ++iter; ++index; } return 1; } static int Lua_ItemGrid_GetSlotCoords(lua_State * L) { tolua_Error tolua_err; if ( !tolua_isusertype(L, 1, "const cItemGrid", 0, &tolua_err) || !tolua_isnumber (L, 2, 0, &tolua_err) || !tolua_isnoobj (L, 3, &tolua_err) ) { goto tolua_lerror; } { const cItemGrid * self = (const cItemGrid *)tolua_tousertype(L, 1, 0); int SlotNum = (int)tolua_tonumber(L, 2, 0); if (self == NULL) { tolua_error(L, "invalid 'self' in function 'cItemGrid:GetSlotCoords'", NULL); return 0; } int X, Y; self->GetSlotCoords(SlotNum, X, Y); tolua_pushnumber(L, (lua_Number)X); tolua_pushnumber(L, (lua_Number)Y); return 2; } tolua_lerror: tolua_error(L, "#ferror in function 'cItemGrid:GetSlotCoords'.", &tolua_err); return 0; } void ManualBindings::Bind(lua_State * tolua_S) { tolua_beginmodule(tolua_S,NULL); tolua_function(tolua_S, "StringSplit", tolua_StringSplit); tolua_function(tolua_S, "LOG", tolua_LOG); tolua_function(tolua_S, "LOGINFO", tolua_LOGINFO); tolua_function(tolua_S, "LOGWARN", tolua_LOGWARN); tolua_function(tolua_S, "LOGWARNING", tolua_LOGWARN); tolua_function(tolua_S, "LOGERROR", tolua_LOGERROR); tolua_beginmodule(tolua_S, "cRoot"); tolua_function(tolua_S, "FindAndDoWithPlayer", tolua_DoWith <cRoot, cPlayer, &cRoot::FindAndDoWithPlayer>); tolua_function(tolua_S, "ForEachPlayer", tolua_ForEach<cRoot, cPlayer, &cRoot::ForEachPlayer>); tolua_function(tolua_S, "ForEachWorld", tolua_ForEach<cRoot, cWorld, &cRoot::ForEachWorld>); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cWorld"); tolua_function(tolua_S, "DoWithChestAt", tolua_DoWithXYZ<cWorld, cChestEntity, &cWorld::DoWithChestAt>); tolua_function(tolua_S, "DoWithDispenserAt", tolua_DoWithXYZ<cWorld, cDispenserEntity, &cWorld::DoWithDispenserAt>); tolua_function(tolua_S, "DoWithDropSpenserAt", tolua_DoWithXYZ<cWorld, cDropSpenserEntity, &cWorld::DoWithDropSpenserAt>); tolua_function(tolua_S, "DoWithDropperAt", tolua_DoWithXYZ<cWorld, cDropperEntity, &cWorld::DoWithDropperAt>); tolua_function(tolua_S, "DoWithEntityByID", tolua_DoWithID< cWorld, cEntity, &cWorld::DoWithEntityByID>); tolua_function(tolua_S, "DoWithFurnaceAt", tolua_DoWithXYZ<cWorld, cFurnaceEntity, &cWorld::DoWithFurnaceAt>); tolua_function(tolua_S, "DoWithPlayer", tolua_DoWith< cWorld, cPlayer, &cWorld::DoWithPlayer>); tolua_function(tolua_S, "FindAndDoWithPlayer", tolua_DoWith< cWorld, cPlayer, &cWorld::FindAndDoWithPlayer>); tolua_function(tolua_S, "ForEachChestInChunk", tolua_ForEachInChunk<cWorld, cChestEntity, &cWorld::ForEachChestInChunk>); tolua_function(tolua_S, "ForEachEntity", tolua_ForEach< cWorld, cEntity, &cWorld::ForEachEntity>); tolua_function(tolua_S, "ForEachEntityInChunk", tolua_ForEachInChunk<cWorld, cEntity, &cWorld::ForEachEntityInChunk>); tolua_function(tolua_S, "ForEachFurnaceInChunk", tolua_ForEachInChunk<cWorld, cFurnaceEntity, &cWorld::ForEachFurnaceInChunk>); tolua_function(tolua_S, "ForEachPlayer", tolua_ForEach< cWorld, cPlayer, &cWorld::ForEachPlayer>); tolua_function(tolua_S, "SetSignLines", tolua_cWorld_SetSignLines); tolua_function(tolua_S, "TryGetHeight", tolua_cWorld_TryGetHeight); tolua_function(tolua_S, "UpdateSign", tolua_cWorld_SetSignLines); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cPlugin"); tolua_function(tolua_S, "Call", tolua_cPlugin_Call); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cPluginManager"); tolua_function(tolua_S, "BindCommand", tolua_cPluginManager_BindCommand); tolua_function(tolua_S, "BindConsoleCommand", tolua_cPluginManager_BindConsoleCommand); tolua_function(tolua_S, "ForEachCommand", tolua_cPluginManager_ForEachCommand); tolua_function(tolua_S, "ForEachConsoleCommand", tolua_cPluginManager_ForEachConsoleCommand); tolua_function(tolua_S, "GetAllPlugins", tolua_cPluginManager_GetAllPlugins); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cPlayer"); tolua_function(tolua_S, "GetGroups", tolua_cPlayer_GetGroups); tolua_function(tolua_S, "GetResolvedPermissions", tolua_cPlayer_GetResolvedPermissions); tolua_function(tolua_S, "OpenWindow", tolua_cPlayer_OpenWindow); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cLuaWindow"); tolua_function(tolua_S, "SetOnClosing", tolua_SetObjectCallback<cLuaWindow, &cLuaWindow::SetOnClosing>); tolua_function(tolua_S, "SetOnSlotChanged", tolua_SetObjectCallback<cLuaWindow, &cLuaWindow::SetOnSlotChanged>); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cPlugin_NewLua"); tolua_function(tolua_S, "AddTab", tolua_cPlugin_NewLua_AddTab); tolua_function(tolua_S, "AddWebTab", tolua_cPlugin_NewLua_AddWebTab); tolua_endmodule(tolua_S); tolua_cclass(tolua_S,"HTTPRequest","HTTPRequest","",NULL); tolua_beginmodule(tolua_S,"HTTPRequest"); // tolua_variable(tolua_S,"Method",tolua_get_HTTPRequest_Method,tolua_set_HTTPRequest_Method); // tolua_variable(tolua_S,"Path",tolua_get_HTTPRequest_Path,tolua_set_HTTPRequest_Path); tolua_variable(tolua_S,"FormData",tolua_get_HTTPRequest_FormData,0); tolua_variable(tolua_S,"Params",tolua_get_HTTPRequest_Params,0); tolua_variable(tolua_S,"PostParams",tolua_get_HTTPRequest_PostParams,0); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cWebAdmin"); tolua_function(tolua_S, "GetPlugins", tolua_cWebAdmin_GetPlugins); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cWebPlugin"); tolua_function(tolua_S, "GetTabNames", tolua_cWebPlugin_GetTabNames); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cClientHandle"); tolua_constant(tolua_S, "MAX_VIEW_DISTANCE", cClientHandle::MAX_VIEW_DISTANCE); tolua_constant(tolua_S, "MIN_VIEW_DISTANCE", cClientHandle::MIN_VIEW_DISTANCE); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cItemGrid"); tolua_function(tolua_S, "GetSlotCoords", Lua_ItemGrid_GetSlotCoords); tolua_endmodule(tolua_S); tolua_function(tolua_S, "md5", tolua_md5); tolua_endmodule(tolua_S); } Fixed compilation in ManualBindings #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "ManualBindings.h" #include "tolua++.h" #include "Root.h" #include "World.h" #include "Plugin.h" #include "Plugin_NewLua.h" #include "PluginManager.h" #include "Player.h" #include "WebAdmin.h" #include "StringMap.h" #include "ClientHandle.h" #include "BlockEntities/ChestEntity.h" #include "BlockEntities/DispenserEntity.h" #include "BlockEntities/DropperEntity.h" #include "BlockEntities/FurnaceEntity.h" #include "md5/md5.h" #include "LuaWindow.h" #include "LuaState.h" /**************************** * Better error reporting for Lua **/ int tolua_do_error(lua_State* L, const char * a_pMsg, tolua_Error * a_pToLuaError) { // Retrieve current function name lua_Debug entry; VERIFY(lua_getstack(L, 0, &entry)); VERIFY(lua_getinfo(L, "n", &entry)); // Insert function name into error msg AString msg(a_pMsg); ReplaceString(msg, "#funcname#", entry.name?entry.name:"?"); // Send the error to Lua tolua_error(L, msg.c_str(), a_pToLuaError); return 0; } int lua_do_error(lua_State* L, const char * a_pFormat, ...) { // Retrieve current function name lua_Debug entry; VERIFY(lua_getstack(L, 0, &entry)); VERIFY(lua_getinfo(L, "n", &entry)); // Insert function name into error msg AString msg(a_pFormat); ReplaceString(msg, "#funcname#", entry.name?entry.name:"?"); // Copied from luaL_error and modified va_list argp; va_start(argp, a_pFormat); luaL_where(L, 1); lua_pushvfstring(L, msg.c_str(), argp); va_end(argp); lua_concat(L, 2); return lua_error(L); } /**************************** * Lua bound functions with special return types **/ static int tolua_StringSplit(lua_State * tolua_S) { cLuaState LuaState(tolua_S); std::string str = (std::string)tolua_tocppstring(LuaState, 1, 0); std::string delim = (std::string)tolua_tocppstring(LuaState, 2, 0); AStringVector Split = StringSplit(str, delim); LuaState.PushStringVector(Split); return 1; } static int tolua_LOG(lua_State* tolua_S) { const char* str = tolua_tocppstring(tolua_S,1,0); cMCLogger::GetInstance()->LogSimple( str, 0 ); return 0; } static int tolua_LOGINFO(lua_State* tolua_S) { const char* str = tolua_tocppstring(tolua_S,1,0); cMCLogger::GetInstance()->LogSimple( str, 1 ); return 0; } static int tolua_LOGWARN(lua_State* tolua_S) { const char* str = tolua_tocppstring(tolua_S,1,0); cMCLogger::GetInstance()->LogSimple( str, 2 ); return 0; } static int tolua_LOGERROR(lua_State* tolua_S) { const char* str = tolua_tocppstring(tolua_S,1,0); cMCLogger::GetInstance()->LogSimple( str, 3 ); return 0; } cPlugin_NewLua * GetLuaPlugin(lua_State * L) { // Get the plugin identification out of LuaState: lua_getglobal(L, LUA_PLUGIN_INSTANCE_VAR_NAME); if (!lua_islightuserdata(L, -1)) { LOGWARNING("%s: cannot get plugin instance, what have you done to my Lua state?", __FUNCTION__); lua_pop(L, 1); return NULL; } cPlugin_NewLua * Plugin = (cPlugin_NewLua *)lua_topointer(L, -1); lua_pop(L, 1); return Plugin; } template< class Ty1, class Ty2, bool (Ty1::*Func1)(const AString &, cItemCallback<Ty2> &) > static int tolua_DoWith(lua_State* tolua_S) { int NumArgs = lua_gettop(tolua_S) - 1; /* This includes 'self' */ if ((NumArgs != 2) && (NumArgs != 3)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 2 or 3 arguments, got %i", NumArgs); } Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, 0); const char * ItemName = tolua_tocppstring(tolua_S, 2, ""); if ((ItemName == NULL) || (ItemName[0] == 0)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a non-empty string for parameter #1", NumArgs); } if (!lua_isfunction( tolua_S, 3)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a function for parameter #2", NumArgs); } /* luaL_ref gets reference to value on top of the stack, the table is the last argument and therefore on the top */ int TableRef = LUA_REFNIL; if (NumArgs == 3) { TableRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (TableRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get value reference of parameter #3", NumArgs); } } /* table value is popped, and now function is on top of the stack */ int FuncRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (FuncRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get function reference of parameter #2", NumArgs); } class cLuaCallback : public cItemCallback<Ty2> { public: cLuaCallback(lua_State* a_LuaState, int a_FuncRef, int a_TableRef) : LuaState( a_LuaState ) , FuncRef( a_FuncRef ) , TableRef( a_TableRef ) {} private: virtual bool Item(Ty2 * a_Item) override { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, FuncRef); /* Push function reference */ tolua_pushusertype(LuaState, a_Item, Ty2::GetClassStatic()); if (TableRef != LUA_REFNIL) { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, TableRef); /* Push table reference */ } int s = lua_pcall(LuaState, (TableRef == LUA_REFNIL ? 1 : 2), 1, 0); if (cLuaState::ReportErrors(LuaState, s)) { return true; // Abort enumeration } if (lua_isboolean(LuaState, -1)) { return (tolua_toboolean(LuaState, -1, 0) > 0); } return false; /* Continue enumeration */ } lua_State * LuaState; int FuncRef; int TableRef; } Callback(tolua_S, FuncRef, TableRef); bool bRetVal = (self->*Func1)(ItemName, Callback); /* Unreference the values again, so the LUA_REGISTRYINDEX can make place for other references */ luaL_unref(tolua_S, LUA_REGISTRYINDEX, TableRef); luaL_unref(tolua_S, LUA_REGISTRYINDEX, FuncRef); /* Push return value on stack */ tolua_pushboolean(tolua_S, bRetVal ); return 1; } template< class Ty1, class Ty2, bool (Ty1::*Func1)(int, cItemCallback<Ty2> &) > static int tolua_DoWithID(lua_State* tolua_S) { int NumArgs = lua_gettop(tolua_S) - 1; /* This includes 'self' */ if ((NumArgs != 2) && (NumArgs != 3)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 2 or 3 arguments, got %i", NumArgs); } Ty1 * self = (Ty1 *)tolua_tousertype(tolua_S, 1, 0); int ItemID = (int)tolua_tonumber(tolua_S, 2, 0); if (!lua_isfunction(tolua_S, 3)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a function for parameter #2", NumArgs); } /* luaL_ref gets reference to value on top of the stack, the table is the last argument and therefore on the top */ int TableRef = LUA_REFNIL; if (NumArgs == 3) { TableRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (TableRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get value reference of parameter #3", NumArgs); } } /* table value is popped, and now function is on top of the stack */ int FuncRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (FuncRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get function reference of parameter #2", NumArgs); } class cLuaCallback : public cItemCallback<Ty2> { public: cLuaCallback(lua_State * a_LuaState, int a_FuncRef, int a_TableRef) : LuaState(a_LuaState), FuncRef(a_FuncRef), TableRef(a_TableRef) {} private: virtual bool Item(Ty2 * a_Item) override { lua_rawgeti(LuaState, LUA_REGISTRYINDEX, FuncRef); // Push function to call tolua_pushusertype(LuaState, a_Item, Ty2::GetClassStatic()); // Push the item if (TableRef != LUA_REFNIL) { lua_rawgeti(LuaState, LUA_REGISTRYINDEX, TableRef); // Push the optional callbackdata param } int s = lua_pcall(LuaState, (TableRef == LUA_REFNIL ? 1 : 2), 1, 0); if (cLuaState::ReportErrors(LuaState, s)) { return true; // Abort enumeration } if (lua_isboolean(LuaState, -1)) { return (tolua_toboolean(LuaState, -1, 0) > 0); } return false; /* Continue enumeration */ } lua_State * LuaState; int FuncRef; int TableRef; } Callback(tolua_S, FuncRef, TableRef); bool bRetVal = (self->*Func1)(ItemID, Callback); /* Unreference the values again, so the LUA_REGISTRYINDEX can make place for other references */ luaL_unref(tolua_S, LUA_REGISTRYINDEX, TableRef); luaL_unref(tolua_S, LUA_REGISTRYINDEX, FuncRef); /* Push return value on stack */ tolua_pushboolean(tolua_S, bRetVal ); return 1; } template< class Ty1, class Ty2, bool (Ty1::*Func1)(int, int, int, cItemCallback<Ty2> &) > static int tolua_DoWithXYZ(lua_State* tolua_S) { int NumArgs = lua_gettop(tolua_S) - 1; /* This includes 'self' */ if ((NumArgs != 4) && (NumArgs != 5)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 4 or 5 arguments, got %i", NumArgs); } Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, 0); if (!lua_isnumber(tolua_S, 2) || !lua_isnumber(tolua_S, 3) || !lua_isnumber(tolua_S, 4)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a number for parameters #1, #2 and #3"); } int ItemX = ((int)tolua_tonumber(tolua_S, 2, 0)); int ItemY = ((int)tolua_tonumber(tolua_S, 3, 0)); int ItemZ = ((int)tolua_tonumber(tolua_S, 4, 0)); LOG("x %i y %i z %i", ItemX, ItemY, ItemZ ); if (!lua_isfunction( tolua_S, 5)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a function for parameter #4"); } /* luaL_ref gets reference to value on top of the stack, the table is the last argument and therefore on the top */ int TableRef = LUA_REFNIL; if (NumArgs == 5) { TableRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (TableRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get value reference of parameter #5"); } } /* table value is popped, and now function is on top of the stack */ int FuncRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (FuncRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get function reference of parameter #4"); } class cLuaCallback : public cItemCallback<Ty2> { public: cLuaCallback(lua_State* a_LuaState, int a_FuncRef, int a_TableRef) : LuaState( a_LuaState ) , FuncRef( a_FuncRef ) , TableRef( a_TableRef ) {} private: virtual bool Item(Ty2 * a_Item) override { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, FuncRef); /* Push function reference */ tolua_pushusertype(LuaState, a_Item, Ty2::GetClassStatic()); if (TableRef != LUA_REFNIL) { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, TableRef); /* Push table reference */ } int s = lua_pcall(LuaState, (TableRef == LUA_REFNIL ? 1 : 2), 1, 0); if (cLuaState::ReportErrors(LuaState, s)) { return true; // Abort enumeration } if (lua_isboolean(LuaState, -1)) { return (tolua_toboolean(LuaState, -1, 0) > 0); } return false; /* Continue enumeration */ } lua_State * LuaState; int FuncRef; int TableRef; } Callback(tolua_S, FuncRef, TableRef); bool bRetVal = (self->*Func1)(ItemX, ItemY, ItemZ, Callback); /* Unreference the values again, so the LUA_REGISTRYINDEX can make place for other references */ luaL_unref(tolua_S, LUA_REGISTRYINDEX, TableRef); luaL_unref(tolua_S, LUA_REGISTRYINDEX, FuncRef); /* Push return value on stack */ tolua_pushboolean(tolua_S, bRetVal ); return 1; } template< class Ty1, class Ty2, bool (Ty1::*Func1)(int, int, cItemCallback<Ty2> &) > static int tolua_ForEachInChunk(lua_State* tolua_S) { int NumArgs = lua_gettop(tolua_S) - 1; /* This includes 'self' */ if ((NumArgs != 3) && (NumArgs != 4)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 3 or 4 arguments, got %i", NumArgs); } Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, 0); if (!lua_isnumber(tolua_S, 2) || !lua_isnumber(tolua_S, 3)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a number for parameters #1 and #2"); } int ChunkX = ((int)tolua_tonumber(tolua_S, 2, 0)); int ChunkZ = ((int)tolua_tonumber(tolua_S, 3, 0)); if (!lua_isfunction( tolua_S, 4)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a function for parameter #3"); } /* luaL_ref gets reference to value on top of the stack, the table is the last argument and therefore on the top */ int TableRef = LUA_REFNIL; if (NumArgs == 4) { TableRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (TableRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get value reference of parameter #4"); } } /* table value is popped, and now function is on top of the stack */ int FuncRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (FuncRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get function reference of parameter #3"); } class cLuaCallback : public cItemCallback<Ty2> { public: cLuaCallback(lua_State* a_LuaState, int a_FuncRef, int a_TableRef) : LuaState( a_LuaState ) , FuncRef( a_FuncRef ) , TableRef( a_TableRef ) {} private: virtual bool Item(Ty2 * a_Item) override { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, FuncRef); /* Push function reference */ tolua_pushusertype(LuaState, a_Item, Ty2::GetClassStatic()); if (TableRef != LUA_REFNIL) { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, TableRef); /* Push table reference */ } int s = lua_pcall(LuaState, (TableRef == LUA_REFNIL ? 1 : 2), 1, 0); if (cLuaState::ReportErrors(LuaState, s)) { return true; /* Abort enumeration */ } if (lua_isboolean(LuaState, -1)) { return (tolua_toboolean(LuaState, -1, 0) > 0); } return false; /* Continue enumeration */ } lua_State * LuaState; int FuncRef; int TableRef; } Callback(tolua_S, FuncRef, TableRef); bool bRetVal = (self->*Func1)(ChunkX, ChunkZ, Callback); /* Unreference the values again, so the LUA_REGISTRYINDEX can make place for other references */ luaL_unref(tolua_S, LUA_REGISTRYINDEX, TableRef); luaL_unref(tolua_S, LUA_REGISTRYINDEX, FuncRef); /* Push return value on stack */ tolua_pushboolean(tolua_S, bRetVal ); return 1; } template< class Ty1, class Ty2, bool (Ty1::*Func1)(cItemCallback<Ty2> &) > static int tolua_ForEach(lua_State * tolua_S) { int NumArgs = lua_gettop(tolua_S) - 1; /* This includes 'self' */ if( NumArgs != 1 && NumArgs != 2) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 1 or 2 arguments, got %i", NumArgs); } Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, 0); if (self == NULL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Not called on an object instance"); } if (!lua_isfunction( tolua_S, 2)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a function for parameter #1"); } /* luaL_ref gets reference to value on top of the stack, the table is the last argument and therefore on the top */ int TableRef = LUA_REFNIL; if (NumArgs == 2) { TableRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (TableRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get value reference of parameter #2"); } } /* table value is popped, and now function is on top of the stack */ int FuncRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (FuncRef == LUA_REFNIL) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get function reference of parameter #1"); } class cLuaCallback : public cItemCallback<Ty2> { public: cLuaCallback(lua_State* a_LuaState, int a_FuncRef, int a_TableRef) : LuaState( a_LuaState ) , FuncRef( a_FuncRef ) , TableRef( a_TableRef ) {} private: virtual bool Item(Ty2 * a_Item) override { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, FuncRef); /* Push function reference */ tolua_pushusertype( LuaState, a_Item, Ty2::GetClassStatic() ); if (TableRef != LUA_REFNIL) { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, TableRef); /* Push table reference */ } int s = lua_pcall(LuaState, (TableRef == LUA_REFNIL ? 1 : 2), 1, 0); if (cLuaState::ReportErrors(LuaState, s)) { return true; /* Abort enumeration */ } if (lua_isboolean(LuaState, -1)) { return (tolua_toboolean( LuaState, -1, 0) > 0); } return false; /* Continue enumeration */ } lua_State * LuaState; int FuncRef; int TableRef; } Callback(tolua_S, FuncRef, TableRef); bool bRetVal = (self->*Func1)(Callback); /* Unreference the values again, so the LUA_REGISTRYINDEX can make place for other references */ luaL_unref(tolua_S, LUA_REGISTRYINDEX, TableRef); luaL_unref(tolua_S, LUA_REGISTRYINDEX, FuncRef); /* Push return value on stack */ tolua_pushboolean(tolua_S, bRetVal ); return 1; } static int tolua_cWorld_SetSignLines(lua_State * tolua_S) { // Exported manually, because tolua would generate useless additional return values (a_Line1 .. a_Line4) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype (tolua_S, 1, "cWorld", 0, &tolua_err) || !tolua_isnumber (tolua_S, 2, 0, &tolua_err) || !tolua_isnumber (tolua_S, 3, 0, &tolua_err) || !tolua_isnumber (tolua_S, 4, 0, &tolua_err) || !tolua_iscppstring(tolua_S, 5, 0, &tolua_err) || !tolua_iscppstring(tolua_S, 6, 0, &tolua_err) || !tolua_iscppstring(tolua_S, 7, 0, &tolua_err) || !tolua_iscppstring(tolua_S, 8, 0, &tolua_err) || !tolua_isusertype (tolua_S, 9, "cPlayer", 1, &tolua_err) || !tolua_isnoobj (tolua_S, 10, &tolua_err) ) goto tolua_lerror; else #endif { cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, 0); int BlockX = (int) tolua_tonumber (tolua_S, 2, 0); int BlockY = (int) tolua_tonumber (tolua_S, 3, 0); int BlockZ = (int) tolua_tonumber (tolua_S, 4, 0); const AString Line1 = tolua_tocppstring(tolua_S, 5, 0); const AString Line2 = tolua_tocppstring(tolua_S, 6, 0); const AString Line3 = tolua_tocppstring(tolua_S, 7, 0); const AString Line4 = tolua_tocppstring(tolua_S, 8, 0); cPlayer * Player = (cPlayer *)tolua_tousertype (tolua_S, 9, NULL); #ifndef TOLUA_RELEASE if (self == NULL) { tolua_error(tolua_S, "invalid 'self' in function 'SetSignLines' / 'UpdateSign'", NULL); } #endif { bool res = self->UpdateSign(BlockX, BlockY, BlockZ, Line1, Line2, Line3, Line4, Player); tolua_pushboolean(tolua_S, res ? 1 : 0); } } return 1; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S, "#ferror in function 'SetSignLines' / 'UpdateSign'.", &tolua_err); return 0; #endif } static int tolua_cWorld_TryGetHeight(lua_State * tolua_S) { // Exported manually, because tolua would require the out-only param a_Height to be used when calling // Takes (a_World,) a_BlockX, a_BlockZ // Returns Height, IsValid #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype (tolua_S, 1, "cWorld", 0, &tolua_err) || !tolua_isnumber (tolua_S, 2, 0, &tolua_err) || !tolua_isnumber (tolua_S, 3, 0, &tolua_err) || !tolua_isnoobj (tolua_S, 4, &tolua_err) ) goto tolua_lerror; else #endif { cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, 0); int BlockX = (int) tolua_tonumber (tolua_S, 2, 0); int BlockZ = (int) tolua_tonumber (tolua_S, 3, 0); #ifndef TOLUA_RELEASE if (self == NULL) { tolua_error(tolua_S, "Invalid 'self' in function 'TryGetHeight'", NULL); } #endif { int Height = 0; bool res = self->TryGetHeight(BlockX, BlockZ, Height); tolua_pushnumber(tolua_S, Height); tolua_pushboolean(tolua_S, res ? 1 : 0); } } return 1; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S, "#ferror in function 'TryGetHeight'.", &tolua_err); return 0; #endif } static int tolua_cPluginManager_GetAllPlugins(lua_State * tolua_S) { cPluginManager* self = (cPluginManager*) tolua_tousertype(tolua_S,1,0); const cPluginManager::PluginMap & AllPlugins = self->GetAllPlugins(); lua_newtable(tolua_S); //lua_createtable(tolua_S, AllPlugins.size(), 0); int newTable = lua_gettop(tolua_S); int index = 1; cPluginManager::PluginMap::const_iterator iter = AllPlugins.begin(); while(iter != AllPlugins.end()) { const cPlugin* Plugin = iter->second; tolua_pushstring( tolua_S, iter->first.c_str() ); if( Plugin != NULL ) { tolua_pushusertype( tolua_S, (void*)Plugin, "const cPlugin" ); } else { tolua_pushboolean(tolua_S, 0); } //lua_rawseti(tolua_S, newTable, index); lua_rawset(tolua_S, -3); ++iter; ++index; } return 1; } static int tolua_cPluginManager_ForEachCommand(lua_State * tolua_S) { int NumArgs = lua_gettop(tolua_S) - 1; /* This includes 'self' */ if( NumArgs != 1) { LOGWARN("Error in function call 'ForEachCommand': Requires 1 argument, got %i", NumArgs); return 0; } cPluginManager * self = (cPluginManager *)tolua_tousertype(tolua_S, 1, 0); if (self == NULL) { LOGWARN("Error in function call 'ForEachCommand': Not called on an object instance"); return 0; } if (!lua_isfunction(tolua_S, 2)) { LOGWARN("Error in function call 'ForEachCommand': Expected a function for parameter #1"); return 0; } int FuncRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (FuncRef == LUA_REFNIL) { LOGWARN("Error in function call 'ForEachCommand': Could not get function reference of parameter #1"); return 0; } class cLuaCallback : public cPluginManager::cCommandEnumCallback { public: cLuaCallback(lua_State * a_LuaState, int a_FuncRef) : LuaState( a_LuaState ) , FuncRef( a_FuncRef ) {} private: virtual bool Command(const AString & a_Command, const cPlugin * a_Plugin, const AString & a_Permission, const AString & a_HelpString) override { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, FuncRef); /* Push function reference */ tolua_pushcppstring(LuaState, a_Command); tolua_pushcppstring(LuaState, a_Permission); tolua_pushcppstring(LuaState, a_HelpString); int s = lua_pcall(LuaState, 3, 1, 0); if (cLuaState::ReportErrors(LuaState, s)) { return true; /* Abort enumeration */ } if (lua_isboolean(LuaState, -1)) { return (tolua_toboolean( LuaState, -1, 0) > 0); } return false; /* Continue enumeration */ } lua_State * LuaState; int FuncRef; } Callback(tolua_S, FuncRef); bool bRetVal = self->ForEachCommand(Callback); /* Unreference the values again, so the LUA_REGISTRYINDEX can make place for other references */ luaL_unref(tolua_S, LUA_REGISTRYINDEX, FuncRef); /* Push return value on stack */ tolua_pushboolean(tolua_S, bRetVal); return 1; } static int tolua_cPluginManager_ForEachConsoleCommand(lua_State * tolua_S) { int NumArgs = lua_gettop(tolua_S) - 1; /* This includes 'self' */ if( NumArgs != 1) { LOGWARN("Error in function call 'ForEachConsoleCommand': Requires 1 argument, got %i", NumArgs); return 0; } cPluginManager * self = (cPluginManager *)tolua_tousertype(tolua_S, 1, 0); if (self == NULL) { LOGWARN("Error in function call 'ForEachConsoleCommand': Not called on an object instance"); return 0; } if (!lua_isfunction(tolua_S, 2)) { LOGWARN("Error in function call 'ForEachConsoleCommand': Expected a function for parameter #1"); return 0; } int FuncRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (FuncRef == LUA_REFNIL) { LOGWARN("Error in function call 'ForEachConsoleCommand': Could not get function reference of parameter #1"); return 0; } class cLuaCallback : public cPluginManager::cCommandEnumCallback { public: cLuaCallback(lua_State * a_LuaState, int a_FuncRef) : LuaState( a_LuaState ) , FuncRef( a_FuncRef ) {} private: virtual bool Command(const AString & a_Command, const cPlugin * a_Plugin, const AString & a_Permission, const AString & a_HelpString) override { lua_rawgeti( LuaState, LUA_REGISTRYINDEX, FuncRef); /* Push function reference */ tolua_pushcppstring(LuaState, a_Command); tolua_pushcppstring(LuaState, a_HelpString); int s = lua_pcall(LuaState, 2, 1, 0); if (cLuaState::ReportErrors(LuaState, s)) { return true; /* Abort enumeration */ } if (lua_isboolean(LuaState, -1)) { return (tolua_toboolean( LuaState, -1, 0) > 0); } return false; /* Continue enumeration */ } lua_State * LuaState; int FuncRef; } Callback(tolua_S, FuncRef); bool bRetVal = self->ForEachConsoleCommand(Callback); /* Unreference the values again, so the LUA_REGISTRYINDEX can make place for other references */ luaL_unref(tolua_S, LUA_REGISTRYINDEX, FuncRef); /* Push return value on stack */ tolua_pushboolean(tolua_S, bRetVal); return 1; } static int tolua_cPluginManager_BindCommand(lua_State * L) { // Function signature: cPluginManager:BindCommand(Command, Permission, Function, HelpString) cPlugin_NewLua * Plugin = GetLuaPlugin(L); if (Plugin == NULL) { return 0; } // Read the arguments to this API call: tolua_Error tolua_err; if ( !tolua_isusertype (L, 1, "cPluginManager", 0, &tolua_err) || !tolua_iscppstring(L, 2, 0, &tolua_err) || !tolua_iscppstring(L, 3, 0, &tolua_err) || !tolua_iscppstring(L, 5, 0, &tolua_err) || !tolua_isnoobj (L, 6, &tolua_err) ) { tolua_error(L, "#ferror in function 'BindCommand'.", &tolua_err); return 0; } if (!lua_isfunction(L, 4)) { luaL_error(L, "\"BindCommand\" function expects a function as its 3rd parameter. Command-binding aborted."); return 0; } cPluginManager * self = (cPluginManager *)tolua_tousertype(L, 1, 0); AString Command (tolua_tocppstring(L, 2, "")); AString Permission(tolua_tocppstring(L, 3, "")); AString HelpString(tolua_tocppstring(L, 5, "")); // Store the function reference: lua_pop(L, 1); // Pop the help string off the stack int FnRef = luaL_ref(L, LUA_REGISTRYINDEX); // Store function reference if (FnRef == LUA_REFNIL) { LOGERROR("\"BindCommand\": Cannot create a function reference. Command \"%s\" not bound.", Command.c_str()); return 0; } if (!self->BindCommand(Command, Plugin, Permission, HelpString)) { // Refused. Possibly already bound. Error message has been given, bail out silently. return 0; } Plugin->BindCommand(Command, FnRef); return 0; } static int tolua_cPluginManager_BindConsoleCommand(lua_State * L) { // Function signature: cPluginManager:BindConsoleCommand(Command, Function, HelpString) // Get the plugin identification out of LuaState: lua_getglobal(L, LUA_PLUGIN_INSTANCE_VAR_NAME); if (!lua_islightuserdata(L, -1)) { LOGERROR("cPluginManager:BindConsoleCommand() cannot get plugin instance, what have you done to my Lua state? Command-binding aborted."); } cPlugin_NewLua * Plugin = (cPlugin_NewLua *)lua_topointer(L, -1); lua_pop(L, 1); // Read the arguments to this API call: tolua_Error tolua_err; if ( !tolua_isusertype (L, 1, "cPluginManager", 0, &tolua_err) || // self !tolua_iscppstring(L, 2, 0, &tolua_err) || // Command !tolua_iscppstring(L, 4, 0, &tolua_err) || // HelpString !tolua_isnoobj (L, 5, &tolua_err) ) { tolua_error(L, "#ferror in function 'BindConsoleCommand'.", &tolua_err); return 0; } if (!lua_isfunction(L, 3)) { luaL_error(L, "\"BindConsoleCommand\" function expects a function as its 2nd parameter. Command-binding aborted."); return 0; } cPluginManager * self = (cPluginManager *)tolua_tousertype(L, 1, 0); AString Command (tolua_tocppstring(L, 2, "")); AString HelpString(tolua_tocppstring(L, 4, "")); // Store the function reference: lua_pop(L, 1); // Pop the help string off the stack int FnRef = luaL_ref(L, LUA_REGISTRYINDEX); // Store function reference if (FnRef == LUA_REFNIL) { LOGERROR("\"BindConsoleCommand\": Cannot create a function reference. Console Command \"%s\" not bound.", Command.c_str()); return 0; } if (!self->BindConsoleCommand(Command, Plugin, HelpString)) { // Refused. Possibly already bound. Error message has been given, bail out silently. return 0; } Plugin->BindConsoleCommand(Command, FnRef); return 0; } static int tolua_cPlayer_GetGroups(lua_State* tolua_S) { cPlayer* self = (cPlayer*) tolua_tousertype(tolua_S,1,0); const cPlayer::GroupList & AllGroups = self->GetGroups(); lua_createtable(tolua_S, AllGroups.size(), 0); int newTable = lua_gettop(tolua_S); int index = 1; cPlayer::GroupList::const_iterator iter = AllGroups.begin(); while(iter != AllGroups.end()) { const cGroup* Group = *iter; tolua_pushusertype( tolua_S, (void*)Group, "const cGroup" ); lua_rawseti(tolua_S, newTable, index); ++iter; ++index; } return 1; } static int tolua_cPlayer_GetResolvedPermissions(lua_State* tolua_S) { cPlayer* self = (cPlayer*) tolua_tousertype(tolua_S,1,0); cPlayer::StringList AllPermissions = self->GetResolvedPermissions(); lua_createtable(tolua_S, AllPermissions.size(), 0); int newTable = lua_gettop(tolua_S); int index = 1; cPlayer::StringList::iterator iter = AllPermissions.begin(); while(iter != AllPermissions.end()) { std::string& Permission = *iter; tolua_pushstring( tolua_S, Permission.c_str() ); lua_rawseti(tolua_S, newTable, index); ++iter; ++index; } return 1; } static int tolua_cPlayer_OpenWindow(lua_State * tolua_S) { // Function signature: cPlayer:OpenWindow(Window) // Retrieve the plugin instance from the Lua state cPlugin_NewLua * Plugin = GetLuaPlugin(tolua_S); if (Plugin == NULL) { return 0; } // Get the parameters: cPlayer * self = (cPlayer *)tolua_tousertype(tolua_S, 1, NULL); cWindow * wnd = (cWindow *)tolua_tousertype(tolua_S, 2, NULL); if ((self == NULL) || (wnd == NULL)) { LOGWARNING("%s: invalid self (%p) or wnd (%p)", __FUNCTION__, self, wnd); return 0; } // If cLuaWindow, add a reference, so that Lua won't delete the cLuaWindow object mid-processing tolua_Error err; if (tolua_isusertype(tolua_S, 2, "cLuaWindow", 0, &err)) { cLuaWindow * LuaWnd = (cLuaWindow *)wnd; // Only if not already referenced if (!LuaWnd->IsLuaReferenced()) { int LuaRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); if (LuaRef == LUA_REFNIL) { LOGWARNING("%s: Cannot create a window reference. Cannot open window \"%s\".", __FUNCTION__, wnd->GetWindowTitle().c_str() ); return 0; } LuaWnd->SetLuaRef(Plugin, LuaRef); } } // Open the window self->OpenWindow(wnd); return 0; } template < class OBJTYPE, void (OBJTYPE::*SetCallback)(cPlugin_NewLua * a_Plugin, int a_FnRef) > static int tolua_SetObjectCallback(lua_State * tolua_S) { // Function signature: OBJTYPE:SetWhateverCallback(CallbackFunction) // Retrieve the plugin instance from the Lua state cPlugin_NewLua * Plugin = GetLuaPlugin(tolua_S); if (Plugin == NULL) { // Warning message has already been printed by GetLuaPlugin(), bail out silently return 0; } // Get the parameters - self and the function reference: OBJTYPE * self = (OBJTYPE *)tolua_tousertype(tolua_S, 1, NULL); if (self == NULL) { LOGWARNING("%s: invalid self (%p)", __FUNCTION__, self); return 0; } int FnRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX); // Store function reference for later retrieval if (FnRef == LUA_REFNIL) { LOGERROR("%s: Cannot create a function reference. Callback not set.", __FUNCTION__); return 0; } // Set the callback (self->*SetCallback)(Plugin, FnRef); return 0; } static int tolua_cPlugin_NewLua_AddWebTab(lua_State * tolua_S) { cPlugin_NewLua * self = (cPlugin_NewLua*)tolua_tousertype(tolua_S,1,0); tolua_Error tolua_err; tolua_err.array = 0; tolua_err.index = 0; tolua_err.type = 0; std::string Title = ""; int Reference = LUA_REFNIL; if( tolua_isstring( tolua_S, 2, 0, &tolua_err ) && lua_isfunction( tolua_S, 3 ) ) { Reference = luaL_ref(tolua_S, LUA_REGISTRYINDEX); Title = ((std::string) tolua_tocppstring(tolua_S,2,0)); } else { return tolua_do_error(tolua_S, "#ferror calling function '#funcname#'", &tolua_err); } if( Reference != LUA_REFNIL ) { if( !self->AddWebTab( Title.c_str(), tolua_S, Reference ) ) { luaL_unref( tolua_S, LUA_REGISTRYINDEX, Reference ); } } else { LOGERROR("ERROR: cPlugin_NewLua:AddWebTab invalid function reference in 2nd argument (Title: \"%s\")", Title.c_str() ); } return 0; } static int tolua_cPlugin_NewLua_AddTab(lua_State* tolua_S) { cPlugin_NewLua * self = (cPlugin_NewLua *) tolua_tousertype(tolua_S, 1, 0); LOGWARN("WARNING: Using deprecated function AddTab()! Use AddWebTab() instead. (plugin \"%s\" in folder \"%s\")", self->GetName().c_str(), self->GetDirectory().c_str() ); return tolua_cPlugin_NewLua_AddWebTab( tolua_S ); } // Perhaps use this as well for copying tables https://github.com/keplerproject/rings/pull/1 static int copy_lua_values(lua_State * a_Source, lua_State * a_Destination, int i, int top) { for(; i <= top; ++i ) { int t = lua_type(a_Source, i); switch (t) { case LUA_TSTRING: /* strings */ { const char * s = lua_tostring(a_Source, i); LOGD("%i push string: %s", i, s); tolua_pushstring(a_Destination, s); } break; case LUA_TBOOLEAN: /* booleans */ { int b = tolua_toboolean(a_Source, i, false); LOGD("%i push bool: %i", i, b); tolua_pushboolean(a_Destination, b ); } break; case LUA_TNUMBER: /* numbers */ { lua_Number d = tolua_tonumber(a_Source, i, 0); LOGD("%i push number: %0.2f", i, d); tolua_pushnumber(a_Destination, d ); } break; case LUA_TUSERDATA: { const char * type = 0; if (lua_getmetatable(a_Source,i)) { lua_rawget(a_Source, LUA_REGISTRYINDEX); type = lua_tostring(a_Source, -1); lua_pop(a_Source, 1); // Pop.. something?! I don't knooow~~ T_T } // don't need tolua_tousertype we already have the type void * ud = tolua_touserdata(a_Source, i, 0); LOGD("%i push usertype: %p of type '%s'", i, ud, type); if( type == 0 ) { LOGERROR("Call(): Something went wrong when trying to get usertype name!"); return 0; } tolua_pushusertype(a_Destination, ud, type); } break; default: /* other values */ LOGERROR("Call(): Unsupported value: '%s'. Can only use numbers and strings!", lua_typename(a_Source, t)); return 0; } } return 1; } static int tolua_cPlugin_Call(lua_State* tolua_S) { cPlugin_NewLua * self = (cPlugin_NewLua *) tolua_tousertype(tolua_S, 1, 0); lua_State* targetState = self->GetLuaState(); int targetTop = lua_gettop(targetState); int top = lua_gettop(tolua_S); LOGD("total in stack: %i", top ); std::string funcName = tolua_tostring(tolua_S, 2, ""); LOGD("Func name: %s", funcName.c_str() ); lua_getglobal(targetState, funcName.c_str()); if(!lua_isfunction(targetState,-1)) { LOGWARN("Error could not find function '%s' in plugin '%s'", funcName.c_str(), self->GetName().c_str() ); lua_pop(targetState,1); return 0; } if( copy_lua_values(tolua_S, targetState, 3, top) == 0 ) // Start at 3 because 1 and 2 are the plugin and function name respectively { // something went wrong, exit return 0; } int s = lua_pcall(targetState, top - 2, LUA_MULTRET, 0); if (cLuaState::ReportErrors(targetState, s)) { LOGWARN("Error while calling function '%s' in plugin '%s'", funcName.c_str(), self->GetName().c_str() ); return 0; } int nresults = lua_gettop(targetState) - targetTop; LOGD("num results: %i", nresults); int ttop = lua_gettop(targetState); if( copy_lua_values(targetState, tolua_S, targetTop+1, ttop) == 0 ) // Start at targetTop+1 and I have no idea why xD { // something went wrong, exit return 0; } lua_pop(targetState, nresults); // I have no idea what I'm doing, but it works return nresults; } static int tolua_md5(lua_State* tolua_S) { std::string SourceString = tolua_tostring(tolua_S, 1, 0); std::string CryptedString = md5( SourceString ); tolua_pushstring( tolua_S, CryptedString.c_str() ); return 1; } static int tolua_push_StringStringMap(lua_State* tolua_S, std::map< std::string, std::string >& a_StringStringMap ) { lua_newtable(tolua_S); int top = lua_gettop(tolua_S); for( std::map< std::string, std::string >::iterator it = a_StringStringMap.begin(); it != a_StringStringMap.end(); ++it ) { const char* key = it->first.c_str(); const char* value = it->second.c_str(); lua_pushstring(tolua_S, key); lua_pushstring(tolua_S, value); lua_settable(tolua_S, top); } return 1; } static int tolua_get_HTTPRequest_Params(lua_State* tolua_S) { HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S,1,0); return tolua_push_StringStringMap(tolua_S, self->Params); } static int tolua_get_HTTPRequest_PostParams(lua_State* tolua_S) { HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S,1,0); return tolua_push_StringStringMap(tolua_S, self->PostParams); } static int tolua_get_HTTPRequest_FormData(lua_State* tolua_S) { HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S,1,0); std::map< std::string, HTTPFormData >& FormData = self->FormData; lua_newtable(tolua_S); int top = lua_gettop(tolua_S); for( std::map< std::string, HTTPFormData >::iterator it = FormData.begin(); it != FormData.end(); ++it ) { lua_pushstring(tolua_S, it->first.c_str() ); tolua_pushusertype(tolua_S, &(it->second), "HTTPFormData" ); //lua_pushlstring(tolua_S, it->second.Value.c_str(), it->second.Value.size() ); // Might contain binary data lua_settable(tolua_S, top); } return 1; } static int tolua_cWebAdmin_GetPlugins(lua_State * tolua_S) { cWebAdmin* self = (cWebAdmin*) tolua_tousertype(tolua_S,1,0); const cWebAdmin::PluginList & AllPlugins = self->GetPlugins(); lua_createtable(tolua_S, AllPlugins.size(), 0); int newTable = lua_gettop(tolua_S); int index = 1; cWebAdmin::PluginList::const_iterator iter = AllPlugins.begin(); while(iter != AllPlugins.end()) { const cWebPlugin* Plugin = *iter; tolua_pushusertype( tolua_S, (void*)Plugin, "const cWebPlugin" ); lua_rawseti(tolua_S, newTable, index); ++iter; ++index; } return 1; } static int tolua_cWebPlugin_GetTabNames(lua_State * tolua_S) { cWebPlugin* self = (cWebPlugin*) tolua_tousertype(tolua_S,1,0); const cWebPlugin::TabNameList & TabNames = self->GetTabNames(); lua_newtable(tolua_S); int newTable = lua_gettop(tolua_S); int index = 1; cWebPlugin::TabNameList::const_iterator iter = TabNames.begin(); while(iter != TabNames.end()) { const AString & FancyName = iter->first; const AString & WebName = iter->second; tolua_pushstring( tolua_S, WebName.c_str() ); // Because the WebName is supposed to be unique, use it as key tolua_pushstring( tolua_S, FancyName.c_str() ); // lua_rawset(tolua_S, -3); ++iter; ++index; } return 1; } static int Lua_ItemGrid_GetSlotCoords(lua_State * L) { tolua_Error tolua_err; if ( !tolua_isusertype(L, 1, "const cItemGrid", 0, &tolua_err) || !tolua_isnumber (L, 2, 0, &tolua_err) || !tolua_isnoobj (L, 3, &tolua_err) ) { goto tolua_lerror; } { const cItemGrid * self = (const cItemGrid *)tolua_tousertype(L, 1, 0); int SlotNum = (int)tolua_tonumber(L, 2, 0); if (self == NULL) { tolua_error(L, "invalid 'self' in function 'cItemGrid:GetSlotCoords'", NULL); return 0; } int X, Y; self->GetSlotCoords(SlotNum, X, Y); tolua_pushnumber(L, (lua_Number)X); tolua_pushnumber(L, (lua_Number)Y); return 2; } tolua_lerror: tolua_error(L, "#ferror in function 'cItemGrid:GetSlotCoords'.", &tolua_err); return 0; } void ManualBindings::Bind(lua_State * tolua_S) { tolua_beginmodule(tolua_S,NULL); tolua_function(tolua_S, "StringSplit", tolua_StringSplit); tolua_function(tolua_S, "LOG", tolua_LOG); tolua_function(tolua_S, "LOGINFO", tolua_LOGINFO); tolua_function(tolua_S, "LOGWARN", tolua_LOGWARN); tolua_function(tolua_S, "LOGWARNING", tolua_LOGWARN); tolua_function(tolua_S, "LOGERROR", tolua_LOGERROR); tolua_beginmodule(tolua_S, "cRoot"); tolua_function(tolua_S, "FindAndDoWithPlayer", tolua_DoWith <cRoot, cPlayer, &cRoot::FindAndDoWithPlayer>); tolua_function(tolua_S, "ForEachPlayer", tolua_ForEach<cRoot, cPlayer, &cRoot::ForEachPlayer>); tolua_function(tolua_S, "ForEachWorld", tolua_ForEach<cRoot, cWorld, &cRoot::ForEachWorld>); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cWorld"); tolua_function(tolua_S, "DoWithChestAt", tolua_DoWithXYZ<cWorld, cChestEntity, &cWorld::DoWithChestAt>); tolua_function(tolua_S, "DoWithDispenserAt", tolua_DoWithXYZ<cWorld, cDispenserEntity, &cWorld::DoWithDispenserAt>); tolua_function(tolua_S, "DoWithDropSpenserAt", tolua_DoWithXYZ<cWorld, cDropSpenserEntity, &cWorld::DoWithDropSpenserAt>); tolua_function(tolua_S, "DoWithDropperAt", tolua_DoWithXYZ<cWorld, cDropperEntity, &cWorld::DoWithDropperAt>); tolua_function(tolua_S, "DoWithEntityByID", tolua_DoWithID< cWorld, cEntity, &cWorld::DoWithEntityByID>); tolua_function(tolua_S, "DoWithFurnaceAt", tolua_DoWithXYZ<cWorld, cFurnaceEntity, &cWorld::DoWithFurnaceAt>); tolua_function(tolua_S, "DoWithPlayer", tolua_DoWith< cWorld, cPlayer, &cWorld::DoWithPlayer>); tolua_function(tolua_S, "FindAndDoWithPlayer", tolua_DoWith< cWorld, cPlayer, &cWorld::FindAndDoWithPlayer>); tolua_function(tolua_S, "ForEachChestInChunk", tolua_ForEachInChunk<cWorld, cChestEntity, &cWorld::ForEachChestInChunk>); tolua_function(tolua_S, "ForEachEntity", tolua_ForEach< cWorld, cEntity, &cWorld::ForEachEntity>); tolua_function(tolua_S, "ForEachEntityInChunk", tolua_ForEachInChunk<cWorld, cEntity, &cWorld::ForEachEntityInChunk>); tolua_function(tolua_S, "ForEachFurnaceInChunk", tolua_ForEachInChunk<cWorld, cFurnaceEntity, &cWorld::ForEachFurnaceInChunk>); tolua_function(tolua_S, "ForEachPlayer", tolua_ForEach< cWorld, cPlayer, &cWorld::ForEachPlayer>); tolua_function(tolua_S, "SetSignLines", tolua_cWorld_SetSignLines); tolua_function(tolua_S, "TryGetHeight", tolua_cWorld_TryGetHeight); tolua_function(tolua_S, "UpdateSign", tolua_cWorld_SetSignLines); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cPlugin"); tolua_function(tolua_S, "Call", tolua_cPlugin_Call); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cPluginManager"); tolua_function(tolua_S, "BindCommand", tolua_cPluginManager_BindCommand); tolua_function(tolua_S, "BindConsoleCommand", tolua_cPluginManager_BindConsoleCommand); tolua_function(tolua_S, "ForEachCommand", tolua_cPluginManager_ForEachCommand); tolua_function(tolua_S, "ForEachConsoleCommand", tolua_cPluginManager_ForEachConsoleCommand); tolua_function(tolua_S, "GetAllPlugins", tolua_cPluginManager_GetAllPlugins); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cPlayer"); tolua_function(tolua_S, "GetGroups", tolua_cPlayer_GetGroups); tolua_function(tolua_S, "GetResolvedPermissions", tolua_cPlayer_GetResolvedPermissions); tolua_function(tolua_S, "OpenWindow", tolua_cPlayer_OpenWindow); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cLuaWindow"); tolua_function(tolua_S, "SetOnClosing", tolua_SetObjectCallback<cLuaWindow, &cLuaWindow::SetOnClosing>); tolua_function(tolua_S, "SetOnSlotChanged", tolua_SetObjectCallback<cLuaWindow, &cLuaWindow::SetOnSlotChanged>); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cPlugin_NewLua"); tolua_function(tolua_S, "AddTab", tolua_cPlugin_NewLua_AddTab); tolua_function(tolua_S, "AddWebTab", tolua_cPlugin_NewLua_AddWebTab); tolua_endmodule(tolua_S); tolua_cclass(tolua_S,"HTTPRequest","HTTPRequest","",NULL); tolua_beginmodule(tolua_S,"HTTPRequest"); // tolua_variable(tolua_S,"Method",tolua_get_HTTPRequest_Method,tolua_set_HTTPRequest_Method); // tolua_variable(tolua_S,"Path",tolua_get_HTTPRequest_Path,tolua_set_HTTPRequest_Path); tolua_variable(tolua_S,"FormData",tolua_get_HTTPRequest_FormData,0); tolua_variable(tolua_S,"Params",tolua_get_HTTPRequest_Params,0); tolua_variable(tolua_S,"PostParams",tolua_get_HTTPRequest_PostParams,0); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cWebAdmin"); tolua_function(tolua_S, "GetPlugins", tolua_cWebAdmin_GetPlugins); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cWebPlugin"); tolua_function(tolua_S, "GetTabNames", tolua_cWebPlugin_GetTabNames); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cClientHandle"); tolua_constant(tolua_S, "MAX_VIEW_DISTANCE", cClientHandle::MAX_VIEW_DISTANCE); tolua_constant(tolua_S, "MIN_VIEW_DISTANCE", cClientHandle::MIN_VIEW_DISTANCE); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cItemGrid"); tolua_function(tolua_S, "GetSlotCoords", Lua_ItemGrid_GetSlotCoords); tolua_endmodule(tolua_S); tolua_function(tolua_S, "md5", tolua_md5); tolua_endmodule(tolua_S); }
/***************************************************************************** * mkv.cpp : matroska demuxer ***************************************************************************** * Copyright (C) 2003-2005, 2008, 2010 VLC authors and VideoLAN * $Id$ * * Authors: Laurent Aimar <fenrir@via.ecp.fr> * Steve Lhomme <steve.lhomme@free.fr> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "mkv.hpp" #include "util.hpp" #include "matroska_segment.hpp" #include "demux.hpp" #include "chapters.hpp" #include "Ebml_parser.hpp" #include "stream_io_callback.hpp" #include <vlc_fs.h> #include <vlc_url.h> /***************************************************************************** * Module descriptor *****************************************************************************/ static int Open ( vlc_object_t * ); static void Close( vlc_object_t * ); vlc_module_begin () set_shortname( "Matroska" ) set_description( N_("Matroska stream demuxer" ) ) set_capability( "demux", 50 ) set_callbacks( Open, Close ) set_category( CAT_INPUT ) set_subcategory( SUBCAT_INPUT_DEMUX ) add_bool( "mkv-use-ordered-chapters", true, N_("Respect ordered chapters"), N_("Play chapters in the order specified in the segment."), false ); add_bool( "mkv-use-chapter-codec", true, N_("Chapter codecs"), N_("Use chapter codecs found in the segment."), true ); add_bool( "mkv-preload-local-dir", true, N_("Preload MKV files in the same directory"), N_("Preload matroska files in the same directory to find linked segments (not good for broken files)."), false ); add_bool( "mkv-seek-percent", false, N_("Seek based on percent not time"), N_("Seek based on percent not time."), true ); add_bool( "mkv-use-dummy", false, N_("Dummy Elements"), N_("Read and discard unknown EBML elements (not good for broken files)."), true ); add_shortcut( "mka", "mkv" ) vlc_module_end () class demux_sys_t; static int Demux ( demux_t * ); static int Control( demux_t *, int, va_list ); static void Seek ( demux_t *, mtime_t i_date, double f_percent, virtual_chapter_c *p_chapter ); /***************************************************************************** * Open: initializes matroska demux structures *****************************************************************************/ static int Open( vlc_object_t * p_this ) { demux_t *p_demux = (demux_t*)p_this; demux_sys_t *p_sys; matroska_stream_c *p_stream; matroska_segment_c *p_segment; const uint8_t *p_peek; std::string s_path, s_filename; vlc_stream_io_callback *p_io_callback; EbmlStream *p_io_stream; bool b_need_preload = false; /* peek the begining */ if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC; /* is a valid file */ if( p_peek[0] != 0x1a || p_peek[1] != 0x45 || p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC; /* Set the demux function */ p_demux->pf_demux = Demux; p_demux->pf_control = Control; p_demux->p_sys = p_sys = new demux_sys_t( *p_demux ); p_io_callback = new vlc_stream_io_callback( p_demux->s, false ); p_io_stream = new EbmlStream( *p_io_callback ); if( p_io_stream == NULL ) { msg_Err( p_demux, "failed to create EbmlStream" ); delete p_io_callback; delete p_sys; return VLC_EGENERIC; } p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_io_stream, true ); if( p_stream == NULL ) { msg_Err( p_demux, "cannot find KaxSegment or missing mandatory KaxInfo" ); goto error; } p_sys->streams.push_back( p_stream ); p_stream->p_io_callback = p_io_callback; p_stream->p_estream = p_io_stream; for (size_t i=0; i<p_stream->segments.size(); i++) { p_stream->segments[i]->Preload(); b_need_preload |= p_stream->segments[i]->b_ref_external_segments; } p_segment = p_stream->segments[0]; if( p_segment->cluster == NULL ) { msg_Err( p_demux, "cannot find any cluster, damaged file ?" ); goto error; } if (b_need_preload && var_InheritBool( p_demux, "mkv-preload-local-dir" )) { msg_Dbg( p_demux, "Preloading local dir" ); /* get the files from the same dir from the same family (based on p_demux->psz_path) */ if ( p_demux->psz_file && !strcmp( p_demux->psz_access, "file" ) ) { // assume it's a regular file // get the directory path s_path = p_demux->psz_file; if (s_path.at(s_path.length() - 1) == DIR_SEP_CHAR) { s_path = s_path.substr(0,s_path.length()-1); } else { if (s_path.find_last_of(DIR_SEP_CHAR) > 0) { s_path = s_path.substr(0,s_path.find_last_of(DIR_SEP_CHAR)); } } DIR *p_src_dir = vlc_opendir(s_path.c_str()); if (p_src_dir != NULL) { const char *psz_file; while ((psz_file = vlc_readdir(p_src_dir)) != NULL) { if (strlen(psz_file) > 4) { s_filename = s_path + DIR_SEP_CHAR + psz_file; #if defined(_WIN32) || defined(__OS2__) if (!strcasecmp(s_filename.c_str(), p_demux->psz_file)) #else if (!s_filename.compare(p_demux->psz_file)) #endif { continue; // don't reuse the original opened file } if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") || !s_filename.compare(s_filename.length() - 3, 3, "mka")) { // test whether this file belongs to our family const uint8_t *p_peek; bool file_ok = false; #warning Memory leak! std::string s_url = vlc_path2uri( s_filename.c_str(), "file" ); stream_t *p_file_stream = stream_UrlNew( p_demux, s_url.c_str() ); /* peek the begining */ if( p_file_stream && stream_Peek( p_file_stream, &p_peek, 4 ) >= 4 && p_peek[0] == 0x1a && p_peek[1] == 0x45 && p_peek[2] == 0xdf && p_peek[3] == 0xa3 ) file_ok = true; if ( file_ok ) { vlc_stream_io_callback *p_file_io = new vlc_stream_io_callback( p_file_stream, true ); EbmlStream *p_estream = new EbmlStream(*p_file_io); p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_estream ); if ( p_stream == NULL ) { msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() ); delete p_estream; delete p_file_io; } else { p_stream->p_io_callback = p_file_io; p_stream->p_estream = p_estream; p_sys->streams.push_back( p_stream ); } } else { if( p_file_stream ) { stream_Delete( p_file_stream ); } msg_Dbg( p_demux, "the file '%s' cannot be opened", s_filename.c_str() ); } } } } closedir( p_src_dir ); } } p_sys->PreloadFamily( *p_segment ); } else if (b_need_preload) msg_Warn( p_demux, "This file references other files, you may want to enable the preload of local directory"); if ( !p_sys->PreloadLinked() || !p_sys->PreparePlayback( NULL ) ) { msg_Err( p_demux, "cannot use the segment" ); goto error; } p_sys->FreeUnused(); p_sys->InitUi(); return VLC_SUCCESS; error: delete p_sys; return VLC_EGENERIC; } /***************************************************************************** * Close: frees unused data *****************************************************************************/ static void Close( vlc_object_t *p_this ) { demux_t *p_demux = (demux_t*)p_this; demux_sys_t *p_sys = p_demux->p_sys; virtual_segment_c *p_vsegment = p_sys->p_current_segment; if( p_vsegment ) { matroska_segment_c *p_segment = p_vsegment->CurrentSegment(); if( p_segment ) p_segment->UnSelect(); } delete p_sys; } /***************************************************************************** * Control: *****************************************************************************/ static int Control( demux_t *p_demux, int i_query, va_list args ) { demux_sys_t *p_sys = p_demux->p_sys; int64_t *pi64, i64; double *pf, f; int i_skp; size_t i_idx; vlc_meta_t *p_meta; input_attachment_t ***ppp_attach; int *pi_int; switch( i_query ) { case DEMUX_GET_ATTACHMENTS: ppp_attach = (input_attachment_t***)va_arg( args, input_attachment_t*** ); pi_int = (int*)va_arg( args, int * ); if( p_sys->stored_attachments.size() <= 0 ) return VLC_EGENERIC; *pi_int = p_sys->stored_attachments.size(); *ppp_attach = (input_attachment_t**)malloc( sizeof(input_attachment_t*) * p_sys->stored_attachments.size() ); if( !(*ppp_attach) ) return VLC_ENOMEM; for( size_t i = 0; i < p_sys->stored_attachments.size(); i++ ) { attachment_c *a = p_sys->stored_attachments[i]; (*ppp_attach)[i] = vlc_input_attachment_New( a->fileName(), a->mimeType(), NULL, a->p_data, a->size() ); } return VLC_SUCCESS; case DEMUX_GET_META: p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* ); vlc_meta_Merge( p_meta, p_sys->meta ); return VLC_SUCCESS; case DEMUX_GET_LENGTH: pi64 = (int64_t*)va_arg( args, int64_t * ); if( p_sys->f_duration > 0.0 ) { *pi64 = (int64_t)(p_sys->f_duration * 1000); return VLC_SUCCESS; } return VLC_EGENERIC; case DEMUX_GET_POSITION: pf = (double*)va_arg( args, double * ); if ( p_sys->f_duration > 0.0 ) *pf = (double)(p_sys->i_pts >= p_sys->i_start_pts ? p_sys->i_pts : p_sys->i_start_pts ) / (1000.0 * p_sys->f_duration); return VLC_SUCCESS; case DEMUX_SET_POSITION: if( p_sys->f_duration > 0.0 ) { f = (double)va_arg( args, double ); Seek( p_demux, -1, f, NULL ); return VLC_SUCCESS; } return VLC_EGENERIC; case DEMUX_GET_TIME: pi64 = (int64_t*)va_arg( args, int64_t * ); *pi64 = p_sys->i_pts; return VLC_SUCCESS; case DEMUX_GET_TITLE_INFO: if( p_sys->titles.size() > 1 || ( p_sys->titles.size() == 1 && p_sys->titles[0]->i_seekpoint > 0 ) ) { input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** ); int *pi_int = (int*)va_arg( args, int* ); *pi_int = p_sys->titles.size(); *ppp_title = (input_title_t**)malloc( sizeof( input_title_t* ) * p_sys->titles.size() ); for( size_t i = 0; i < p_sys->titles.size(); i++ ) (*ppp_title)[i] = vlc_input_title_Duplicate( p_sys->titles[i] ); return VLC_SUCCESS; } return VLC_EGENERIC; case DEMUX_SET_TITLE: /* handle editions as titles */ i_idx = (int)va_arg( args, int ); if(i_idx < p_sys->titles.size() && p_sys->titles[i_idx]->i_seekpoint) { p_sys->p_current_segment->i_current_edition = i_idx; p_sys->i_current_title = i_idx; p_sys->p_current_segment->p_current_chapter = p_sys->p_current_segment->editions[p_sys->p_current_segment->i_current_edition]->getChapterbyTimecode(0); Seek( p_demux, (int64_t)p_sys->titles[i_idx]->seekpoint[0]->i_time_offset, -1, NULL); p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT|INPUT_UPDATE_TITLE; p_demux->info.i_seekpoint = 0; p_demux->info.i_title = i_idx; p_sys->f_duration = (float) p_sys->titles[i_idx]->i_length / 1000.f; return VLC_SUCCESS; } return VLC_EGENERIC; case DEMUX_SET_SEEKPOINT: i_skp = (int)va_arg( args, int ); // TODO change the way it works with the << & >> buttons on the UI (+1/-1 instead of a number) if( p_sys->titles.size() && i_skp < p_sys->titles[p_sys->i_current_title]->i_seekpoint) { Seek( p_demux, (int64_t)p_sys->titles[p_sys->i_current_title]->seekpoint[i_skp]->i_time_offset, -1, NULL); p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT; p_demux->info.i_seekpoint = i_skp; return VLC_SUCCESS; } return VLC_EGENERIC; case DEMUX_GET_FPS: pf = (double *)va_arg( args, double * ); *pf = 0.0; if( p_sys->p_current_segment && p_sys->p_current_segment->CurrentSegment() ) { const matroska_segment_c *p_segment = p_sys->p_current_segment->CurrentSegment(); for( size_t i = 0; i < p_segment->tracks.size(); i++ ) { mkv_track_t *tk = p_segment->tracks[i]; if( tk->fmt.i_cat == VIDEO_ES && tk->fmt.video.i_frame_rate_base > 0 ) { *pf = (double)tk->fmt.video.i_frame_rate / tk->fmt.video.i_frame_rate_base; break; } } } return VLC_SUCCESS; case DEMUX_SET_TIME: i64 = (int64_t) va_arg( args, int64_t ); msg_Dbg(p_demux,"SET_TIME to %"PRId64, i64 ); Seek( p_demux, i64, -1, NULL ); return VLC_SUCCESS; default: return VLC_EGENERIC; } } /* Seek */ static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, virtual_chapter_c *p_chapter ) { demux_sys_t *p_sys = p_demux->p_sys; virtual_segment_c *p_vsegment = p_sys->p_current_segment; matroska_segment_c *p_segment = p_vsegment->CurrentSegment(); mtime_t i_time_offset = 0; int64_t i_global_position = -1; int i_index; msg_Dbg( p_demux, "seek request to %"PRId64" (%f%%)", i_date, f_percent ); if( i_date < 0 && f_percent < 0 ) { msg_Warn( p_demux, "cannot seek nowhere!" ); return; } if( f_percent > 1.0 ) { msg_Warn( p_demux, "cannot seek so far!" ); return; } if( p_sys->f_duration < 0 ) { msg_Warn( p_demux, "cannot seek without duration!"); return; } if( !p_segment ) { msg_Warn( p_demux, "cannot seek without valid segment position"); return; } /* seek without index or without date */ if( f_percent >= 0 && (var_InheritBool( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 )) { i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 ); if( !p_segment->b_cues ) { int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) ); msg_Dbg( p_demux, "lengthy way of seeking for pos:%"PRId64, i_pos ); for( i_index = 0; i_index < p_segment->i_index; i_index++ ) { if( p_segment->p_indexes[i_index].i_position >= i_pos && p_segment->p_indexes[i_index].i_time > 0 ) break; } if( i_index == p_segment->i_index ) i_index--; if( p_segment->p_indexes[i_index].i_position < i_pos ) { msg_Dbg( p_demux, "no cues, seek request to global pos: %"PRId64, i_pos ); i_global_position = i_pos; } } } p_vsegment->Seek( *p_demux, i_date, i_time_offset, p_chapter, i_global_position ); } /* Needed by matroska_segment::Seek() and Seek */ void BlockDecode( demux_t *p_demux, KaxBlock *block, KaxSimpleBlock *simpleblock, mtime_t i_pts, mtime_t i_duration, bool f_mandatory ) { demux_sys_t *p_sys = p_demux->p_sys; matroska_segment_c *p_segment = p_sys->p_current_segment->CurrentSegment(); if( !p_segment ) return; size_t i_track; if( p_segment->BlockFindTrackIndex( &i_track, block, simpleblock ) ) { msg_Err( p_demux, "invalid track number" ); return; } mkv_track_t *tk = p_segment->tracks[i_track]; if( tk->fmt.i_cat != NAV_ES && tk->p_es == NULL ) { msg_Err( p_demux, "unknown track number" ); return; } i_pts -= tk->i_codec_delay; if ( tk->fmt.i_cat != NAV_ES ) { bool b; es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b ); if( !b ) { tk->b_inited = false; if( tk->fmt.i_cat == VIDEO_ES || tk->fmt.i_cat == AUDIO_ES ) tk->i_last_dts = i_pts; return; } } /* First send init data */ if( !tk->b_inited && tk->i_data_init > 0 ) { block_t *p_init; msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init ); p_init = MemToBlock( tk->p_data_init, tk->i_data_init, 0 ); if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init ); } tk->b_inited = true; size_t frame_size = 0; size_t block_size = 0; if( simpleblock != NULL ) block_size = simpleblock->GetSize(); else block_size = block->GetSize(); for( unsigned int i = 0; ( block != NULL && i < block->NumberFrames()) || ( simpleblock != NULL && i < simpleblock->NumberFrames() ); i++ ) { block_t *p_block; DataBuffer *data; if( simpleblock != NULL ) { data = &simpleblock->GetBuffer(i); // condition when the DTS is correct (keyframe or B frame == NOT P frame) f_mandatory = simpleblock->IsDiscardable() || simpleblock->IsKeyframe(); } else { data = &block->GetBuffer(i); // condition when the DTS is correct (keyframe or B frame == NOT P frame) } frame_size += data->Size(); if( !data->Buffer() || data->Size() > SIZE_MAX || frame_size > block_size ) { msg_Warn( p_demux, "Cannot read frame (too long or no frame)" ); break; } if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER && tk->p_compression_data != NULL && tk->i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES ) p_block = MemToBlock( data->Buffer(), data->Size(), tk->p_compression_data->GetSize() ); else if( unlikely( tk->fmt.i_codec == VLC_CODEC_WAVPACK ) ) p_block = packetize_wavpack(tk, data->Buffer(), data->Size()); else p_block = MemToBlock( data->Buffer(), data->Size(), 0 ); if( p_block == NULL ) { break; } #if defined(HAVE_ZLIB_H) if( tk->i_compression_type == MATROSKA_COMPRESSION_ZLIB && tk->i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES ) { p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block ); if( p_block == NULL ) break; } else #endif if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER && tk->i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES ) { memcpy( p_block->p_buffer, tk->p_compression_data->GetBuffer(), tk->p_compression_data->GetSize() ); } switch( tk->fmt.i_codec ) { case VLC_CODEC_COOK: case VLC_CODEC_ATRAC3: { handle_real_audio(p_demux, tk, p_block, i_pts); block_Release(p_block); i_pts = ( tk->i_default_duration )? i_pts + ( mtime_t )( tk->i_default_duration / 1000 ): VLC_TS_INVALID; continue; } case VLC_CODEC_OPUS: mtime_t i_length = i_duration * tk-> f_timecodescale * (double) p_segment->i_timescale / 1000.0; if ( i_length < 0 ) i_length = 0; p_block->i_nb_samples = i_length * tk->fmt.audio.i_rate / CLOCK_FREQ; break; } if( tk->fmt.i_cat != VIDEO_ES ) { if ( tk->fmt.i_cat == NAV_ES ) { // TODO handle the start/stop times of this packet p_sys->p_ev->SetPci( (const pci_t *)&p_block->p_buffer[1]); block_Release( p_block ); return; } else if( tk->fmt.i_cat == AUDIO_ES ) { if( tk->i_chans_to_reorder ) aout_ChannelReorder( p_block->p_buffer, p_block->i_buffer, tk->fmt.audio.i_channels, tk->pi_chan_table, tk->fmt.i_codec ); } p_block->i_dts = p_block->i_pts = i_pts; } else { // correct timestamping when B frames are used if( tk->b_dts_only ) { p_block->i_pts = VLC_TS_INVALID; p_block->i_dts = i_pts; } else if( tk->b_pts_only ) { p_block->i_pts = i_pts; p_block->i_dts = i_pts; } else { p_block->i_pts = i_pts; if ( f_mandatory ) p_block->i_dts = p_block->i_pts; else p_block->i_dts = min( i_pts, tk->i_last_dts + ( mtime_t )( tk->i_default_duration / 1000 ) ); } } if( p_block->i_dts > VLC_TS_INVALID && ( tk->fmt.i_cat == VIDEO_ES || tk->fmt.i_cat == AUDIO_ES ) ) { tk->i_last_dts = p_block->i_dts; } #if 0 msg_Dbg( p_demux, "block i_dts: %"PRId64" / i_pts: %"PRId64, p_block->i_dts, p_block->i_pts); #endif if( !tk->b_no_duration ) { p_block->i_length = i_duration * tk-> f_timecodescale * (double) p_segment->i_timescale / 1000.0; } /* FIXME remove when VLC_TS_INVALID work is done */ if( i == 0 || p_block->i_dts > VLC_TS_INVALID ) p_block->i_dts += VLC_TS_0; if( !tk->b_dts_only && ( i == 0 || p_block->i_pts > VLC_TS_INVALID ) ) p_block->i_pts += VLC_TS_0; es_out_Send( p_demux->out, tk->p_es, p_block ); /* use time stamp only for first block */ i_pts = ( tk->i_default_duration )? i_pts + ( mtime_t )( tk->i_default_duration / 1000 ): VLC_TS_INVALID; } } /***************************************************************************** * Demux: reads and demuxes data packets ***************************************************************************** * Returns -1 in case of error, 0 in case of EOF, 1 otherwise *****************************************************************************/ static int Demux( demux_t *p_demux) { demux_sys_t *p_sys = p_demux->p_sys; vlc_mutex_lock( &p_sys->lock_demuxer ); virtual_segment_c *p_vsegment = p_sys->p_current_segment; matroska_segment_c *p_segment = p_vsegment->CurrentSegment(); if ( p_segment == NULL ) { vlc_mutex_unlock( &p_sys->lock_demuxer ); return 0; } int i_block_count = 0; int i_return = 0; for( ;; ) { if( p_sys->i_pts >= p_sys->i_start_pts ) if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) ) { i_return = 1; break; } if ( p_vsegment->CurrentEdition() && p_vsegment->CurrentEdition()->b_ordered && p_vsegment->CurrentChapter() == NULL ) /* nothing left to read in this ordered edition */ break; KaxBlock *block; KaxSimpleBlock *simpleblock; int64_t i_block_duration = 0; bool b_key_picture; bool b_discardable_picture; if( p_segment->BlockGet( block, simpleblock, &b_key_picture, &b_discardable_picture, &i_block_duration ) ) { if ( p_vsegment->CurrentEdition() && p_vsegment->CurrentEdition()->b_ordered ) { const virtual_chapter_c *p_chap = p_vsegment->CurrentChapter(); // check if there are more chapters to read if ( p_chap != NULL ) { /* TODO handle successive chapters with the same user_start_time/user_end_time */ p_sys->i_pts = p_chap->i_virtual_stop_time; p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content i_return = 1; } break; } else { msg_Warn( p_demux, "cannot get block EOF?" ); break; } } if( simpleblock != NULL ) p_sys->i_pts = p_sys->i_chapter_time + ( (mtime_t)simpleblock->GlobalTimecode() / INT64_C(1000) ); else p_sys->i_pts = p_sys->i_chapter_time + ( (mtime_t)block->GlobalTimecode() / INT64_C(1000) ); mtime_t i_pcr = VLC_TS_INVALID; for( size_t i = 0; i < p_segment->tracks.size(); i++) if( p_segment->tracks[i]->i_last_dts > VLC_TS_INVALID && ( p_segment->tracks[i]->i_last_dts < i_pcr || i_pcr == VLC_TS_INVALID )) i_pcr = p_segment->tracks[i]->i_last_dts; if( i_pcr > p_sys->i_pcr + 300000 ) { es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr ); p_sys->i_pcr = i_pcr; } if( p_sys->i_pts >= p_sys->i_start_pts ) { if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) ) { i_return = 1; delete block; break; } } if ( p_vsegment->CurrentEdition() && p_vsegment->CurrentEdition()->b_ordered && p_vsegment->CurrentChapter() == NULL ) { /* nothing left to read in this ordered edition */ delete block; break; } BlockDecode( p_demux, block, simpleblock, p_sys->i_pts, i_block_duration, b_key_picture || b_discardable_picture ); delete block; i_block_count++; // TODO optimize when there is need to leave or when seeking has been called if( i_block_count > 5 ) { i_return = 1; break; } } vlc_mutex_unlock( &p_sys->lock_demuxer ); return i_return; } Don't demux 5 blocks each time pf_demux is called Close #2658 /***************************************************************************** * mkv.cpp : matroska demuxer ***************************************************************************** * Copyright (C) 2003-2005, 2008, 2010 VLC authors and VideoLAN * $Id$ * * Authors: Laurent Aimar <fenrir@via.ecp.fr> * Steve Lhomme <steve.lhomme@free.fr> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "mkv.hpp" #include "util.hpp" #include "matroska_segment.hpp" #include "demux.hpp" #include "chapters.hpp" #include "Ebml_parser.hpp" #include "stream_io_callback.hpp" #include <vlc_fs.h> #include <vlc_url.h> /***************************************************************************** * Module descriptor *****************************************************************************/ static int Open ( vlc_object_t * ); static void Close( vlc_object_t * ); vlc_module_begin () set_shortname( "Matroska" ) set_description( N_("Matroska stream demuxer" ) ) set_capability( "demux", 50 ) set_callbacks( Open, Close ) set_category( CAT_INPUT ) set_subcategory( SUBCAT_INPUT_DEMUX ) add_bool( "mkv-use-ordered-chapters", true, N_("Respect ordered chapters"), N_("Play chapters in the order specified in the segment."), false ); add_bool( "mkv-use-chapter-codec", true, N_("Chapter codecs"), N_("Use chapter codecs found in the segment."), true ); add_bool( "mkv-preload-local-dir", true, N_("Preload MKV files in the same directory"), N_("Preload matroska files in the same directory to find linked segments (not good for broken files)."), false ); add_bool( "mkv-seek-percent", false, N_("Seek based on percent not time"), N_("Seek based on percent not time."), true ); add_bool( "mkv-use-dummy", false, N_("Dummy Elements"), N_("Read and discard unknown EBML elements (not good for broken files)."), true ); add_shortcut( "mka", "mkv" ) vlc_module_end () class demux_sys_t; static int Demux ( demux_t * ); static int Control( demux_t *, int, va_list ); static void Seek ( demux_t *, mtime_t i_date, double f_percent, virtual_chapter_c *p_chapter ); /***************************************************************************** * Open: initializes matroska demux structures *****************************************************************************/ static int Open( vlc_object_t * p_this ) { demux_t *p_demux = (demux_t*)p_this; demux_sys_t *p_sys; matroska_stream_c *p_stream; matroska_segment_c *p_segment; const uint8_t *p_peek; std::string s_path, s_filename; vlc_stream_io_callback *p_io_callback; EbmlStream *p_io_stream; bool b_need_preload = false; /* peek the begining */ if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC; /* is a valid file */ if( p_peek[0] != 0x1a || p_peek[1] != 0x45 || p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC; /* Set the demux function */ p_demux->pf_demux = Demux; p_demux->pf_control = Control; p_demux->p_sys = p_sys = new demux_sys_t( *p_demux ); p_io_callback = new vlc_stream_io_callback( p_demux->s, false ); p_io_stream = new EbmlStream( *p_io_callback ); if( p_io_stream == NULL ) { msg_Err( p_demux, "failed to create EbmlStream" ); delete p_io_callback; delete p_sys; return VLC_EGENERIC; } p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_io_stream, true ); if( p_stream == NULL ) { msg_Err( p_demux, "cannot find KaxSegment or missing mandatory KaxInfo" ); goto error; } p_sys->streams.push_back( p_stream ); p_stream->p_io_callback = p_io_callback; p_stream->p_estream = p_io_stream; for (size_t i=0; i<p_stream->segments.size(); i++) { p_stream->segments[i]->Preload(); b_need_preload |= p_stream->segments[i]->b_ref_external_segments; } p_segment = p_stream->segments[0]; if( p_segment->cluster == NULL ) { msg_Err( p_demux, "cannot find any cluster, damaged file ?" ); goto error; } if (b_need_preload && var_InheritBool( p_demux, "mkv-preload-local-dir" )) { msg_Dbg( p_demux, "Preloading local dir" ); /* get the files from the same dir from the same family (based on p_demux->psz_path) */ if ( p_demux->psz_file && !strcmp( p_demux->psz_access, "file" ) ) { // assume it's a regular file // get the directory path s_path = p_demux->psz_file; if (s_path.at(s_path.length() - 1) == DIR_SEP_CHAR) { s_path = s_path.substr(0,s_path.length()-1); } else { if (s_path.find_last_of(DIR_SEP_CHAR) > 0) { s_path = s_path.substr(0,s_path.find_last_of(DIR_SEP_CHAR)); } } DIR *p_src_dir = vlc_opendir(s_path.c_str()); if (p_src_dir != NULL) { const char *psz_file; while ((psz_file = vlc_readdir(p_src_dir)) != NULL) { if (strlen(psz_file) > 4) { s_filename = s_path + DIR_SEP_CHAR + psz_file; #if defined(_WIN32) || defined(__OS2__) if (!strcasecmp(s_filename.c_str(), p_demux->psz_file)) #else if (!s_filename.compare(p_demux->psz_file)) #endif { continue; // don't reuse the original opened file } if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") || !s_filename.compare(s_filename.length() - 3, 3, "mka")) { // test whether this file belongs to our family const uint8_t *p_peek; bool file_ok = false; #warning Memory leak! std::string s_url = vlc_path2uri( s_filename.c_str(), "file" ); stream_t *p_file_stream = stream_UrlNew( p_demux, s_url.c_str() ); /* peek the begining */ if( p_file_stream && stream_Peek( p_file_stream, &p_peek, 4 ) >= 4 && p_peek[0] == 0x1a && p_peek[1] == 0x45 && p_peek[2] == 0xdf && p_peek[3] == 0xa3 ) file_ok = true; if ( file_ok ) { vlc_stream_io_callback *p_file_io = new vlc_stream_io_callback( p_file_stream, true ); EbmlStream *p_estream = new EbmlStream(*p_file_io); p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_estream ); if ( p_stream == NULL ) { msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() ); delete p_estream; delete p_file_io; } else { p_stream->p_io_callback = p_file_io; p_stream->p_estream = p_estream; p_sys->streams.push_back( p_stream ); } } else { if( p_file_stream ) { stream_Delete( p_file_stream ); } msg_Dbg( p_demux, "the file '%s' cannot be opened", s_filename.c_str() ); } } } } closedir( p_src_dir ); } } p_sys->PreloadFamily( *p_segment ); } else if (b_need_preload) msg_Warn( p_demux, "This file references other files, you may want to enable the preload of local directory"); if ( !p_sys->PreloadLinked() || !p_sys->PreparePlayback( NULL ) ) { msg_Err( p_demux, "cannot use the segment" ); goto error; } p_sys->FreeUnused(); p_sys->InitUi(); return VLC_SUCCESS; error: delete p_sys; return VLC_EGENERIC; } /***************************************************************************** * Close: frees unused data *****************************************************************************/ static void Close( vlc_object_t *p_this ) { demux_t *p_demux = (demux_t*)p_this; demux_sys_t *p_sys = p_demux->p_sys; virtual_segment_c *p_vsegment = p_sys->p_current_segment; if( p_vsegment ) { matroska_segment_c *p_segment = p_vsegment->CurrentSegment(); if( p_segment ) p_segment->UnSelect(); } delete p_sys; } /***************************************************************************** * Control: *****************************************************************************/ static int Control( demux_t *p_demux, int i_query, va_list args ) { demux_sys_t *p_sys = p_demux->p_sys; int64_t *pi64, i64; double *pf, f; int i_skp; size_t i_idx; vlc_meta_t *p_meta; input_attachment_t ***ppp_attach; int *pi_int; switch( i_query ) { case DEMUX_GET_ATTACHMENTS: ppp_attach = (input_attachment_t***)va_arg( args, input_attachment_t*** ); pi_int = (int*)va_arg( args, int * ); if( p_sys->stored_attachments.size() <= 0 ) return VLC_EGENERIC; *pi_int = p_sys->stored_attachments.size(); *ppp_attach = (input_attachment_t**)malloc( sizeof(input_attachment_t*) * p_sys->stored_attachments.size() ); if( !(*ppp_attach) ) return VLC_ENOMEM; for( size_t i = 0; i < p_sys->stored_attachments.size(); i++ ) { attachment_c *a = p_sys->stored_attachments[i]; (*ppp_attach)[i] = vlc_input_attachment_New( a->fileName(), a->mimeType(), NULL, a->p_data, a->size() ); } return VLC_SUCCESS; case DEMUX_GET_META: p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* ); vlc_meta_Merge( p_meta, p_sys->meta ); return VLC_SUCCESS; case DEMUX_GET_LENGTH: pi64 = (int64_t*)va_arg( args, int64_t * ); if( p_sys->f_duration > 0.0 ) { *pi64 = (int64_t)(p_sys->f_duration * 1000); return VLC_SUCCESS; } return VLC_EGENERIC; case DEMUX_GET_POSITION: pf = (double*)va_arg( args, double * ); if ( p_sys->f_duration > 0.0 ) *pf = (double)(p_sys->i_pts >= p_sys->i_start_pts ? p_sys->i_pts : p_sys->i_start_pts ) / (1000.0 * p_sys->f_duration); return VLC_SUCCESS; case DEMUX_SET_POSITION: if( p_sys->f_duration > 0.0 ) { f = (double)va_arg( args, double ); Seek( p_demux, -1, f, NULL ); return VLC_SUCCESS; } return VLC_EGENERIC; case DEMUX_GET_TIME: pi64 = (int64_t*)va_arg( args, int64_t * ); *pi64 = p_sys->i_pts; return VLC_SUCCESS; case DEMUX_GET_TITLE_INFO: if( p_sys->titles.size() > 1 || ( p_sys->titles.size() == 1 && p_sys->titles[0]->i_seekpoint > 0 ) ) { input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** ); int *pi_int = (int*)va_arg( args, int* ); *pi_int = p_sys->titles.size(); *ppp_title = (input_title_t**)malloc( sizeof( input_title_t* ) * p_sys->titles.size() ); for( size_t i = 0; i < p_sys->titles.size(); i++ ) (*ppp_title)[i] = vlc_input_title_Duplicate( p_sys->titles[i] ); return VLC_SUCCESS; } return VLC_EGENERIC; case DEMUX_SET_TITLE: /* handle editions as titles */ i_idx = (int)va_arg( args, int ); if(i_idx < p_sys->titles.size() && p_sys->titles[i_idx]->i_seekpoint) { p_sys->p_current_segment->i_current_edition = i_idx; p_sys->i_current_title = i_idx; p_sys->p_current_segment->p_current_chapter = p_sys->p_current_segment->editions[p_sys->p_current_segment->i_current_edition]->getChapterbyTimecode(0); Seek( p_demux, (int64_t)p_sys->titles[i_idx]->seekpoint[0]->i_time_offset, -1, NULL); p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT|INPUT_UPDATE_TITLE; p_demux->info.i_seekpoint = 0; p_demux->info.i_title = i_idx; p_sys->f_duration = (float) p_sys->titles[i_idx]->i_length / 1000.f; return VLC_SUCCESS; } return VLC_EGENERIC; case DEMUX_SET_SEEKPOINT: i_skp = (int)va_arg( args, int ); // TODO change the way it works with the << & >> buttons on the UI (+1/-1 instead of a number) if( p_sys->titles.size() && i_skp < p_sys->titles[p_sys->i_current_title]->i_seekpoint) { Seek( p_demux, (int64_t)p_sys->titles[p_sys->i_current_title]->seekpoint[i_skp]->i_time_offset, -1, NULL); p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT; p_demux->info.i_seekpoint = i_skp; return VLC_SUCCESS; } return VLC_EGENERIC; case DEMUX_GET_FPS: pf = (double *)va_arg( args, double * ); *pf = 0.0; if( p_sys->p_current_segment && p_sys->p_current_segment->CurrentSegment() ) { const matroska_segment_c *p_segment = p_sys->p_current_segment->CurrentSegment(); for( size_t i = 0; i < p_segment->tracks.size(); i++ ) { mkv_track_t *tk = p_segment->tracks[i]; if( tk->fmt.i_cat == VIDEO_ES && tk->fmt.video.i_frame_rate_base > 0 ) { *pf = (double)tk->fmt.video.i_frame_rate / tk->fmt.video.i_frame_rate_base; break; } } } return VLC_SUCCESS; case DEMUX_SET_TIME: i64 = (int64_t) va_arg( args, int64_t ); msg_Dbg(p_demux,"SET_TIME to %"PRId64, i64 ); Seek( p_demux, i64, -1, NULL ); return VLC_SUCCESS; default: return VLC_EGENERIC; } } /* Seek */ static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, virtual_chapter_c *p_chapter ) { demux_sys_t *p_sys = p_demux->p_sys; virtual_segment_c *p_vsegment = p_sys->p_current_segment; matroska_segment_c *p_segment = p_vsegment->CurrentSegment(); mtime_t i_time_offset = 0; int64_t i_global_position = -1; int i_index; msg_Dbg( p_demux, "seek request to %"PRId64" (%f%%)", i_date, f_percent ); if( i_date < 0 && f_percent < 0 ) { msg_Warn( p_demux, "cannot seek nowhere!" ); return; } if( f_percent > 1.0 ) { msg_Warn( p_demux, "cannot seek so far!" ); return; } if( p_sys->f_duration < 0 ) { msg_Warn( p_demux, "cannot seek without duration!"); return; } if( !p_segment ) { msg_Warn( p_demux, "cannot seek without valid segment position"); return; } /* seek without index or without date */ if( f_percent >= 0 && (var_InheritBool( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 )) { i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 ); if( !p_segment->b_cues ) { int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) ); msg_Dbg( p_demux, "lengthy way of seeking for pos:%"PRId64, i_pos ); for( i_index = 0; i_index < p_segment->i_index; i_index++ ) { if( p_segment->p_indexes[i_index].i_position >= i_pos && p_segment->p_indexes[i_index].i_time > 0 ) break; } if( i_index == p_segment->i_index ) i_index--; if( p_segment->p_indexes[i_index].i_position < i_pos ) { msg_Dbg( p_demux, "no cues, seek request to global pos: %"PRId64, i_pos ); i_global_position = i_pos; } } } p_vsegment->Seek( *p_demux, i_date, i_time_offset, p_chapter, i_global_position ); } /* Needed by matroska_segment::Seek() and Seek */ void BlockDecode( demux_t *p_demux, KaxBlock *block, KaxSimpleBlock *simpleblock, mtime_t i_pts, mtime_t i_duration, bool f_mandatory ) { demux_sys_t *p_sys = p_demux->p_sys; matroska_segment_c *p_segment = p_sys->p_current_segment->CurrentSegment(); if( !p_segment ) return; size_t i_track; if( p_segment->BlockFindTrackIndex( &i_track, block, simpleblock ) ) { msg_Err( p_demux, "invalid track number" ); return; } mkv_track_t *tk = p_segment->tracks[i_track]; if( tk->fmt.i_cat != NAV_ES && tk->p_es == NULL ) { msg_Err( p_demux, "unknown track number" ); return; } i_pts -= tk->i_codec_delay; if ( tk->fmt.i_cat != NAV_ES ) { bool b; es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b ); if( !b ) { tk->b_inited = false; if( tk->fmt.i_cat == VIDEO_ES || tk->fmt.i_cat == AUDIO_ES ) tk->i_last_dts = i_pts; return; } } /* First send init data */ if( !tk->b_inited && tk->i_data_init > 0 ) { block_t *p_init; msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init ); p_init = MemToBlock( tk->p_data_init, tk->i_data_init, 0 ); if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init ); } tk->b_inited = true; size_t frame_size = 0; size_t block_size = 0; if( simpleblock != NULL ) block_size = simpleblock->GetSize(); else block_size = block->GetSize(); for( unsigned int i = 0; ( block != NULL && i < block->NumberFrames()) || ( simpleblock != NULL && i < simpleblock->NumberFrames() ); i++ ) { block_t *p_block; DataBuffer *data; if( simpleblock != NULL ) { data = &simpleblock->GetBuffer(i); // condition when the DTS is correct (keyframe or B frame == NOT P frame) f_mandatory = simpleblock->IsDiscardable() || simpleblock->IsKeyframe(); } else { data = &block->GetBuffer(i); // condition when the DTS is correct (keyframe or B frame == NOT P frame) } frame_size += data->Size(); if( !data->Buffer() || data->Size() > SIZE_MAX || frame_size > block_size ) { msg_Warn( p_demux, "Cannot read frame (too long or no frame)" ); break; } if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER && tk->p_compression_data != NULL && tk->i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES ) p_block = MemToBlock( data->Buffer(), data->Size(), tk->p_compression_data->GetSize() ); else if( unlikely( tk->fmt.i_codec == VLC_CODEC_WAVPACK ) ) p_block = packetize_wavpack(tk, data->Buffer(), data->Size()); else p_block = MemToBlock( data->Buffer(), data->Size(), 0 ); if( p_block == NULL ) { break; } #if defined(HAVE_ZLIB_H) if( tk->i_compression_type == MATROSKA_COMPRESSION_ZLIB && tk->i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES ) { p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block ); if( p_block == NULL ) break; } else #endif if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER && tk->i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES ) { memcpy( p_block->p_buffer, tk->p_compression_data->GetBuffer(), tk->p_compression_data->GetSize() ); } switch( tk->fmt.i_codec ) { case VLC_CODEC_COOK: case VLC_CODEC_ATRAC3: { handle_real_audio(p_demux, tk, p_block, i_pts); block_Release(p_block); i_pts = ( tk->i_default_duration )? i_pts + ( mtime_t )( tk->i_default_duration / 1000 ): VLC_TS_INVALID; continue; } case VLC_CODEC_OPUS: mtime_t i_length = i_duration * tk-> f_timecodescale * (double) p_segment->i_timescale / 1000.0; if ( i_length < 0 ) i_length = 0; p_block->i_nb_samples = i_length * tk->fmt.audio.i_rate / CLOCK_FREQ; break; } if( tk->fmt.i_cat != VIDEO_ES ) { if ( tk->fmt.i_cat == NAV_ES ) { // TODO handle the start/stop times of this packet p_sys->p_ev->SetPci( (const pci_t *)&p_block->p_buffer[1]); block_Release( p_block ); return; } else if( tk->fmt.i_cat == AUDIO_ES ) { if( tk->i_chans_to_reorder ) aout_ChannelReorder( p_block->p_buffer, p_block->i_buffer, tk->fmt.audio.i_channels, tk->pi_chan_table, tk->fmt.i_codec ); } p_block->i_dts = p_block->i_pts = i_pts; } else { // correct timestamping when B frames are used if( tk->b_dts_only ) { p_block->i_pts = VLC_TS_INVALID; p_block->i_dts = i_pts; } else if( tk->b_pts_only ) { p_block->i_pts = i_pts; p_block->i_dts = i_pts; } else { p_block->i_pts = i_pts; if ( f_mandatory ) p_block->i_dts = p_block->i_pts; else p_block->i_dts = min( i_pts, tk->i_last_dts + ( mtime_t )( tk->i_default_duration / 1000 ) ); } } if( p_block->i_dts > VLC_TS_INVALID && ( tk->fmt.i_cat == VIDEO_ES || tk->fmt.i_cat == AUDIO_ES ) ) { tk->i_last_dts = p_block->i_dts; } #if 0 msg_Dbg( p_demux, "block i_dts: %"PRId64" / i_pts: %"PRId64, p_block->i_dts, p_block->i_pts); #endif if( !tk->b_no_duration ) { p_block->i_length = i_duration * tk-> f_timecodescale * (double) p_segment->i_timescale / 1000.0; } /* FIXME remove when VLC_TS_INVALID work is done */ if( i == 0 || p_block->i_dts > VLC_TS_INVALID ) p_block->i_dts += VLC_TS_0; if( !tk->b_dts_only && ( i == 0 || p_block->i_pts > VLC_TS_INVALID ) ) p_block->i_pts += VLC_TS_0; es_out_Send( p_demux->out, tk->p_es, p_block ); /* use time stamp only for first block */ i_pts = ( tk->i_default_duration )? i_pts + ( mtime_t )( tk->i_default_duration / 1000 ): VLC_TS_INVALID; } } /***************************************************************************** * Demux: reads and demuxes data packets ***************************************************************************** * Returns -1 in case of error, 0 in case of EOF, 1 otherwise *****************************************************************************/ static int Demux( demux_t *p_demux) { demux_sys_t *p_sys = p_demux->p_sys; vlc_mutex_lock( &p_sys->lock_demuxer ); virtual_segment_c *p_vsegment = p_sys->p_current_segment; matroska_segment_c *p_segment = p_vsegment->CurrentSegment(); if ( p_segment == NULL ) { vlc_mutex_unlock( &p_sys->lock_demuxer ); return 0; } int i_return = 0; for( ;; ) { if( p_sys->i_pts >= p_sys->i_start_pts ) if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) ) { i_return = 1; break; } if ( p_vsegment->CurrentEdition() && p_vsegment->CurrentEdition()->b_ordered && p_vsegment->CurrentChapter() == NULL ) /* nothing left to read in this ordered edition */ break; KaxBlock *block; KaxSimpleBlock *simpleblock; int64_t i_block_duration = 0; bool b_key_picture; bool b_discardable_picture; if( p_segment->BlockGet( block, simpleblock, &b_key_picture, &b_discardable_picture, &i_block_duration ) ) { if ( p_vsegment->CurrentEdition() && p_vsegment->CurrentEdition()->b_ordered ) { const virtual_chapter_c *p_chap = p_vsegment->CurrentChapter(); // check if there are more chapters to read if ( p_chap != NULL ) { /* TODO handle successive chapters with the same user_start_time/user_end_time */ p_sys->i_pts = p_chap->i_virtual_stop_time; p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content i_return = 1; } break; } else { msg_Warn( p_demux, "cannot get block EOF?" ); break; } } if( simpleblock != NULL ) p_sys->i_pts = p_sys->i_chapter_time + ( (mtime_t)simpleblock->GlobalTimecode() / INT64_C(1000) ); else p_sys->i_pts = p_sys->i_chapter_time + ( (mtime_t)block->GlobalTimecode() / INT64_C(1000) ); mtime_t i_pcr = VLC_TS_INVALID; for( size_t i = 0; i < p_segment->tracks.size(); i++) if( p_segment->tracks[i]->i_last_dts > VLC_TS_INVALID && ( p_segment->tracks[i]->i_last_dts < i_pcr || i_pcr == VLC_TS_INVALID )) i_pcr = p_segment->tracks[i]->i_last_dts; if( i_pcr > p_sys->i_pcr + 300000 ) { es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr ); p_sys->i_pcr = i_pcr; } if( p_sys->i_pts >= p_sys->i_start_pts ) { if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) ) { i_return = 1; delete block; break; } } if ( p_vsegment->CurrentEdition() && p_vsegment->CurrentEdition()->b_ordered && p_vsegment->CurrentChapter() == NULL ) { /* nothing left to read in this ordered edition */ delete block; break; } BlockDecode( p_demux, block, simpleblock, p_sys->i_pts, i_block_duration, b_key_picture || b_discardable_picture ); delete block; vlc_mutex_unlock( &p_sys->lock_demuxer ); return 1; } vlc_mutex_unlock( &p_sys->lock_demuxer ); return i_return; }
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" CvNormalBayesClassifier::CvNormalBayesClassifier() { var_count = var_all = 0; var_idx = 0; cls_labels = 0; count = 0; sum = 0; productsum = 0; avg = 0; inv_eigen_values = 0; cov_rotate_mats = 0; c = 0; default_model_name = "my_nb"; } void CvNormalBayesClassifier::clear() { if( cls_labels ) { for( int cls = 0; cls < cls_labels->cols; cls++ ) { cvReleaseMat( &count[cls] ); cvReleaseMat( &sum[cls] ); cvReleaseMat( &productsum[cls] ); cvReleaseMat( &avg[cls] ); cvReleaseMat( &inv_eigen_values[cls] ); cvReleaseMat( &cov_rotate_mats[cls] ); } } cvReleaseMat( &cls_labels ); cvReleaseMat( &var_idx ); cvReleaseMat( &c ); cvFree( &count ); } CvNormalBayesClassifier::~CvNormalBayesClassifier() { clear(); } CvNormalBayesClassifier::CvNormalBayesClassifier( const CvMat* _train_data, const CvMat* _responses, const CvMat* _var_idx, const CvMat* _sample_idx ) { var_count = var_all = 0; var_idx = 0; cls_labels = 0; count = 0; sum = 0; productsum = 0; avg = 0; inv_eigen_values = 0; cov_rotate_mats = 0; c = 0; default_model_name = "my_nb"; train( _train_data, _responses, _var_idx, _sample_idx ); } bool CvNormalBayesClassifier::train( const CvMat* _train_data, const CvMat* _responses, const CvMat* _var_idx, const CvMat* _sample_idx, bool update ) { const float min_variation = FLT_EPSILON; bool result = false; CvMat* responses = 0; const float** train_data = 0; CvMat* __cls_labels = 0; CvMat* __var_idx = 0; CvMat* cov = 0; CV_FUNCNAME( "CvNormalBayesClassifier::train" ); __BEGIN__; int cls, nsamples = 0, _var_count = 0, _var_all = 0, nclasses = 0; int s, c1, c2; const int* responses_data; CV_CALL( cvPrepareTrainData( 0, _train_data, CV_ROW_SAMPLE, _responses, CV_VAR_CATEGORICAL, _var_idx, _sample_idx, false, &train_data, &nsamples, &_var_count, &_var_all, &responses, &__cls_labels, &__var_idx )); if( !update ) { const size_t mat_size = sizeof(CvMat*); size_t data_size; clear(); var_idx = __var_idx; cls_labels = __cls_labels; __var_idx = __cls_labels = 0; var_count = _var_count; var_all = _var_all; nclasses = cls_labels->cols; data_size = nclasses*6*mat_size; CV_CALL( count = (CvMat**)cvAlloc( data_size )); memset( count, 0, data_size ); sum = count + nclasses; productsum = sum + nclasses; avg = productsum + nclasses; inv_eigen_values= avg + nclasses; cov_rotate_mats = inv_eigen_values + nclasses; CV_CALL( c = cvCreateMat( 1, nclasses, CV_64FC1 )); for( cls = 0; cls < nclasses; cls++ ) { CV_CALL(count[cls] = cvCreateMat( 1, var_count, CV_32SC1 )); CV_CALL(sum[cls] = cvCreateMat( 1, var_count, CV_64FC1 )); CV_CALL(productsum[cls] = cvCreateMat( var_count, var_count, CV_64FC1 )); CV_CALL(avg[cls] = cvCreateMat( 1, var_count, CV_64FC1 )); CV_CALL(inv_eigen_values[cls] = cvCreateMat( 1, var_count, CV_64FC1 )); CV_CALL(cov_rotate_mats[cls] = cvCreateMat( var_count, var_count, CV_64FC1 )); CV_CALL(cvZero( count[cls] )); CV_CALL(cvZero( sum[cls] )); CV_CALL(cvZero( productsum[cls] )); CV_CALL(cvZero( avg[cls] )); CV_CALL(cvZero( inv_eigen_values[cls] )); CV_CALL(cvZero( cov_rotate_mats[cls] )); } } else { // check that the new training data has the same dimensionality etc. if( _var_count != var_count || _var_all != var_all || !((!_var_idx && !var_idx) || (_var_idx && var_idx && cvNorm(_var_idx,var_idx,CV_C) < DBL_EPSILON)) ) CV_ERROR( CV_StsBadArg, "The new training data is inconsistent with the original training data" ); if( cls_labels->cols != __cls_labels->cols || cvNorm(cls_labels, __cls_labels, CV_C) > DBL_EPSILON ) CV_ERROR( CV_StsNotImplemented, "In the current implementation the new training data must have absolutely " "the same set of class labels as used in the original training data" ); nclasses = cls_labels->cols; } responses_data = responses->data.i; CV_CALL( cov = cvCreateMat( _var_count, _var_count, CV_64FC1 )); /* process train data (count, sum , productsum) */ for( s = 0; s < nsamples; s++ ) { cls = responses_data[s]; int* count_data = count[cls]->data.i; double* sum_data = sum[cls]->data.db; double* prod_data = productsum[cls]->data.db; const float* train_vec = train_data[s]; for( c1 = 0; c1 < _var_count; c1++, prod_data += _var_count ) { double val1 = train_vec[c1]; sum_data[c1] += val1; count_data[c1]++; for( c2 = c1; c2 < _var_count; c2++ ) prod_data[c2] += train_vec[c2]*val1; } } /* calculate avg, covariance matrix, c */ for( cls = 0; cls < nclasses; cls++ ) { double det = 1; int i, j; CvMat* w = inv_eigen_values[cls]; int* count_data = count[cls]->data.i; double* avg_data = avg[cls]->data.db; double* sum1 = sum[cls]->data.db; cvCompleteSymm( productsum[cls], 0 ); for( j = 0; j < _var_count; j++ ) { int n = count_data[j]; avg_data[j] = n ? sum1[j] / n : 0.; } count_data = count[cls]->data.i; avg_data = avg[cls]->data.db; sum1 = sum[cls]->data.db; for( i = 0; i < _var_count; i++ ) { double* avg2_data = avg[cls]->data.db; double* sum2 = sum[cls]->data.db; double* prod_data = productsum[cls]->data.db + i*_var_count; double* cov_data = cov->data.db + i*_var_count; double s1val = sum1[i]; double avg1 = avg_data[i]; int count = count_data[i]; for( j = 0; j <= i; j++ ) { double avg2 = avg2_data[j]; double cov_val = prod_data[j] - avg1 * sum2[j] - avg2 * s1val + avg1 * avg2 * count; cov_val = (count > 1) ? cov_val / (count - 1) : cov_val; cov_data[j] = cov_val; } } CV_CALL( cvCompleteSymm( cov, 1 )); CV_CALL( cvSVD( cov, w, cov_rotate_mats[cls], 0, CV_SVD_U_T )); CV_CALL( cvMaxS( w, min_variation, w )); for( j = 0; j < _var_count; j++ ) det *= w->data.db[j]; CV_CALL( cvDiv( NULL, w, w )); c->data.db[cls] = log( det ); } result = true; __END__; if( !result || cvGetErrStatus() < 0 ) clear(); cvReleaseMat( &cov ); cvReleaseMat( &__cls_labels ); cvReleaseMat( &__var_idx ); cvFree( &train_data ); return result; } float CvNormalBayesClassifier::predict( const CvMat* samples, CvMat* results ) const { float value = 0; void* buffer = 0; int allocated_buffer = 0; CV_FUNCNAME( "CvNormalBayesClassifier::predict" ); __BEGIN__; int i, j, k, cls = -1, _var_count, nclasses; double opt = FLT_MAX; CvMat diff; int rtype = 0, rstep = 0, size; const int* vidx = 0; nclasses = cls_labels->cols; _var_count = avg[0]->cols; if( !CV_IS_MAT(samples) || CV_MAT_TYPE(samples->type) != CV_32FC1 || samples->cols != var_all ) CV_ERROR( CV_StsBadArg, "The input samples must be 32f matrix with the number of columns = var_all" ); if( samples->rows > 1 && !results ) CV_ERROR( CV_StsNullPtr, "When the number of input samples is >1, the output vector of results must be passed" ); if( results ) { if( !CV_IS_MAT(results) || (CV_MAT_TYPE(results->type) != CV_32FC1 && CV_MAT_TYPE(results->type) != CV_32SC1) || (results->cols != 1 && results->rows != 1) || results->cols + results->rows - 1 != samples->rows ) CV_ERROR( CV_StsBadArg, "The output array must be integer or floating-point vector " "with the number of elements = number of rows in the input matrix" ); rtype = CV_MAT_TYPE(results->type); rstep = CV_IS_MAT_CONT(results->type) ? 1 : results->step/CV_ELEM_SIZE(rtype); } if( var_idx ) vidx = var_idx->data.i; // allocate memory and initializing headers for calculating size = sizeof(double) * (nclasses + var_count); if( size <= CV_MAX_LOCAL_SIZE ) buffer = cvStackAlloc( size ); else { CV_CALL( buffer = cvAlloc( size )); allocated_buffer = 1; } diff = cvMat( 1, var_count, CV_64FC1, buffer ); for( k = 0; k < samples->rows; k++ ) { int ival; for( i = 0; i < nclasses; i++ ) { double cur = c->data.db[i]; CvMat* u = cov_rotate_mats[i]; CvMat* w = inv_eigen_values[i]; const double* avg_data = avg[i]->data.db; const float* x = (const float*)(samples->data.ptr + samples->step*k); // cov = u w u' --> cov^(-1) = u w^(-1) u' for( j = 0; j < _var_count; j++ ) diff.data.db[j] = avg_data[j] - x[vidx ? vidx[j] : j]; CV_CALL(cvGEMM( &diff, u, 1, 0, 0, &diff, CV_GEMM_B_T )); for( j = 0; j < _var_count; j++ ) { double d = diff.data.db[j]; cur += d*d*w->data.db[j]; } if( cur < opt ) { cls = i; opt = cur; } /* probability = exp( -0.5 * cur ) */ } ival = cls_labels->data.i[cls]; if( results ) { if( rtype == CV_32SC1 ) results->data.i[k*rstep] = ival; else results->data.fl[k*rstep] = (float)ival; } if( k == 0 ) value = (float)ival; /*if( _probs ) { CV_CALL( cvConvertScale( &expo, &expo, -0.5 )); CV_CALL( cvExp( &expo, &expo )); if( _probs->cols == 1 ) CV_CALL( cvReshape( &expo, &expo, 1, nclasses )); CV_CALL( cvConvertScale( &expo, _probs, 1./cvSum( &expo ).val[0] )); }*/ } __END__; if( allocated_buffer ) cvFree( &buffer ); return value; } void CvNormalBayesClassifier::write( CvFileStorage* fs, const char* name ) const { CV_FUNCNAME( "CvNormalBayesClassifier::write" ); __BEGIN__; int nclasses, i; nclasses = cls_labels->cols; cvStartWriteStruct( fs, name, CV_NODE_MAP, CV_TYPE_NAME_ML_NBAYES ); CV_CALL( cvWriteInt( fs, "var_count", var_count )); CV_CALL( cvWriteInt( fs, "var_all", var_all )); if( var_idx ) CV_CALL( cvWrite( fs, "var_idx", var_idx )); CV_CALL( cvWrite( fs, "cls_labels", cls_labels )); CV_CALL( cvStartWriteStruct( fs, "count", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, count[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "sum", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, sum[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "productsum", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, productsum[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "avg", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, avg[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "inv_eigen_values", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, inv_eigen_values[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "cov_rotate_mats", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, cov_rotate_mats[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvWrite( fs, "c", c )); cvEndWriteStruct( fs ); __END__; } void CvNormalBayesClassifier::read( CvFileStorage* fs, CvFileNode* root_node ) { bool ok = false; CV_FUNCNAME( "CvNormalBayesClassifier::read" ); __BEGIN__; int nclasses, i; size_t data_size; CvFileNode* node; CvSeq* seq; CvSeqReader reader; clear(); CV_CALL( var_count = cvReadIntByName( fs, root_node, "var_count", -1 )); CV_CALL( var_all = cvReadIntByName( fs, root_node, "var_all", -1 )); CV_CALL( var_idx = (CvMat*)cvReadByName( fs, root_node, "var_idx" )); CV_CALL( cls_labels = (CvMat*)cvReadByName( fs, root_node, "cls_labels" )); if( !cls_labels ) CV_ERROR( CV_StsParseError, "No \"cls_labels\" in NBayes classifier" ); if( cls_labels->cols < 1 ) CV_ERROR( CV_StsBadArg, "Number of classes is less 1" ); if( var_count <= 0 ) CV_ERROR( CV_StsParseError, "The field \"var_count\" of NBayes classifier is missing" ); nclasses = cls_labels->cols; data_size = nclasses*6*sizeof(CvMat*); CV_CALL( count = (CvMat**)cvAlloc( data_size )); memset( count, 0, data_size ); sum = count + nclasses; productsum = sum + nclasses; avg = productsum + nclasses; inv_eigen_values = avg + nclasses; cov_rotate_mats = inv_eigen_values + nclasses; CV_CALL( node = cvGetFileNodeByName( fs, root_node, "count" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( count[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "sum" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( sum[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "productsum" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( productsum[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "avg" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( avg[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "inv_eigen_values" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( inv_eigen_values[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "cov_rotate_mats" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( cov_rotate_mats[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( c = (CvMat*)cvReadByName( fs, root_node, "c" )); ok = true; __END__; if( !ok ) clear(); } using namespace cv; CvNormalBayesClassifier::CvNormalBayesClassifier( const Mat& _train_data, const Mat& _responses, const Mat& _var_idx, const Mat& _sample_idx ) { var_count = var_all = 0; var_idx = 0; cls_labels = 0; count = 0; sum = 0; productsum = 0; avg = 0; inv_eigen_values = 0; cov_rotate_mats = 0; c = 0; default_model_name = "my_nb"; CvMat tdata = _train_data, responses = _responses, vidx = _var_idx, sidx = _sample_idx; train(&tdata, &responses, vidx.data.ptr ? &vidx : 0, sidx.data.ptr ? &sidx : 0); } bool CvNormalBayesClassifier::train( const Mat& _train_data, const Mat& _responses, const Mat& _var_idx, const Mat& _sample_idx, bool update ) { CvMat tdata = _train_data, responses = _responses, vidx = _var_idx, sidx = _sample_idx; return train(&tdata, &responses, vidx.data.ptr ? &vidx : 0, sidx.data.ptr ? &sidx : 0, update); } float CvNormalBayesClassifier::predict( const Mat& _samples, Mat* _results ) const { CvMat samples = _samples, results, *presults = 0; if( _results ) { if( !(_results->data && _results->type() == CV_32F && (_results->cols == 1 || _results->rows == 1) && _results->cols + _results->rows - 1 == _samples.rows) ) _results->create(_samples.rows, 1, CV_32F); presults = &(results = *_results); } return predict(&samples, presults); } /* End of file. */ improved naive bayes robustness in the case of singular data /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" CvNormalBayesClassifier::CvNormalBayesClassifier() { var_count = var_all = 0; var_idx = 0; cls_labels = 0; count = 0; sum = 0; productsum = 0; avg = 0; inv_eigen_values = 0; cov_rotate_mats = 0; c = 0; default_model_name = "my_nb"; } void CvNormalBayesClassifier::clear() { if( cls_labels ) { for( int cls = 0; cls < cls_labels->cols; cls++ ) { cvReleaseMat( &count[cls] ); cvReleaseMat( &sum[cls] ); cvReleaseMat( &productsum[cls] ); cvReleaseMat( &avg[cls] ); cvReleaseMat( &inv_eigen_values[cls] ); cvReleaseMat( &cov_rotate_mats[cls] ); } } cvReleaseMat( &cls_labels ); cvReleaseMat( &var_idx ); cvReleaseMat( &c ); cvFree( &count ); } CvNormalBayesClassifier::~CvNormalBayesClassifier() { clear(); } CvNormalBayesClassifier::CvNormalBayesClassifier( const CvMat* _train_data, const CvMat* _responses, const CvMat* _var_idx, const CvMat* _sample_idx ) { var_count = var_all = 0; var_idx = 0; cls_labels = 0; count = 0; sum = 0; productsum = 0; avg = 0; inv_eigen_values = 0; cov_rotate_mats = 0; c = 0; default_model_name = "my_nb"; train( _train_data, _responses, _var_idx, _sample_idx ); } bool CvNormalBayesClassifier::train( const CvMat* _train_data, const CvMat* _responses, const CvMat* _var_idx, const CvMat* _sample_idx, bool update ) { const float min_variation = FLT_EPSILON; bool result = false; CvMat* responses = 0; const float** train_data = 0; CvMat* __cls_labels = 0; CvMat* __var_idx = 0; CvMat* cov = 0; CV_FUNCNAME( "CvNormalBayesClassifier::train" ); __BEGIN__; int cls, nsamples = 0, _var_count = 0, _var_all = 0, nclasses = 0; int s, c1, c2; const int* responses_data; CV_CALL( cvPrepareTrainData( 0, _train_data, CV_ROW_SAMPLE, _responses, CV_VAR_CATEGORICAL, _var_idx, _sample_idx, false, &train_data, &nsamples, &_var_count, &_var_all, &responses, &__cls_labels, &__var_idx )); if( !update ) { const size_t mat_size = sizeof(CvMat*); size_t data_size; clear(); var_idx = __var_idx; cls_labels = __cls_labels; __var_idx = __cls_labels = 0; var_count = _var_count; var_all = _var_all; nclasses = cls_labels->cols; data_size = nclasses*6*mat_size; CV_CALL( count = (CvMat**)cvAlloc( data_size )); memset( count, 0, data_size ); sum = count + nclasses; productsum = sum + nclasses; avg = productsum + nclasses; inv_eigen_values= avg + nclasses; cov_rotate_mats = inv_eigen_values + nclasses; CV_CALL( c = cvCreateMat( 1, nclasses, CV_64FC1 )); for( cls = 0; cls < nclasses; cls++ ) { CV_CALL(count[cls] = cvCreateMat( 1, var_count, CV_32SC1 )); CV_CALL(sum[cls] = cvCreateMat( 1, var_count, CV_64FC1 )); CV_CALL(productsum[cls] = cvCreateMat( var_count, var_count, CV_64FC1 )); CV_CALL(avg[cls] = cvCreateMat( 1, var_count, CV_64FC1 )); CV_CALL(inv_eigen_values[cls] = cvCreateMat( 1, var_count, CV_64FC1 )); CV_CALL(cov_rotate_mats[cls] = cvCreateMat( var_count, var_count, CV_64FC1 )); CV_CALL(cvZero( count[cls] )); CV_CALL(cvZero( sum[cls] )); CV_CALL(cvZero( productsum[cls] )); CV_CALL(cvZero( avg[cls] )); CV_CALL(cvZero( inv_eigen_values[cls] )); CV_CALL(cvZero( cov_rotate_mats[cls] )); } } else { // check that the new training data has the same dimensionality etc. if( _var_count != var_count || _var_all != var_all || !((!_var_idx && !var_idx) || (_var_idx && var_idx && cvNorm(_var_idx,var_idx,CV_C) < DBL_EPSILON)) ) CV_ERROR( CV_StsBadArg, "The new training data is inconsistent with the original training data" ); if( cls_labels->cols != __cls_labels->cols || cvNorm(cls_labels, __cls_labels, CV_C) > DBL_EPSILON ) CV_ERROR( CV_StsNotImplemented, "In the current implementation the new training data must have absolutely " "the same set of class labels as used in the original training data" ); nclasses = cls_labels->cols; } responses_data = responses->data.i; CV_CALL( cov = cvCreateMat( _var_count, _var_count, CV_64FC1 )); /* process train data (count, sum , productsum) */ for( s = 0; s < nsamples; s++ ) { cls = responses_data[s]; int* count_data = count[cls]->data.i; double* sum_data = sum[cls]->data.db; double* prod_data = productsum[cls]->data.db; const float* train_vec = train_data[s]; for( c1 = 0; c1 < _var_count; c1++, prod_data += _var_count ) { double val1 = train_vec[c1]; sum_data[c1] += val1; count_data[c1]++; for( c2 = c1; c2 < _var_count; c2++ ) prod_data[c2] += train_vec[c2]*val1; } } /* calculate avg, covariance matrix, c */ for( cls = 0; cls < nclasses; cls++ ) { double det = 1; int i, j; CvMat* w = inv_eigen_values[cls]; int* count_data = count[cls]->data.i; double* avg_data = avg[cls]->data.db; double* sum1 = sum[cls]->data.db; cvCompleteSymm( productsum[cls], 0 ); for( j = 0; j < _var_count; j++ ) { int n = count_data[j]; avg_data[j] = n ? sum1[j] / n : 0.; } count_data = count[cls]->data.i; avg_data = avg[cls]->data.db; sum1 = sum[cls]->data.db; for( i = 0; i < _var_count; i++ ) { double* avg2_data = avg[cls]->data.db; double* sum2 = sum[cls]->data.db; double* prod_data = productsum[cls]->data.db + i*_var_count; double* cov_data = cov->data.db + i*_var_count; double s1val = sum1[i]; double avg1 = avg_data[i]; int count = count_data[i]; for( j = 0; j <= i; j++ ) { double avg2 = avg2_data[j]; double cov_val = prod_data[j] - avg1 * sum2[j] - avg2 * s1val + avg1 * avg2 * count; cov_val = (count > 1) ? cov_val / (count - 1) : cov_val; cov_data[j] = cov_val; } } CV_CALL( cvCompleteSymm( cov, 1 )); CV_CALL( cvSVD( cov, w, cov_rotate_mats[cls], 0, CV_SVD_U_T )); CV_CALL( cvMaxS( w, min_variation, w )); for( j = 0; j < _var_count; j++ ) det *= w->data.db[j]; CV_CALL( cvDiv( NULL, w, w )); c->data.db[cls] = det > 0 ? log(det) : -700; } result = true; __END__; if( !result || cvGetErrStatus() < 0 ) clear(); cvReleaseMat( &cov ); cvReleaseMat( &__cls_labels ); cvReleaseMat( &__var_idx ); cvFree( &train_data ); return result; } float CvNormalBayesClassifier::predict( const CvMat* samples, CvMat* results ) const { float value = 0; void* buffer = 0; int allocated_buffer = 0; CV_FUNCNAME( "CvNormalBayesClassifier::predict" ); __BEGIN__; int i, j, k, cls = -1, _var_count, nclasses; double opt = FLT_MAX; CvMat diff; int rtype = 0, rstep = 0, size; const int* vidx = 0; nclasses = cls_labels->cols; _var_count = avg[0]->cols; if( !CV_IS_MAT(samples) || CV_MAT_TYPE(samples->type) != CV_32FC1 || samples->cols != var_all ) CV_ERROR( CV_StsBadArg, "The input samples must be 32f matrix with the number of columns = var_all" ); if( samples->rows > 1 && !results ) CV_ERROR( CV_StsNullPtr, "When the number of input samples is >1, the output vector of results must be passed" ); if( results ) { if( !CV_IS_MAT(results) || (CV_MAT_TYPE(results->type) != CV_32FC1 && CV_MAT_TYPE(results->type) != CV_32SC1) || (results->cols != 1 && results->rows != 1) || results->cols + results->rows - 1 != samples->rows ) CV_ERROR( CV_StsBadArg, "The output array must be integer or floating-point vector " "with the number of elements = number of rows in the input matrix" ); rtype = CV_MAT_TYPE(results->type); rstep = CV_IS_MAT_CONT(results->type) ? 1 : results->step/CV_ELEM_SIZE(rtype); } if( var_idx ) vidx = var_idx->data.i; // allocate memory and initializing headers for calculating size = sizeof(double) * (nclasses + var_count); if( size <= CV_MAX_LOCAL_SIZE ) buffer = cvStackAlloc( size ); else { CV_CALL( buffer = cvAlloc( size )); allocated_buffer = 1; } diff = cvMat( 1, var_count, CV_64FC1, buffer ); for( k = 0; k < samples->rows; k++ ) { int ival; for( i = 0; i < nclasses; i++ ) { double cur = c->data.db[i]; CvMat* u = cov_rotate_mats[i]; CvMat* w = inv_eigen_values[i]; const double* avg_data = avg[i]->data.db; const float* x = (const float*)(samples->data.ptr + samples->step*k); // cov = u w u' --> cov^(-1) = u w^(-1) u' for( j = 0; j < _var_count; j++ ) diff.data.db[j] = avg_data[j] - x[vidx ? vidx[j] : j]; CV_CALL(cvGEMM( &diff, u, 1, 0, 0, &diff, CV_GEMM_B_T )); for( j = 0; j < _var_count; j++ ) { double d = diff.data.db[j]; cur += d*d*w->data.db[j]; } if( cur < opt ) { cls = i; opt = cur; } /* probability = exp( -0.5 * cur ) */ } ival = cls_labels->data.i[cls]; if( results ) { if( rtype == CV_32SC1 ) results->data.i[k*rstep] = ival; else results->data.fl[k*rstep] = (float)ival; } if( k == 0 ) value = (float)ival; /*if( _probs ) { CV_CALL( cvConvertScale( &expo, &expo, -0.5 )); CV_CALL( cvExp( &expo, &expo )); if( _probs->cols == 1 ) CV_CALL( cvReshape( &expo, &expo, 1, nclasses )); CV_CALL( cvConvertScale( &expo, _probs, 1./cvSum( &expo ).val[0] )); }*/ } __END__; if( allocated_buffer ) cvFree( &buffer ); return value; } void CvNormalBayesClassifier::write( CvFileStorage* fs, const char* name ) const { CV_FUNCNAME( "CvNormalBayesClassifier::write" ); __BEGIN__; int nclasses, i; nclasses = cls_labels->cols; cvStartWriteStruct( fs, name, CV_NODE_MAP, CV_TYPE_NAME_ML_NBAYES ); CV_CALL( cvWriteInt( fs, "var_count", var_count )); CV_CALL( cvWriteInt( fs, "var_all", var_all )); if( var_idx ) CV_CALL( cvWrite( fs, "var_idx", var_idx )); CV_CALL( cvWrite( fs, "cls_labels", cls_labels )); CV_CALL( cvStartWriteStruct( fs, "count", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, count[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "sum", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, sum[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "productsum", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, productsum[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "avg", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, avg[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "inv_eigen_values", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, inv_eigen_values[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "cov_rotate_mats", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, cov_rotate_mats[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvWrite( fs, "c", c )); cvEndWriteStruct( fs ); __END__; } void CvNormalBayesClassifier::read( CvFileStorage* fs, CvFileNode* root_node ) { bool ok = false; CV_FUNCNAME( "CvNormalBayesClassifier::read" ); __BEGIN__; int nclasses, i; size_t data_size; CvFileNode* node; CvSeq* seq; CvSeqReader reader; clear(); CV_CALL( var_count = cvReadIntByName( fs, root_node, "var_count", -1 )); CV_CALL( var_all = cvReadIntByName( fs, root_node, "var_all", -1 )); CV_CALL( var_idx = (CvMat*)cvReadByName( fs, root_node, "var_idx" )); CV_CALL( cls_labels = (CvMat*)cvReadByName( fs, root_node, "cls_labels" )); if( !cls_labels ) CV_ERROR( CV_StsParseError, "No \"cls_labels\" in NBayes classifier" ); if( cls_labels->cols < 1 ) CV_ERROR( CV_StsBadArg, "Number of classes is less 1" ); if( var_count <= 0 ) CV_ERROR( CV_StsParseError, "The field \"var_count\" of NBayes classifier is missing" ); nclasses = cls_labels->cols; data_size = nclasses*6*sizeof(CvMat*); CV_CALL( count = (CvMat**)cvAlloc( data_size )); memset( count, 0, data_size ); sum = count + nclasses; productsum = sum + nclasses; avg = productsum + nclasses; inv_eigen_values = avg + nclasses; cov_rotate_mats = inv_eigen_values + nclasses; CV_CALL( node = cvGetFileNodeByName( fs, root_node, "count" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( count[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "sum" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( sum[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "productsum" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( productsum[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "avg" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( avg[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "inv_eigen_values" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( inv_eigen_values[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "cov_rotate_mats" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( cov_rotate_mats[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( c = (CvMat*)cvReadByName( fs, root_node, "c" )); ok = true; __END__; if( !ok ) clear(); } using namespace cv; CvNormalBayesClassifier::CvNormalBayesClassifier( const Mat& _train_data, const Mat& _responses, const Mat& _var_idx, const Mat& _sample_idx ) { var_count = var_all = 0; var_idx = 0; cls_labels = 0; count = 0; sum = 0; productsum = 0; avg = 0; inv_eigen_values = 0; cov_rotate_mats = 0; c = 0; default_model_name = "my_nb"; CvMat tdata = _train_data, responses = _responses, vidx = _var_idx, sidx = _sample_idx; train(&tdata, &responses, vidx.data.ptr ? &vidx : 0, sidx.data.ptr ? &sidx : 0); } bool CvNormalBayesClassifier::train( const Mat& _train_data, const Mat& _responses, const Mat& _var_idx, const Mat& _sample_idx, bool update ) { CvMat tdata = _train_data, responses = _responses, vidx = _var_idx, sidx = _sample_idx; return train(&tdata, &responses, vidx.data.ptr ? &vidx : 0, sidx.data.ptr ? &sidx : 0, update); } float CvNormalBayesClassifier::predict( const Mat& _samples, Mat* _results ) const { CvMat samples = _samples, results, *presults = 0; if( _results ) { if( !(_results->data && _results->type() == CV_32F && (_results->cols == 1 || _results->rows == 1) && _results->cols + _results->rows - 1 == _samples.rows) ) _results->create(_samples.rows, 1, CV_32F); presults = &(results = *_results); } return predict(&samples, presults); } /* End of file. */
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" CvNormalBayesClassifier::CvNormalBayesClassifier() { var_count = var_all = 0; var_idx = 0; cls_labels = 0; count = 0; sum = 0; productsum = 0; avg = 0; inv_eigen_values = 0; cov_rotate_mats = 0; c = 0; default_model_name = "my_nb"; } void CvNormalBayesClassifier::clear() { if( cls_labels ) { for( int cls = 0; cls < cls_labels->cols; cls++ ) { cvReleaseMat( &count[cls] ); cvReleaseMat( &sum[cls] ); cvReleaseMat( &productsum[cls] ); cvReleaseMat( &avg[cls] ); cvReleaseMat( &inv_eigen_values[cls] ); cvReleaseMat( &cov_rotate_mats[cls] ); } } cvReleaseMat( &cls_labels ); cvReleaseMat( &var_idx ); cvReleaseMat( &c ); cvFree( &count ); } CvNormalBayesClassifier::~CvNormalBayesClassifier() { clear(); } CvNormalBayesClassifier::CvNormalBayesClassifier( const CvMat* _train_data, const CvMat* _responses, const CvMat* _var_idx, const CvMat* _sample_idx ) { var_count = var_all = 0; var_idx = 0; cls_labels = 0; count = 0; sum = 0; productsum = 0; avg = 0; inv_eigen_values = 0; cov_rotate_mats = 0; c = 0; default_model_name = "my_nb"; train( _train_data, _responses, _var_idx, _sample_idx ); } bool CvNormalBayesClassifier::train( const CvMat* _train_data, const CvMat* _responses, const CvMat* _var_idx, const CvMat* _sample_idx, bool update ) { const float min_variation = FLT_EPSILON; bool result = false; CvMat* responses = 0; const float** train_data = 0; CvMat* __cls_labels = 0; CvMat* __var_idx = 0; CvMat* cov = 0; CV_FUNCNAME( "CvNormalBayesClassifier::train" ); __BEGIN__; int cls, nsamples = 0, _var_count = 0, _var_all = 0, nclasses = 0; int s, c1, c2; const int* responses_data; CV_CALL( cvPrepareTrainData( 0, _train_data, CV_ROW_SAMPLE, _responses, CV_VAR_CATEGORICAL, _var_idx, _sample_idx, false, &train_data, &nsamples, &_var_count, &_var_all, &responses, &__cls_labels, &__var_idx )); if( !update ) { const size_t mat_size = sizeof(CvMat*); size_t data_size; clear(); var_idx = __var_idx; cls_labels = __cls_labels; __var_idx = __cls_labels = 0; var_count = _var_count; var_all = _var_all; nclasses = cls_labels->cols; data_size = nclasses*6*mat_size; CV_CALL( count = (CvMat**)cvAlloc( data_size )); memset( count, 0, data_size ); sum = count + nclasses; productsum = sum + nclasses; avg = productsum + nclasses; inv_eigen_values= avg + nclasses; cov_rotate_mats = inv_eigen_values + nclasses; CV_CALL( c = cvCreateMat( 1, nclasses, CV_64FC1 )); for( cls = 0; cls < nclasses; cls++ ) { CV_CALL(count[cls] = cvCreateMat( 1, var_count, CV_32SC1 )); CV_CALL(sum[cls] = cvCreateMat( 1, var_count, CV_64FC1 )); CV_CALL(productsum[cls] = cvCreateMat( var_count, var_count, CV_64FC1 )); CV_CALL(avg[cls] = cvCreateMat( 1, var_count, CV_64FC1 )); CV_CALL(inv_eigen_values[cls] = cvCreateMat( 1, var_count, CV_64FC1 )); CV_CALL(cov_rotate_mats[cls] = cvCreateMat( var_count, var_count, CV_64FC1 )); CV_CALL(cvZero( count[cls] )); CV_CALL(cvZero( sum[cls] )); CV_CALL(cvZero( productsum[cls] )); CV_CALL(cvZero( avg[cls] )); CV_CALL(cvZero( inv_eigen_values[cls] )); CV_CALL(cvZero( cov_rotate_mats[cls] )); } } else { // check that the new training data has the same dimensionality etc. if( _var_count != var_count || _var_all != var_all || !((!_var_idx && !var_idx) || (_var_idx && var_idx && cvNorm(_var_idx,var_idx,CV_C) < DBL_EPSILON)) ) CV_ERROR( CV_StsBadArg, "The new training data is inconsistent with the original training data" ); if( cls_labels->cols != __cls_labels->cols || cvNorm(cls_labels, __cls_labels, CV_C) > DBL_EPSILON ) CV_ERROR( CV_StsNotImplemented, "In the current implementation the new training data must have absolutely " "the same set of class labels as used in the original training data" ); nclasses = cls_labels->cols; } responses_data = responses->data.i; CV_CALL( cov = cvCreateMat( _var_count, _var_count, CV_64FC1 )); /* process train data (count, sum , productsum) */ for( s = 0; s < nsamples; s++ ) { cls = responses_data[s]; int* count_data = count[cls]->data.i; double* sum_data = sum[cls]->data.db; double* prod_data = productsum[cls]->data.db; const float* train_vec = train_data[s]; for( c1 = 0; c1 < _var_count; c1++, prod_data += _var_count ) { double val1 = train_vec[c1]; sum_data[c1] += val1; count_data[c1]++; for( c2 = c1; c2 < _var_count; c2++ ) prod_data[c2] += train_vec[c2]*val1; } } cvReleaseMat( &responses ); responses = 0; /* calculate avg, covariance matrix, c */ for( cls = 0; cls < nclasses; cls++ ) { double det = 1; int i, j; CvMat* w = inv_eigen_values[cls]; int* count_data = count[cls]->data.i; double* avg_data = avg[cls]->data.db; double* sum1 = sum[cls]->data.db; cvCompleteSymm( productsum[cls], 0 ); for( j = 0; j < _var_count; j++ ) { int n = count_data[j]; avg_data[j] = n ? sum1[j] / n : 0.; } count_data = count[cls]->data.i; avg_data = avg[cls]->data.db; sum1 = sum[cls]->data.db; for( i = 0; i < _var_count; i++ ) { double* avg2_data = avg[cls]->data.db; double* sum2 = sum[cls]->data.db; double* prod_data = productsum[cls]->data.db + i*_var_count; double* cov_data = cov->data.db + i*_var_count; double s1val = sum1[i]; double avg1 = avg_data[i]; int _count = count_data[i]; for( j = 0; j <= i; j++ ) { double avg2 = avg2_data[j]; double cov_val = prod_data[j] - avg1 * sum2[j] - avg2 * s1val + avg1 * avg2 * _count; cov_val = (_count > 1) ? cov_val / (_count - 1) : cov_val; cov_data[j] = cov_val; } } CV_CALL( cvCompleteSymm( cov, 1 )); CV_CALL( cvSVD( cov, w, cov_rotate_mats[cls], 0, CV_SVD_U_T )); CV_CALL( cvMaxS( w, min_variation, w )); for( j = 0; j < _var_count; j++ ) det *= w->data.db[j]; CV_CALL( cvDiv( NULL, w, w )); c->data.db[cls] = det > 0 ? log(det) : -700; } result = true; __END__; if( !result || cvGetErrStatus() < 0 ) clear(); cvReleaseMat( &cov ); cvReleaseMat( &__cls_labels ); cvReleaseMat( &__var_idx ); cvFree( &train_data ); return result; } struct predict_body : cv::ParallelLoopBody { predict_body(CvMat* _c, CvMat** _cov_rotate_mats, CvMat** _inv_eigen_values, CvMat** _avg, const CvMat* _samples, const int* _vidx, CvMat* _cls_labels, CvMat* _results, float* _value, int _var_count1, CvMat* _results_prob ) { c = _c; cov_rotate_mats = _cov_rotate_mats; inv_eigen_values = _inv_eigen_values; avg = _avg; samples = _samples; vidx = _vidx; cls_labels = _cls_labels; results = _results; value = _value; var_count1 = _var_count1; results_prob = _results_prob; } CvMat* c; CvMat** cov_rotate_mats; CvMat** inv_eigen_values; CvMat** avg; const CvMat* samples; const int* vidx; CvMat* cls_labels; CvMat* results_prob; CvMat* results; float* value; int var_count1; void operator()( const cv::Range& range ) const { int cls = -1; int rtype = 0, rstep = 0, rptype = 0, rpstep = 0; int nclasses = cls_labels->cols; int _var_count = avg[0]->cols; double probability = 0; if (results) { rtype = CV_MAT_TYPE(results->type); rstep = CV_IS_MAT_CONT(results->type) ? 1 : results->step/CV_ELEM_SIZE(rtype); } if (results_prob) { rptype = CV_MAT_TYPE(results_prob->type); rpstep = CV_IS_MAT_CONT(results_prob->type) ? 1 : results_prob->step/CV_ELEM_SIZE(rptype); } // allocate memory and initializing headers for calculating cv::AutoBuffer<double> buffer(nclasses + var_count1); CvMat diff = cvMat( 1, var_count1, CV_64FC1, &buffer[0] ); for(int k = range.start; k < range.end; k += 1 ) { int ival; double opt = FLT_MAX; for(int i = 0; i < nclasses; i++ ) { double cur = c->data.db[i]; CvMat* u = cov_rotate_mats[i]; CvMat* w = inv_eigen_values[i]; const double* avg_data = avg[i]->data.db; const float* x = (const float*)(samples->data.ptr + samples->step*k); // cov = u w u' --> cov^(-1) = u w^(-1) u' for(int j = 0; j < _var_count; j++ ) diff.data.db[j] = avg_data[j] - x[vidx ? vidx[j] : j]; cvGEMM( &diff, u, 1, 0, 0, &diff, CV_GEMM_B_T ); for(int j = 0; j < _var_count; j++ ) { double d = diff.data.db[j]; cur += d*d*w->data.db[j]; } if( cur < opt ) { cls = i; opt = cur; } /* probability = exp( -0.5 * cur ) */ probability = exp( -0.5 * cur ); } ival = cls_labels->data.i[cls]; if( results ) { if( rtype == CV_32SC1 ) results->data.i[k*rstep] = ival; else results->data.fl[k*rstep] = (float)ival; } if ( results_prob ) { if ( rptype == CV_32FC1 ) results_prob->data.fl[k*rpstep] = (float)probability; else results_prob->data.db[k*rpstep] = probability; } if( k == 0 ) *value = (float)ival; } } }; float CvNormalBayesClassifier::predict( const CvMat* samples, CvMat* results, CvMat* results_prob ) const { float value = 0; if( !CV_IS_MAT(samples) || CV_MAT_TYPE(samples->type) != CV_32FC1 || samples->cols != var_all ) CV_Error( CV_StsBadArg, "The input samples must be 32f matrix with the number of columns = var_all" ); if( samples->rows > 1 && !results ) CV_Error( CV_StsNullPtr, "When the number of input samples is >1, the output vector of results must be passed" ); if( results ) { if( !CV_IS_MAT(results) || (CV_MAT_TYPE(results->type) != CV_32FC1 && CV_MAT_TYPE(results->type) != CV_32SC1) || (results->cols != 1 && results->rows != 1) || results->cols + results->rows - 1 != samples->rows ) CV_Error( CV_StsBadArg, "The output array must be integer or floating-point vector " "with the number of elements = number of rows in the input matrix" ); } if( results_prob ) { if( !CV_IS_MAT(results_prob) || (CV_MAT_TYPE(results_prob->type) != CV_32FC1 && CV_MAT_TYPE(results_prob->type) != CV_64FC1) || (results_prob->cols != 1 && results_prob->rows != 1) || results_prob->cols + results_prob->rows - 1 != samples->rows ) CV_Error( CV_StsBadArg, "The output array must be double or float vector " "with the number of elements = number of rows in the input matrix" ); } const int* vidx = var_idx ? var_idx->data.i : 0; cv::parallel_for_(cv::Range(0, samples->rows), predict_body(c, cov_rotate_mats, inv_eigen_values, avg, samples, vidx, cls_labels, results, &value, var_count, results_prob)); return value; } void CvNormalBayesClassifier::write( CvFileStorage* fs, const char* name ) const { CV_FUNCNAME( "CvNormalBayesClassifier::write" ); __BEGIN__; int nclasses, i; nclasses = cls_labels->cols; cvStartWriteStruct( fs, name, CV_NODE_MAP, CV_TYPE_NAME_ML_NBAYES ); CV_CALL( cvWriteInt( fs, "var_count", var_count )); CV_CALL( cvWriteInt( fs, "var_all", var_all )); if( var_idx ) CV_CALL( cvWrite( fs, "var_idx", var_idx )); CV_CALL( cvWrite( fs, "cls_labels", cls_labels )); CV_CALL( cvStartWriteStruct( fs, "count", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, count[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "sum", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, sum[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "productsum", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, productsum[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "avg", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, avg[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "inv_eigen_values", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, inv_eigen_values[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "cov_rotate_mats", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, cov_rotate_mats[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvWrite( fs, "c", c )); cvEndWriteStruct( fs ); __END__; } void CvNormalBayesClassifier::read( CvFileStorage* fs, CvFileNode* root_node ) { bool ok = false; CV_FUNCNAME( "CvNormalBayesClassifier::read" ); __BEGIN__; int nclasses, i; size_t data_size; CvFileNode* node; CvSeq* seq; CvSeqReader reader; clear(); CV_CALL( var_count = cvReadIntByName( fs, root_node, "var_count", -1 )); CV_CALL( var_all = cvReadIntByName( fs, root_node, "var_all", -1 )); CV_CALL( var_idx = (CvMat*)cvReadByName( fs, root_node, "var_idx" )); CV_CALL( cls_labels = (CvMat*)cvReadByName( fs, root_node, "cls_labels" )); if( !cls_labels ) CV_ERROR( CV_StsParseError, "No \"cls_labels\" in NBayes classifier" ); if( cls_labels->cols < 1 ) CV_ERROR( CV_StsBadArg, "Number of classes is less 1" ); if( var_count <= 0 ) CV_ERROR( CV_StsParseError, "The field \"var_count\" of NBayes classifier is missing" ); nclasses = cls_labels->cols; data_size = nclasses*6*sizeof(CvMat*); CV_CALL( count = (CvMat**)cvAlloc( data_size )); memset( count, 0, data_size ); sum = count + nclasses; productsum = sum + nclasses; avg = productsum + nclasses; inv_eigen_values = avg + nclasses; cov_rotate_mats = inv_eigen_values + nclasses; CV_CALL( node = cvGetFileNodeByName( fs, root_node, "count" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( count[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "sum" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( sum[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "productsum" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( productsum[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "avg" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( avg[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "inv_eigen_values" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( inv_eigen_values[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "cov_rotate_mats" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( cov_rotate_mats[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( c = (CvMat*)cvReadByName( fs, root_node, "c" )); ok = true; __END__; if( !ok ) clear(); } using namespace cv; CvNormalBayesClassifier::CvNormalBayesClassifier( const Mat& _train_data, const Mat& _responses, const Mat& _var_idx, const Mat& _sample_idx ) { var_count = var_all = 0; var_idx = 0; cls_labels = 0; count = 0; sum = 0; productsum = 0; avg = 0; inv_eigen_values = 0; cov_rotate_mats = 0; c = 0; default_model_name = "my_nb"; CvMat tdata = _train_data, responses = _responses, vidx = _var_idx, sidx = _sample_idx; train(&tdata, &responses, vidx.data.ptr ? &vidx : 0, sidx.data.ptr ? &sidx : 0); } bool CvNormalBayesClassifier::train( const Mat& _train_data, const Mat& _responses, const Mat& _var_idx, const Mat& _sample_idx, bool update ) { CvMat tdata = _train_data, responses = _responses, vidx = _var_idx, sidx = _sample_idx; return train(&tdata, &responses, vidx.data.ptr ? &vidx : 0, sidx.data.ptr ? &sidx : 0, update); } float CvNormalBayesClassifier::predict( const Mat& _samples, Mat* _results, Mat* _results_prob ) const { CvMat samples = _samples, results, *presults = 0, results_prob, *presults_prob = 0; if( _results ) { if( !(_results->data && _results->type() == CV_32F && (_results->cols == 1 || _results->rows == 1) && _results->cols + _results->rows - 1 == _samples.rows) ) _results->create(_samples.rows, 1, CV_32F); presults = &(results = *_results); } if( _results_prob ) { if( !(_results_prob->data && _results_prob->type() == CV_64F && (_results_prob->cols == 1 || _results_prob->rows == 1) && _results_prob->cols + _results_prob->rows - 1 == _samples.rows) ) _results_prob->create(_samples.rows, 1, CV_64F); presults_prob = &(results_prob = *_results_prob); } return predict(&samples, presults, presults_prob); } /* End of file. */ Fixed alignment /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" CvNormalBayesClassifier::CvNormalBayesClassifier() { var_count = var_all = 0; var_idx = 0; cls_labels = 0; count = 0; sum = 0; productsum = 0; avg = 0; inv_eigen_values = 0; cov_rotate_mats = 0; c = 0; default_model_name = "my_nb"; } void CvNormalBayesClassifier::clear() { if( cls_labels ) { for( int cls = 0; cls < cls_labels->cols; cls++ ) { cvReleaseMat( &count[cls] ); cvReleaseMat( &sum[cls] ); cvReleaseMat( &productsum[cls] ); cvReleaseMat( &avg[cls] ); cvReleaseMat( &inv_eigen_values[cls] ); cvReleaseMat( &cov_rotate_mats[cls] ); } } cvReleaseMat( &cls_labels ); cvReleaseMat( &var_idx ); cvReleaseMat( &c ); cvFree( &count ); } CvNormalBayesClassifier::~CvNormalBayesClassifier() { clear(); } CvNormalBayesClassifier::CvNormalBayesClassifier( const CvMat* _train_data, const CvMat* _responses, const CvMat* _var_idx, const CvMat* _sample_idx ) { var_count = var_all = 0; var_idx = 0; cls_labels = 0; count = 0; sum = 0; productsum = 0; avg = 0; inv_eigen_values = 0; cov_rotate_mats = 0; c = 0; default_model_name = "my_nb"; train( _train_data, _responses, _var_idx, _sample_idx ); } bool CvNormalBayesClassifier::train( const CvMat* _train_data, const CvMat* _responses, const CvMat* _var_idx, const CvMat* _sample_idx, bool update ) { const float min_variation = FLT_EPSILON; bool result = false; CvMat* responses = 0; const float** train_data = 0; CvMat* __cls_labels = 0; CvMat* __var_idx = 0; CvMat* cov = 0; CV_FUNCNAME( "CvNormalBayesClassifier::train" ); __BEGIN__; int cls, nsamples = 0, _var_count = 0, _var_all = 0, nclasses = 0; int s, c1, c2; const int* responses_data; CV_CALL( cvPrepareTrainData( 0, _train_data, CV_ROW_SAMPLE, _responses, CV_VAR_CATEGORICAL, _var_idx, _sample_idx, false, &train_data, &nsamples, &_var_count, &_var_all, &responses, &__cls_labels, &__var_idx )); if( !update ) { const size_t mat_size = sizeof(CvMat*); size_t data_size; clear(); var_idx = __var_idx; cls_labels = __cls_labels; __var_idx = __cls_labels = 0; var_count = _var_count; var_all = _var_all; nclasses = cls_labels->cols; data_size = nclasses*6*mat_size; CV_CALL( count = (CvMat**)cvAlloc( data_size )); memset( count, 0, data_size ); sum = count + nclasses; productsum = sum + nclasses; avg = productsum + nclasses; inv_eigen_values= avg + nclasses; cov_rotate_mats = inv_eigen_values + nclasses; CV_CALL( c = cvCreateMat( 1, nclasses, CV_64FC1 )); for( cls = 0; cls < nclasses; cls++ ) { CV_CALL(count[cls] = cvCreateMat( 1, var_count, CV_32SC1 )); CV_CALL(sum[cls] = cvCreateMat( 1, var_count, CV_64FC1 )); CV_CALL(productsum[cls] = cvCreateMat( var_count, var_count, CV_64FC1 )); CV_CALL(avg[cls] = cvCreateMat( 1, var_count, CV_64FC1 )); CV_CALL(inv_eigen_values[cls] = cvCreateMat( 1, var_count, CV_64FC1 )); CV_CALL(cov_rotate_mats[cls] = cvCreateMat( var_count, var_count, CV_64FC1 )); CV_CALL(cvZero( count[cls] )); CV_CALL(cvZero( sum[cls] )); CV_CALL(cvZero( productsum[cls] )); CV_CALL(cvZero( avg[cls] )); CV_CALL(cvZero( inv_eigen_values[cls] )); CV_CALL(cvZero( cov_rotate_mats[cls] )); } } else { // check that the new training data has the same dimensionality etc. if( _var_count != var_count || _var_all != var_all || !((!_var_idx && !var_idx) || (_var_idx && var_idx && cvNorm(_var_idx,var_idx,CV_C) < DBL_EPSILON)) ) CV_ERROR( CV_StsBadArg, "The new training data is inconsistent with the original training data" ); if( cls_labels->cols != __cls_labels->cols || cvNorm(cls_labels, __cls_labels, CV_C) > DBL_EPSILON ) CV_ERROR( CV_StsNotImplemented, "In the current implementation the new training data must have absolutely " "the same set of class labels as used in the original training data" ); nclasses = cls_labels->cols; } responses_data = responses->data.i; CV_CALL( cov = cvCreateMat( _var_count, _var_count, CV_64FC1 )); /* process train data (count, sum , productsum) */ for( s = 0; s < nsamples; s++ ) { cls = responses_data[s]; int* count_data = count[cls]->data.i; double* sum_data = sum[cls]->data.db; double* prod_data = productsum[cls]->data.db; const float* train_vec = train_data[s]; for( c1 = 0; c1 < _var_count; c1++, prod_data += _var_count ) { double val1 = train_vec[c1]; sum_data[c1] += val1; count_data[c1]++; for( c2 = c1; c2 < _var_count; c2++ ) prod_data[c2] += train_vec[c2]*val1; } } cvReleaseMat( &responses ); responses = 0; /* calculate avg, covariance matrix, c */ for( cls = 0; cls < nclasses; cls++ ) { double det = 1; int i, j; CvMat* w = inv_eigen_values[cls]; int* count_data = count[cls]->data.i; double* avg_data = avg[cls]->data.db; double* sum1 = sum[cls]->data.db; cvCompleteSymm( productsum[cls], 0 ); for( j = 0; j < _var_count; j++ ) { int n = count_data[j]; avg_data[j] = n ? sum1[j] / n : 0.; } count_data = count[cls]->data.i; avg_data = avg[cls]->data.db; sum1 = sum[cls]->data.db; for( i = 0; i < _var_count; i++ ) { double* avg2_data = avg[cls]->data.db; double* sum2 = sum[cls]->data.db; double* prod_data = productsum[cls]->data.db + i*_var_count; double* cov_data = cov->data.db + i*_var_count; double s1val = sum1[i]; double avg1 = avg_data[i]; int _count = count_data[i]; for( j = 0; j <= i; j++ ) { double avg2 = avg2_data[j]; double cov_val = prod_data[j] - avg1 * sum2[j] - avg2 * s1val + avg1 * avg2 * _count; cov_val = (_count > 1) ? cov_val / (_count - 1) : cov_val; cov_data[j] = cov_val; } } CV_CALL( cvCompleteSymm( cov, 1 )); CV_CALL( cvSVD( cov, w, cov_rotate_mats[cls], 0, CV_SVD_U_T )); CV_CALL( cvMaxS( w, min_variation, w )); for( j = 0; j < _var_count; j++ ) det *= w->data.db[j]; CV_CALL( cvDiv( NULL, w, w )); c->data.db[cls] = det > 0 ? log(det) : -700; } result = true; __END__; if( !result || cvGetErrStatus() < 0 ) clear(); cvReleaseMat( &cov ); cvReleaseMat( &__cls_labels ); cvReleaseMat( &__var_idx ); cvFree( &train_data ); return result; } struct predict_body : cv::ParallelLoopBody { predict_body(CvMat* _c, CvMat** _cov_rotate_mats, CvMat** _inv_eigen_values, CvMat** _avg, const CvMat* _samples, const int* _vidx, CvMat* _cls_labels, CvMat* _results, float* _value, int _var_count1, CvMat* _results_prob ) { c = _c; cov_rotate_mats = _cov_rotate_mats; inv_eigen_values = _inv_eigen_values; avg = _avg; samples = _samples; vidx = _vidx; cls_labels = _cls_labels; results = _results; value = _value; var_count1 = _var_count1; results_prob = _results_prob; } CvMat* c; CvMat** cov_rotate_mats; CvMat** inv_eigen_values; CvMat** avg; const CvMat* samples; const int* vidx; CvMat* cls_labels; CvMat* results_prob; CvMat* results; float* value; int var_count1; void operator()( const cv::Range& range ) const { int cls = -1; int rtype = 0, rstep = 0, rptype = 0, rpstep = 0; int nclasses = cls_labels->cols; int _var_count = avg[0]->cols; double probability = 0; if (results) { rtype = CV_MAT_TYPE(results->type); rstep = CV_IS_MAT_CONT(results->type) ? 1 : results->step/CV_ELEM_SIZE(rtype); } if (results_prob) { rptype = CV_MAT_TYPE(results_prob->type); rpstep = CV_IS_MAT_CONT(results_prob->type) ? 1 : results_prob->step/CV_ELEM_SIZE(rptype); } // allocate memory and initializing headers for calculating cv::AutoBuffer<double> buffer(nclasses + var_count1); CvMat diff = cvMat( 1, var_count1, CV_64FC1, &buffer[0] ); for(int k = range.start; k < range.end; k += 1 ) { int ival; double opt = FLT_MAX; for(int i = 0; i < nclasses; i++ ) { double cur = c->data.db[i]; CvMat* u = cov_rotate_mats[i]; CvMat* w = inv_eigen_values[i]; const double* avg_data = avg[i]->data.db; const float* x = (const float*)(samples->data.ptr + samples->step*k); // cov = u w u' --> cov^(-1) = u w^(-1) u' for(int j = 0; j < _var_count; j++ ) diff.data.db[j] = avg_data[j] - x[vidx ? vidx[j] : j]; cvGEMM( &diff, u, 1, 0, 0, &diff, CV_GEMM_B_T ); for(int j = 0; j < _var_count; j++ ) { double d = diff.data.db[j]; cur += d*d*w->data.db[j]; } if( cur < opt ) { cls = i; opt = cur; } /* probability = exp( -0.5 * cur ) */ probability = exp( -0.5 * cur ); } ival = cls_labels->data.i[cls]; if( results ) { if( rtype == CV_32SC1 ) results->data.i[k*rstep] = ival; else results->data.fl[k*rstep] = (float)ival; } if ( results_prob ) { if ( rptype == CV_32FC1 ) results_prob->data.fl[k*rpstep] = (float)probability; else results_prob->data.db[k*rpstep] = probability; } if( k == 0 ) *value = (float)ival; } } }; float CvNormalBayesClassifier::predict( const CvMat* samples, CvMat* results, CvMat* results_prob ) const { float value = 0; if( !CV_IS_MAT(samples) || CV_MAT_TYPE(samples->type) != CV_32FC1 || samples->cols != var_all ) CV_Error( CV_StsBadArg, "The input samples must be 32f matrix with the number of columns = var_all" ); if( samples->rows > 1 && !results ) CV_Error( CV_StsNullPtr, "When the number of input samples is >1, the output vector of results must be passed" ); if( results ) { if( !CV_IS_MAT(results) || (CV_MAT_TYPE(results->type) != CV_32FC1 && CV_MAT_TYPE(results->type) != CV_32SC1) || (results->cols != 1 && results->rows != 1) || results->cols + results->rows - 1 != samples->rows ) CV_Error( CV_StsBadArg, "The output array must be integer or floating-point vector " "with the number of elements = number of rows in the input matrix" ); } if( results_prob ) { if( !CV_IS_MAT(results_prob) || (CV_MAT_TYPE(results_prob->type) != CV_32FC1 && CV_MAT_TYPE(results_prob->type) != CV_64FC1) || (results_prob->cols != 1 && results_prob->rows != 1) || results_prob->cols + results_prob->rows - 1 != samples->rows ) CV_Error( CV_StsBadArg, "The output array must be double or float vector " "with the number of elements = number of rows in the input matrix" ); } const int* vidx = var_idx ? var_idx->data.i : 0; cv::parallel_for_(cv::Range(0, samples->rows), predict_body(c, cov_rotate_mats, inv_eigen_values, avg, samples, vidx, cls_labels, results, &value, var_count, results_prob)); return value; } void CvNormalBayesClassifier::write( CvFileStorage* fs, const char* name ) const { CV_FUNCNAME( "CvNormalBayesClassifier::write" ); __BEGIN__; int nclasses, i; nclasses = cls_labels->cols; cvStartWriteStruct( fs, name, CV_NODE_MAP, CV_TYPE_NAME_ML_NBAYES ); CV_CALL( cvWriteInt( fs, "var_count", var_count )); CV_CALL( cvWriteInt( fs, "var_all", var_all )); if( var_idx ) CV_CALL( cvWrite( fs, "var_idx", var_idx )); CV_CALL( cvWrite( fs, "cls_labels", cls_labels )); CV_CALL( cvStartWriteStruct( fs, "count", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, count[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "sum", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, sum[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "productsum", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, productsum[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "avg", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, avg[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "inv_eigen_values", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, inv_eigen_values[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvStartWriteStruct( fs, "cov_rotate_mats", CV_NODE_SEQ )); for( i = 0; i < nclasses; i++ ) CV_CALL( cvWrite( fs, NULL, cov_rotate_mats[i] )); CV_CALL( cvEndWriteStruct( fs )); CV_CALL( cvWrite( fs, "c", c )); cvEndWriteStruct( fs ); __END__; } void CvNormalBayesClassifier::read( CvFileStorage* fs, CvFileNode* root_node ) { bool ok = false; CV_FUNCNAME( "CvNormalBayesClassifier::read" ); __BEGIN__; int nclasses, i; size_t data_size; CvFileNode* node; CvSeq* seq; CvSeqReader reader; clear(); CV_CALL( var_count = cvReadIntByName( fs, root_node, "var_count", -1 )); CV_CALL( var_all = cvReadIntByName( fs, root_node, "var_all", -1 )); CV_CALL( var_idx = (CvMat*)cvReadByName( fs, root_node, "var_idx" )); CV_CALL( cls_labels = (CvMat*)cvReadByName( fs, root_node, "cls_labels" )); if( !cls_labels ) CV_ERROR( CV_StsParseError, "No \"cls_labels\" in NBayes classifier" ); if( cls_labels->cols < 1 ) CV_ERROR( CV_StsBadArg, "Number of classes is less 1" ); if( var_count <= 0 ) CV_ERROR( CV_StsParseError, "The field \"var_count\" of NBayes classifier is missing" ); nclasses = cls_labels->cols; data_size = nclasses*6*sizeof(CvMat*); CV_CALL( count = (CvMat**)cvAlloc( data_size )); memset( count, 0, data_size ); sum = count + nclasses; productsum = sum + nclasses; avg = productsum + nclasses; inv_eigen_values = avg + nclasses; cov_rotate_mats = inv_eigen_values + nclasses; CV_CALL( node = cvGetFileNodeByName( fs, root_node, "count" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( count[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "sum" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( sum[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "productsum" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( productsum[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "avg" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( avg[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "inv_eigen_values" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( inv_eigen_values[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( node = cvGetFileNodeByName( fs, root_node, "cov_rotate_mats" )); seq = node->data.seq; if( !CV_NODE_IS_SEQ(node->tag) || seq->total != nclasses) CV_ERROR( CV_StsBadArg, "" ); CV_CALL( cvStartReadSeq( seq, &reader, 0 )); for( i = 0; i < nclasses; i++ ) { CV_CALL( cov_rotate_mats[i] = (CvMat*)cvRead( fs, (CvFileNode*)reader.ptr )); CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); } CV_CALL( c = (CvMat*)cvReadByName( fs, root_node, "c" )); ok = true; __END__; if( !ok ) clear(); } using namespace cv; CvNormalBayesClassifier::CvNormalBayesClassifier( const Mat& _train_data, const Mat& _responses, const Mat& _var_idx, const Mat& _sample_idx ) { var_count = var_all = 0; var_idx = 0; cls_labels = 0; count = 0; sum = 0; productsum = 0; avg = 0; inv_eigen_values = 0; cov_rotate_mats = 0; c = 0; default_model_name = "my_nb"; CvMat tdata = _train_data, responses = _responses, vidx = _var_idx, sidx = _sample_idx; train(&tdata, &responses, vidx.data.ptr ? &vidx : 0, sidx.data.ptr ? &sidx : 0); } bool CvNormalBayesClassifier::train( const Mat& _train_data, const Mat& _responses, const Mat& _var_idx, const Mat& _sample_idx, bool update ) { CvMat tdata = _train_data, responses = _responses, vidx = _var_idx, sidx = _sample_idx; return train(&tdata, &responses, vidx.data.ptr ? &vidx : 0, sidx.data.ptr ? &sidx : 0, update); } float CvNormalBayesClassifier::predict( const Mat& _samples, Mat* _results, Mat* _results_prob ) const { CvMat samples = _samples, results, *presults = 0, results_prob, *presults_prob = 0; if( _results ) { if( !(_results->data && _results->type() == CV_32F && (_results->cols == 1 || _results->rows == 1) && _results->cols + _results->rows - 1 == _samples.rows) ) _results->create(_samples.rows, 1, CV_32F); presults = &(results = *_results); } if( _results_prob ) { if( !(_results_prob->data && _results_prob->type() == CV_64F && (_results_prob->cols == 1 || _results_prob->rows == 1) && _results_prob->cols + _results_prob->rows - 1 == _samples.rows) ) _results_prob->create(_samples.rows, 1, CV_64F); presults_prob = &(results_prob = *_results_prob); } return predict(&samples, presults, presults_prob); } /* End of file. */
// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_BASE_HH #define DUNE_GDT_OPERATORS_BASE_HH #include <dune/stuff/la/solver.hh> #include "interfaces.hh" namespace Dune { namespace GDT { namespace Operators { template <class Traits> class MatrixBased : public AssemblableOperatorInterface<Traits> { typedef AssemblableOperatorInterface<Traits> BaseType; public: using typename BaseType::GridViewType; using typename BaseType::SourceSpaceType; using typename BaseType::RangeSpaceType; using typename BaseType::MatrixType; private: typedef Stuff::LA::Solver<MatrixType> LinearSolverType; public: MatrixBased(MatrixType& matrix, const SourceSpaceType& source_space, const RangeSpaceType& range_space, const GridViewType& grid_view) : matrix_(matrix) , source_space_(source_space) , range_space_(range_space) , grid_view_(grid_view) , assembled_(false) { } MatrixBased(MatrixType& matrix, const SourceSpaceType& source_space, const RangeSpaceType& range_space) : matrix_(matrix) , source_space_(source_space) , range_space_(range_space) , grid_view_(*(source_space_.grid_view())) , assembled_(false) { } MatrixBased(MatrixType& matrix, const SourceSpaceType& source_space) : matrix_(matrix) , source_space_(source_space) , range_space_(source_space_) , grid_view_(*(source_space_.grid_view())) , assembled_(false) { } const GridViewType& grid_view() const { return grid_view_; } const RangeSpaceType& range_space() const { return range_space_; } const SourceSpaceType& source_space() const { return source_space_; } MatrixType& matrix() { return matrix_; } const MatrixType& matrix() const { return matrix_; } virtual void assemble() = 0; template <class S, class R> void apply(const Stuff::LA::VectorInterface<S>& source, Stuff::LA::VectorInterface<R>& range) { assemble(); matrix_.mv(source.as_imp(), range.as_imp()); } // ... apply(...) static std::vector<std::string> invert_options() { return LinearSolverType::options(); } static Stuff::Common::ConfigTree invert_options(const std::string& type) { return LinearSolverType::options(type); } template <class R, class S> void apply_inverse(const Stuff::LA::VectorInterface<R>& range, Stuff::LA::VectorInterface<S>& source, const Stuff::Common::ConfigTree& opts) { assemble(); LinearSolverType(matrix).apply(range.as_imp(), source.as_imp(), opts); } // ... apply_inverse(...) private: MatrixType& matrix_; const SourceSpaceType& source_space_; const RangeSpaceType& range_space_; const GridViewType& grid_view_; bool assembled_; }; // class MatrixBased } // namespace Operators } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_BASE_HH [operators.base] added missing vortial dtor // This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_BASE_HH #define DUNE_GDT_OPERATORS_BASE_HH #include <dune/stuff/la/solver.hh> #include "interfaces.hh" namespace Dune { namespace GDT { namespace Operators { template <class Traits> class MatrixBased : public AssemblableOperatorInterface<Traits> { typedef AssemblableOperatorInterface<Traits> BaseType; public: using typename BaseType::GridViewType; using typename BaseType::SourceSpaceType; using typename BaseType::RangeSpaceType; using typename BaseType::MatrixType; private: typedef Stuff::LA::Solver<MatrixType> LinearSolverType; public: MatrixBased(MatrixType& matrix, const SourceSpaceType& source_space, const RangeSpaceType& range_space, const GridViewType& grid_view) : matrix_(matrix) , source_space_(source_space) , range_space_(range_space) , grid_view_(grid_view) , assembled_(false) { } MatrixBased(MatrixType& matrix, const SourceSpaceType& source_space, const RangeSpaceType& range_space) : matrix_(matrix) , source_space_(source_space) , range_space_(range_space) , grid_view_(*(source_space_.grid_view())) , assembled_(false) { } MatrixBased(MatrixType& matrix, const SourceSpaceType& source_space) : matrix_(matrix) , source_space_(source_space) , range_space_(source_space_) , grid_view_(*(source_space_.grid_view())) , assembled_(false) { } virtual ~MatrixBased() { } const GridViewType& grid_view() const { return grid_view_; } const RangeSpaceType& range_space() const { return range_space_; } const SourceSpaceType& source_space() const { return source_space_; } MatrixType& matrix() { return matrix_; } const MatrixType& matrix() const { return matrix_; } virtual void assemble() = 0; template <class S, class R> void apply(const Stuff::LA::VectorInterface<S>& source, Stuff::LA::VectorInterface<R>& range) { assemble(); matrix_.mv(source.as_imp(), range.as_imp()); } // ... apply(...) static std::vector<std::string> invert_options() { return LinearSolverType::options(); } static Stuff::Common::ConfigTree invert_options(const std::string& type) { return LinearSolverType::options(type); } template <class R, class S> void apply_inverse(const Stuff::LA::VectorInterface<R>& range, Stuff::LA::VectorInterface<S>& source, const Stuff::Common::ConfigTree& opts) { assemble(); LinearSolverType(matrix).apply(range.as_imp(), source.as_imp(), opts); } // ... apply_inverse(...) private: MatrixType& matrix_; const SourceSpaceType& source_space_; const RangeSpaceType& range_space_; const GridViewType& grid_view_; bool assembled_; }; // class MatrixBased } // namespace Operators } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_BASE_HH
/************************************************************************* * * $RCSfile: editbrowsebox.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: fs $ $Date: 2002-09-10 14:32:09 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVTOOLS_EDITBROWSEBOX_HXX_ #include "editbrowsebox.hxx" #endif #ifndef _SVTOOLS_EDITBROWSEBOX_HRC_ #include "editbrowsebox.hrc" #endif #ifndef _APP_HXX //autogen #include <vcl/svapp.hxx> #endif #ifndef _DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _WINDOW_HXX //autogen #include <vcl/window.hxx> #endif #ifndef _EDIT_HXX //autogen #include <vcl/edit.hxx> #endif #ifndef _TOOLS_RESID_HXX //autogen #include <tools/resid.hxx> #endif #ifndef _SV_SPINFLD_HXX //autogen #include <vcl/spinfld.hxx> #endif #ifndef _SVTOOLS_SVTDATA_HXX #include "svtdata.hxx" #endif #ifndef _SVTOOLS_HRC #include "svtools.hrc" #endif #include <algorithm> #ifndef _SV_MULTISEL_HXX #include <tools/multisel.hxx> #endif #ifndef SVTOOLS_EDITBROWSEBOX_IMPL_HXX #include "editbrowseboximpl.hxx" #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_ #include <drafts/com/sun/star/accessibility/AccessibleEventId.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_ #include <drafts/com/sun/star/accessibility/XAccessible.hpp> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef _SVTOOLS_ACCESSIBILEEDITBROWSEBOXTABLECELL_HXX #include "editbrowseboxcell.hxx" #endif // ....................................................................... namespace svt { // ....................................................................... namespace { //.............................................................. sal_Bool isHiContrast(Window* _pWindow) { OSL_ENSURE(_pWindow,"Window must be not null!"); Window* pIter = _pWindow; // while( pIter && pIter->GetBackground().GetColor().GetColor() == COL_TRANSPARENT ) while( pIter ) { const Color& aColor = pIter->GetBackground().GetColor(); if ( aColor.GetColor() == COL_TRANSPARENT ) pIter = pIter->GetParent(); else break; } return pIter && pIter->GetBackground().GetColor().IsDark(); } //.............................................................. sal_uInt16 getRealGetFocusFlags( Window* _pWindow ) { sal_uInt16 nFlags = 0; while ( _pWindow && !nFlags ) { nFlags = _pWindow->GetGetFocusFlags( ); _pWindow = _pWindow->GetParent(); } return nFlags; } } using namespace drafts::com::sun::star::accessibility::AccessibleEventId; using drafts::com::sun::star::accessibility::XAccessible; using ::com::sun::star::uno::Reference; //================================================================== #define HANDLE_ID 0 //================================================================== //= EditBrowserHeader //================================================================== //------------------------------------------------------------------------------ void EditBrowserHeader::DoubleClick() { sal_uInt16 nColId = GetCurItemId(); if (nColId) { sal_uInt32 nAutoWidth = ((EditBrowseBox*)GetParent())->GetAutoColumnWidth(nColId); if (nAutoWidth != ((EditBrowseBox*)GetParent())->GetColumnWidth(nColId)) { ((EditBrowseBox*)GetParent())->SetColumnWidth(nColId, nAutoWidth); ((EditBrowseBox*)GetParent())->ColumnResized(nColId); } } } //================================================================== //= EditBrowseBox //================================================================== //------------------------------------------------------------------------------ void EditBrowseBox::BrowserMouseEventPtr::Clear() { DELETEZ(pEvent); } //------------------------------------------------------------------------------ void EditBrowseBox::BrowserMouseEventPtr::Set(const BrowserMouseEvent* pEvt, sal_Bool bIsDown) { if (pEvt == pEvent) { bDown = bIsDown; return; } Clear(); if (pEvt) { pEvent = new BrowserMouseEvent(pEvt->GetWindow(), *pEvt, pEvt->GetRow(), pEvt->GetColumn(), pEvt->GetColumnId(), pEvt->GetRect()); bDown = bIsDown; } } DBG_NAME(EditBrowseBox); void EditBrowseBox::Construct() { m_aImpl = ::std::auto_ptr<EditBrowseBoxImpl>(new EditBrowseBoxImpl()); m_aImpl->m_pFocusCell = NULL; m_aImpl->m_bHiContrast = isHiContrast(&GetDataWindow()); SetCompoundControl(sal_True); SetLineColor(Color(COL_LIGHTGRAY)); // HACK: the BrowseBox does not invalidate it's children (as it should be) // Thus we reset WB_CLIPCHILDREN, which forces the invalidation of the children WinBits aStyle = GetStyle(); if( aStyle & WB_CLIPCHILDREN ) { aStyle &= ~WB_CLIPCHILDREN; SetStyle( aStyle ); } ImplInitSettings(sal_True, sal_True, sal_True); pCheckBoxPaint = new CheckBoxControl(&GetDataWindow()); pCheckBoxPaint->SetPaintTransparent( sal_True ); pCheckBoxPaint->SetBackground(); } //------------------------------------------------------------------------------ EditBrowseBox::EditBrowseBox(Window* pParent, const ResId& rId, sal_Int32 nBrowserFlags, BrowserMode _nMode ) :BrowseBox( pParent, rId, _nMode ) ,nEditRow(-1) ,nPaintRow(-1) ,nOldEditRow(-1) ,nEditCol(0) ,nOldEditCol(0) ,bHasFocus(sal_False) ,bPaintStatus(sal_True) ,nStartEvent(0) ,nEndEvent(0) ,nCellModifiedEvent(0) ,m_nBrowserFlags(nBrowserFlags) { DBG_CTOR(EditBrowseBox,NULL); Construct(); } //================================================================== EditBrowseBox::EditBrowseBox( Window* pParent, sal_Int32 nBrowserFlags, WinBits nBits, BrowserMode _nMode ) :BrowseBox( pParent, nBits, _nMode ) ,nEditRow(-1) ,nPaintRow(-1) ,nOldEditRow(-1) ,nEditCol(0) ,nOldEditCol(0) ,bHasFocus(sal_False) ,bPaintStatus(sal_True) ,nStartEvent(0) ,nEndEvent(0) ,nCellModifiedEvent(0) ,pHeader(NULL) ,m_nBrowserFlags(nBrowserFlags) { DBG_CTOR(EditBrowseBox,NULL); Construct(); } //------------------------------------------------------------------------------ void EditBrowseBox::Init() { // spaetes Construieren, } //------------------------------------------------------------------------------ EditBrowseBox::~EditBrowseBox() { if (nStartEvent) Application::RemoveUserEvent(nStartEvent); if (nEndEvent) Application::RemoveUserEvent(nEndEvent); if (nCellModifiedEvent) Application::RemoveUserEvent(nCellModifiedEvent); delete pCheckBoxPaint; DBG_DTOR(EditBrowseBox,NULL); } //------------------------------------------------------------------------------ void EditBrowseBox::RemoveRows() { BrowseBox::Clear(); nOldEditRow = nEditRow = nPaintRow = -1; nEditCol = nOldEditCol = 0; } //------------------------------------------------------------------------------ BrowserHeader* EditBrowseBox::CreateHeaderBar(BrowseBox* pParent) { pHeader = imp_CreateHeaderBar(pParent); if (!IsUpdateMode()) pHeader->SetUpdateMode(sal_False); return pHeader; } //------------------------------------------------------------------------------ BrowserHeader* EditBrowseBox::imp_CreateHeaderBar(BrowseBox* pParent) { return new EditBrowserHeader(pParent); } //------------------------------------------------------------------------------ void EditBrowseBox::LoseFocus() { BrowseBox::LoseFocus(); DetermineFocus( 0 ); } //------------------------------------------------------------------------------ void EditBrowseBox::GetFocus() { BrowseBox::GetFocus(); // This should handle the case that the BrowseBox (or one of it's children) // gets the focus from outside by pressing Tab if (IsEditing() && Controller()->GetWindow().IsVisible()) Controller()->GetWindow().GrabFocus(); DetermineFocus( getRealGetFocusFlags( this ) ); } //------------------------------------------------------------------------------ sal_Bool EditBrowseBox::SeekRow(long nRow) { nPaintRow = nRow; return sal_True; } //------------------------------------------------------------------------------ IMPL_LINK(EditBrowseBox, StartEditHdl, void*, EMPTYTAG) { nStartEvent = 0; if (IsEditing()) { aController->GetWindow().Show(); if (!aController->GetWindow().HasFocus() && (m_pFocusWhileRequest == Application::GetFocusWindow())) aController->GetWindow().GrabFocus(); } return 0; } //------------------------------------------------------------------------------ void EditBrowseBox::PaintField( OutputDevice& rDev, const Rectangle& rRect, sal_uInt16 nColumnId ) const { if (nColumnId == HANDLE_ID) { if (bPaintStatus) PaintStatusCell(rDev, rRect); } else { // don't paint the current cell if (&rDev == &GetDataWindow()) // but only if we're painting onto our data win (which is the usual painting) if (nPaintRow == nEditRow) { if (IsEditing() && nEditCol == nColumnId && aController->GetWindow().IsVisible()) return; } PaintCell(rDev, rRect, nColumnId); } } //------------------------------------------------------------------------------ Image EditBrowseBox::GetImage(RowStatus eStatus) const { sal_Bool bHiContrast = isHiContrast(&GetDataWindow()); if ( !m_aStatusImages.GetImageCount() || (bHiContrast != m_aImpl->m_bHiContrast) ) { m_aImpl->m_bHiContrast = bHiContrast; const_cast<EditBrowseBox*>(this)->m_aStatusImages = ImageList(SvtResId(bHiContrast ? RID_SVTOOLS_IMAGELIST_EDITBWSEBOX_H : RID_SVTOOLS_IMAGELIST_EDITBROWSEBOX)); } Image aImage; switch (eStatus) { case CURRENT: aImage = m_aStatusImages.GetImage(IMG_EBB_CURRENT); break; case CURRENTNEW: aImage = m_aStatusImages.GetImage(IMG_EBB_CURRENTNEW); break; case MODIFIED: aImage = m_aStatusImages.GetImage(IMG_EBB_MODIFIED); break; case NEW: aImage = m_aStatusImages.GetImage(IMG_EBB_NEW); break; case DELETED: aImage = m_aStatusImages.GetImage(IMG_EBB_DELETED); break; case PRIMARYKEY: aImage = m_aStatusImages.GetImage(IMG_EBB_PRIMARYKEY); break; case CURRENT_PRIMARYKEY: aImage = m_aStatusImages.GetImage(IMG_EBB_CURRENT_PRIMARYKEY); break; case FILTER: aImage = m_aStatusImages.GetImage(IMG_EBB_FILTER); break; } return aImage; } //------------------------------------------------------------------------------ void EditBrowseBox::PaintStatusCell(OutputDevice& rDev, const Rectangle& rRect) const { if (nPaintRow < 0) return; RowStatus eStatus = GetRowStatus( nPaintRow ); sal_Int32 nBrowserFlags = GetBrowserFlags(); if (nBrowserFlags & EBBF_NO_HANDLE_COLUMN_CONTENT) return; // draw the text of the header column if (nBrowserFlags & EBBF_HANDLE_COLUMN_TEXT ) { rDev.DrawText( rRect, GetCellText( nPaintRow, 0 ), TEXT_DRAW_CENTER | TEXT_DRAW_VCENTER | TEXT_DRAW_CLIP ); } // draw an image else if (eStatus != CLEAN && rDev.GetOutDevType() == OUTDEV_WINDOW) { Image aImage(GetImage(eStatus)); // calc the image position Size aImageSize(aImage.GetSizePixel()); aImageSize.Width() = CalcZoom(aImageSize.Width()); aImageSize.Height() = CalcZoom(aImageSize.Height()); Point aPos(rRect.TopLeft()); if (aImageSize.Width() > rRect.GetWidth() || aImageSize.Height() > rRect.GetHeight()) rDev.SetClipRegion(rRect); if (aImageSize.Width() < rRect.GetWidth()) aPos.X() += (rRect.GetWidth() - aImageSize.Width()) / 2; if (IsZoom()) rDev.DrawImage(aPos, aImageSize, aImage, 0); else rDev.DrawImage(aPos, aImage, 0); if (rDev.IsClipRegion()) rDev.SetClipRegion(); } } //------------------------------------------------------------------------------ EditBrowseBox::RowStatus EditBrowseBox::GetRowStatus(long nRow) const { return CLEAN; } //------------------------------------------------------------------------------ void EditBrowseBox::KeyInput( const KeyEvent& rEvt ) { sal_uInt16 nCode = rEvt.GetKeyCode().GetCode(); sal_Bool bShift = rEvt.GetKeyCode().IsShift(); sal_Bool bCtrl = rEvt.GetKeyCode().IsMod1(); switch (nCode) { case KEY_RETURN: if (!bCtrl && !bShift && IsTabAllowed(sal_True)) { Dispatch(BROWSER_CURSORRIGHT); } else BrowseBox::KeyInput(rEvt); return; case KEY_TAB: if (!bCtrl && !bShift) { if (IsTabAllowed(sal_True)) Dispatch(BROWSER_CURSORRIGHT); else // do NOT call BrowseBox::KeyInput : this would handle the tab, but we already now // that tab isn't allowed here. So give the Control class a chance Control::KeyInput(rEvt); return; } else if (!bCtrl && bShift) { if (IsTabAllowed(sal_False)) Dispatch(BROWSER_CURSORLEFT); else // do NOT call BrowseBox::KeyInput : this would handle the tab, but we already now // that tab isn't allowed here. So give the Control class a chance Control::KeyInput(rEvt); return; } default: BrowseBox::KeyInput(rEvt); } } //------------------------------------------------------------------------------ void EditBrowseBox::MouseButtonDown(const BrowserMouseEvent& rEvt) { sal_uInt16 nColPos = GetColumnPos( rEvt.GetColumnId() ); long nRow = rEvt.GetRow(); // absorb double clicks if (rEvt.GetClicks() > 1 && rEvt.GetRow() >= 0) return; // change to a new position if (IsEditing() && (nColPos != nEditCol || nRow != nEditRow) && (nColPos != BROWSER_INVALIDID) && (nRow < GetRowCount())) { CellControllerRef aController(Controller()); HideAndDisable(aController); } if (0 == rEvt.GetColumnId()) { // it was the handle column. save the current cell content if necessary // (clicking on the handle column results in selecting the current row) // 23.01.2001 - 82797 - FS if (IsEditing() && aController->IsModified()) SaveModified(); } aMouseEvent.Set(&rEvt,sal_True); BrowseBox::MouseButtonDown(rEvt); aMouseEvent.Clear(); if (0 != (m_nBrowserFlags & EBBF_ACTIVATE_ON_BUTTONDOWN)) { // the base class does not travel upon MouseButtonDown, but implActivateCellOnMouseEvent assumes we traveled ... GoToRowColumnId( rEvt.GetRow(), rEvt.GetColumnId() ); if (rEvt.GetRow() >= 0) implActivateCellOnMouseEvent(rEvt, sal_False); } } //------------------------------------------------------------------------------ void EditBrowseBox::MouseButtonUp( const BrowserMouseEvent& rEvt ) { // unused variables. Sideeffects? sal_uInt16 nColPos = GetColumnPos( rEvt.GetColumnId() ); long nRow = rEvt.GetRow(); // absorb double clicks if (rEvt.GetClicks() > 1 && rEvt.GetRow() >= 0) return; aMouseEvent.Set(&rEvt,sal_False); BrowseBox::MouseButtonUp(rEvt); aMouseEvent.Clear(); if (0 == (m_nBrowserFlags & EBBF_ACTIVATE_ON_BUTTONDOWN)) if (rEvt.GetRow() >= 0) implActivateCellOnMouseEvent(rEvt, sal_True); } //------------------------------------------------------------------------------ void EditBrowseBox::implActivateCellOnMouseEvent(const BrowserMouseEvent& _rEvt, sal_Bool _bUp) { if (!IsEditing()) ActivateCell(); else if (IsEditing() && !aController->GetWindow().IsEnabled()) DeactivateCell(); else if (IsEditing() && !aController->GetWindow().HasChildPathFocus()) AsynchGetFocus(); if (IsEditing() && aController->GetWindow().IsEnabled() && aController->WantMouseEvent()) { // forwards the event to the control // If the field has been moved previously, we have to adjust the position aController->GetWindow().GrabFocus(); // the position of the event relative to the controller's window Point aPos = _rEvt.GetPosPixel() - _rEvt.GetRect().TopLeft(); // the (child) window which should really get the event Window* pRealHandler = aController->GetWindow().FindWindow(aPos); if (pRealHandler) // the coords relative to this real handler aPos -= pRealHandler->GetPosPixel(); else pRealHandler = &aController->GetWindow(); // the faked event MouseEvent aEvent(aPos, _rEvt.GetClicks(), _rEvt.GetMode(), _rEvt.GetButtons(), _rEvt.GetModifier()); pRealHandler->MouseButtonDown(aEvent); if (_bUp) pRealHandler->MouseButtonUp(aEvent); Window *pWin = &aController->GetWindow(); if (!pWin->IsTracking()) { for (pWin = pWin->GetWindow(WINDOW_FIRSTCHILD); pWin && !pWin->IsTracking(); pWin = pWin->GetWindow(WINDOW_NEXT)) { } } if (pWin && pWin->IsTracking()) pWin->EndTracking(); } } //------------------------------------------------------------------------------ void EditBrowseBox::Dispatch( sal_uInt16 _nId ) { if ( _nId == BROWSER_ENHANCESELECTION ) { // this is a workaround for the bug in the base class: // if the row selection is to be extended (which is what BROWSER_ENHANCESELECTION tells us) // then the base class does not revert any column selections, while, for doing a "simple" // selection (BROWSER_SELECT), it does. In fact, it does not only revert the col selection then, // but also any current row selections. // This clearly tells me that the both ids are for row selection only - there this behaviour does // make sense. // But here, where we have column selection, too, we take care of this ourself. if ( GetSelectColumnCount( ) ) { while ( GetSelectColumnCount( ) ) SelectColumnPos( FirstSelectedColumn(), sal_False ); Select(); } } BrowseBox::Dispatch( _nId ); } //------------------------------------------------------------------------------ long EditBrowseBox::PreNotify(NotifyEvent& rEvt) { switch (rEvt.GetType()) { case EVENT_KEYINPUT: if ( (IsEditing() && Controller()->GetWindow().HasChildPathFocus()) || rEvt.GetWindow() == &GetDataWindow() || (!IsEditing() && HasChildPathFocus()) ) { const KeyEvent* pKeyEvent = rEvt.GetKeyEvent(); sal_uInt16 nCode = pKeyEvent->GetKeyCode().GetCode(); sal_Bool bShift = pKeyEvent->GetKeyCode().IsShift(); sal_Bool bCtrl = pKeyEvent->GetKeyCode().IsMod1(); sal_Bool bAlt = pKeyEvent->GetKeyCode().IsMod2(); sal_Bool bSelect= sal_False; sal_Bool bNonEditOnly = sal_False; sal_uInt16 nId = BROWSER_NONE; if (!bAlt && !bCtrl && !bShift ) switch ( nCode ) { case KEY_DOWN: nId = BROWSER_CURSORDOWN; break; case KEY_UP: nId = BROWSER_CURSORUP; break; case KEY_PAGEDOWN: nId = BROWSER_CURSORPAGEDOWN; break; case KEY_PAGEUP: nId = BROWSER_CURSORPAGEUP; break; case KEY_HOME: nId = BROWSER_CURSORHOME; break; case KEY_END: nId = BROWSER_CURSOREND; break; case KEY_TAB: // ask if traveling to the next cell is allowed if (IsTabAllowed(sal_True)) nId = BROWSER_CURSORRIGHT; break; case KEY_RETURN: // save the cell content (if necessary) if (IsEditing() && aController->IsModified() && !((EditBrowseBox *) this)->SaveModified()) { // maybe we're not visible ... EnableAndShow(); aController->GetWindow().GrabFocus(); return 1; } // ask if traveling to the next cell is allowed if (IsTabAllowed(sal_True)) nId = BROWSER_CURSORRIGHT; break; case KEY_RIGHT: nId = BROWSER_CURSORRIGHT; break; case KEY_LEFT: nId = BROWSER_CURSORLEFT; break; case KEY_SPACE: nId = BROWSER_SELECT; bNonEditOnly = bSelect = sal_True;break; } if ( !bAlt && !bCtrl && bShift ) switch ( nCode ) { case KEY_DOWN: nId = BROWSER_SELECTDOWN; bSelect = sal_True;break; case KEY_UP: nId = BROWSER_SELECTUP; bSelect = sal_True;break; case KEY_HOME: nId = BROWSER_SELECTHOME; bSelect = sal_True;break; case KEY_END: nId = BROWSER_SELECTEND; bSelect = sal_True;break; case KEY_SPACE: nId = BROWSER_SELECTCOLUMN; bSelect = sal_True; break; case KEY_TAB: if (IsTabAllowed(sal_False)) nId = BROWSER_CURSORLEFT; break; } if ( !bAlt && bCtrl && !bShift ) switch ( nCode ) { case KEY_DOWN: nId = BROWSER_SCROLLUP; break; case KEY_UP: nId = BROWSER_SCROLLDOWN; break; case KEY_PAGEDOWN: nId = BROWSER_CURSORENDOFFILE; break; case KEY_PAGEUP: nId = BROWSER_CURSORTOPOFFILE; break; case KEY_HOME: nId = BROWSER_CURSORTOPOFSCREEN; break; case KEY_END: nId = BROWSER_CURSORENDOFSCREEN; break; case KEY_SPACE: nId = BROWSER_ENHANCESELECTION; bSelect = sal_True;break; } if ( ( nId != BROWSER_NONE ) && ( !IsEditing() || ( !bNonEditOnly && aController->MoveAllowed( *pKeyEvent ) ) ) ) { if (nId == BROWSER_SELECT) { // save the cell content (if necessary) if (IsEditing() && aController->IsModified() && !((EditBrowseBox *) this)->SaveModified()) { // maybe we're not visible ... EnableAndShow(); aController->GetWindow().GrabFocus(); return 1; } } Dispatch(nId); if (bSelect && (GetSelectRowCount() || GetSelection() != NULL)) DeactivateCell(); return 1; } } } return BrowseBox::PreNotify(rEvt); } //------------------------------------------------------------------------------ sal_Bool EditBrowseBox::IsTabAllowed(sal_Bool bRight) const { return sal_True; } //------------------------------------------------------------------------------ long EditBrowseBox::Notify(NotifyEvent& rEvt) { switch (rEvt.GetType()) { case EVENT_GETFOCUS: DetermineFocus( getRealGetFocusFlags( this ) ); break; case EVENT_LOSEFOCUS: DetermineFocus( 0 ); break; } return BrowseBox::Notify(rEvt); } //------------------------------------------------------------------------------ void EditBrowseBox::StateChanged( StateChangedType nType ) { BrowseBox::StateChanged( nType ); if ( nType == STATE_CHANGE_ZOOM ) { ImplInitSettings( sal_True, sal_False, sal_False ); if (IsEditing()) { DeactivateCell(); ActivateCell(); } } else if ( nType == STATE_CHANGE_CONTROLFONT ) { ImplInitSettings( sal_True, sal_False, sal_False ); Invalidate(); } else if ( nType == STATE_CHANGE_CONTROLFOREGROUND ) { ImplInitSettings( sal_False, sal_True, sal_False ); Invalidate(); } else if ( nType == STATE_CHANGE_CONTROLBACKGROUND ) { ImplInitSettings( sal_False, sal_False, sal_True ); Invalidate(); } else if (nType == STATE_CHANGE_STYLE) { WinBits nStyle = GetStyle(); if (!(nStyle & WB_NOTABSTOP) ) nStyle |= WB_TABSTOP; SetStyle(nStyle); } } //------------------------------------------------------------------------------ void EditBrowseBox::DataChanged( const DataChangedEvent& rDCEvt ) { BrowseBox::DataChanged( rDCEvt ); if ((( rDCEvt.GetType() == DATACHANGED_SETTINGS ) || ( rDCEvt.GetType() == DATACHANGED_DISPLAY )) && ( rDCEvt.GetFlags() & SETTINGS_STYLE )) { ImplInitSettings( sal_True, sal_True, sal_True ); Invalidate(); } } //------------------------------------------------------------------------------ void EditBrowseBox::ImplInitSettings( sal_Bool bFont, sal_Bool bForeground, sal_Bool bBackground ) { const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings(); if (bFont) { Font aFont = rStyleSettings.GetFieldFont(); if (IsControlFont()) { GetDataWindow().SetControlFont(GetControlFont()); aFont.Merge(GetControlFont()); } else GetDataWindow().SetControlFont(); GetDataWindow().SetZoomedPointFont(aFont); } if ( bFont || bForeground ) { Color aTextColor = rStyleSettings.GetFieldTextColor(); if (IsControlForeground()) { aTextColor = GetControlForeground(); GetDataWindow().SetControlForeground(aTextColor); } else GetDataWindow().SetControlForeground(); GetDataWindow().SetTextColor( aTextColor ); } if ( bBackground ) { if (GetDataWindow().IsControlBackground()) { GetDataWindow().SetControlBackground(GetControlBackground()); GetDataWindow().SetBackground(GetDataWindow().GetControlBackground()); GetDataWindow().SetFillColor(GetDataWindow().GetControlBackground()); } else { GetDataWindow().SetControlBackground(); GetDataWindow().SetBackground( rStyleSettings.GetFieldColor() ); GetDataWindow().SetFillColor( rStyleSettings.GetFieldColor() ); } } } //------------------------------------------------------------------------------ sal_Bool EditBrowseBox::IsCursorMoveAllowed(long nNewRow, sal_uInt16 nNewColId) const { sal_uInt16 nInfo = 0; if (GetSelectColumnCount() || (aMouseEvent.Is() && aMouseEvent->GetRow() < 0)) nInfo |= COLSELECT; if ((GetSelection() != NULL && GetSelectRowCount()) || (aMouseEvent.Is() && aMouseEvent->GetColumnId() == HANDLE_ID)) nInfo |= ROWSELECT; if (!nInfo && nNewRow != nEditRow) nInfo |= ROWCHANGE; if (!nInfo && nNewColId != nEditCol) nInfo |= COLCHANGE; if (nInfo == 0) // nothing happened return sal_True; // save the cell content if (IsEditing() && aController->IsModified() && !((EditBrowseBox *) this)->SaveModified()) { // maybe we're not visible ... EnableAndShow(); aController->GetWindow().GrabFocus(); return sal_False; } EditBrowseBox * pTHIS = (EditBrowseBox *) this; // save the cell content if // a) a selection is beeing made // b) the row is changing if (IsModified() && (nInfo & (ROWCHANGE | COLSELECT | ROWSELECT)) && !pTHIS->SaveRow()) { if (nInfo & COLSELECT || nInfo & ROWSELECT) { // cancel selected pTHIS->SetNoSelection(); } if (IsEditing()) { if (!Controller()->GetWindow().IsVisible()) { EnableAndShow(); } aController->GetWindow().GrabFocus(); } return sal_False; } if (nNewRow != nEditRow) { Window& rWindow = GetDataWindow(); // don't paint too much // update the status immediatly if possible if ((nEditRow >= 0) && (GetBrowserFlags() & EBBF_NO_HANDLE_COLUMN_CONTENT) == 0) { Rectangle aRect = GetFieldRectPixel(nEditRow, 0, sal_False ); // status cell should be painted if and only if text is displayed // note: bPaintStatus is mutable, but Solaris has problems with assigning // probably because it is part of a bitfield pTHIS->bPaintStatus = static_cast< sal_Bool > (( GetBrowserFlags() & EBBF_HANDLE_COLUMN_TEXT ) == EBBF_HANDLE_COLUMN_TEXT ); rWindow.Paint(aRect); pTHIS->bPaintStatus = sal_True; } // don't paint during row change rWindow.EnablePaint(sal_False); // the last veto chance for derived classes if (!pTHIS->CursorMoving(nNewRow, nNewColId)) { pTHIS->InvalidateStatusCell(nEditRow); rWindow.EnablePaint(sal_True); return sal_False; } else return sal_True; } else return pTHIS->CursorMoving(nNewRow, nNewColId); } //------------------------------------------------------------------------------ void EditBrowseBox::ColumnMoved(sal_uInt16 nId) { BrowseBox::ColumnMoved(nId); if (IsEditing()) { Rectangle aRect( GetCellRect(nEditRow, nEditCol, sal_False)); CellControllerRef aControllerRef = Controller(); ResizeController(aControllerRef, aRect); Controller()->GetWindow().GrabFocus(); } } //------------------------------------------------------------------------------ sal_Bool EditBrowseBox::SaveRow() { return sal_True; } //------------------------------------------------------------------------------ sal_Bool EditBrowseBox::CursorMoving(long nNewRow, sal_uInt16 nNewCol) { ((EditBrowseBox *) this)->DeactivateCell(sal_False); return sal_True; } //------------------------------------------------------------------------------ void EditBrowseBox::CursorMoved() { long nNewRow = GetCurRow(); if (nEditRow != nNewRow) { if ((GetBrowserFlags() & EBBF_NO_HANDLE_COLUMN_CONTENT) == 0) InvalidateStatusCell(nNewRow); nEditRow = nNewRow; } ActivateCell(); GetDataWindow().EnablePaint(sal_True); // should not be called here because the descant event is not needed here //BrowseBox::CursorMoved(); } //------------------------------------------------------------------------------ void EditBrowseBox::EndScroll() { if (IsEditing()) { Rectangle aRect = GetCellRect(nEditRow, nEditCol, sal_False); ResizeController(aController,aRect); AsynchGetFocus(); } BrowseBox::EndScroll(); } //------------------------------------------------------------------------------ void EditBrowseBox::ActivateCell(long nRow, sal_uInt16 nCol, sal_Bool bCellFocus) { if (IsEditing()) return; nEditCol = nCol; if ((GetSelectRowCount() && GetSelection() != NULL) || GetSelectColumnCount() || (aMouseEvent.Is() && (aMouseEvent.IsDown() || aMouseEvent->GetClicks() > 1))) // bei MouseDown passiert noch nichts { return; } if (nEditRow >= 0 && nEditCol > HANDLE_ID) { aController = GetController(nRow, nCol); if (aController.Is()) { Rectangle aRect( GetCellRect(nEditRow, nEditCol, sal_False)); ResizeController(aController, aRect); InitController(aController, nEditRow, nEditCol); aController->ClearModified(); aController->SetModifyHdl(LINK(this,EditBrowseBox,ModifyHdl)); EnableAndShow(); // activate the cell only of the browser has the focus if ( bHasFocus && bCellFocus ) { CreateAccessibleControl(0); AsynchGetFocus(); } } else if ( isAccessibleCreated() && HasFocus() ) commitTableEvent(ACCESSIBLE_ACTIVE_DESCENDANT_EVENT, com::sun::star::uno::makeAny(CreateAccessibleCell(nRow,nCol)), com::sun::star::uno::Any()); } } //------------------------------------------------------------------------------ void EditBrowseBox::DeactivateCell(sal_Bool bUpdate) { if (IsEditing()) { commitBrowseBoxEvent(ACCESSIBLE_CHILD_EVENT,com::sun::star::uno::Any(),com::sun::star::uno::makeAny(m_aImpl->m_xActiveCell)); m_aImpl->disposeCell(); m_aImpl->m_pFocusCell = NULL; m_aImpl->m_xActiveCell = NULL; aOldController = aController; aController.Clear(); // reset the modify handler aOldController->SetModifyHdl(Link()); if (bHasFocus) GrabFocus(); // ensure that we have (and keep) the focus HideAndDisable(aOldController); // update if requested if (bUpdate) Update(); nOldEditCol = nEditCol; nOldEditRow = nEditRow; // release the controller (asynchronously) if (nEndEvent) Application::RemoveUserEvent(nEndEvent); nEndEvent = Application::PostUserEvent(LINK(this,EditBrowseBox,EndEditHdl)); } } //------------------------------------------------------------------------------ Rectangle EditBrowseBox::GetCellRect(long nRow, sal_uInt16 nColId, sal_Bool bRel) const { Rectangle aRect( GetFieldRectPixel(nRow, nColId, bRel)); if ((GetMode() & BROWSER_CURSOR_WO_FOCUS) == BROWSER_CURSOR_WO_FOCUS) { aRect.Top() += 1; aRect.Bottom() -= 1; } return aRect; } //------------------------------------------------------------------------------ IMPL_LINK(EditBrowseBox, EndEditHdl, void*, EMPTYTAG) { nEndEvent = 0; ReleaseController(aOldController, nOldEditRow, nOldEditCol); aOldController = CellControllerRef(); nOldEditRow = -1; nOldEditCol = 0; return 0; } //------------------------------------------------------------------------------ IMPL_LINK(EditBrowseBox, ModifyHdl, void*, EMPTYTAG) { if (nCellModifiedEvent) Application::RemoveUserEvent(nCellModifiedEvent); nCellModifiedEvent = Application::PostUserEvent(LINK(this,EditBrowseBox,CellModifiedHdl)); return 0; } //------------------------------------------------------------------------------ IMPL_LINK(EditBrowseBox, CellModifiedHdl, void*, EMPTYTAG) { nCellModifiedEvent = 0; CellModified(); return 0; } //------------------------------------------------------------------------------ void EditBrowseBox::ColumnResized( sal_uInt16 nColId ) { if (IsEditing()) { Rectangle aRect( GetCellRect(nEditRow, nEditCol, sal_False)); CellControllerRef aControllerRef = Controller(); ResizeController(aControllerRef, aRect); Controller()->GetWindow().GrabFocus(); } } //------------------------------------------------------------------------------ sal_uInt16 EditBrowseBox::GetDefaultColumnWidth(const String& rName) const { return GetDataWindow().GetTextWidth(rName) + GetDataWindow().GetTextWidth('0') * 4; } //------------------------------------------------------------------------------ void EditBrowseBox::InsertHandleColumn(sal_uInt16 nWidth) { if (!nWidth) nWidth = GetDefaultColumnWidth(String()); BrowseBox::InsertHandleColumn(nWidth, sal_True); } //------------------------------------------------------------------------------ sal_uInt16 EditBrowseBox::AppendColumn(const String& rName, sal_uInt16 nWidth, sal_uInt16 nPos, sal_uInt16 nId) { if (nId == (sal_uInt16)-1) { // look for the next free id for (nId = ColCount(); nId > 0 && GetColumnPos(nId) != BROWSER_INVALIDID; nId--) ; if (!nId) { // if there is no handle column // increment the id if (!ColCount() || GetColumnId(0)) nId = ColCount() + 1; } } DBG_ASSERT(nId, "EditBrowseBox::AppendColumn: invalid id!"); if (!nWidth) nWidth = GetDefaultColumnWidth(rName); InsertDataColumn(nId, rName, nWidth, (HIB_CENTER | HIB_VCENTER | HIB_CLICKABLE), nPos); return nId; } //------------------------------------------------------------------------------ void EditBrowseBox::Resize() { BrowseBox::Resize(); // if the window is smaller than "title line height" + "control area", // do nothing if (GetOutputSizePixel().Height() < (GetControlArea().GetHeight() + GetDataWindow().GetPosPixel().Y())) return; // the size of the control area Point aPoint(GetControlArea().TopLeft()); sal_uInt16 nX = (sal_uInt16)aPoint.X(); ArrangeControls(nX, (sal_uInt16)aPoint.Y()); if (!nX) nX = 0; ReserveControlArea((sal_uInt16)nX); } //------------------------------------------------------------------------------ void EditBrowseBox::ArrangeControls(sal_uInt16& nX, sal_uInt16 nY) { } //------------------------------------------------------------------------------ CellController* EditBrowseBox::GetController(long, sal_uInt16) { return NULL; } //----------------------------------------------------------------------------- void EditBrowseBox::ResizeController(CellControllerRef& rController, const Rectangle& rRect) { rController->GetWindow().SetPosSizePixel(rRect.TopLeft(), rRect.GetSize()); } //------------------------------------------------------------------------------ void EditBrowseBox::InitController(CellControllerRef& rController, long nRow, sal_uInt16 nCol) { } //------------------------------------------------------------------------------ void EditBrowseBox::ReleaseController(CellControllerRef& rController, long nRow, sal_uInt16 nCol) { } //------------------------------------------------------------------------------ void EditBrowseBox::CellModified() { } //------------------------------------------------------------------------------ sal_Bool EditBrowseBox::SaveModified() { return sal_True; } //------------------------------------------------------------------------------ void EditBrowseBox::DoubleClick(const BrowserMouseEvent& rEvt) { // when double clicking on the column, the optimum size will be calculated sal_uInt16 nColId = rEvt.GetColumnId(); if (nColId != HANDLE_ID) SetColumnWidth(nColId, GetAutoColumnWidth(nColId)); } //------------------------------------------------------------------------------ sal_uInt32 EditBrowseBox::GetAutoColumnWidth(sal_uInt16 nColId) { sal_uInt32 nCurColWidth = GetColumnWidth(nColId); sal_uInt32 nMinColWidth = CalcZoom(20); // minimum sal_uInt32 nNewColWidth = nMinColWidth; long nMaxRows = Min(long(GetVisibleRows()), GetRowCount()); long nLastVisRow = GetTopRow() + nMaxRows - 1; if (GetTopRow() <= nLastVisRow) // calc the column with using the cell contents { for (long i = GetTopRow(); i <= nLastVisRow; ++i) nNewColWidth = std::max(nNewColWidth,GetTotalCellWidth(i,nColId) + 12); if (nNewColWidth == nCurColWidth) // size has not changed nNewColWidth = GetDefaultColumnWidth(GetColumnTitle(nColId)); } else nNewColWidth = GetDefaultColumnWidth(GetColumnTitle(nColId)); return nNewColWidth; } //------------------------------------------------------------------------------ sal_uInt32 EditBrowseBox::GetTotalCellWidth(long nRow, sal_uInt16 nColId) { return 0; } //------------------------------------------------------------------------------ void EditBrowseBox::InvalidateHandleColumn() { Rectangle aHdlFieldRect( GetFieldRectPixel( 0, 0 )); Rectangle aInvalidRect( Point(0,0), GetOutputSizePixel() ); aInvalidRect.Right() = aHdlFieldRect.Right(); Invalidate( aInvalidRect ); } //------------------------------------------------------------------------------ void EditBrowseBox::PaintTristate(OutputDevice& rDev, const Rectangle& rRect,const TriState& eState,sal_Bool _bEnabled) const { pCheckBoxPaint->GetBox().SetState(eState); pCheckBoxPaint->SetPosSizePixel(rRect.TopLeft(), rRect.GetSize()); // First update the parent, preventing that while painting this window // an update for the parent is done (because it's in the queue already) // which may lead to hiding this window immediately // #95598# comment out OJ /* if (pCheckBoxPaint->GetParent()) pCheckBoxPaint->GetParent()->Update(); */ pCheckBoxPaint->GetBox().Enable(_bEnabled); pCheckBoxPaint->Show(); pCheckBoxPaint->SetParentUpdateMode( sal_False ); pCheckBoxPaint->Update(); pCheckBoxPaint->Hide(); pCheckBoxPaint->SetParentUpdateMode( sal_True ); } //------------------------------------------------------------------------------ void EditBrowseBox::AsynchGetFocus() { if (nStartEvent) Application::RemoveUserEvent(nStartEvent); m_pFocusWhileRequest = Application::GetFocusWindow(); nStartEvent = Application::PostUserEvent(LINK(this,EditBrowseBox,StartEditHdl)); } //------------------------------------------------------------------------------ void EditBrowseBox::SetBrowserFlags(sal_Int32 nFlags) { if (m_nBrowserFlags == nFlags) return; sal_Bool RowPicturesChanges = ((m_nBrowserFlags & EBBF_NO_HANDLE_COLUMN_CONTENT) != (nFlags & EBBF_NO_HANDLE_COLUMN_CONTENT)); m_nBrowserFlags = nFlags; if (RowPicturesChanges) InvalidateStatusCell(GetCurRow()); } //------------------------------------------------------------------------------ inline void EditBrowseBox::HideAndDisable(CellControllerRef& rController) { rController->GetWindow().Hide(); rController->GetWindow().Disable(); } //------------------------------------------------------------------------------ inline void EditBrowseBox::EnableAndShow() const { Controller()->GetWindow().Enable(); Controller()->GetWindow().Show(); } //=============================================================================== DBG_NAME(CellController); //------------------------------------------------------------------------------ CellController::CellController(Window* pW) :pWindow(pW) { DBG_CTOR(CellController,NULL); DBG_ASSERT(pWindow, "CellController::CellController: missing the window!"); DBG_ASSERT(!pWindow->IsVisible(), "CellController::CellController: window should not be visible!"); } //----------------------------------------------------------------------------- CellController::~CellController() { DBG_DTOR(CellController,NULL); } //----------------------------------------------------------------------------- sal_Bool CellController::WantMouseEvent() const { return sal_False; } //----------------------------------------------------------------------------- void CellController::SetModified() { } //----------------------------------------------------------------------------- sal_Bool CellController::MoveAllowed(const KeyEvent& rEvt) const { return sal_True; } //------------------------------------------------------------------------------ EditCellController::EditCellController(Edit* pWin) :CellController(pWin) { } //----------------------------------------------------------------------------- void EditCellController::SetModified() { GetEditWindow().SetModifyFlag(); } //----------------------------------------------------------------------------- void EditCellController::ClearModified() { GetEditWindow().ClearModifyFlag(); } //------------------------------------------------------------------------------ sal_Bool EditCellController::MoveAllowed(const KeyEvent& rEvt) const { sal_Bool bResult; switch (rEvt.GetKeyCode().GetCode()) { case KEY_END: case KEY_RIGHT: { Selection aSel = GetEditWindow().GetSelection(); bResult = !aSel && aSel.Max() == GetEditWindow().GetText().Len(); } break; case KEY_HOME: case KEY_LEFT: { Selection aSel = GetEditWindow().GetSelection(); bResult = !aSel && aSel.Min() == 0; } break; default: bResult = sal_True; } return bResult; } //------------------------------------------------------------------------------ sal_Bool EditCellController::IsModified() const { return GetEditWindow().IsModified(); } //------------------------------------------------------------------------------ void EditCellController::SetModifyHdl(const Link& rLink) { GetEditWindow().SetModifyHdl(rLink); } //------------------------------------------------------------------------------ SpinCellController::SpinCellController(SpinField* pWin) :CellController(pWin) { } //----------------------------------------------------------------------------- void SpinCellController::SetModified() { GetSpinWindow().SetModifyFlag(); } //----------------------------------------------------------------------------- void SpinCellController::ClearModified() { GetSpinWindow().ClearModifyFlag(); } //------------------------------------------------------------------------------ sal_Bool SpinCellController::MoveAllowed(const KeyEvent& rEvt) const { sal_Bool bResult; switch (rEvt.GetKeyCode().GetCode()) { case KEY_END: case KEY_RIGHT: { Selection aSel = GetSpinWindow().GetSelection(); bResult = !aSel && aSel.Max() == GetSpinWindow().GetText().Len(); } break; case KEY_HOME: case KEY_LEFT: { Selection aSel = GetSpinWindow().GetSelection(); bResult = !aSel && aSel.Min() == 0; } break; default: bResult = sal_True; } return bResult; } //------------------------------------------------------------------------------ sal_Bool SpinCellController::IsModified() const { return GetSpinWindow().IsModified(); } //------------------------------------------------------------------------------ void SpinCellController::SetModifyHdl(const Link& rLink) { GetSpinWindow().SetModifyHdl(rLink); } // ....................................................................... } // namespace svt // ....................................................................... /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.14 2002/08/08 11:43:35 oj * #102008# only send a ACCESSIBLE_ACTIVE_DESCENDANT_EVENT event when we have the focus * * Revision 1.13 2002/07/26 07:44:24 bm * #101228# new browser flag EBBF_HANDLE_COLUMN_TEXT for displaying text in column * 0 in the handle column (like in the normal browse-box). * EBBF_NOROWPICTURE => EBBF_NO_HANDLE_COLUMN_CONTENT to reduce confusion now * * Revision 1.12 2002/06/21 14:04:32 oj * #99812# new helper method used to know if accessible object was already created * * Revision 1.11 2002/06/21 08:29:15 oj * #99812# correct event notifications to make the browsebox accessible * * Revision 1.10 2002/06/12 13:41:38 dr * #99812# create an acc. cell before asking for it * * Revision 1.9 2002/05/31 13:25:17 oj * #99812# accessible adjustments * * Revision 1.8 2002/04/30 15:27:44 fs * #99048# corrected column selection * * Revision 1.7 2002/04/29 14:25:33 oj * #98772# enable new imagelist * * Revision 1.6 2002/04/17 11:56:23 oj * #98286# improve accessibility * * Revision 1.5 2002/04/11 15:57:05 fs * #98483# allow for row/column selection (event when currently editing) * * Revision 1.4 2001/12/05 14:37:37 oj * #95598# PaintTristate correct for parentupdate * * Revision 1.3 2001/10/12 16:57:26 hr * #92830#: required change: std::min()/std::max() * * Revision 1.2 2001/09/28 13:00:28 hr * #65293#: gcc-3.0.1. needs lvalue * * Revision 1.1 2001/06/15 12:49:19 fs * initial checkin - moved this herein from svx/source/fmcomp/dbbrowse* * * * Revision 1.0 15.06.01 12:45:03 fs ************************************************************************/ #95826# +FormattedFieldCellController / +CellController::CommitModifications / +supending of controllers /************************************************************************* * * $RCSfile: editbrowsebox.cxx,v $ * * $Revision: 1.16 $ * * last change: $Author: fs $ $Date: 2002-10-15 07:35:52 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVTOOLS_EDITBROWSEBOX_HXX_ #include "editbrowsebox.hxx" #endif #ifndef _SVTOOLS_EDITBROWSEBOX_HRC_ #include "editbrowsebox.hrc" #endif #ifndef _APP_HXX //autogen #include <vcl/svapp.hxx> #endif #ifndef _DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _WINDOW_HXX //autogen #include <vcl/window.hxx> #endif #ifndef _EDIT_HXX //autogen #include <vcl/edit.hxx> #endif #ifndef _TOOLS_RESID_HXX //autogen #include <tools/resid.hxx> #endif #ifndef _SV_SPINFLD_HXX //autogen #include <vcl/spinfld.hxx> #endif #ifndef _SVTOOLS_SVTDATA_HXX #include "svtdata.hxx" #endif #ifndef _SVTOOLS_HRC #include "svtools.hrc" #endif #include <algorithm> #ifndef _SV_MULTISEL_HXX #include <tools/multisel.hxx> #endif #ifndef SVTOOLS_EDITBROWSEBOX_IMPL_HXX #include "editbrowseboximpl.hxx" #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_ #include <drafts/com/sun/star/accessibility/AccessibleEventId.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_ #include <drafts/com/sun/star/accessibility/XAccessible.hpp> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef _SVTOOLS_ACCESSIBILEEDITBROWSEBOXTABLECELL_HXX #include "editbrowseboxcell.hxx" #endif // ....................................................................... namespace svt { // ....................................................................... namespace { //.............................................................. sal_Bool isHiContrast(Window* _pWindow) { OSL_ENSURE(_pWindow,"Window must be not null!"); Window* pIter = _pWindow; // while( pIter && pIter->GetBackground().GetColor().GetColor() == COL_TRANSPARENT ) while( pIter ) { const Color& aColor = pIter->GetBackground().GetColor(); if ( aColor.GetColor() == COL_TRANSPARENT ) pIter = pIter->GetParent(); else break; } return pIter && pIter->GetBackground().GetColor().IsDark(); } //.............................................................. sal_uInt16 getRealGetFocusFlags( Window* _pWindow ) { sal_uInt16 nFlags = 0; while ( _pWindow && !nFlags ) { nFlags = _pWindow->GetGetFocusFlags( ); _pWindow = _pWindow->GetParent(); } return nFlags; } } using namespace drafts::com::sun::star::accessibility::AccessibleEventId; using drafts::com::sun::star::accessibility::XAccessible; using ::com::sun::star::uno::Reference; //================================================================== #define HANDLE_ID 0 //================================================================== //= EditBrowserHeader //================================================================== //------------------------------------------------------------------------------ void EditBrowserHeader::DoubleClick() { sal_uInt16 nColId = GetCurItemId(); if (nColId) { sal_uInt32 nAutoWidth = ((EditBrowseBox*)GetParent())->GetAutoColumnWidth(nColId); if (nAutoWidth != ((EditBrowseBox*)GetParent())->GetColumnWidth(nColId)) { ((EditBrowseBox*)GetParent())->SetColumnWidth(nColId, nAutoWidth); ((EditBrowseBox*)GetParent())->ColumnResized(nColId); } } } //================================================================== //= EditBrowseBox //================================================================== //------------------------------------------------------------------------------ void EditBrowseBox::BrowserMouseEventPtr::Clear() { DELETEZ(pEvent); } //------------------------------------------------------------------------------ void EditBrowseBox::BrowserMouseEventPtr::Set(const BrowserMouseEvent* pEvt, sal_Bool bIsDown) { if (pEvt == pEvent) { bDown = bIsDown; return; } Clear(); if (pEvt) { pEvent = new BrowserMouseEvent(pEvt->GetWindow(), *pEvt, pEvt->GetRow(), pEvt->GetColumn(), pEvt->GetColumnId(), pEvt->GetRect()); bDown = bIsDown; } } DBG_NAME(EditBrowseBox); void EditBrowseBox::Construct() { m_aImpl = ::std::auto_ptr<EditBrowseBoxImpl>(new EditBrowseBoxImpl()); m_aImpl->m_pFocusCell = NULL; m_aImpl->m_bHiContrast = isHiContrast(&GetDataWindow()); SetCompoundControl(sal_True); SetLineColor(Color(COL_LIGHTGRAY)); // HACK: the BrowseBox does not invalidate it's children (as it should be) // Thus we reset WB_CLIPCHILDREN, which forces the invalidation of the children WinBits aStyle = GetStyle(); if( aStyle & WB_CLIPCHILDREN ) { aStyle &= ~WB_CLIPCHILDREN; SetStyle( aStyle ); } ImplInitSettings(sal_True, sal_True, sal_True); pCheckBoxPaint = new CheckBoxControl(&GetDataWindow()); pCheckBoxPaint->SetPaintTransparent( sal_True ); pCheckBoxPaint->SetBackground(); } //------------------------------------------------------------------------------ EditBrowseBox::EditBrowseBox(Window* pParent, const ResId& rId, sal_Int32 nBrowserFlags, BrowserMode _nMode ) :BrowseBox( pParent, rId, _nMode ) ,nEditRow(-1) ,nPaintRow(-1) ,nOldEditRow(-1) ,nEditCol(0) ,nOldEditCol(0) ,bHasFocus(sal_False) ,bPaintStatus(sal_True) ,nStartEvent(0) ,nEndEvent(0) ,nCellModifiedEvent(0) ,m_nBrowserFlags(nBrowserFlags) { DBG_CTOR(EditBrowseBox,NULL); Construct(); } //================================================================== EditBrowseBox::EditBrowseBox( Window* pParent, sal_Int32 nBrowserFlags, WinBits nBits, BrowserMode _nMode ) :BrowseBox( pParent, nBits, _nMode ) ,nEditRow(-1) ,nPaintRow(-1) ,nOldEditRow(-1) ,nEditCol(0) ,nOldEditCol(0) ,bHasFocus(sal_False) ,bPaintStatus(sal_True) ,nStartEvent(0) ,nEndEvent(0) ,nCellModifiedEvent(0) ,pHeader(NULL) ,m_nBrowserFlags(nBrowserFlags) { DBG_CTOR(EditBrowseBox,NULL); Construct(); } //------------------------------------------------------------------------------ void EditBrowseBox::Init() { // spaetes Construieren, } //------------------------------------------------------------------------------ EditBrowseBox::~EditBrowseBox() { if (nStartEvent) Application::RemoveUserEvent(nStartEvent); if (nEndEvent) Application::RemoveUserEvent(nEndEvent); if (nCellModifiedEvent) Application::RemoveUserEvent(nCellModifiedEvent); delete pCheckBoxPaint; DBG_DTOR(EditBrowseBox,NULL); } //------------------------------------------------------------------------------ void EditBrowseBox::RemoveRows() { BrowseBox::Clear(); nOldEditRow = nEditRow = nPaintRow = -1; nEditCol = nOldEditCol = 0; } //------------------------------------------------------------------------------ BrowserHeader* EditBrowseBox::CreateHeaderBar(BrowseBox* pParent) { pHeader = imp_CreateHeaderBar(pParent); if (!IsUpdateMode()) pHeader->SetUpdateMode(sal_False); return pHeader; } //------------------------------------------------------------------------------ BrowserHeader* EditBrowseBox::imp_CreateHeaderBar(BrowseBox* pParent) { return new EditBrowserHeader(pParent); } //------------------------------------------------------------------------------ void EditBrowseBox::LoseFocus() { BrowseBox::LoseFocus(); DetermineFocus( 0 ); } //------------------------------------------------------------------------------ void EditBrowseBox::GetFocus() { BrowseBox::GetFocus(); // This should handle the case that the BrowseBox (or one of it's children) // gets the focus from outside by pressing Tab if (IsEditing() && Controller()->GetWindow().IsVisible()) Controller()->GetWindow().GrabFocus(); DetermineFocus( getRealGetFocusFlags( this ) ); } //------------------------------------------------------------------------------ sal_Bool EditBrowseBox::SeekRow(long nRow) { nPaintRow = nRow; return sal_True; } //------------------------------------------------------------------------------ IMPL_LINK(EditBrowseBox, StartEditHdl, void*, EMPTYTAG) { nStartEvent = 0; if (IsEditing()) { EnableAndShow(); if (!aController->GetWindow().HasFocus() && (m_pFocusWhileRequest == Application::GetFocusWindow())) aController->GetWindow().GrabFocus(); } return 0; } //------------------------------------------------------------------------------ void EditBrowseBox::PaintField( OutputDevice& rDev, const Rectangle& rRect, sal_uInt16 nColumnId ) const { if (nColumnId == HANDLE_ID) { if (bPaintStatus) PaintStatusCell(rDev, rRect); } else { // don't paint the current cell if (&rDev == &GetDataWindow()) // but only if we're painting onto our data win (which is the usual painting) if (nPaintRow == nEditRow) { if (IsEditing() && nEditCol == nColumnId && aController->GetWindow().IsVisible()) return; } PaintCell(rDev, rRect, nColumnId); } } //------------------------------------------------------------------------------ Image EditBrowseBox::GetImage(RowStatus eStatus) const { sal_Bool bHiContrast = isHiContrast(&GetDataWindow()); if ( !m_aStatusImages.GetImageCount() || (bHiContrast != m_aImpl->m_bHiContrast) ) { m_aImpl->m_bHiContrast = bHiContrast; const_cast<EditBrowseBox*>(this)->m_aStatusImages = ImageList(SvtResId(bHiContrast ? RID_SVTOOLS_IMAGELIST_EDITBWSEBOX_H : RID_SVTOOLS_IMAGELIST_EDITBROWSEBOX)); } Image aImage; switch (eStatus) { case CURRENT: aImage = m_aStatusImages.GetImage(IMG_EBB_CURRENT); break; case CURRENTNEW: aImage = m_aStatusImages.GetImage(IMG_EBB_CURRENTNEW); break; case MODIFIED: aImage = m_aStatusImages.GetImage(IMG_EBB_MODIFIED); break; case NEW: aImage = m_aStatusImages.GetImage(IMG_EBB_NEW); break; case DELETED: aImage = m_aStatusImages.GetImage(IMG_EBB_DELETED); break; case PRIMARYKEY: aImage = m_aStatusImages.GetImage(IMG_EBB_PRIMARYKEY); break; case CURRENT_PRIMARYKEY: aImage = m_aStatusImages.GetImage(IMG_EBB_CURRENT_PRIMARYKEY); break; case FILTER: aImage = m_aStatusImages.GetImage(IMG_EBB_FILTER); break; } return aImage; } //------------------------------------------------------------------------------ void EditBrowseBox::PaintStatusCell(OutputDevice& rDev, const Rectangle& rRect) const { if (nPaintRow < 0) return; RowStatus eStatus = GetRowStatus( nPaintRow ); sal_Int32 nBrowserFlags = GetBrowserFlags(); if (nBrowserFlags & EBBF_NO_HANDLE_COLUMN_CONTENT) return; // draw the text of the header column if (nBrowserFlags & EBBF_HANDLE_COLUMN_TEXT ) { rDev.DrawText( rRect, GetCellText( nPaintRow, 0 ), TEXT_DRAW_CENTER | TEXT_DRAW_VCENTER | TEXT_DRAW_CLIP ); } // draw an image else if (eStatus != CLEAN && rDev.GetOutDevType() == OUTDEV_WINDOW) { Image aImage(GetImage(eStatus)); // calc the image position Size aImageSize(aImage.GetSizePixel()); aImageSize.Width() = CalcZoom(aImageSize.Width()); aImageSize.Height() = CalcZoom(aImageSize.Height()); Point aPos(rRect.TopLeft()); if (aImageSize.Width() > rRect.GetWidth() || aImageSize.Height() > rRect.GetHeight()) rDev.SetClipRegion(rRect); if (aImageSize.Width() < rRect.GetWidth()) aPos.X() += (rRect.GetWidth() - aImageSize.Width()) / 2; if (IsZoom()) rDev.DrawImage(aPos, aImageSize, aImage, 0); else rDev.DrawImage(aPos, aImage, 0); if (rDev.IsClipRegion()) rDev.SetClipRegion(); } } //------------------------------------------------------------------------------ EditBrowseBox::RowStatus EditBrowseBox::GetRowStatus(long nRow) const { return CLEAN; } //------------------------------------------------------------------------------ void EditBrowseBox::KeyInput( const KeyEvent& rEvt ) { sal_uInt16 nCode = rEvt.GetKeyCode().GetCode(); sal_Bool bShift = rEvt.GetKeyCode().IsShift(); sal_Bool bCtrl = rEvt.GetKeyCode().IsMod1(); switch (nCode) { case KEY_RETURN: if (!bCtrl && !bShift && IsTabAllowed(sal_True)) { Dispatch(BROWSER_CURSORRIGHT); } else BrowseBox::KeyInput(rEvt); return; case KEY_TAB: if (!bCtrl && !bShift) { if (IsTabAllowed(sal_True)) Dispatch(BROWSER_CURSORRIGHT); else // do NOT call BrowseBox::KeyInput : this would handle the tab, but we already now // that tab isn't allowed here. So give the Control class a chance Control::KeyInput(rEvt); return; } else if (!bCtrl && bShift) { if (IsTabAllowed(sal_False)) Dispatch(BROWSER_CURSORLEFT); else // do NOT call BrowseBox::KeyInput : this would handle the tab, but we already now // that tab isn't allowed here. So give the Control class a chance Control::KeyInput(rEvt); return; } default: BrowseBox::KeyInput(rEvt); } } //------------------------------------------------------------------------------ void EditBrowseBox::MouseButtonDown(const BrowserMouseEvent& rEvt) { sal_uInt16 nColPos = GetColumnPos( rEvt.GetColumnId() ); long nRow = rEvt.GetRow(); // absorb double clicks if (rEvt.GetClicks() > 1 && rEvt.GetRow() >= 0) return; // change to a new position if (IsEditing() && (nColPos != nEditCol || nRow != nEditRow) && (nColPos != BROWSER_INVALIDID) && (nRow < GetRowCount())) { CellControllerRef aController(Controller()); HideAndDisable(aController); } // we are about to leave the current cell. If there is a "this cell has been modified" notification // pending (asynchronously), this may be deadly -> do it synchronously // 95826 - 2002-10-14 - fs@openoffice.org if ( nCellModifiedEvent ) { Application::RemoveUserEvent( nCellModifiedEvent ); nCellModifiedEvent = 0; LINK( this, EditBrowseBox, CellModifiedHdl ).Call( NULL ); } if (0 == rEvt.GetColumnId()) { // it was the handle column. save the current cell content if necessary // (clicking on the handle column results in selecting the current row) // 23.01.2001 - 82797 - FS if (IsEditing() && aController->IsModified()) SaveModified(); } aMouseEvent.Set(&rEvt,sal_True); BrowseBox::MouseButtonDown(rEvt); aMouseEvent.Clear(); if (0 != (m_nBrowserFlags & EBBF_ACTIVATE_ON_BUTTONDOWN)) { // the base class does not travel upon MouseButtonDown, but implActivateCellOnMouseEvent assumes we traveled ... GoToRowColumnId( rEvt.GetRow(), rEvt.GetColumnId() ); if (rEvt.GetRow() >= 0) implActivateCellOnMouseEvent(rEvt, sal_False); } } //------------------------------------------------------------------------------ void EditBrowseBox::MouseButtonUp( const BrowserMouseEvent& rEvt ) { // unused variables. Sideeffects? sal_uInt16 nColPos = GetColumnPos( rEvt.GetColumnId() ); long nRow = rEvt.GetRow(); // absorb double clicks if (rEvt.GetClicks() > 1 && rEvt.GetRow() >= 0) return; aMouseEvent.Set(&rEvt,sal_False); BrowseBox::MouseButtonUp(rEvt); aMouseEvent.Clear(); if (0 == (m_nBrowserFlags & EBBF_ACTIVATE_ON_BUTTONDOWN)) if (rEvt.GetRow() >= 0) implActivateCellOnMouseEvent(rEvt, sal_True); } //------------------------------------------------------------------------------ void EditBrowseBox::implActivateCellOnMouseEvent(const BrowserMouseEvent& _rEvt, sal_Bool _bUp) { if (!IsEditing()) ActivateCell(); else if (IsEditing() && !aController->GetWindow().IsEnabled()) DeactivateCell(); else if (IsEditing() && !aController->GetWindow().HasChildPathFocus()) AsynchGetFocus(); if (IsEditing() && aController->GetWindow().IsEnabled() && aController->WantMouseEvent()) { // forwards the event to the control // If the field has been moved previously, we have to adjust the position aController->GetWindow().GrabFocus(); // the position of the event relative to the controller's window Point aPos = _rEvt.GetPosPixel() - _rEvt.GetRect().TopLeft(); // the (child) window which should really get the event Window* pRealHandler = aController->GetWindow().FindWindow(aPos); if (pRealHandler) // the coords relative to this real handler aPos -= pRealHandler->GetPosPixel(); else pRealHandler = &aController->GetWindow(); // the faked event MouseEvent aEvent(aPos, _rEvt.GetClicks(), _rEvt.GetMode(), _rEvt.GetButtons(), _rEvt.GetModifier()); pRealHandler->MouseButtonDown(aEvent); if (_bUp) pRealHandler->MouseButtonUp(aEvent); Window *pWin = &aController->GetWindow(); if (!pWin->IsTracking()) { for (pWin = pWin->GetWindow(WINDOW_FIRSTCHILD); pWin && !pWin->IsTracking(); pWin = pWin->GetWindow(WINDOW_NEXT)) { } } if (pWin && pWin->IsTracking()) pWin->EndTracking(); } } //------------------------------------------------------------------------------ void EditBrowseBox::Dispatch( sal_uInt16 _nId ) { if ( _nId == BROWSER_ENHANCESELECTION ) { // this is a workaround for the bug in the base class: // if the row selection is to be extended (which is what BROWSER_ENHANCESELECTION tells us) // then the base class does not revert any column selections, while, for doing a "simple" // selection (BROWSER_SELECT), it does. In fact, it does not only revert the col selection then, // but also any current row selections. // This clearly tells me that the both ids are for row selection only - there this behaviour does // make sense. // But here, where we have column selection, too, we take care of this ourself. if ( GetSelectColumnCount( ) ) { while ( GetSelectColumnCount( ) ) SelectColumnPos( FirstSelectedColumn(), sal_False ); Select(); } } BrowseBox::Dispatch( _nId ); } //------------------------------------------------------------------------------ long EditBrowseBox::PreNotify(NotifyEvent& rEvt) { switch (rEvt.GetType()) { case EVENT_KEYINPUT: if ( (IsEditing() && Controller()->GetWindow().HasChildPathFocus()) || rEvt.GetWindow() == &GetDataWindow() || (!IsEditing() && HasChildPathFocus()) ) { const KeyEvent* pKeyEvent = rEvt.GetKeyEvent(); sal_uInt16 nCode = pKeyEvent->GetKeyCode().GetCode(); sal_Bool bShift = pKeyEvent->GetKeyCode().IsShift(); sal_Bool bCtrl = pKeyEvent->GetKeyCode().IsMod1(); sal_Bool bAlt = pKeyEvent->GetKeyCode().IsMod2(); sal_Bool bSelect= sal_False; sal_Bool bNonEditOnly = sal_False; sal_uInt16 nId = BROWSER_NONE; if (!bAlt && !bCtrl && !bShift ) switch ( nCode ) { case KEY_DOWN: nId = BROWSER_CURSORDOWN; break; case KEY_UP: nId = BROWSER_CURSORUP; break; case KEY_PAGEDOWN: nId = BROWSER_CURSORPAGEDOWN; break; case KEY_PAGEUP: nId = BROWSER_CURSORPAGEUP; break; case KEY_HOME: nId = BROWSER_CURSORHOME; break; case KEY_END: nId = BROWSER_CURSOREND; break; case KEY_TAB: // ask if traveling to the next cell is allowed if (IsTabAllowed(sal_True)) nId = BROWSER_CURSORRIGHT; break; case KEY_RETURN: // save the cell content (if necessary) if (IsEditing() && aController->IsModified() && !((EditBrowseBox *) this)->SaveModified()) { // maybe we're not visible ... EnableAndShow(); aController->GetWindow().GrabFocus(); return 1; } // ask if traveling to the next cell is allowed if (IsTabAllowed(sal_True)) nId = BROWSER_CURSORRIGHT; break; case KEY_RIGHT: nId = BROWSER_CURSORRIGHT; break; case KEY_LEFT: nId = BROWSER_CURSORLEFT; break; case KEY_SPACE: nId = BROWSER_SELECT; bNonEditOnly = bSelect = sal_True;break; } if ( !bAlt && !bCtrl && bShift ) switch ( nCode ) { case KEY_DOWN: nId = BROWSER_SELECTDOWN; bSelect = sal_True;break; case KEY_UP: nId = BROWSER_SELECTUP; bSelect = sal_True;break; case KEY_HOME: nId = BROWSER_SELECTHOME; bSelect = sal_True;break; case KEY_END: nId = BROWSER_SELECTEND; bSelect = sal_True;break; case KEY_SPACE: nId = BROWSER_SELECTCOLUMN; bSelect = sal_True; break; case KEY_TAB: if (IsTabAllowed(sal_False)) nId = BROWSER_CURSORLEFT; break; } if ( !bAlt && bCtrl && !bShift ) switch ( nCode ) { case KEY_DOWN: nId = BROWSER_SCROLLUP; break; case KEY_UP: nId = BROWSER_SCROLLDOWN; break; case KEY_PAGEDOWN: nId = BROWSER_CURSORENDOFFILE; break; case KEY_PAGEUP: nId = BROWSER_CURSORTOPOFFILE; break; case KEY_HOME: nId = BROWSER_CURSORTOPOFSCREEN; break; case KEY_END: nId = BROWSER_CURSORENDOFSCREEN; break; case KEY_SPACE: nId = BROWSER_ENHANCESELECTION; bSelect = sal_True;break; } if ( ( nId != BROWSER_NONE ) && ( !IsEditing() || ( !bNonEditOnly && aController->MoveAllowed( *pKeyEvent ) ) ) ) { if (nId == BROWSER_SELECT) { // save the cell content (if necessary) if (IsEditing() && aController->IsModified() && !((EditBrowseBox *) this)->SaveModified()) { // maybe we're not visible ... EnableAndShow(); aController->GetWindow().GrabFocus(); return 1; } } Dispatch(nId); if (bSelect && (GetSelectRowCount() || GetSelection() != NULL)) DeactivateCell(); return 1; } } } return BrowseBox::PreNotify(rEvt); } //------------------------------------------------------------------------------ sal_Bool EditBrowseBox::IsTabAllowed(sal_Bool bRight) const { return sal_True; } //------------------------------------------------------------------------------ long EditBrowseBox::Notify(NotifyEvent& rEvt) { switch (rEvt.GetType()) { case EVENT_GETFOCUS: DetermineFocus( getRealGetFocusFlags( this ) ); break; case EVENT_LOSEFOCUS: DetermineFocus( 0 ); break; } return BrowseBox::Notify(rEvt); } //------------------------------------------------------------------------------ void EditBrowseBox::StateChanged( StateChangedType nType ) { BrowseBox::StateChanged( nType ); if ( nType == STATE_CHANGE_ZOOM ) { ImplInitSettings( sal_True, sal_False, sal_False ); if (IsEditing()) { DeactivateCell(); ActivateCell(); } } else if ( nType == STATE_CHANGE_CONTROLFONT ) { ImplInitSettings( sal_True, sal_False, sal_False ); Invalidate(); } else if ( nType == STATE_CHANGE_CONTROLFOREGROUND ) { ImplInitSettings( sal_False, sal_True, sal_False ); Invalidate(); } else if ( nType == STATE_CHANGE_CONTROLBACKGROUND ) { ImplInitSettings( sal_False, sal_False, sal_True ); Invalidate(); } else if (nType == STATE_CHANGE_STYLE) { WinBits nStyle = GetStyle(); if (!(nStyle & WB_NOTABSTOP) ) nStyle |= WB_TABSTOP; SetStyle(nStyle); } } //------------------------------------------------------------------------------ void EditBrowseBox::DataChanged( const DataChangedEvent& rDCEvt ) { BrowseBox::DataChanged( rDCEvt ); if ((( rDCEvt.GetType() == DATACHANGED_SETTINGS ) || ( rDCEvt.GetType() == DATACHANGED_DISPLAY )) && ( rDCEvt.GetFlags() & SETTINGS_STYLE )) { ImplInitSettings( sal_True, sal_True, sal_True ); Invalidate(); } } //------------------------------------------------------------------------------ void EditBrowseBox::ImplInitSettings( sal_Bool bFont, sal_Bool bForeground, sal_Bool bBackground ) { const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings(); if (bFont) { Font aFont = rStyleSettings.GetFieldFont(); if (IsControlFont()) { GetDataWindow().SetControlFont(GetControlFont()); aFont.Merge(GetControlFont()); } else GetDataWindow().SetControlFont(); GetDataWindow().SetZoomedPointFont(aFont); } if ( bFont || bForeground ) { Color aTextColor = rStyleSettings.GetFieldTextColor(); if (IsControlForeground()) { aTextColor = GetControlForeground(); GetDataWindow().SetControlForeground(aTextColor); } else GetDataWindow().SetControlForeground(); GetDataWindow().SetTextColor( aTextColor ); } if ( bBackground ) { if (GetDataWindow().IsControlBackground()) { GetDataWindow().SetControlBackground(GetControlBackground()); GetDataWindow().SetBackground(GetDataWindow().GetControlBackground()); GetDataWindow().SetFillColor(GetDataWindow().GetControlBackground()); } else { GetDataWindow().SetControlBackground(); GetDataWindow().SetBackground( rStyleSettings.GetFieldColor() ); GetDataWindow().SetFillColor( rStyleSettings.GetFieldColor() ); } } } //------------------------------------------------------------------------------ sal_Bool EditBrowseBox::IsCursorMoveAllowed(long nNewRow, sal_uInt16 nNewColId) const { sal_uInt16 nInfo = 0; if (GetSelectColumnCount() || (aMouseEvent.Is() && aMouseEvent->GetRow() < 0)) nInfo |= COLSELECT; if ((GetSelection() != NULL && GetSelectRowCount()) || (aMouseEvent.Is() && aMouseEvent->GetColumnId() == HANDLE_ID)) nInfo |= ROWSELECT; if (!nInfo && nNewRow != nEditRow) nInfo |= ROWCHANGE; if (!nInfo && nNewColId != nEditCol) nInfo |= COLCHANGE; if (nInfo == 0) // nothing happened return sal_True; // save the cell content if (IsEditing() && aController->IsModified() && !((EditBrowseBox *) this)->SaveModified()) { // maybe we're not visible ... EnableAndShow(); aController->GetWindow().GrabFocus(); return sal_False; } EditBrowseBox * pTHIS = (EditBrowseBox *) this; // save the cell content if // a) a selection is beeing made // b) the row is changing if (IsModified() && (nInfo & (ROWCHANGE | COLSELECT | ROWSELECT)) && !pTHIS->SaveRow()) { if (nInfo & COLSELECT || nInfo & ROWSELECT) { // cancel selected pTHIS->SetNoSelection(); } if (IsEditing()) { if (!Controller()->GetWindow().IsVisible()) { EnableAndShow(); } aController->GetWindow().GrabFocus(); } return sal_False; } if (nNewRow != nEditRow) { Window& rWindow = GetDataWindow(); // don't paint too much // update the status immediatly if possible if ((nEditRow >= 0) && (GetBrowserFlags() & EBBF_NO_HANDLE_COLUMN_CONTENT) == 0) { Rectangle aRect = GetFieldRectPixel(nEditRow, 0, sal_False ); // status cell should be painted if and only if text is displayed // note: bPaintStatus is mutable, but Solaris has problems with assigning // probably because it is part of a bitfield pTHIS->bPaintStatus = static_cast< sal_Bool > (( GetBrowserFlags() & EBBF_HANDLE_COLUMN_TEXT ) == EBBF_HANDLE_COLUMN_TEXT ); rWindow.Paint(aRect); pTHIS->bPaintStatus = sal_True; } // don't paint during row change rWindow.EnablePaint(sal_False); // the last veto chance for derived classes if (!pTHIS->CursorMoving(nNewRow, nNewColId)) { pTHIS->InvalidateStatusCell(nEditRow); rWindow.EnablePaint(sal_True); return sal_False; } else return sal_True; } else return pTHIS->CursorMoving(nNewRow, nNewColId); } //------------------------------------------------------------------------------ void EditBrowseBox::ColumnMoved(sal_uInt16 nId) { BrowseBox::ColumnMoved(nId); if (IsEditing()) { Rectangle aRect( GetCellRect(nEditRow, nEditCol, sal_False)); CellControllerRef aControllerRef = Controller(); ResizeController(aControllerRef, aRect); Controller()->GetWindow().GrabFocus(); } } //------------------------------------------------------------------------------ sal_Bool EditBrowseBox::SaveRow() { return sal_True; } //------------------------------------------------------------------------------ sal_Bool EditBrowseBox::CursorMoving(long nNewRow, sal_uInt16 nNewCol) { ((EditBrowseBox *) this)->DeactivateCell(sal_False); return sal_True; } //------------------------------------------------------------------------------ void EditBrowseBox::CursorMoved() { long nNewRow = GetCurRow(); if (nEditRow != nNewRow) { if ((GetBrowserFlags() & EBBF_NO_HANDLE_COLUMN_CONTENT) == 0) InvalidateStatusCell(nNewRow); nEditRow = nNewRow; } ActivateCell(); GetDataWindow().EnablePaint(sal_True); // should not be called here because the descant event is not needed here //BrowseBox::CursorMoved(); } //------------------------------------------------------------------------------ void EditBrowseBox::EndScroll() { if (IsEditing()) { Rectangle aRect = GetCellRect(nEditRow, nEditCol, sal_False); ResizeController(aController,aRect); AsynchGetFocus(); } BrowseBox::EndScroll(); } //------------------------------------------------------------------------------ void EditBrowseBox::ActivateCell(long nRow, sal_uInt16 nCol, sal_Bool bCellFocus) { if (IsEditing()) return; nEditCol = nCol; if ((GetSelectRowCount() && GetSelection() != NULL) || GetSelectColumnCount() || (aMouseEvent.Is() && (aMouseEvent.IsDown() || aMouseEvent->GetClicks() > 1))) // bei MouseDown passiert noch nichts { return; } if (nEditRow >= 0 && nEditCol > HANDLE_ID) { aController = GetController(nRow, nCol); if (aController.Is()) { Rectangle aRect( GetCellRect(nEditRow, nEditCol, sal_False)); ResizeController(aController, aRect); InitController(aController, nEditRow, nEditCol); aController->ClearModified(); aController->SetModifyHdl(LINK(this,EditBrowseBox,ModifyHdl)); EnableAndShow(); // activate the cell only of the browser has the focus if ( bHasFocus && bCellFocus ) { CreateAccessibleControl(0); AsynchGetFocus(); } } else if ( isAccessibleCreated() && HasFocus() ) commitTableEvent(ACCESSIBLE_ACTIVE_DESCENDANT_EVENT, com::sun::star::uno::makeAny(CreateAccessibleCell(nRow,nCol)), com::sun::star::uno::Any()); } } //------------------------------------------------------------------------------ void EditBrowseBox::DeactivateCell(sal_Bool bUpdate) { if (IsEditing()) { commitBrowseBoxEvent(ACCESSIBLE_CHILD_EVENT,com::sun::star::uno::Any(),com::sun::star::uno::makeAny(m_aImpl->m_xActiveCell)); m_aImpl->disposeCell(); m_aImpl->m_pFocusCell = NULL; m_aImpl->m_xActiveCell = NULL; aOldController = aController; aController.Clear(); // reset the modify handler aOldController->SetModifyHdl(Link()); if (bHasFocus) GrabFocus(); // ensure that we have (and keep) the focus HideAndDisable(aOldController); // update if requested if (bUpdate) Update(); nOldEditCol = nEditCol; nOldEditRow = nEditRow; // release the controller (asynchronously) if (nEndEvent) Application::RemoveUserEvent(nEndEvent); nEndEvent = Application::PostUserEvent(LINK(this,EditBrowseBox,EndEditHdl)); } } //------------------------------------------------------------------------------ Rectangle EditBrowseBox::GetCellRect(long nRow, sal_uInt16 nColId, sal_Bool bRel) const { Rectangle aRect( GetFieldRectPixel(nRow, nColId, bRel)); if ((GetMode() & BROWSER_CURSOR_WO_FOCUS) == BROWSER_CURSOR_WO_FOCUS) { aRect.Top() += 1; aRect.Bottom() -= 1; } return aRect; } //------------------------------------------------------------------------------ IMPL_LINK(EditBrowseBox, EndEditHdl, void*, EMPTYTAG) { nEndEvent = 0; ReleaseController(aOldController, nOldEditRow, nOldEditCol); aOldController = CellControllerRef(); nOldEditRow = -1; nOldEditCol = 0; return 0; } //------------------------------------------------------------------------------ IMPL_LINK(EditBrowseBox, ModifyHdl, void*, EMPTYTAG) { if (nCellModifiedEvent) Application::RemoveUserEvent(nCellModifiedEvent); nCellModifiedEvent = Application::PostUserEvent(LINK(this,EditBrowseBox,CellModifiedHdl)); return 0; } //------------------------------------------------------------------------------ IMPL_LINK(EditBrowseBox, CellModifiedHdl, void*, EMPTYTAG) { nCellModifiedEvent = 0; CellModified(); return 0; } //------------------------------------------------------------------------------ void EditBrowseBox::ColumnResized( sal_uInt16 nColId ) { if (IsEditing()) { Rectangle aRect( GetCellRect(nEditRow, nEditCol, sal_False)); CellControllerRef aControllerRef = Controller(); ResizeController(aControllerRef, aRect); Controller()->GetWindow().GrabFocus(); } } //------------------------------------------------------------------------------ sal_uInt16 EditBrowseBox::GetDefaultColumnWidth(const String& rName) const { return GetDataWindow().GetTextWidth(rName) + GetDataWindow().GetTextWidth('0') * 4; } //------------------------------------------------------------------------------ void EditBrowseBox::InsertHandleColumn(sal_uInt16 nWidth) { if (!nWidth) nWidth = GetDefaultColumnWidth(String()); BrowseBox::InsertHandleColumn(nWidth, sal_True); } //------------------------------------------------------------------------------ sal_uInt16 EditBrowseBox::AppendColumn(const String& rName, sal_uInt16 nWidth, sal_uInt16 nPos, sal_uInt16 nId) { if (nId == (sal_uInt16)-1) { // look for the next free id for (nId = ColCount(); nId > 0 && GetColumnPos(nId) != BROWSER_INVALIDID; nId--) ; if (!nId) { // if there is no handle column // increment the id if (!ColCount() || GetColumnId(0)) nId = ColCount() + 1; } } DBG_ASSERT(nId, "EditBrowseBox::AppendColumn: invalid id!"); if (!nWidth) nWidth = GetDefaultColumnWidth(rName); InsertDataColumn(nId, rName, nWidth, (HIB_CENTER | HIB_VCENTER | HIB_CLICKABLE), nPos); return nId; } //------------------------------------------------------------------------------ void EditBrowseBox::Resize() { BrowseBox::Resize(); // if the window is smaller than "title line height" + "control area", // do nothing if (GetOutputSizePixel().Height() < (GetControlArea().GetHeight() + GetDataWindow().GetPosPixel().Y())) return; // the size of the control area Point aPoint(GetControlArea().TopLeft()); sal_uInt16 nX = (sal_uInt16)aPoint.X(); ArrangeControls(nX, (sal_uInt16)aPoint.Y()); if (!nX) nX = 0; ReserveControlArea((sal_uInt16)nX); } //------------------------------------------------------------------------------ void EditBrowseBox::ArrangeControls(sal_uInt16& nX, sal_uInt16 nY) { } //------------------------------------------------------------------------------ CellController* EditBrowseBox::GetController(long, sal_uInt16) { return NULL; } //----------------------------------------------------------------------------- void EditBrowseBox::ResizeController(CellControllerRef& rController, const Rectangle& rRect) { rController->GetWindow().SetPosSizePixel(rRect.TopLeft(), rRect.GetSize()); } //------------------------------------------------------------------------------ void EditBrowseBox::InitController(CellControllerRef& rController, long nRow, sal_uInt16 nCol) { } //------------------------------------------------------------------------------ void EditBrowseBox::ReleaseController(CellControllerRef& rController, long nRow, sal_uInt16 nCol) { } //------------------------------------------------------------------------------ void EditBrowseBox::CellModified() { } //------------------------------------------------------------------------------ sal_Bool EditBrowseBox::SaveModified() { return sal_True; } //------------------------------------------------------------------------------ void EditBrowseBox::DoubleClick(const BrowserMouseEvent& rEvt) { // when double clicking on the column, the optimum size will be calculated sal_uInt16 nColId = rEvt.GetColumnId(); if (nColId != HANDLE_ID) SetColumnWidth(nColId, GetAutoColumnWidth(nColId)); } //------------------------------------------------------------------------------ sal_uInt32 EditBrowseBox::GetAutoColumnWidth(sal_uInt16 nColId) { sal_uInt32 nCurColWidth = GetColumnWidth(nColId); sal_uInt32 nMinColWidth = CalcZoom(20); // minimum sal_uInt32 nNewColWidth = nMinColWidth; long nMaxRows = Min(long(GetVisibleRows()), GetRowCount()); long nLastVisRow = GetTopRow() + nMaxRows - 1; if (GetTopRow() <= nLastVisRow) // calc the column with using the cell contents { for (long i = GetTopRow(); i <= nLastVisRow; ++i) nNewColWidth = std::max(nNewColWidth,GetTotalCellWidth(i,nColId) + 12); if (nNewColWidth == nCurColWidth) // size has not changed nNewColWidth = GetDefaultColumnWidth(GetColumnTitle(nColId)); } else nNewColWidth = GetDefaultColumnWidth(GetColumnTitle(nColId)); return nNewColWidth; } //------------------------------------------------------------------------------ sal_uInt32 EditBrowseBox::GetTotalCellWidth(long nRow, sal_uInt16 nColId) { return 0; } //------------------------------------------------------------------------------ void EditBrowseBox::InvalidateHandleColumn() { Rectangle aHdlFieldRect( GetFieldRectPixel( 0, 0 )); Rectangle aInvalidRect( Point(0,0), GetOutputSizePixel() ); aInvalidRect.Right() = aHdlFieldRect.Right(); Invalidate( aInvalidRect ); } //------------------------------------------------------------------------------ void EditBrowseBox::PaintTristate(OutputDevice& rDev, const Rectangle& rRect,const TriState& eState,sal_Bool _bEnabled) const { pCheckBoxPaint->GetBox().SetState(eState); pCheckBoxPaint->SetPosSizePixel(rRect.TopLeft(), rRect.GetSize()); // First update the parent, preventing that while painting this window // an update for the parent is done (because it's in the queue already) // which may lead to hiding this window immediately // #95598# comment out OJ /* if (pCheckBoxPaint->GetParent()) pCheckBoxPaint->GetParent()->Update(); */ pCheckBoxPaint->GetBox().Enable(_bEnabled); pCheckBoxPaint->Show(); pCheckBoxPaint->SetParentUpdateMode( sal_False ); pCheckBoxPaint->Update(); pCheckBoxPaint->Hide(); pCheckBoxPaint->SetParentUpdateMode( sal_True ); } //------------------------------------------------------------------------------ void EditBrowseBox::AsynchGetFocus() { if (nStartEvent) Application::RemoveUserEvent(nStartEvent); m_pFocusWhileRequest = Application::GetFocusWindow(); nStartEvent = Application::PostUserEvent(LINK(this,EditBrowseBox,StartEditHdl)); } //------------------------------------------------------------------------------ void EditBrowseBox::SetBrowserFlags(sal_Int32 nFlags) { if (m_nBrowserFlags == nFlags) return; sal_Bool RowPicturesChanges = ((m_nBrowserFlags & EBBF_NO_HANDLE_COLUMN_CONTENT) != (nFlags & EBBF_NO_HANDLE_COLUMN_CONTENT)); m_nBrowserFlags = nFlags; if (RowPicturesChanges) InvalidateStatusCell(GetCurRow()); } //------------------------------------------------------------------------------ inline void EditBrowseBox::HideAndDisable(CellControllerRef& rController) { rController->suspend(); } //------------------------------------------------------------------------------ inline void EditBrowseBox::EnableAndShow() const { Controller()->resume(); } //=============================================================================== DBG_NAME(CellController); //------------------------------------------------------------------------------ CellController::CellController(Window* pW) :pWindow( pW ) ,bSuspended( sal_True ) { DBG_CTOR(CellController,NULL); DBG_ASSERT(pWindow, "CellController::CellController: missing the window!"); DBG_ASSERT(!pWindow->IsVisible(), "CellController::CellController: window should not be visible!"); } //----------------------------------------------------------------------------- CellController::~CellController() { DBG_DTOR(CellController,NULL); } //----------------------------------------------------------------------------- void CellController::suspend( ) { DBG_ASSERT( bSuspended == !GetWindow().IsVisible(), "CellController::suspend: inconsistence!" ); if ( !isSuspended( ) ) { CommitModifications(); GetWindow().Hide( ); GetWindow().Disable( ); bSuspended = sal_True; } } //----------------------------------------------------------------------------- void CellController::resume( ) { DBG_ASSERT( bSuspended == !GetWindow().IsVisible(), "CellController::resume: inconsistence!" ); if ( isSuspended( ) ) { GetWindow().Enable( ); GetWindow().Show( ); bSuspended = sal_False; } } //----------------------------------------------------------------------------- void CellController::CommitModifications() { // nothing to do in this base class } //----------------------------------------------------------------------------- sal_Bool CellController::WantMouseEvent() const { return sal_False; } //----------------------------------------------------------------------------- void CellController::SetModified() { } //----------------------------------------------------------------------------- sal_Bool CellController::MoveAllowed(const KeyEvent& rEvt) const { return sal_True; } // ....................................................................... } // namespace svt // ....................................................................... /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.15 2002/09/10 14:32:09 fs * #102119# added optional smart tab traveling (focus first/last cell when getting the focus) * * Revision 1.14 2002/08/08 11:43:35 oj * #102008# only send a ACCESSIBLE_ACTIVE_DESCENDANT_EVENT event when we have the focus * * Revision 1.13 2002/07/26 07:44:24 bm * #101228# new browser flag EBBF_HANDLE_COLUMN_TEXT for displaying text in column * 0 in the handle column (like in the normal browse-box). * EBBF_NOROWPICTURE => EBBF_NO_HANDLE_COLUMN_CONTENT to reduce confusion now * * Revision 1.12 2002/06/21 14:04:32 oj * #99812# new helper method used to know if accessible object was already created * * Revision 1.11 2002/06/21 08:29:15 oj * #99812# correct event notifications to make the browsebox accessible * * Revision 1.10 2002/06/12 13:41:38 dr * #99812# create an acc. cell before asking for it * * Revision 1.9 2002/05/31 13:25:17 oj * #99812# accessible adjustments * * Revision 1.8 2002/04/30 15:27:44 fs * #99048# corrected column selection * * Revision 1.7 2002/04/29 14:25:33 oj * #98772# enable new imagelist * * Revision 1.6 2002/04/17 11:56:23 oj * #98286# improve accessibility * * Revision 1.5 2002/04/11 15:57:05 fs * #98483# allow for row/column selection (event when currently editing) * * Revision 1.4 2001/12/05 14:37:37 oj * #95598# PaintTristate correct for parentupdate * * Revision 1.3 2001/10/12 16:57:26 hr * #92830#: required change: std::min()/std::max() * * Revision 1.2 2001/09/28 13:00:28 hr * #65293#: gcc-3.0.1. needs lvalue * * Revision 1.1 2001/06/15 12:49:19 fs * initial checkin - moved this herein from svx/source/fmcomp/dbbrowse* * * * Revision 1.0 15.06.01 12:45:03 fs ************************************************************************/
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: restrictedpaths.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-11-14 14:07:30 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SVTOOLS_RESTRICTEDPATHS_HXX #include "restrictedpaths.hxx" #endif #include <algorithm> #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _UNOTOOLS_LOCALFILEHELPER_HXX #include <unotools/localfilehelper.hxx> #endif #ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX #include <svtools/syslocale.hxx> #endif namespace svt { namespace { // ---------------------------------------------------------------- /** retrieves the value of an environment variable @return <TRUE/> if and only if the retrieved string value is not empty */ bool lcl_getEnvironmentValue( const sal_Char* _pAsciiEnvName, ::rtl::OUString& _rValue ) { _rValue = ::rtl::OUString(); ::rtl::OUString sEnvName = ::rtl::OUString::createFromAscii( _pAsciiEnvName ); osl_getEnvironment( sEnvName.pData, &_rValue.pData ); return _rValue.getLength() != 0; } //----------------------------------------------------------------- void lcl_convertStringListToUrls( const String& _rColonSeparatedList, ::std::vector< String >& _rTokens, bool _bFinalSlash ) { const sal_Unicode s_cSeparator = #if defined(WNT) ';' #else ':' #endif ; xub_StrLen nTokens = _rColonSeparatedList.GetTokenCount( s_cSeparator ); _rTokens.resize( 0 ); _rTokens.reserve( nTokens ); for ( xub_StrLen i=0; i<nTokens; ++i ) { // the current token in the list String sCurrentToken = _rColonSeparatedList.GetToken( i, s_cSeparator ); if ( !sCurrentToken.Len() ) continue; INetURLObject aCurrentURL; String sURL; if ( ::utl::LocalFileHelper::ConvertPhysicalNameToURL( sCurrentToken, sURL ) ) aCurrentURL = INetURLObject( sURL ); else { // smart URL parsing, assuming FILE protocol aCurrentURL = INetURLObject( sCurrentToken, INET_PROT_FILE ); } if ( _bFinalSlash ) aCurrentURL.setFinalSlash( ); else aCurrentURL.removeFinalSlash( ); _rTokens.push_back( aCurrentURL.GetMainURL( INetURLObject::NO_DECODE ) ); } } } //===================================================================== //= CheckURLAllowed //===================================================================== struct CheckURLAllowed { protected: #ifdef WNT SvtSysLocale m_aSysLocale; #endif String m_sCheckURL; // the URL to check bool m_bAllowParent; public: inline CheckURLAllowed( const String& _rCheckURL, bool bAllowParent = true ) :m_sCheckURL( _rCheckURL ), m_bAllowParent( bAllowParent ) { #ifdef WNT // on windows, assume that the relevant file systems are case insensitive, // thus normalize the URL m_sCheckURL = m_aSysLocale.GetCharClass().toLower( m_sCheckURL, 0, m_sCheckURL.Len() ); #endif } bool operator()( const String& _rApprovedURL ) { #ifdef WNT // on windows, assume that the relevant file systems are case insensitive, // thus normalize the URL String sApprovedURL( m_aSysLocale.GetCharClass().toLower( _rApprovedURL, 0, _rApprovedURL.Len() ) ); #else String sApprovedURL( _rApprovedURL ); #endif xub_StrLen nLenApproved = sApprovedURL.Len(); xub_StrLen nLenChecked = m_sCheckURL.Len(); if ( nLenApproved > nLenChecked ) { if ( m_bAllowParent ) { if ( sApprovedURL.Search( m_sCheckURL ) == 0 ) { if ( ( m_sCheckURL.GetChar( nLenChecked - 1 ) == '/' ) || ( sApprovedURL.GetChar( nLenChecked ) == '/' ) ) return true; } } else { // just a difference in final slash? if ( ( nLenApproved == ( nLenChecked + 1 ) ) && ( sApprovedURL.GetChar( nLenApproved - 1 ) == '/' ) ) return true; } return false; } else if ( nLenApproved < nLenChecked ) { if ( m_sCheckURL.Search( sApprovedURL ) == 0 ) { if ( ( sApprovedURL.GetChar( nLenApproved - 1 ) == '/' ) || ( m_sCheckURL.GetChar( nLenApproved ) == '/' ) ) return true; } return false; } else { // strings have equal length return ( sApprovedURL == m_sCheckURL ); } } }; //===================================================================== //= RestrictedPaths //===================================================================== //--------------------------------------------------------------------- RestrictedPaths::RestrictedPaths() :m_bFilterIsEnabled( true ) { ::rtl::OUString sRestrictedPathList; if ( lcl_getEnvironmentValue( "RestrictedPath", sRestrictedPathList ) ) // append a final slash. This ensures that when we later on check // for unrestricted paths, we don't allow paths like "/home/user35" just because // "/home/user3" is allowed - with the final slash, we make it "/home/user3/". lcl_convertStringListToUrls( sRestrictedPathList, m_aUnrestrictedURLs, true ); } // -------------------------------------------------------------------- bool RestrictedPaths::isUrlAllowed( const String& _rURL ) const { if ( m_aUnrestrictedURLs.empty() || !m_bFilterIsEnabled ) return true; ::std::vector< String >::const_iterator aApprovedURL = ::std::find_if( m_aUnrestrictedURLs.begin(), m_aUnrestrictedURLs.end(), CheckURLAllowed( _rURL, true ) ); return ( aApprovedURL != m_aUnrestrictedURLs.end() ); } // -------------------------------------------------------------------- bool RestrictedPaths::isUrlAllowed( const String& _rURL, bool allowParents ) const { if ( m_aUnrestrictedURLs.empty() || !m_bFilterIsEnabled ) return true; ::std::vector< String >::const_iterator aApprovedURL = ::std::find_if( m_aUnrestrictedURLs.begin(), m_aUnrestrictedURLs.end(), CheckURLAllowed( _rURL, allowParents ) ); return ( aApprovedURL != m_aUnrestrictedURLs.end() ); } } // namespace svt #i57954# fix include statemenr /************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: restrictedpaths.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hjs $ $Date: 2005-11-16 09:03:18 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SVTOOLS_RESTRICTEDPATHS_HXX #include "restrictedpaths.hxx" #endif #include <algorithm> #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _UNOTOOLS_LOCALFILEHELPER_HXX #include <unotools/localfilehelper.hxx> #endif #ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX #include "syslocale.hxx" #endif namespace svt { namespace { // ---------------------------------------------------------------- /** retrieves the value of an environment variable @return <TRUE/> if and only if the retrieved string value is not empty */ bool lcl_getEnvironmentValue( const sal_Char* _pAsciiEnvName, ::rtl::OUString& _rValue ) { _rValue = ::rtl::OUString(); ::rtl::OUString sEnvName = ::rtl::OUString::createFromAscii( _pAsciiEnvName ); osl_getEnvironment( sEnvName.pData, &_rValue.pData ); return _rValue.getLength() != 0; } //----------------------------------------------------------------- void lcl_convertStringListToUrls( const String& _rColonSeparatedList, ::std::vector< String >& _rTokens, bool _bFinalSlash ) { const sal_Unicode s_cSeparator = #if defined(WNT) ';' #else ':' #endif ; xub_StrLen nTokens = _rColonSeparatedList.GetTokenCount( s_cSeparator ); _rTokens.resize( 0 ); _rTokens.reserve( nTokens ); for ( xub_StrLen i=0; i<nTokens; ++i ) { // the current token in the list String sCurrentToken = _rColonSeparatedList.GetToken( i, s_cSeparator ); if ( !sCurrentToken.Len() ) continue; INetURLObject aCurrentURL; String sURL; if ( ::utl::LocalFileHelper::ConvertPhysicalNameToURL( sCurrentToken, sURL ) ) aCurrentURL = INetURLObject( sURL ); else { // smart URL parsing, assuming FILE protocol aCurrentURL = INetURLObject( sCurrentToken, INET_PROT_FILE ); } if ( _bFinalSlash ) aCurrentURL.setFinalSlash( ); else aCurrentURL.removeFinalSlash( ); _rTokens.push_back( aCurrentURL.GetMainURL( INetURLObject::NO_DECODE ) ); } } } //===================================================================== //= CheckURLAllowed //===================================================================== struct CheckURLAllowed { protected: #ifdef WNT SvtSysLocale m_aSysLocale; #endif String m_sCheckURL; // the URL to check bool m_bAllowParent; public: inline CheckURLAllowed( const String& _rCheckURL, bool bAllowParent = true ) :m_sCheckURL( _rCheckURL ), m_bAllowParent( bAllowParent ) { #ifdef WNT // on windows, assume that the relevant file systems are case insensitive, // thus normalize the URL m_sCheckURL = m_aSysLocale.GetCharClass().toLower( m_sCheckURL, 0, m_sCheckURL.Len() ); #endif } bool operator()( const String& _rApprovedURL ) { #ifdef WNT // on windows, assume that the relevant file systems are case insensitive, // thus normalize the URL String sApprovedURL( m_aSysLocale.GetCharClass().toLower( _rApprovedURL, 0, _rApprovedURL.Len() ) ); #else String sApprovedURL( _rApprovedURL ); #endif xub_StrLen nLenApproved = sApprovedURL.Len(); xub_StrLen nLenChecked = m_sCheckURL.Len(); if ( nLenApproved > nLenChecked ) { if ( m_bAllowParent ) { if ( sApprovedURL.Search( m_sCheckURL ) == 0 ) { if ( ( m_sCheckURL.GetChar( nLenChecked - 1 ) == '/' ) || ( sApprovedURL.GetChar( nLenChecked ) == '/' ) ) return true; } } else { // just a difference in final slash? if ( ( nLenApproved == ( nLenChecked + 1 ) ) && ( sApprovedURL.GetChar( nLenApproved - 1 ) == '/' ) ) return true; } return false; } else if ( nLenApproved < nLenChecked ) { if ( m_sCheckURL.Search( sApprovedURL ) == 0 ) { if ( ( sApprovedURL.GetChar( nLenApproved - 1 ) == '/' ) || ( m_sCheckURL.GetChar( nLenApproved ) == '/' ) ) return true; } return false; } else { // strings have equal length return ( sApprovedURL == m_sCheckURL ); } } }; //===================================================================== //= RestrictedPaths //===================================================================== //--------------------------------------------------------------------- RestrictedPaths::RestrictedPaths() :m_bFilterIsEnabled( true ) { ::rtl::OUString sRestrictedPathList; if ( lcl_getEnvironmentValue( "RestrictedPath", sRestrictedPathList ) ) // append a final slash. This ensures that when we later on check // for unrestricted paths, we don't allow paths like "/home/user35" just because // "/home/user3" is allowed - with the final slash, we make it "/home/user3/". lcl_convertStringListToUrls( sRestrictedPathList, m_aUnrestrictedURLs, true ); } // -------------------------------------------------------------------- bool RestrictedPaths::isUrlAllowed( const String& _rURL ) const { if ( m_aUnrestrictedURLs.empty() || !m_bFilterIsEnabled ) return true; ::std::vector< String >::const_iterator aApprovedURL = ::std::find_if( m_aUnrestrictedURLs.begin(), m_aUnrestrictedURLs.end(), CheckURLAllowed( _rURL, true ) ); return ( aApprovedURL != m_aUnrestrictedURLs.end() ); } // -------------------------------------------------------------------- bool RestrictedPaths::isUrlAllowed( const String& _rURL, bool allowParents ) const { if ( m_aUnrestrictedURLs.empty() || !m_bFilterIsEnabled ) return true; ::std::vector< String >::const_iterator aApprovedURL = ::std::find_if( m_aUnrestrictedURLs.begin(), m_aUnrestrictedURLs.end(), CheckURLAllowed( _rURL, allowParents ) ); return ( aApprovedURL != m_aUnrestrictedURLs.end() ); } } // namespace svt
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fontworkgallery.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-09 00:47:44 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _COM_SUN_STAR_TEXT_WRITINGMODE_HPP_ #include <com/sun/star/text/WritingMode.hpp> #endif #ifndef _SFXAPP_HXX //autogen #include <sfx2/app.hxx> #endif #ifndef _SFXITEMPOOL_HXX #include <svtools/itempool.hxx> #endif #ifndef _SVX_FMMODEL_HXX #include <fmmodel.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #include <dlgutil.hxx> #include "svxids.hrc" #include "dialmgr.hxx" #include "dialogs.hrc" #include "gallery.hxx" #include "svdpage.hxx" #include "svdobj.hxx" #include "svdview.hxx" #include "svdoutl.hxx" #include "eeitem.hxx" #define ITEMID_FRAMEDIR EE_PARA_WRITINGDIR #include "frmdiritem.hxx" #include "toolbarmenu.hxx" #include "fontworkgallery.hxx" #include "fontworkgallery.hrc" #include <algorithm> #ifndef _TOOLBOX_HXX //autogen #include <vcl/toolbox.hxx> #endif #ifndef _SVX_HELPID_HRC #include "helpid.hrc" #endif using namespace svx; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; const int nColCount = 4; const int nLineCount = 4; /************************************************************************* |* Svx3DWin - FloatingWindow \************************************************************************/ FontWorkGalleryDialog::FontWorkGalleryDialog( SdrView* pSdrView, Window* pParent, sal_uInt16 nSID ) : ModalDialog( pParent, SVX_RES( RID_SVX_MDLG_FONTWORK_GALLERY ) ), maCtlFavorites ( this, SVX_RES( CTL_FAVORITES ) ), maFLFavorites ( this, SVX_RES( FL_FAVORITES ) ), maOKButton ( this, SVX_RES( BTN_OK ) ), maCancelButton ( this, SVX_RES( BTN_CANCEL ) ), maHelpButton ( this, SVX_RES( BTN_HELP ) ), mnThemeId ( -1 ), maStrClickToAddText ( SVX_RES( STR_CLICK_TO_ADD_TEXT ) ), mpSdrView ( pSdrView ), mpModel ( (FmFormModel*)pSdrView->GetModel() ), mppSdrObject ( NULL ), mpDestModel ( NULL ) { FreeResource(); maCtlFavorites.SetDoubleClickHdl( LINK( this, FontWorkGalleryDialog, DoubleClickFavoriteHdl ) ); maOKButton.SetClickHdl( LINK( this, FontWorkGalleryDialog, ClickOKHdl ) ); maCtlFavorites.SetColCount( nColCount ); maCtlFavorites.SetLineCount( nLineCount ); maCtlFavorites.SetExtraSpacing( 3 ); initfavorites( GALLERY_THEME_FONTWORK, maFavoritesHorizontal ); fillFavorites( GALLERY_THEME_FONTWORK, maFavoritesHorizontal ); } static void delete_bitmap( Bitmap* p ) { delete p; } // ----------------------------------------------------------------------- FontWorkGalleryDialog::~FontWorkGalleryDialog() { std::for_each( maFavoritesHorizontal.begin(), maFavoritesHorizontal.end(), delete_bitmap ); } // ----------------------------------------------------------------------- void FontWorkGalleryDialog::initfavorites(sal_uInt16 nThemeId, std::vector< Bitmap * >& rFavorites) { // Ueber die Gallery werden die Favoriten eingelesen ULONG nFavCount = GalleryExplorer::GetSdrObjCount( nThemeId ); // Gallery thema locken GalleryExplorer::BeginLocking(nThemeId); sal_uInt32 nModelPos; FmFormModel *pModel = NULL; for( nModelPos = 0; nModelPos < nFavCount; nModelPos++ ) { Bitmap* pThumb = new Bitmap; if( GalleryExplorer::GetSdrObj( nThemeId, nModelPos, pModel, pThumb ) ) { /* VirtualDevice aVDev; Size aRenderSize( aThumbSize.Width() * 4, aThumbSize.Height() * 4 ); aVDev.SetOutputSizePixel( aRenderSize ); if( GalleryExplorer::DrawCentered( &aVDev, *pModel ) ) { aThumb = aVDev.GetBitmap( Point(), aVDev.GetOutputSizePixel() ); Size aMS( 4, 4 ); BmpFilterParam aParam( aMS ); aThumb.Filter( BMP_FILTER_MOSAIC, &aParam ); aThumb.Scale( aThumbSize ); } */ } rFavorites.push_back( pThumb ); } // Gallery thema freigeben GalleryExplorer::EndLocking(nThemeId); } void FontWorkGalleryDialog::fillFavorites( sal_uInt16 nThemeId, std::vector< Bitmap * >& rFavorites ) { mnThemeId = nThemeId; Size aThumbSize( maCtlFavorites.GetSizePixel() ); aThumbSize.Width() /= nColCount; aThumbSize.Height() /= nLineCount; aThumbSize.Width() -= 12; aThumbSize.Height() -= 12; sal_uInt16 nFavCount = rFavorites.size(); // ValueSet Favoriten if( nFavCount > (nColCount * nLineCount) ) { WinBits nWinBits = maCtlFavorites.GetStyle(); nWinBits |= WB_VSCROLL; maCtlFavorites.SetStyle( nWinBits ); } maCtlFavorites.Clear(); sal_uInt32 nFavorite; for( nFavorite = 1; nFavorite <= nFavCount; nFavorite++ ) { String aStr(SVX_RES(RID_SVXFLOAT3D_FAVORITE)); aStr += sal_Unicode(' '); aStr += String::CreateFromInt32((sal_Int32)nFavorite); Image aThumbImage( *rFavorites[nFavorite-1] ); maCtlFavorites.InsertItem( (sal_uInt16)nFavorite, aThumbImage, aStr ); } } void FontWorkGalleryDialog::changeText( SdrTextObj* pObj ) { if( pObj ) { SdrOutliner& rOutl = mpModel->GetDrawOutliner(pObj); rOutl.SetMinDepth(0); USHORT nOutlMode = rOutl.GetMode(); USHORT nMinDepth = rOutl.GetMinDepth(); Size aPaperSize = rOutl.GetPaperSize(); BOOL bUpdateMode = rOutl.GetUpdateMode(); rOutl.SetUpdateMode(FALSE); rOutl.SetParaAttribs( 0, rOutl.GetEmptyItemSet() ); // #95114# Always set the object's StyleSheet at the Outliner to // use the current objects StyleSheet. Thus it's the same as in // SetText(...). // #95114# Moved this implementation from where SetObjText(...) was called // to inside this method to work even when outliner is fetched here. rOutl.SetStyleSheet(0, pObj->GetStyleSheet()); rOutl.SetPaperSize( pObj->GetLogicRect().GetSize() ); rOutl.SetText( maStrClickToAddText, rOutl.GetParagraph( 0 ) ); pObj->SetOutlinerParaObject( rOutl.CreateParaObject() ); rOutl.Init( nOutlMode ); rOutl.SetParaAttribs( 0, rOutl.GetEmptyItemSet() ); rOutl.SetUpdateMode( bUpdateMode ); rOutl.SetMinDepth( nMinDepth ); rOutl.SetPaperSize( aPaperSize ); rOutl.Clear(); } } void FontWorkGalleryDialog::SetSdrObjectRef( SdrObject** ppSdrObject, SdrModel* pModel ) { mppSdrObject = ppSdrObject; mpDestModel = pModel; } void FontWorkGalleryDialog::insertSelectedFontwork() { USHORT nItemId = maCtlFavorites.GetSelectItemId(); if( nItemId > 0 ) { FmFormModel* pModel = new FmFormModel(); pModel->GetItemPool().FreezeIdRanges(); if( GalleryExplorer::GetSdrObj( mnThemeId, nItemId-1, pModel ) ) { SdrPage* pPage = pModel->GetPage(0); if( pPage && pPage->GetObjCount() ) { SdrObject* pNewObject = pPage->GetObj(0)->Clone(); // center shape on current view OutputDevice* pOutDev = mpSdrView->GetWin(0); if( pOutDev ) { Rectangle aObjRect( pNewObject->GetLogicRect() ); Rectangle aVisArea = pOutDev->PixelToLogic(Rectangle(Point(0,0), pOutDev->GetOutputSizePixel())); /* sal_Int32 nObjHeight = aObjRect.GetHeight(); VirtualDevice aVirDev( 1 ); // calculating the optimal textwidth Font aFont; aFont.SetHeight( nObjHeight ); aVirDev.SetMapMode( MAP_100TH_MM ); aVirDev.SetFont( aFont ); aObjRect.SetSize( Size( aVirDev.GetTextWidth( maStrClickToAddText ), nObjHeight ) ); */ Point aPagePos = aVisArea.Center(); aPagePos.X() -= aObjRect.GetWidth() / 2; aPagePos.Y() -= aObjRect.GetHeight() / 2; Rectangle aNewObjectRectangle(aPagePos, aObjRect.GetSize()); SdrPageView* pPV = mpSdrView->GetPageViewPvNum(0); pNewObject->SetLogicRect(aNewObjectRectangle); if ( mppSdrObject ) { *mppSdrObject = pNewObject; (*mppSdrObject)->SetModel( mpDestModel ); } else if( pPV ) { mpSdrView->InsertObject( pNewObject, *pPV ); // changeText( PTR_CAST( SdrTextObj, pNewObject ) ); } } } } delete pModel; } } // ----------------------------------------------------------------------- IMPL_LINK( FontWorkGalleryDialog, ClickOKHdl, void*, p ) { insertSelectedFontwork(); EndDialog( true ); return 0; } // ----------------------------------------------------------------------- IMPL_LINK( FontWorkGalleryDialog, DoubleClickFavoriteHdl, void*, p ) { insertSelectedFontwork(); EndDialog( true ); return( 0L ); } // ----------------------------------------------------------------------- SFX_IMPL_TOOLBOX_CONTROL( FontWorkShapeTypeControl, SfxStringItem ); FontWorkShapeTypeControl::FontWorkShapeTypeControl( USHORT nSlotId, USHORT nId, ToolBox &rTbx ) : SfxToolBoxControl( nSlotId, nId, rTbx ) { rTbx.SetItemBits( nId, TIB_DROPDOWNONLY | rTbx.GetItemBits( nId ) ); rTbx.Invalidate(); } // ----------------------------------------------------------------------- FontWorkShapeTypeControl::~FontWorkShapeTypeControl() { } // ----------------------------------------------------------------------- SfxPopupWindowType FontWorkShapeTypeControl::GetPopupWindowType() const { return SFX_POPUPWINDOW_ONCLICK; //( aLastAction.getLength() == 0 ? SFX_POPUPWINDOW_ONCLICK : SFX_POPUPWINDOW_ONTIMEOUT ); } // ----------------------------------------------------------------------- SfxPopupWindow* FontWorkShapeTypeControl::CreatePopupWindow() { rtl::OUString aSubTbxResName( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/fontworkshapetype" ) ); createAndPositionSubToolBar( aSubTbxResName ); return NULL; } // ----------------------------------------------------------------------- void FontWorkShapeTypeControl::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ) { SfxToolBoxControl::StateChanged( nSID, eState, pState ); } // ----------------------------------------------------------------------- void FontWorkShapeTypeControl::Select( BOOL bMod1 ) { } // #################################################################### SFX_IMPL_TOOLBOX_CONTROL( FontWorkAlignmentControl, SfxBoolItem ); FontWorkAlignmentWindow::FontWorkAlignmentWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame ) : SfxPopupWindow( nId, rFrame, SVX_RES( RID_SVXFLOAT_FONTWORK_ALIGNMENT )), maImgAlgin1( SVX_RES( IMG_FONTWORK_ALIGN_LEFT_16 ) ), maImgAlgin2( SVX_RES( IMG_FONTWORK_ALIGN_CENTER_16 ) ), maImgAlgin3( SVX_RES( IMG_FONTWORK_ALIGN_RIGHT_16 ) ), maImgAlgin4( SVX_RES( IMG_FONTWORK_ALIGN_WORD_16 ) ), maImgAlgin5( SVX_RES( IMG_FONTWORK_ALIGN_STRETCH_16 ) ), maImgAlgin1h( SVX_RES( IMG_FONTWORK_ALIGN_LEFT_16_H ) ), maImgAlgin2h( SVX_RES( IMG_FONTWORK_ALIGN_CENTER_16_H ) ), maImgAlgin3h( SVX_RES( IMG_FONTWORK_ALIGN_RIGHT_16_H ) ), maImgAlgin4h( SVX_RES( IMG_FONTWORK_ALIGN_WORD_16_H ) ), maImgAlgin5h( SVX_RES( IMG_FONTWORK_ALIGN_STRETCH_16_H ) ), mbPopupMode( true ), mxFrame( rFrame ) { implInit(); } FontWorkAlignmentWindow::FontWorkAlignmentWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, Window* pParentWindow ) : SfxPopupWindow( nId, rFrame, SVX_RES( RID_SVXFLOAT_FONTWORK_ALIGNMENT )), maImgAlgin1( SVX_RES( IMG_FONTWORK_ALIGN_LEFT_16 ) ), maImgAlgin2( SVX_RES( IMG_FONTWORK_ALIGN_CENTER_16 ) ), maImgAlgin3( SVX_RES( IMG_FONTWORK_ALIGN_RIGHT_16 ) ), maImgAlgin4( SVX_RES( IMG_FONTWORK_ALIGN_WORD_16 ) ), maImgAlgin5( SVX_RES( IMG_FONTWORK_ALIGN_STRETCH_16 ) ), maImgAlgin1h( SVX_RES( IMG_FONTWORK_ALIGN_LEFT_16_H ) ), maImgAlgin2h( SVX_RES( IMG_FONTWORK_ALIGN_CENTER_16_H ) ), maImgAlgin3h( SVX_RES( IMG_FONTWORK_ALIGN_RIGHT_16_H ) ), maImgAlgin4h( SVX_RES( IMG_FONTWORK_ALIGN_WORD_16_H ) ), maImgAlgin5h( SVX_RES( IMG_FONTWORK_ALIGN_STRETCH_16_H ) ), mbPopupMode( true ), mxFrame( rFrame ) { implInit(); } void FontWorkAlignmentWindow::implInit() { SetHelpId( HID_POPUP_FONTWORK_ALIGN ); bool bHighContrast = GetDisplayBackground().GetColor().IsDark(); mpMenu = new ToolbarMenu( this, WB_CLIPCHILDREN ); mpMenu->SetHelpId( HID_POPUP_FONTWORK_ALIGN ); mpMenu->SetSelectHdl( LINK( this, FontWorkAlignmentWindow, SelectHdl ) ); mpMenu->appendEntry( 0, String( SVX_RES( STR_ALIGN_LEFT ) ), bHighContrast ? maImgAlgin1h : maImgAlgin1 ); mpMenu->appendEntry( 1, String( SVX_RES( STR_ALIGN_CENTER ) ), bHighContrast ? maImgAlgin2h : maImgAlgin2 ); mpMenu->appendEntry( 2, String( SVX_RES( STR_ALIGN_RIGHT ) ), bHighContrast ? maImgAlgin3h : maImgAlgin3 ); mpMenu->appendEntry( 3, String( SVX_RES( STR_ALIGN_WORD ) ), bHighContrast ? maImgAlgin4h : maImgAlgin4 ); mpMenu->appendEntry( 4, String( SVX_RES( STR_ALIGN_STRETCH ) ), bHighContrast ? maImgAlgin5h : maImgAlgin5 ); SetOutputSizePixel( mpMenu->getMenuSize() ); mpMenu->SetOutputSizePixel( GetOutputSizePixel() ); mpMenu->Show(); FreeResource(); AddStatusListener( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:FontworkAlignment" ))); } SfxPopupWindow* FontWorkAlignmentWindow::Clone() const { return new FontWorkAlignmentWindow( GetId(), mxFrame ); } // ----------------------------------------------------------------------- FontWorkAlignmentWindow::~FontWorkAlignmentWindow() { delete mpMenu; } // ----------------------------------------------------------------------- void FontWorkAlignmentWindow::implSetAlignment( int nSurface, bool bEnabled ) { if( mpMenu ) { int i; for( i = 0; i < 5; i++ ) { mpMenu->checkEntry( i, (i == nSurface) && bEnabled ); mpMenu->enableEntry( i, bEnabled ); } } } // ----------------------------------------------------------------------- void FontWorkAlignmentWindow::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ) { switch( nSID ) { case SID_FONTWORK_ALIGNMENT: { if( eState == SFX_ITEM_DISABLED ) { implSetAlignment( 0, false ); } else { const SfxInt32Item* pStateItem = PTR_CAST( SfxInt32Item, pState ); if( pStateItem ) implSetAlignment( pStateItem->GetValue(), true ); } break; } } } // ----------------------------------------------------------------------- void FontWorkAlignmentWindow::DataChanged( const DataChangedEvent& rDCEvt ) { SfxPopupWindow::DataChanged( rDCEvt ); if( ( rDCEvt.GetType() == DATACHANGED_SETTINGS ) && ( rDCEvt.GetFlags() & SETTINGS_STYLE ) ) { bool bHighContrast = GetDisplayBackground().GetColor().IsDark(); mpMenu->appendEntry( 0, String( SVX_RES( STR_ALIGN_LEFT ) ), bHighContrast ? maImgAlgin1h : maImgAlgin1 ); mpMenu->appendEntry( 1, String( SVX_RES( STR_ALIGN_CENTER ) ), bHighContrast ? maImgAlgin2h : maImgAlgin2 ); mpMenu->appendEntry( 2, String( SVX_RES( STR_ALIGN_RIGHT ) ), bHighContrast ? maImgAlgin3h : maImgAlgin3 ); mpMenu->appendEntry( 3, String( SVX_RES( STR_ALIGN_WORD ) ), bHighContrast ? maImgAlgin4h : maImgAlgin4 ); mpMenu->appendEntry( 4, String( SVX_RES( STR_ALIGN_STRETCH ) ), bHighContrast ? maImgAlgin5h : maImgAlgin5 ); } } // ----------------------------------------------------------------------- IMPL_LINK( FontWorkAlignmentWindow, SelectHdl, void *, pControl ) { if ( IsInPopupMode() ) EndPopupMode(); // SfxDispatcher* pDisp = GetBindings().GetDispatcher(); sal_Int32 nAlignment = mpMenu->getSelectedEntryId(); if( nAlignment >= 0 ) { SfxInt32Item aItem( SID_FONTWORK_ALIGNMENT, nAlignment ); rtl::OUString aCommand( RTL_CONSTASCII_USTRINGPARAM( ".uno:FontworkAlignment" )); Any a; INetURLObject aObj( aCommand ); Sequence< PropertyValue > aArgs( 1 ); aArgs[0].Name = aObj.GetURLPath(); aItem.QueryValue( a ); aArgs[0].Value = a; SfxToolBoxControl::Dispatch( Reference< ::com::sun::star::frame::XDispatchProvider >( mxFrame->getController(), UNO_QUERY ), aCommand, aArgs ); implSetAlignment( nAlignment, true ); } return 0; } // ----------------------------------------------------------------------- void FontWorkAlignmentWindow::StartSelection() { } // ----------------------------------------------------------------------- BOOL FontWorkAlignmentWindow::Close() { return SfxPopupWindow::Close(); } // ----------------------------------------------------------------------- void FontWorkAlignmentWindow::PopupModeEnd() { if ( IsVisible() ) { mbPopupMode = FALSE; } SfxPopupWindow::PopupModeEnd(); } // ----------------------------------------------------------------------- void FontWorkAlignmentWindow::GetFocus (void) { SfxPopupWindow::GetFocus(); // Grab the focus to the line ends value set so that it can be controlled // with the keyboard. if( mpMenu ) mpMenu->GrabFocus(); } // ======================================================================== FontWorkAlignmentControl::FontWorkAlignmentControl( USHORT nSlotId, USHORT nId, ToolBox &rTbx ) : SfxToolBoxControl( nSlotId, nId, rTbx ) { rTbx.SetItemBits( nId, TIB_DROPDOWNONLY | rTbx.GetItemBits( nId ) ); } // ----------------------------------------------------------------------- FontWorkAlignmentControl::~FontWorkAlignmentControl() { } // ----------------------------------------------------------------------- SfxPopupWindowType FontWorkAlignmentControl::GetPopupWindowType() const { return SFX_POPUPWINDOW_ONCLICK; } // ----------------------------------------------------------------------- SfxPopupWindow* FontWorkAlignmentControl::CreatePopupWindow() { FontWorkAlignmentWindow* pWin = new FontWorkAlignmentWindow( GetId(), m_xFrame, &GetToolBox() ); pWin->StartPopupMode( &GetToolBox(), TRUE ); pWin->StartSelection(); SetPopupWindow( pWin ); return pWin; } // ----------------------------------------------------------------------- void FontWorkAlignmentControl::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ) { USHORT nId = GetId(); ToolBox& rTbx = GetToolBox(); rTbx.EnableItem( nId, SFX_ITEM_DISABLED != eState ); rTbx.SetItemState( nId, ( SFX_ITEM_DONTCARE == eState ) ? STATE_DONTKNOW : STATE_NOCHECK ); } // #################################################################### SFX_IMPL_TOOLBOX_CONTROL( FontWorkCharacterSpacingControl, SfxBoolItem ); FontWorkCharacterSpacingWindow::FontWorkCharacterSpacingWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame ) : SfxPopupWindow( nId, rFrame, SVX_RES( RID_SVXFLOAT_FONTWORK_CHARSPACING )), mbPopupMode( true ), mxFrame( rFrame ) { implInit(); } FontWorkCharacterSpacingWindow::FontWorkCharacterSpacingWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, Window* pParentWindow ) : SfxPopupWindow( nId, rFrame, pParentWindow, SVX_RES( RID_SVXFLOAT_FONTWORK_CHARSPACING )), mbPopupMode( true ), mxFrame( rFrame ) { implInit(); } void FontWorkCharacterSpacingWindow::implInit() { SetHelpId( HID_POPUP_FONTWORK_CHARSPACE ); bool bHighContrast = GetDisplayBackground().GetColor().IsDark(); mpMenu = new ToolbarMenu( this, WB_CLIPCHILDREN ); mpMenu->SetHelpId( HID_POPUP_FONTWORK_CHARSPACE ); mpMenu->SetSelectHdl( LINK( this, FontWorkCharacterSpacingWindow, SelectHdl ) ); mpMenu->appendEntry( 0, String( SVX_RES( STR_CHARS_SPACING_VERY_TIGHT ) ), MIB_RADIOCHECK ); mpMenu->appendEntry( 1, String( SVX_RES( STR_CHARS_SPACING_TIGHT ) ), MIB_RADIOCHECK ); mpMenu->appendEntry( 2, String( SVX_RES( STR_CHARS_SPACING_NORMAL ) ), MIB_RADIOCHECK ); mpMenu->appendEntry( 3, String( SVX_RES( STR_CHARS_SPACING_LOOSE ) ), MIB_RADIOCHECK ); mpMenu->appendEntry( 4, String( SVX_RES( STR_CHARS_SPACING_VERY_LOOSE ) ), MIB_RADIOCHECK ); mpMenu->appendEntry( 5, String( SVX_RES( STR_CHARS_SPACING_CUSTOM ) ), MIB_RADIOCHECK ); mpMenu->appendSeparator(); mpMenu->appendEntry( 6, String( SVX_RES( STR_CHARS_SPACING_KERN_PAIRS ) ), MIB_CHECKABLE ); SetOutputSizePixel( mpMenu->getMenuSize() ); mpMenu->SetOutputSizePixel( GetOutputSizePixel() ); mpMenu->Show(); FreeResource(); AddStatusListener( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:FontworkCharacterSpacing" ))); } SfxPopupWindow* FontWorkCharacterSpacingWindow::Clone() const { return new FontWorkCharacterSpacingWindow( GetId(), mxFrame ); } // ----------------------------------------------------------------------- FontWorkCharacterSpacingWindow::~FontWorkCharacterSpacingWindow() { delete mpMenu; } // ----------------------------------------------------------------------- void FontWorkCharacterSpacingWindow::implSetCharacterSpacing( sal_Int32 nCharacterSpacing, bool bEnabled ) { if( mpMenu ) { sal_Int32 i; for ( i = 0; i < 6; i++ ) { mpMenu->checkEntry( i, sal_False ); mpMenu->enableEntry( i, bEnabled ); } if ( nCharacterSpacing != -1 ) { sal_Int32 nEntry; switch( nCharacterSpacing ) { case 80 : nEntry = 0; break; case 90 : nEntry = 1; break; case 100 : nEntry = 2; break; case 120 : nEntry = 3; break; case 150 : nEntry = 4; break; default : nEntry = 5; break; } mpMenu->checkEntry( nEntry, bEnabled ); } } } void FontWorkCharacterSpacingWindow::implSetKernCharacterPairs( sal_Bool bKernOnOff, bool bEnabled ) { if( mpMenu ) { mpMenu->enableEntry( 6, bEnabled ); mpMenu->checkEntry( 6, bEnabled ); } } // ----------------------------------------------------------------------- void FontWorkCharacterSpacingWindow::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ) { switch( nSID ) { case SID_FONTWORK_CHARACTER_SPACING: { if( eState == SFX_ITEM_DISABLED ) implSetCharacterSpacing( 0, false ); else { const SfxInt32Item* pStateItem = PTR_CAST( SfxInt32Item, pState ); if( pStateItem ) implSetCharacterSpacing( pStateItem->GetValue(), true ); } break; } break; case SID_FONTWORK_KERN_CHARACTER_PAIRS : { if( eState == SFX_ITEM_DISABLED ) implSetKernCharacterPairs( 0, false ); else { const SfxBoolItem* pStateItem = PTR_CAST( SfxBoolItem, pState ); if( pStateItem ) implSetKernCharacterPairs( pStateItem->GetValue(), true ); } } break; } } // ----------------------------------------------------------------------- void FontWorkCharacterSpacingWindow::DataChanged( const DataChangedEvent& rDCEvt ) { SfxPopupWindow::DataChanged( rDCEvt ); if( ( rDCEvt.GetType() == DATACHANGED_SETTINGS ) && ( rDCEvt.GetFlags() & SETTINGS_STYLE ) ) { bool bHighContrast = GetDisplayBackground().GetColor().IsDark(); mpMenu->appendEntry( 0, String( SVX_RES( STR_CHARS_SPACING_VERY_TIGHT ) ), MIB_CHECKABLE ); mpMenu->appendEntry( 1, String( SVX_RES( STR_CHARS_SPACING_TIGHT ) ), MIB_CHECKABLE ); mpMenu->appendEntry( 2, String( SVX_RES( STR_CHARS_SPACING_NORMAL ) ), MIB_CHECKABLE ); mpMenu->appendEntry( 3, String( SVX_RES( STR_CHARS_SPACING_LOOSE ) ), MIB_CHECKABLE ); mpMenu->appendEntry( 4, String( SVX_RES( STR_CHARS_SPACING_VERY_LOOSE ) ), MIB_CHECKABLE ); mpMenu->appendEntry( 5, String( SVX_RES( STR_CHARS_SPACING_CUSTOM ) ), MIB_CHECKABLE ); mpMenu->appendSeparator(); mpMenu->appendEntry( 6, String( SVX_RES( STR_CHARS_SPACING_KERN_PAIRS ) ), MIB_CHECKABLE ); } } // ----------------------------------------------------------------------- IMPL_LINK( FontWorkCharacterSpacingWindow, SelectHdl, void *, pControl ) { if ( IsInPopupMode() ) EndPopupMode(); sal_Int32 nSelection = mpMenu->getSelectedEntryId(); sal_Int32 nCharacterSpacing; switch( nSelection ) { case 0 : nCharacterSpacing = 80; break; case 1 : nCharacterSpacing = 90; break; case 2 : nCharacterSpacing = 100; break; case 3 : nCharacterSpacing = 120; break; case 4 : nCharacterSpacing = 150; break; default : nCharacterSpacing = 100; break; } if ( nSelection == 5 ) // custom spacing { SfxInt32Item aItem( SID_FONTWORK_CHARACTER_SPACING, nCharacterSpacing ); rtl::OUString aCommand( RTL_CONSTASCII_USTRINGPARAM( ".uno:FontworkCharacterSpacingDialog" )); Any a; Sequence< PropertyValue > aArgs( 1 ); aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "FontworkCharacterSpacing" )); aItem.QueryValue( a ); aArgs[0].Value = a; SfxToolBoxControl::Dispatch( Reference< ::com::sun::star::frame::XDispatchProvider >( mxFrame->getController(), UNO_QUERY ), aCommand, aArgs ); } else if ( nSelection == 6 ) // KernCharacterPairs { sal_Bool bOnOff = sal_True; SfxBoolItem aItem( SID_FONTWORK_KERN_CHARACTER_PAIRS, bOnOff ); rtl::OUString aCommand( RTL_CONSTASCII_USTRINGPARAM( ".uno:FontworkKernCharacterPairs" )); Any a; Sequence< PropertyValue > aArgs( 1 ); aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "FontworkKernCharacterPairs" )); aItem.QueryValue( a ); aArgs[0].Value = a; SfxToolBoxControl::Dispatch( Reference< ::com::sun::star::frame::XDispatchProvider >( mxFrame->getController(), UNO_QUERY ), aCommand, aArgs ); implSetKernCharacterPairs( bOnOff, true ); } else if( nSelection >= 0 ) { SfxInt32Item aItem( SID_FONTWORK_CHARACTER_SPACING, nCharacterSpacing ); rtl::OUString aCommand( RTL_CONSTASCII_USTRINGPARAM( ".uno:FontworkCharacterSpacing" )); Any a; INetURLObject aObj( aCommand ); Sequence< PropertyValue > aArgs( 1 ); aArgs[0].Name = aObj.GetURLPath(); aItem.QueryValue( a ); aArgs[0].Value = a; SfxToolBoxControl::Dispatch( Reference< ::com::sun::star::frame::XDispatchProvider >( mxFrame->getController(), UNO_QUERY ), aCommand, aArgs ); implSetCharacterSpacing( nCharacterSpacing, true ); } return 0; } // ----------------------------------------------------------------------- void FontWorkCharacterSpacingWindow::StartSelection() { } // ----------------------------------------------------------------------- BOOL FontWorkCharacterSpacingWindow::Close() { return SfxPopupWindow::Close(); } // ----------------------------------------------------------------------- void FontWorkCharacterSpacingWindow::PopupModeEnd() { if ( IsVisible() ) { mbPopupMode = FALSE; } SfxPopupWindow::PopupModeEnd(); } // ----------------------------------------------------------------------- void FontWorkCharacterSpacingWindow::GetFocus (void) { SfxPopupWindow::GetFocus(); // Grab the focus to the line ends value set so that it can be controlled // with the keyboard. if( mpMenu ) mpMenu->GrabFocus(); } // ======================================================================== FontWorkCharacterSpacingControl::FontWorkCharacterSpacingControl( USHORT nSlotId, USHORT nId, ToolBox &rTbx ) : SfxToolBoxControl( nSlotId, nId, rTbx ) { rTbx.SetItemBits( nId, TIB_DROPDOWNONLY | rTbx.GetItemBits( nId ) ); } // ----------------------------------------------------------------------- FontWorkCharacterSpacingControl::~FontWorkCharacterSpacingControl() { } // ----------------------------------------------------------------------- SfxPopupWindowType FontWorkCharacterSpacingControl::GetPopupWindowType() const { return SFX_POPUPWINDOW_ONCLICK; } // ----------------------------------------------------------------------- SfxPopupWindow* FontWorkCharacterSpacingControl::CreatePopupWindow() { FontWorkCharacterSpacingWindow* pWin = new FontWorkCharacterSpacingWindow( GetId(), m_xFrame, &GetToolBox() ); pWin->StartPopupMode( &GetToolBox(), TRUE ); pWin->StartSelection(); SetPopupWindow( pWin ); return pWin; } // ----------------------------------------------------------------------- void FontWorkCharacterSpacingControl::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ) { USHORT nId = GetId(); ToolBox& rTbx = GetToolBox(); rTbx.EnableItem( nId, SFX_ITEM_DISABLED != eState ); rTbx.SetItemState( nId, ( SFX_ITEM_DONTCARE == eState ) ? STATE_DONTKNOW : STATE_NOCHECK ); } // ----------------------------------------------------------------------- FontworkCharacterSpacingDialog::FontworkCharacterSpacingDialog( Window* pParent, sal_Int32 nScale ) : ModalDialog( pParent, SVX_RES( RID_SVX_MDLG_FONTWORK_CHARSPACING ) ), maFLScale( this, SVX_RES( FT_VALUE ) ), maMtrScale( this, SVX_RES( MF_VALUE ) ), maOKButton( this, SVX_RES( BTN_OK ) ), maCancelButton( this, SVX_RES( BTN_CANCEL ) ), maHelpButton( this, SVX_RES( BTN_HELP ) ) { maMtrScale.SetValue( nScale ); FreeResource(); } FontworkCharacterSpacingDialog::~FontworkCharacterSpacingDialog() { } sal_Int32 FontworkCharacterSpacingDialog::getScale() const { return (sal_Int32)maMtrScale.GetValue(); } INTEGRATION: CWS pchfix02 (1.8.532); FILE MERGED 2006/09/01 17:47:32 kaib 1.8.532.1: #i68856# Added header markers and pch files /************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fontworkgallery.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2006-09-17 06:04:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifndef _COM_SUN_STAR_TEXT_WRITINGMODE_HPP_ #include <com/sun/star/text/WritingMode.hpp> #endif #ifndef _SFXAPP_HXX //autogen #include <sfx2/app.hxx> #endif #ifndef _SFXITEMPOOL_HXX #include <svtools/itempool.hxx> #endif #ifndef _SVX_FMMODEL_HXX #include <fmmodel.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #include <dlgutil.hxx> #include "svxids.hrc" #include "dialmgr.hxx" #include "dialogs.hrc" #include "gallery.hxx" #include "svdpage.hxx" #include "svdobj.hxx" #include "svdview.hxx" #include "svdoutl.hxx" #include "eeitem.hxx" #define ITEMID_FRAMEDIR EE_PARA_WRITINGDIR #include "frmdiritem.hxx" #include "toolbarmenu.hxx" #include "fontworkgallery.hxx" #include "fontworkgallery.hrc" #include <algorithm> #ifndef _TOOLBOX_HXX //autogen #include <vcl/toolbox.hxx> #endif #ifndef _SVX_HELPID_HRC #include "helpid.hrc" #endif using namespace svx; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; const int nColCount = 4; const int nLineCount = 4; /************************************************************************* |* Svx3DWin - FloatingWindow \************************************************************************/ FontWorkGalleryDialog::FontWorkGalleryDialog( SdrView* pSdrView, Window* pParent, sal_uInt16 nSID ) : ModalDialog( pParent, SVX_RES( RID_SVX_MDLG_FONTWORK_GALLERY ) ), maCtlFavorites ( this, SVX_RES( CTL_FAVORITES ) ), maFLFavorites ( this, SVX_RES( FL_FAVORITES ) ), maOKButton ( this, SVX_RES( BTN_OK ) ), maCancelButton ( this, SVX_RES( BTN_CANCEL ) ), maHelpButton ( this, SVX_RES( BTN_HELP ) ), mnThemeId ( -1 ), maStrClickToAddText ( SVX_RES( STR_CLICK_TO_ADD_TEXT ) ), mpSdrView ( pSdrView ), mpModel ( (FmFormModel*)pSdrView->GetModel() ), mppSdrObject ( NULL ), mpDestModel ( NULL ) { FreeResource(); maCtlFavorites.SetDoubleClickHdl( LINK( this, FontWorkGalleryDialog, DoubleClickFavoriteHdl ) ); maOKButton.SetClickHdl( LINK( this, FontWorkGalleryDialog, ClickOKHdl ) ); maCtlFavorites.SetColCount( nColCount ); maCtlFavorites.SetLineCount( nLineCount ); maCtlFavorites.SetExtraSpacing( 3 ); initfavorites( GALLERY_THEME_FONTWORK, maFavoritesHorizontal ); fillFavorites( GALLERY_THEME_FONTWORK, maFavoritesHorizontal ); } static void delete_bitmap( Bitmap* p ) { delete p; } // ----------------------------------------------------------------------- FontWorkGalleryDialog::~FontWorkGalleryDialog() { std::for_each( maFavoritesHorizontal.begin(), maFavoritesHorizontal.end(), delete_bitmap ); } // ----------------------------------------------------------------------- void FontWorkGalleryDialog::initfavorites(sal_uInt16 nThemeId, std::vector< Bitmap * >& rFavorites) { // Ueber die Gallery werden die Favoriten eingelesen ULONG nFavCount = GalleryExplorer::GetSdrObjCount( nThemeId ); // Gallery thema locken GalleryExplorer::BeginLocking(nThemeId); sal_uInt32 nModelPos; FmFormModel *pModel = NULL; for( nModelPos = 0; nModelPos < nFavCount; nModelPos++ ) { Bitmap* pThumb = new Bitmap; if( GalleryExplorer::GetSdrObj( nThemeId, nModelPos, pModel, pThumb ) ) { /* VirtualDevice aVDev; Size aRenderSize( aThumbSize.Width() * 4, aThumbSize.Height() * 4 ); aVDev.SetOutputSizePixel( aRenderSize ); if( GalleryExplorer::DrawCentered( &aVDev, *pModel ) ) { aThumb = aVDev.GetBitmap( Point(), aVDev.GetOutputSizePixel() ); Size aMS( 4, 4 ); BmpFilterParam aParam( aMS ); aThumb.Filter( BMP_FILTER_MOSAIC, &aParam ); aThumb.Scale( aThumbSize ); } */ } rFavorites.push_back( pThumb ); } // Gallery thema freigeben GalleryExplorer::EndLocking(nThemeId); } void FontWorkGalleryDialog::fillFavorites( sal_uInt16 nThemeId, std::vector< Bitmap * >& rFavorites ) { mnThemeId = nThemeId; Size aThumbSize( maCtlFavorites.GetSizePixel() ); aThumbSize.Width() /= nColCount; aThumbSize.Height() /= nLineCount; aThumbSize.Width() -= 12; aThumbSize.Height() -= 12; sal_uInt16 nFavCount = rFavorites.size(); // ValueSet Favoriten if( nFavCount > (nColCount * nLineCount) ) { WinBits nWinBits = maCtlFavorites.GetStyle(); nWinBits |= WB_VSCROLL; maCtlFavorites.SetStyle( nWinBits ); } maCtlFavorites.Clear(); sal_uInt32 nFavorite; for( nFavorite = 1; nFavorite <= nFavCount; nFavorite++ ) { String aStr(SVX_RES(RID_SVXFLOAT3D_FAVORITE)); aStr += sal_Unicode(' '); aStr += String::CreateFromInt32((sal_Int32)nFavorite); Image aThumbImage( *rFavorites[nFavorite-1] ); maCtlFavorites.InsertItem( (sal_uInt16)nFavorite, aThumbImage, aStr ); } } void FontWorkGalleryDialog::changeText( SdrTextObj* pObj ) { if( pObj ) { SdrOutliner& rOutl = mpModel->GetDrawOutliner(pObj); rOutl.SetMinDepth(0); USHORT nOutlMode = rOutl.GetMode(); USHORT nMinDepth = rOutl.GetMinDepth(); Size aPaperSize = rOutl.GetPaperSize(); BOOL bUpdateMode = rOutl.GetUpdateMode(); rOutl.SetUpdateMode(FALSE); rOutl.SetParaAttribs( 0, rOutl.GetEmptyItemSet() ); // #95114# Always set the object's StyleSheet at the Outliner to // use the current objects StyleSheet. Thus it's the same as in // SetText(...). // #95114# Moved this implementation from where SetObjText(...) was called // to inside this method to work even when outliner is fetched here. rOutl.SetStyleSheet(0, pObj->GetStyleSheet()); rOutl.SetPaperSize( pObj->GetLogicRect().GetSize() ); rOutl.SetText( maStrClickToAddText, rOutl.GetParagraph( 0 ) ); pObj->SetOutlinerParaObject( rOutl.CreateParaObject() ); rOutl.Init( nOutlMode ); rOutl.SetParaAttribs( 0, rOutl.GetEmptyItemSet() ); rOutl.SetUpdateMode( bUpdateMode ); rOutl.SetMinDepth( nMinDepth ); rOutl.SetPaperSize( aPaperSize ); rOutl.Clear(); } } void FontWorkGalleryDialog::SetSdrObjectRef( SdrObject** ppSdrObject, SdrModel* pModel ) { mppSdrObject = ppSdrObject; mpDestModel = pModel; } void FontWorkGalleryDialog::insertSelectedFontwork() { USHORT nItemId = maCtlFavorites.GetSelectItemId(); if( nItemId > 0 ) { FmFormModel* pModel = new FmFormModel(); pModel->GetItemPool().FreezeIdRanges(); if( GalleryExplorer::GetSdrObj( mnThemeId, nItemId-1, pModel ) ) { SdrPage* pPage = pModel->GetPage(0); if( pPage && pPage->GetObjCount() ) { SdrObject* pNewObject = pPage->GetObj(0)->Clone(); // center shape on current view OutputDevice* pOutDev = mpSdrView->GetWin(0); if( pOutDev ) { Rectangle aObjRect( pNewObject->GetLogicRect() ); Rectangle aVisArea = pOutDev->PixelToLogic(Rectangle(Point(0,0), pOutDev->GetOutputSizePixel())); /* sal_Int32 nObjHeight = aObjRect.GetHeight(); VirtualDevice aVirDev( 1 ); // calculating the optimal textwidth Font aFont; aFont.SetHeight( nObjHeight ); aVirDev.SetMapMode( MAP_100TH_MM ); aVirDev.SetFont( aFont ); aObjRect.SetSize( Size( aVirDev.GetTextWidth( maStrClickToAddText ), nObjHeight ) ); */ Point aPagePos = aVisArea.Center(); aPagePos.X() -= aObjRect.GetWidth() / 2; aPagePos.Y() -= aObjRect.GetHeight() / 2; Rectangle aNewObjectRectangle(aPagePos, aObjRect.GetSize()); SdrPageView* pPV = mpSdrView->GetPageViewPvNum(0); pNewObject->SetLogicRect(aNewObjectRectangle); if ( mppSdrObject ) { *mppSdrObject = pNewObject; (*mppSdrObject)->SetModel( mpDestModel ); } else if( pPV ) { mpSdrView->InsertObject( pNewObject, *pPV ); // changeText( PTR_CAST( SdrTextObj, pNewObject ) ); } } } } delete pModel; } } // ----------------------------------------------------------------------- IMPL_LINK( FontWorkGalleryDialog, ClickOKHdl, void*, p ) { insertSelectedFontwork(); EndDialog( true ); return 0; } // ----------------------------------------------------------------------- IMPL_LINK( FontWorkGalleryDialog, DoubleClickFavoriteHdl, void*, p ) { insertSelectedFontwork(); EndDialog( true ); return( 0L ); } // ----------------------------------------------------------------------- SFX_IMPL_TOOLBOX_CONTROL( FontWorkShapeTypeControl, SfxStringItem ); FontWorkShapeTypeControl::FontWorkShapeTypeControl( USHORT nSlotId, USHORT nId, ToolBox &rTbx ) : SfxToolBoxControl( nSlotId, nId, rTbx ) { rTbx.SetItemBits( nId, TIB_DROPDOWNONLY | rTbx.GetItemBits( nId ) ); rTbx.Invalidate(); } // ----------------------------------------------------------------------- FontWorkShapeTypeControl::~FontWorkShapeTypeControl() { } // ----------------------------------------------------------------------- SfxPopupWindowType FontWorkShapeTypeControl::GetPopupWindowType() const { return SFX_POPUPWINDOW_ONCLICK; //( aLastAction.getLength() == 0 ? SFX_POPUPWINDOW_ONCLICK : SFX_POPUPWINDOW_ONTIMEOUT ); } // ----------------------------------------------------------------------- SfxPopupWindow* FontWorkShapeTypeControl::CreatePopupWindow() { rtl::OUString aSubTbxResName( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/fontworkshapetype" ) ); createAndPositionSubToolBar( aSubTbxResName ); return NULL; } // ----------------------------------------------------------------------- void FontWorkShapeTypeControl::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ) { SfxToolBoxControl::StateChanged( nSID, eState, pState ); } // ----------------------------------------------------------------------- void FontWorkShapeTypeControl::Select( BOOL bMod1 ) { } // #################################################################### SFX_IMPL_TOOLBOX_CONTROL( FontWorkAlignmentControl, SfxBoolItem ); FontWorkAlignmentWindow::FontWorkAlignmentWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame ) : SfxPopupWindow( nId, rFrame, SVX_RES( RID_SVXFLOAT_FONTWORK_ALIGNMENT )), maImgAlgin1( SVX_RES( IMG_FONTWORK_ALIGN_LEFT_16 ) ), maImgAlgin2( SVX_RES( IMG_FONTWORK_ALIGN_CENTER_16 ) ), maImgAlgin3( SVX_RES( IMG_FONTWORK_ALIGN_RIGHT_16 ) ), maImgAlgin4( SVX_RES( IMG_FONTWORK_ALIGN_WORD_16 ) ), maImgAlgin5( SVX_RES( IMG_FONTWORK_ALIGN_STRETCH_16 ) ), maImgAlgin1h( SVX_RES( IMG_FONTWORK_ALIGN_LEFT_16_H ) ), maImgAlgin2h( SVX_RES( IMG_FONTWORK_ALIGN_CENTER_16_H ) ), maImgAlgin3h( SVX_RES( IMG_FONTWORK_ALIGN_RIGHT_16_H ) ), maImgAlgin4h( SVX_RES( IMG_FONTWORK_ALIGN_WORD_16_H ) ), maImgAlgin5h( SVX_RES( IMG_FONTWORK_ALIGN_STRETCH_16_H ) ), mbPopupMode( true ), mxFrame( rFrame ) { implInit(); } FontWorkAlignmentWindow::FontWorkAlignmentWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, Window* pParentWindow ) : SfxPopupWindow( nId, rFrame, SVX_RES( RID_SVXFLOAT_FONTWORK_ALIGNMENT )), maImgAlgin1( SVX_RES( IMG_FONTWORK_ALIGN_LEFT_16 ) ), maImgAlgin2( SVX_RES( IMG_FONTWORK_ALIGN_CENTER_16 ) ), maImgAlgin3( SVX_RES( IMG_FONTWORK_ALIGN_RIGHT_16 ) ), maImgAlgin4( SVX_RES( IMG_FONTWORK_ALIGN_WORD_16 ) ), maImgAlgin5( SVX_RES( IMG_FONTWORK_ALIGN_STRETCH_16 ) ), maImgAlgin1h( SVX_RES( IMG_FONTWORK_ALIGN_LEFT_16_H ) ), maImgAlgin2h( SVX_RES( IMG_FONTWORK_ALIGN_CENTER_16_H ) ), maImgAlgin3h( SVX_RES( IMG_FONTWORK_ALIGN_RIGHT_16_H ) ), maImgAlgin4h( SVX_RES( IMG_FONTWORK_ALIGN_WORD_16_H ) ), maImgAlgin5h( SVX_RES( IMG_FONTWORK_ALIGN_STRETCH_16_H ) ), mbPopupMode( true ), mxFrame( rFrame ) { implInit(); } void FontWorkAlignmentWindow::implInit() { SetHelpId( HID_POPUP_FONTWORK_ALIGN ); bool bHighContrast = GetDisplayBackground().GetColor().IsDark(); mpMenu = new ToolbarMenu( this, WB_CLIPCHILDREN ); mpMenu->SetHelpId( HID_POPUP_FONTWORK_ALIGN ); mpMenu->SetSelectHdl( LINK( this, FontWorkAlignmentWindow, SelectHdl ) ); mpMenu->appendEntry( 0, String( SVX_RES( STR_ALIGN_LEFT ) ), bHighContrast ? maImgAlgin1h : maImgAlgin1 ); mpMenu->appendEntry( 1, String( SVX_RES( STR_ALIGN_CENTER ) ), bHighContrast ? maImgAlgin2h : maImgAlgin2 ); mpMenu->appendEntry( 2, String( SVX_RES( STR_ALIGN_RIGHT ) ), bHighContrast ? maImgAlgin3h : maImgAlgin3 ); mpMenu->appendEntry( 3, String( SVX_RES( STR_ALIGN_WORD ) ), bHighContrast ? maImgAlgin4h : maImgAlgin4 ); mpMenu->appendEntry( 4, String( SVX_RES( STR_ALIGN_STRETCH ) ), bHighContrast ? maImgAlgin5h : maImgAlgin5 ); SetOutputSizePixel( mpMenu->getMenuSize() ); mpMenu->SetOutputSizePixel( GetOutputSizePixel() ); mpMenu->Show(); FreeResource(); AddStatusListener( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:FontworkAlignment" ))); } SfxPopupWindow* FontWorkAlignmentWindow::Clone() const { return new FontWorkAlignmentWindow( GetId(), mxFrame ); } // ----------------------------------------------------------------------- FontWorkAlignmentWindow::~FontWorkAlignmentWindow() { delete mpMenu; } // ----------------------------------------------------------------------- void FontWorkAlignmentWindow::implSetAlignment( int nSurface, bool bEnabled ) { if( mpMenu ) { int i; for( i = 0; i < 5; i++ ) { mpMenu->checkEntry( i, (i == nSurface) && bEnabled ); mpMenu->enableEntry( i, bEnabled ); } } } // ----------------------------------------------------------------------- void FontWorkAlignmentWindow::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ) { switch( nSID ) { case SID_FONTWORK_ALIGNMENT: { if( eState == SFX_ITEM_DISABLED ) { implSetAlignment( 0, false ); } else { const SfxInt32Item* pStateItem = PTR_CAST( SfxInt32Item, pState ); if( pStateItem ) implSetAlignment( pStateItem->GetValue(), true ); } break; } } } // ----------------------------------------------------------------------- void FontWorkAlignmentWindow::DataChanged( const DataChangedEvent& rDCEvt ) { SfxPopupWindow::DataChanged( rDCEvt ); if( ( rDCEvt.GetType() == DATACHANGED_SETTINGS ) && ( rDCEvt.GetFlags() & SETTINGS_STYLE ) ) { bool bHighContrast = GetDisplayBackground().GetColor().IsDark(); mpMenu->appendEntry( 0, String( SVX_RES( STR_ALIGN_LEFT ) ), bHighContrast ? maImgAlgin1h : maImgAlgin1 ); mpMenu->appendEntry( 1, String( SVX_RES( STR_ALIGN_CENTER ) ), bHighContrast ? maImgAlgin2h : maImgAlgin2 ); mpMenu->appendEntry( 2, String( SVX_RES( STR_ALIGN_RIGHT ) ), bHighContrast ? maImgAlgin3h : maImgAlgin3 ); mpMenu->appendEntry( 3, String( SVX_RES( STR_ALIGN_WORD ) ), bHighContrast ? maImgAlgin4h : maImgAlgin4 ); mpMenu->appendEntry( 4, String( SVX_RES( STR_ALIGN_STRETCH ) ), bHighContrast ? maImgAlgin5h : maImgAlgin5 ); } } // ----------------------------------------------------------------------- IMPL_LINK( FontWorkAlignmentWindow, SelectHdl, void *, pControl ) { if ( IsInPopupMode() ) EndPopupMode(); // SfxDispatcher* pDisp = GetBindings().GetDispatcher(); sal_Int32 nAlignment = mpMenu->getSelectedEntryId(); if( nAlignment >= 0 ) { SfxInt32Item aItem( SID_FONTWORK_ALIGNMENT, nAlignment ); rtl::OUString aCommand( RTL_CONSTASCII_USTRINGPARAM( ".uno:FontworkAlignment" )); Any a; INetURLObject aObj( aCommand ); Sequence< PropertyValue > aArgs( 1 ); aArgs[0].Name = aObj.GetURLPath(); aItem.QueryValue( a ); aArgs[0].Value = a; SfxToolBoxControl::Dispatch( Reference< ::com::sun::star::frame::XDispatchProvider >( mxFrame->getController(), UNO_QUERY ), aCommand, aArgs ); implSetAlignment( nAlignment, true ); } return 0; } // ----------------------------------------------------------------------- void FontWorkAlignmentWindow::StartSelection() { } // ----------------------------------------------------------------------- BOOL FontWorkAlignmentWindow::Close() { return SfxPopupWindow::Close(); } // ----------------------------------------------------------------------- void FontWorkAlignmentWindow::PopupModeEnd() { if ( IsVisible() ) { mbPopupMode = FALSE; } SfxPopupWindow::PopupModeEnd(); } // ----------------------------------------------------------------------- void FontWorkAlignmentWindow::GetFocus (void) { SfxPopupWindow::GetFocus(); // Grab the focus to the line ends value set so that it can be controlled // with the keyboard. if( mpMenu ) mpMenu->GrabFocus(); } // ======================================================================== FontWorkAlignmentControl::FontWorkAlignmentControl( USHORT nSlotId, USHORT nId, ToolBox &rTbx ) : SfxToolBoxControl( nSlotId, nId, rTbx ) { rTbx.SetItemBits( nId, TIB_DROPDOWNONLY | rTbx.GetItemBits( nId ) ); } // ----------------------------------------------------------------------- FontWorkAlignmentControl::~FontWorkAlignmentControl() { } // ----------------------------------------------------------------------- SfxPopupWindowType FontWorkAlignmentControl::GetPopupWindowType() const { return SFX_POPUPWINDOW_ONCLICK; } // ----------------------------------------------------------------------- SfxPopupWindow* FontWorkAlignmentControl::CreatePopupWindow() { FontWorkAlignmentWindow* pWin = new FontWorkAlignmentWindow( GetId(), m_xFrame, &GetToolBox() ); pWin->StartPopupMode( &GetToolBox(), TRUE ); pWin->StartSelection(); SetPopupWindow( pWin ); return pWin; } // ----------------------------------------------------------------------- void FontWorkAlignmentControl::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ) { USHORT nId = GetId(); ToolBox& rTbx = GetToolBox(); rTbx.EnableItem( nId, SFX_ITEM_DISABLED != eState ); rTbx.SetItemState( nId, ( SFX_ITEM_DONTCARE == eState ) ? STATE_DONTKNOW : STATE_NOCHECK ); } // #################################################################### SFX_IMPL_TOOLBOX_CONTROL( FontWorkCharacterSpacingControl, SfxBoolItem ); FontWorkCharacterSpacingWindow::FontWorkCharacterSpacingWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame ) : SfxPopupWindow( nId, rFrame, SVX_RES( RID_SVXFLOAT_FONTWORK_CHARSPACING )), mbPopupMode( true ), mxFrame( rFrame ) { implInit(); } FontWorkCharacterSpacingWindow::FontWorkCharacterSpacingWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, Window* pParentWindow ) : SfxPopupWindow( nId, rFrame, pParentWindow, SVX_RES( RID_SVXFLOAT_FONTWORK_CHARSPACING )), mbPopupMode( true ), mxFrame( rFrame ) { implInit(); } void FontWorkCharacterSpacingWindow::implInit() { SetHelpId( HID_POPUP_FONTWORK_CHARSPACE ); bool bHighContrast = GetDisplayBackground().GetColor().IsDark(); mpMenu = new ToolbarMenu( this, WB_CLIPCHILDREN ); mpMenu->SetHelpId( HID_POPUP_FONTWORK_CHARSPACE ); mpMenu->SetSelectHdl( LINK( this, FontWorkCharacterSpacingWindow, SelectHdl ) ); mpMenu->appendEntry( 0, String( SVX_RES( STR_CHARS_SPACING_VERY_TIGHT ) ), MIB_RADIOCHECK ); mpMenu->appendEntry( 1, String( SVX_RES( STR_CHARS_SPACING_TIGHT ) ), MIB_RADIOCHECK ); mpMenu->appendEntry( 2, String( SVX_RES( STR_CHARS_SPACING_NORMAL ) ), MIB_RADIOCHECK ); mpMenu->appendEntry( 3, String( SVX_RES( STR_CHARS_SPACING_LOOSE ) ), MIB_RADIOCHECK ); mpMenu->appendEntry( 4, String( SVX_RES( STR_CHARS_SPACING_VERY_LOOSE ) ), MIB_RADIOCHECK ); mpMenu->appendEntry( 5, String( SVX_RES( STR_CHARS_SPACING_CUSTOM ) ), MIB_RADIOCHECK ); mpMenu->appendSeparator(); mpMenu->appendEntry( 6, String( SVX_RES( STR_CHARS_SPACING_KERN_PAIRS ) ), MIB_CHECKABLE ); SetOutputSizePixel( mpMenu->getMenuSize() ); mpMenu->SetOutputSizePixel( GetOutputSizePixel() ); mpMenu->Show(); FreeResource(); AddStatusListener( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:FontworkCharacterSpacing" ))); } SfxPopupWindow* FontWorkCharacterSpacingWindow::Clone() const { return new FontWorkCharacterSpacingWindow( GetId(), mxFrame ); } // ----------------------------------------------------------------------- FontWorkCharacterSpacingWindow::~FontWorkCharacterSpacingWindow() { delete mpMenu; } // ----------------------------------------------------------------------- void FontWorkCharacterSpacingWindow::implSetCharacterSpacing( sal_Int32 nCharacterSpacing, bool bEnabled ) { if( mpMenu ) { sal_Int32 i; for ( i = 0; i < 6; i++ ) { mpMenu->checkEntry( i, sal_False ); mpMenu->enableEntry( i, bEnabled ); } if ( nCharacterSpacing != -1 ) { sal_Int32 nEntry; switch( nCharacterSpacing ) { case 80 : nEntry = 0; break; case 90 : nEntry = 1; break; case 100 : nEntry = 2; break; case 120 : nEntry = 3; break; case 150 : nEntry = 4; break; default : nEntry = 5; break; } mpMenu->checkEntry( nEntry, bEnabled ); } } } void FontWorkCharacterSpacingWindow::implSetKernCharacterPairs( sal_Bool bKernOnOff, bool bEnabled ) { if( mpMenu ) { mpMenu->enableEntry( 6, bEnabled ); mpMenu->checkEntry( 6, bEnabled ); } } // ----------------------------------------------------------------------- void FontWorkCharacterSpacingWindow::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ) { switch( nSID ) { case SID_FONTWORK_CHARACTER_SPACING: { if( eState == SFX_ITEM_DISABLED ) implSetCharacterSpacing( 0, false ); else { const SfxInt32Item* pStateItem = PTR_CAST( SfxInt32Item, pState ); if( pStateItem ) implSetCharacterSpacing( pStateItem->GetValue(), true ); } break; } break; case SID_FONTWORK_KERN_CHARACTER_PAIRS : { if( eState == SFX_ITEM_DISABLED ) implSetKernCharacterPairs( 0, false ); else { const SfxBoolItem* pStateItem = PTR_CAST( SfxBoolItem, pState ); if( pStateItem ) implSetKernCharacterPairs( pStateItem->GetValue(), true ); } } break; } } // ----------------------------------------------------------------------- void FontWorkCharacterSpacingWindow::DataChanged( const DataChangedEvent& rDCEvt ) { SfxPopupWindow::DataChanged( rDCEvt ); if( ( rDCEvt.GetType() == DATACHANGED_SETTINGS ) && ( rDCEvt.GetFlags() & SETTINGS_STYLE ) ) { bool bHighContrast = GetDisplayBackground().GetColor().IsDark(); mpMenu->appendEntry( 0, String( SVX_RES( STR_CHARS_SPACING_VERY_TIGHT ) ), MIB_CHECKABLE ); mpMenu->appendEntry( 1, String( SVX_RES( STR_CHARS_SPACING_TIGHT ) ), MIB_CHECKABLE ); mpMenu->appendEntry( 2, String( SVX_RES( STR_CHARS_SPACING_NORMAL ) ), MIB_CHECKABLE ); mpMenu->appendEntry( 3, String( SVX_RES( STR_CHARS_SPACING_LOOSE ) ), MIB_CHECKABLE ); mpMenu->appendEntry( 4, String( SVX_RES( STR_CHARS_SPACING_VERY_LOOSE ) ), MIB_CHECKABLE ); mpMenu->appendEntry( 5, String( SVX_RES( STR_CHARS_SPACING_CUSTOM ) ), MIB_CHECKABLE ); mpMenu->appendSeparator(); mpMenu->appendEntry( 6, String( SVX_RES( STR_CHARS_SPACING_KERN_PAIRS ) ), MIB_CHECKABLE ); } } // ----------------------------------------------------------------------- IMPL_LINK( FontWorkCharacterSpacingWindow, SelectHdl, void *, pControl ) { if ( IsInPopupMode() ) EndPopupMode(); sal_Int32 nSelection = mpMenu->getSelectedEntryId(); sal_Int32 nCharacterSpacing; switch( nSelection ) { case 0 : nCharacterSpacing = 80; break; case 1 : nCharacterSpacing = 90; break; case 2 : nCharacterSpacing = 100; break; case 3 : nCharacterSpacing = 120; break; case 4 : nCharacterSpacing = 150; break; default : nCharacterSpacing = 100; break; } if ( nSelection == 5 ) // custom spacing { SfxInt32Item aItem( SID_FONTWORK_CHARACTER_SPACING, nCharacterSpacing ); rtl::OUString aCommand( RTL_CONSTASCII_USTRINGPARAM( ".uno:FontworkCharacterSpacingDialog" )); Any a; Sequence< PropertyValue > aArgs( 1 ); aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "FontworkCharacterSpacing" )); aItem.QueryValue( a ); aArgs[0].Value = a; SfxToolBoxControl::Dispatch( Reference< ::com::sun::star::frame::XDispatchProvider >( mxFrame->getController(), UNO_QUERY ), aCommand, aArgs ); } else if ( nSelection == 6 ) // KernCharacterPairs { sal_Bool bOnOff = sal_True; SfxBoolItem aItem( SID_FONTWORK_KERN_CHARACTER_PAIRS, bOnOff ); rtl::OUString aCommand( RTL_CONSTASCII_USTRINGPARAM( ".uno:FontworkKernCharacterPairs" )); Any a; Sequence< PropertyValue > aArgs( 1 ); aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "FontworkKernCharacterPairs" )); aItem.QueryValue( a ); aArgs[0].Value = a; SfxToolBoxControl::Dispatch( Reference< ::com::sun::star::frame::XDispatchProvider >( mxFrame->getController(), UNO_QUERY ), aCommand, aArgs ); implSetKernCharacterPairs( bOnOff, true ); } else if( nSelection >= 0 ) { SfxInt32Item aItem( SID_FONTWORK_CHARACTER_SPACING, nCharacterSpacing ); rtl::OUString aCommand( RTL_CONSTASCII_USTRINGPARAM( ".uno:FontworkCharacterSpacing" )); Any a; INetURLObject aObj( aCommand ); Sequence< PropertyValue > aArgs( 1 ); aArgs[0].Name = aObj.GetURLPath(); aItem.QueryValue( a ); aArgs[0].Value = a; SfxToolBoxControl::Dispatch( Reference< ::com::sun::star::frame::XDispatchProvider >( mxFrame->getController(), UNO_QUERY ), aCommand, aArgs ); implSetCharacterSpacing( nCharacterSpacing, true ); } return 0; } // ----------------------------------------------------------------------- void FontWorkCharacterSpacingWindow::StartSelection() { } // ----------------------------------------------------------------------- BOOL FontWorkCharacterSpacingWindow::Close() { return SfxPopupWindow::Close(); } // ----------------------------------------------------------------------- void FontWorkCharacterSpacingWindow::PopupModeEnd() { if ( IsVisible() ) { mbPopupMode = FALSE; } SfxPopupWindow::PopupModeEnd(); } // ----------------------------------------------------------------------- void FontWorkCharacterSpacingWindow::GetFocus (void) { SfxPopupWindow::GetFocus(); // Grab the focus to the line ends value set so that it can be controlled // with the keyboard. if( mpMenu ) mpMenu->GrabFocus(); } // ======================================================================== FontWorkCharacterSpacingControl::FontWorkCharacterSpacingControl( USHORT nSlotId, USHORT nId, ToolBox &rTbx ) : SfxToolBoxControl( nSlotId, nId, rTbx ) { rTbx.SetItemBits( nId, TIB_DROPDOWNONLY | rTbx.GetItemBits( nId ) ); } // ----------------------------------------------------------------------- FontWorkCharacterSpacingControl::~FontWorkCharacterSpacingControl() { } // ----------------------------------------------------------------------- SfxPopupWindowType FontWorkCharacterSpacingControl::GetPopupWindowType() const { return SFX_POPUPWINDOW_ONCLICK; } // ----------------------------------------------------------------------- SfxPopupWindow* FontWorkCharacterSpacingControl::CreatePopupWindow() { FontWorkCharacterSpacingWindow* pWin = new FontWorkCharacterSpacingWindow( GetId(), m_xFrame, &GetToolBox() ); pWin->StartPopupMode( &GetToolBox(), TRUE ); pWin->StartSelection(); SetPopupWindow( pWin ); return pWin; } // ----------------------------------------------------------------------- void FontWorkCharacterSpacingControl::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ) { USHORT nId = GetId(); ToolBox& rTbx = GetToolBox(); rTbx.EnableItem( nId, SFX_ITEM_DISABLED != eState ); rTbx.SetItemState( nId, ( SFX_ITEM_DONTCARE == eState ) ? STATE_DONTKNOW : STATE_NOCHECK ); } // ----------------------------------------------------------------------- FontworkCharacterSpacingDialog::FontworkCharacterSpacingDialog( Window* pParent, sal_Int32 nScale ) : ModalDialog( pParent, SVX_RES( RID_SVX_MDLG_FONTWORK_CHARSPACING ) ), maFLScale( this, SVX_RES( FT_VALUE ) ), maMtrScale( this, SVX_RES( MF_VALUE ) ), maOKButton( this, SVX_RES( BTN_OK ) ), maCancelButton( this, SVX_RES( BTN_CANCEL ) ), maHelpButton( this, SVX_RES( BTN_HELP ) ) { maMtrScale.SetValue( nScale ); FreeResource(); } FontworkCharacterSpacingDialog::~FontworkCharacterSpacingDialog() { } sal_Int32 FontworkCharacterSpacingDialog::getScale() const { return (sal_Int32)maMtrScale.GetValue(); }
/************************************************************************* * * $RCSfile: unoparagraph.cxx,v $ * * $Revision: 1.30 $ * * last change: $Author: obo $ $Date: 2005-04-18 11:30:13 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include <cmdid.h> #ifndef _UNOMID_H #include <unomid.h> #endif #ifndef _UNOOBJ_HXX #include <unoobj.hxx> #endif #ifndef _UNOMAP_HXX #include <unomap.hxx> #endif #ifndef _UNOCRSR_HXX #include <unocrsr.hxx> #endif #ifndef _UNOPRNMS_HXX #include <unoprnms.hxx> #endif #ifndef _UNOCRSRHELPER_HXX #include <unocrsrhelper.hxx> #endif #ifndef _DOC_HXX //autogen #include <doc.hxx> #endif #ifndef _NDTXT_HXX //autogen #include <ndtxt.hxx> #endif #ifndef _VOS_MUTEX_HXX_ //autogen #include <vos/mutex.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #define _SVSTDARR_USHORTS #define _SVSTDARR_USHORTSSORT #include <svtools/svstdarr.hxx> //#ifndef _COM_SUN_STAR_BEANS_SETPROPERTYTOLERANTFAILED_HPP_ //#include <com/sun/star/beans/SetPropertyTolerantFailed.hpp> //#endif //#ifndef _COM_SUN_STAR_BEANS_GETPROPERTYTOLERANTRESULT_HPP_ //#include <com/sun/star/beans/GetPropertyTolerantResult.hpp> //#endif //#ifndef _COM_SUN_STAR_BEANS_TOLERANTPROPERTYSETRESULTTYPE_HPP_ //#include <com/sun/star/beans/TolerantPropertySetResultType.hpp> //#endif #ifndef _COM_SUN_STAR_BEANS_PropertyAttribute_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_WRAPTEXTMODE_HPP_ #include <com/sun/star/text/WrapTextMode.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_TEXTCONTENTANCHORTYPE_HPP_ #include <com/sun/star/text/TextContentAnchorType.hpp> #endif using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::text; using namespace ::com::sun::star::container; using namespace ::com::sun::star::beans; //using namespace ::com::sun::star::drawing; using namespace ::rtl; /****************************************************************** * forward declarations ******************************************************************/ beans::PropertyState lcl_SwXParagraph_getPropertyState( SwUnoCrsr& rUnoCrsr, const SwAttrSet** ppSet, const SfxItemPropertyMap& rMap, sal_Bool &rAttrSetFetched ) throw( beans::UnknownPropertyException); /****************************************************************** * SwXParagraph ******************************************************************/ /* -----------------------------11.07.00 12:10-------------------------------- ---------------------------------------------------------------------------*/ SwXParagraph* SwXParagraph::GetImplementation(Reference< XInterface> xRef ) { uno::Reference<lang::XUnoTunnel> xParaTunnel( xRef, uno::UNO_QUERY); if(xParaTunnel.is()) return (SwXParagraph*)xParaTunnel->getSomething(SwXParagraph::getUnoTunnelId()); return 0; } /* -----------------------------13.03.00 12:15-------------------------------- ---------------------------------------------------------------------------*/ const uno::Sequence< sal_Int8 > & SwXParagraph::getUnoTunnelId() { static uno::Sequence< sal_Int8 > aSeq = ::CreateUnoTunnelId(); return aSeq; } /* -----------------------------10.03.00 18:04-------------------------------- ---------------------------------------------------------------------------*/ sal_Int64 SAL_CALL SwXParagraph::getSomething( const uno::Sequence< sal_Int8 >& rId ) throw(uno::RuntimeException) { if( rId.getLength() == 16 && 0 == rtl_compareMemory( getUnoTunnelId().getConstArray(), rId.getConstArray(), 16 ) ) { return (sal_Int64)this; } return 0; } /* -----------------------------06.04.00 16:37-------------------------------- ---------------------------------------------------------------------------*/ OUString SwXParagraph::getImplementationName(void) throw( RuntimeException ) { return C2U("SwXParagraph"); } /* -----------------------------06.04.00 16:37-------------------------------- ---------------------------------------------------------------------------*/ BOOL SwXParagraph::supportsService(const OUString& rServiceName) throw( RuntimeException ) { String sServiceName(rServiceName); return sServiceName.EqualsAscii("com.sun.star.text.TextContent") || sServiceName.EqualsAscii("com.sun.star.text.Paragraph") || sServiceName.EqualsAscii("com.sun.star.style.CharacterProperties")|| sServiceName.EqualsAscii("com.sun.star.style.CharacterPropertiesAsian")|| sServiceName.EqualsAscii("com.sun.star.style.CharacterPropertiesComplex")|| sServiceName.EqualsAscii("com.sun.star.style.ParagraphProperties") || sServiceName.EqualsAscii("com.sun.star.style.ParagraphPropertiesAsian") || sServiceName.EqualsAscii("com.sun.star.style.ParagraphPropertiesComplex"); } /* -----------------------------06.04.00 16:37-------------------------------- ---------------------------------------------------------------------------*/ Sequence< OUString > SwXParagraph::getSupportedServiceNames(void) throw( RuntimeException ) { Sequence< OUString > aRet(8); OUString* pArray = aRet.getArray(); pArray[0] = C2U("com.sun.star.text.Paragraph"); pArray[1] = C2U("com.sun.star.style.CharacterProperties"); pArray[2] = C2U("com.sun.star.style.CharacterPropertiesAsian"); pArray[3] = C2U("com.sun.star.style.CharacterPropertiesComplex"); pArray[4] = C2U("com.sun.star.style.ParagraphProperties"); pArray[5] = C2U("com.sun.star.style.ParagraphPropertiesAsian"); pArray[6] = C2U("com.sun.star.style.ParagraphPropertiesComplex"); pArray[7] = C2U("com.sun.star.text.TextContent"); return aRet; } /*-- 11.12.98 08:12:47--------------------------------------------------- -----------------------------------------------------------------------*/ SwXParagraph::SwXParagraph() : aLstnrCntnr( (XTextRange*)this), xParentText(0), aPropSet(aSwMapProvider.GetPropertyMap(PROPERTY_MAP_PARAGRAPH)), m_bIsDescriptor(TRUE), nSelectionStartPos(-1), nSelectionEndPos(-1) { } /*-- 11.12.98 08:12:47--------------------------------------------------- -----------------------------------------------------------------------*/ SwXParagraph::SwXParagraph(SwXText* pParent, SwUnoCrsr* pCrsr, sal_Int32 nSelStart, sal_Int32 nSelEnd) : SwClient(pCrsr), xParentText(pParent), aLstnrCntnr( (XTextRange*)this), aPropSet(aSwMapProvider.GetPropertyMap(PROPERTY_MAP_PARAGRAPH)), m_bIsDescriptor(FALSE), nSelectionStartPos(nSelStart), nSelectionEndPos(nSelEnd) { } /*-- 11.12.98 08:12:48--------------------------------------------------- -----------------------------------------------------------------------*/ SwXParagraph::~SwXParagraph() { SwUnoCrsr* pUnoCrsr = GetCrsr(); if(pUnoCrsr) delete pUnoCrsr; } /* -----------------------------11.07.00 14:48-------------------------------- ---------------------------------------------------------------------------*/ void SwXParagraph::attachToText(SwXText* pParent, SwUnoCrsr* pCrsr) { DBG_ASSERT(m_bIsDescriptor, "Paragraph is not a descriptor") if(m_bIsDescriptor) { m_bIsDescriptor = FALSE; pCrsr->Add(this); xParentText = pParent; if(m_sText.getLength()) { try { setString(m_sText); } catch(...){} m_sText = OUString(); } } } /*-- 11.12.98 08:12:49--------------------------------------------------- -----------------------------------------------------------------------*/ Reference< XPropertySetInfo > SwXParagraph::getPropertySetInfo(void) throw( RuntimeException ) { static Reference< XPropertySetInfo > xRef = aPropSet.getPropertySetInfo(); return xRef; } /*-- 11.12.98 08:12:49--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::setPropertyValue(const OUString& rPropertyName, const Any& aValue) throw( UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); Sequence<OUString> aPropertyNames(1); aPropertyNames.getArray()[0] = rPropertyName; Sequence<Any> aValues(1); aValues.getArray()[0] = aValue; SetPropertyValues_Impl( aPropertyNames, aValues ); } /*-- 11.12.98 08:12:49--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Any SwXParagraph::getPropertyValue(const OUString& rPropertyName) throw( UnknownPropertyException, WrappedTargetException, RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); Sequence<OUString> aPropertyNames(1); aPropertyNames.getArray()[0] = rPropertyName; Sequence< Any > aRet = GetPropertyValues_Impl(aPropertyNames ); return aRet.getConstArray()[0]; } /* -----------------------------02.04.01 11:43-------------------------------- ---------------------------------------------------------------------------*/ void SAL_CALL SwXParagraph::SetPropertyValues_Impl( const uno::Sequence< OUString >& rPropertyNames, const uno::Sequence< Any >& rValues ) throw( UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException) { SwUnoCrsr* pUnoCrsr = GetCrsr(); if(pUnoCrsr) { const OUString* pPropertyNames = rPropertyNames.getConstArray(); const Any* pValues = rValues.getConstArray(); const SfxItemPropertyMap* pMap = aPropSet.getPropertyMap(); OUString sTmp; SwParaSelection aParaSel(pUnoCrsr); for(sal_Int32 nProp = 0; nProp < rPropertyNames.getLength(); nProp++) { pMap = SfxItemPropertyMap::GetByName(pMap, pPropertyNames[nProp]); if(!pMap) throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + pPropertyNames[nProp], static_cast < cppu::OWeakObject * > ( this ) ); else { if ( pMap->nFlags & PropertyAttribute::READONLY) throw PropertyVetoException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only: " ) ) + pPropertyNames[nProp], static_cast < cppu::OWeakObject * > ( this ) ); SwXTextCursor::SetPropertyValue(*pUnoCrsr, aPropSet, sTmp, pValues[nProp], pMap); pMap++; } } } else throw uno::RuntimeException(); } void SwXParagraph::setPropertyValues( const Sequence< OUString >& rPropertyNames, const Sequence< Any >& rValues ) throw(PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException) { vos::OGuard aGuard(Application::GetSolarMutex()); // workaround for bad designed API try { SetPropertyValues_Impl( rPropertyNames, rValues ); } catch (UnknownPropertyException &rException) { // wrap the original (here not allowed) exception in // a WrappedTargetException that gets thrown instead. WrappedTargetException aWExc; aWExc.TargetException <<= rException; throw aWExc; } } /* -----------------------------02.04.01 11:43-------------------------------- ---------------------------------------------------------------------------*/ uno::Sequence< Any > SAL_CALL SwXParagraph::GetPropertyValues_Impl( const uno::Sequence< OUString > & rPropertyNames ) throw( UnknownPropertyException, WrappedTargetException, RuntimeException ) { Sequence< Any > aValues(rPropertyNames.getLength()); SwUnoCrsr* pUnoCrsr = ((SwXParagraph*)this)->GetCrsr(); if(pUnoCrsr) { Any* pValues = aValues.getArray(); const OUString* pPropertyNames = rPropertyNames.getConstArray(); const SfxItemPropertyMap* pMap = aPropSet.getPropertyMap(); SwNode& rTxtNode = pUnoCrsr->GetPoint()->nNode.GetNode(); SwAttrSet& rAttrSet = ((SwTxtNode&)rTxtNode).GetSwAttrSet(); for(sal_Int32 nProp = 0; nProp < rPropertyNames.getLength(); nProp++) { pMap = SfxItemPropertyMap::GetByName(pMap, pPropertyNames[nProp]); if(pMap) { if(!SwXParagraph::getDefaultTextContentValue( pValues[nProp], pPropertyNames[nProp], pMap->nWID)) { BOOL bDone = FALSE; PropertyState eTemp; bDone = SwUnoCursorHelper::getCrsrPropertyValue( pMap, *pUnoCrsr, &(pValues[nProp]), eTemp, rTxtNode.GetTxtNode() ); if(!bDone) pValues[nProp] = aPropSet.getPropertyValue(*pMap, rAttrSet); } ++pMap; } else throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + pPropertyNames[nProp], static_cast < cppu::OWeakObject * > ( this ) ); } } else throw RuntimeException(); return aValues; } /* -----------------------------04.11.03 11:43-------------------------------- ---------------------------------------------------------------------------*/ Sequence< Any > SwXParagraph::getPropertyValues( const Sequence< OUString >& rPropertyNames ) throw(RuntimeException) { vos::OGuard aGuard(Application::GetSolarMutex()); Sequence< Any > aValues; // workaround for bad designed API try { aValues = GetPropertyValues_Impl( rPropertyNames ); } catch (UnknownPropertyException &) { throw RuntimeException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property exception caught" ) ), static_cast < cppu::OWeakObject * > ( this ) ); } catch (WrappedTargetException &) { throw RuntimeException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "WrappedTargetException caught" ) ), static_cast < cppu::OWeakObject * > ( this ) ); } return aValues; } /* -----------------------------02.04.01 11:43-------------------------------- ---------------------------------------------------------------------------*/ void SwXParagraph::addPropertiesChangeListener( const Sequence< OUString >& aPropertyNames, const Reference< XPropertiesChangeListener >& xListener ) throw(RuntimeException) {} /* -----------------------------02.04.01 11:43-------------------------------- ---------------------------------------------------------------------------*/ void SwXParagraph::removePropertiesChangeListener( const Reference< XPropertiesChangeListener >& xListener ) throw(RuntimeException) {} /* -----------------------------02.04.01 11:43-------------------------------- ---------------------------------------------------------------------------*/ void SwXParagraph::firePropertiesChangeEvent( const Sequence< OUString >& aPropertyNames, const Reference< XPropertiesChangeListener >& xListener ) throw(RuntimeException) {} /* -----------------------------25.09.03 11:09-------------------------------- ---------------------------------------------------------------------------*/ /* disabled for #i46921# uno::Sequence< SetPropertyTolerantFailed > SAL_CALL SwXParagraph::setPropertyValuesTolerant( const uno::Sequence< OUString >& rPropertyNames, const uno::Sequence< Any >& rValues ) throw (lang::IllegalArgumentException, uno::RuntimeException) { vos::OGuard aGuard( Application::GetSolarMutex() ); if (rPropertyNames.getLength() != rValues.getLength()) throw IllegalArgumentException(); SwUnoCrsr* pUnoCrsr = ((SwXParagraph*)this)->GetCrsr(); if(!pUnoCrsr) throw RuntimeException(); SwNode& rTxtNode = pUnoCrsr->GetPoint()->nNode.GetNode(); SwAttrSet& rAttrSet = ((SwTxtNode&)rTxtNode).GetSwAttrSet(); USHORT nAttrCount = rAttrSet.Count(); sal_Int32 nProps = rPropertyNames.getLength(); const OUString *pProp = rPropertyNames.getConstArray(); sal_Int32 nVals = rValues.getLength(); const Any *pValue = rValues.getConstArray(); sal_Int32 nFailed = 0; uno::Sequence< SetPropertyTolerantFailed > aFailed( nProps ); SetPropertyTolerantFailed *pFailed = aFailed.getArray(); // get entry to start with const SfxItemPropertyMap* pStartEntry = aPropSet.getPropertyMap(); OUString sTmp; SwParaSelection aParaSel( pUnoCrsr ); for (sal_Int32 i = 0; i < nProps; ++i) { try { pFailed[ nFailed ].Name = pProp[i]; const SfxItemPropertyMap* pEntry = SfxItemPropertyMap::GetByName( pStartEntry, pProp[i] ); if (!pEntry) pFailed[ nFailed++ ].Result = TolerantPropertySetResultType::UNKNOWN_PROPERTY; else { // set property value // (compare to SwXParagraph::setPropertyValues) if (pEntry->nFlags & PropertyAttribute::READONLY) pFailed[ nFailed++ ].Result = TolerantPropertySetResultType::PROPERTY_VETO; else { SwXTextCursor::SetPropertyValue( *pUnoCrsr, aPropSet, sTmp, pValue[i], pEntry ); } // continue with search for next property after current entry // (property map and sequence of property names are sorted!) pStartEntry = ++pEntry; } } catch (UnknownPropertyException &) { // should not occur because property was searched for before DBG_ERROR( "unexpected exception catched" ); pFailed[ nFailed++ ].Result = TolerantPropertySetResultType::UNKNOWN_PROPERTY; } catch (IllegalArgumentException &) { pFailed[ nFailed++ ].Result = TolerantPropertySetResultType::ILLEGAL_ARGUMENT; } catch (PropertyVetoException &) { pFailed[ nFailed++ ].Result = TolerantPropertySetResultType::PROPERTY_VETO; } catch (WrappedTargetException &) { pFailed[ nFailed++ ].Result = TolerantPropertySetResultType::WRAPPED_TARGET; } } aFailed.realloc( nFailed ); return aFailed; } uno::Sequence< GetPropertyTolerantResult > SAL_CALL SwXParagraph::getPropertyValuesTolerant( const uno::Sequence< OUString >& rPropertyNames ) throw (uno::RuntimeException) { vos::OGuard aGuard( Application::GetSolarMutex() ); uno::Sequence< GetDirectPropertyTolerantResult > aTmpRes( GetPropertyValuesTolerant_Impl( rPropertyNames, sal_False ) ); const GetDirectPropertyTolerantResult *pTmpRes = aTmpRes.getConstArray(); // copy temporary result to final result type sal_Int32 nLen = aTmpRes.getLength(); uno::Sequence< GetPropertyTolerantResult > aRes( nLen ); GetPropertyTolerantResult *pRes = aRes.getArray(); for (sal_Int32 i = 0; i < nLen; i++) *pRes++ = *pTmpRes++; return aRes; } uno::Sequence< GetDirectPropertyTolerantResult > SAL_CALL SwXParagraph::getDirectPropertyValuesTolerant( const uno::Sequence< OUString >& rPropertyNames ) throw (uno::RuntimeException) { vos::OGuard aGuard( Application::GetSolarMutex() ); return GetPropertyValuesTolerant_Impl( rPropertyNames, sal_True ); } uno::Sequence< GetDirectPropertyTolerantResult > SAL_CALL SwXParagraph::GetPropertyValuesTolerant_Impl( const uno::Sequence< OUString >& rPropertyNames, sal_Bool bDirectValuesOnly ) throw (uno::RuntimeException) { vos::OGuard aGuard( Application::GetSolarMutex() ); SwUnoCrsr* pUnoCrsr = ((SwXParagraph*)this)->GetCrsr(); if (!pUnoCrsr) throw RuntimeException(); SwNode& rTxtNode = pUnoCrsr->GetPoint()->nNode.GetNode(); SwAttrSet& rAttrSet = ((SwTxtNode&)rTxtNode).GetSwAttrSet(); USHORT nAttrCount = rAttrSet.Count(); sal_Int32 nProps = rPropertyNames.getLength(); const OUString *pProp = rPropertyNames.getConstArray(); uno::Sequence< GetDirectPropertyTolerantResult > aResult( nProps ); GetDirectPropertyTolerantResult *pResult = aResult.getArray(); sal_Int32 nIdx = 0; // get entry to start with const SfxItemPropertyMap *pStartEntry = aPropSet.getPropertyMap(); for (sal_Int32 i = 0; i < nProps; ++i) { DBG_ASSERT( nIdx < nProps, "index out ouf bounds" ); GetDirectPropertyTolerantResult &rResult = pResult[nIdx]; try { rResult.Name = pProp[i]; const SfxItemPropertyMap *pEntry = SfxItemPropertyMap::GetByName( pStartEntry, pProp[i] ); if (!pEntry) // property available? rResult.Result = TolerantPropertySetResultType::UNKNOWN_PROPERTY; else { // get property state // (compare to SwXParagraph::getPropertyState) const SwAttrSet *pAttrSet = &rAttrSet; sal_Bool bAttrSetFetched = sal_True; PropertyState eState = lcl_SwXParagraph_getPropertyState( *pUnoCrsr, &pAttrSet, *pEntry, bAttrSetFetched ); rResult.State = eState; // if (bDirectValuesOnly && PropertyState_DIRECT_VALUE != eState) // rResult.Result = TolerantPropertySetResultType::NO_DIRECT_VALUE; // else rResult.Result = TolerantPropertySetResultType::UNKNOWN_FAILURE; if (!bDirectValuesOnly || PropertyState_DIRECT_VALUE == eState) { // get property value // (compare to SwXParagraph::getPropertyValue(s)) Any aValue; if (!SwXParagraph::getDefaultTextContentValue( aValue, pProp[i], pEntry->nWID ) ) { // handle properties that are not part of the attribute // and thus only pretendend to be paragraph attributes BOOL bDone = FALSE; PropertyState eTemp; bDone = SwUnoCursorHelper::getCrsrPropertyValue( pEntry, *pUnoCrsr, &aValue, eTemp, rTxtNode.GetTxtNode() ); // if not found try the real paragraph attributes... if (!bDone) aValue = aPropSet.getPropertyValue( *pEntry, rAttrSet ); } rResult.Value = aValue; rResult.Result = TolerantPropertySetResultType::SUCCESS; nIdx++; } // this assertion should never occur! DBG_ASSERT( nIdx < 1 || pResult[nIdx - 1].Result != TolerantPropertySetResultType::UNKNOWN_FAILURE, "unknown failure while retrieving property" ); // continue with search for next property after current entry // (property map and sequence of property names are sorted!) pStartEntry = ++pEntry; } } catch (UnknownPropertyException &) { // should not occur because property was searched for before DBG_ERROR( "unexpected exception catched" ); rResult.Result = TolerantPropertySetResultType::UNKNOWN_PROPERTY; } catch (IllegalArgumentException &) { rResult.Result = TolerantPropertySetResultType::ILLEGAL_ARGUMENT; } catch (PropertyVetoException &) { rResult.Result = TolerantPropertySetResultType::PROPERTY_VETO; } catch (WrappedTargetException &) { rResult.Result = TolerantPropertySetResultType::WRAPPED_TARGET; } } // resize to actually used size aResult.realloc( nIdx ); return aResult; } */ /* -----------------------------12.09.00 11:09-------------------------------- ---------------------------------------------------------------------------*/ BOOL SwXParagraph::getDefaultTextContentValue(Any& rAny, const OUString& rPropertyName, USHORT nWID) { if(!nWID) { if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_ANCHOR_TYPE))) nWID = FN_UNO_ANCHOR_TYPE; else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_ANCHOR_TYPES))) nWID = FN_UNO_ANCHOR_TYPES; else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_TEXT_WRAP))) nWID = FN_UNO_TEXT_WRAP; else return FALSE; } switch(nWID) { case FN_UNO_TEXT_WRAP: rAny <<= WrapTextMode_NONE; break; case FN_UNO_ANCHOR_TYPE: rAny <<= TextContentAnchorType_AT_PARAGRAPH; break; case FN_UNO_ANCHOR_TYPES: { Sequence<TextContentAnchorType> aTypes(1); TextContentAnchorType* pArray = aTypes.getArray(); pArray[0] = TextContentAnchorType_AT_PARAGRAPH; rAny.setValue(&aTypes, ::getCppuType((uno::Sequence<TextContentAnchorType>*)0)); } break; default: return FALSE; } return TRUE; } /*-- 11.12.98 08:12:50--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::addPropertyChangeListener( const OUString& PropertyName, const uno::Reference< beans::XPropertyChangeListener > & aListener) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException ) { DBG_WARNING("not implemented") } /*-- 11.12.98 08:12:50--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::removePropertyChangeListener(const OUString& PropertyName, const uno::Reference< beans::XPropertyChangeListener > & aListener) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException ) { DBG_WARNING("not implemented") } /*-- 11.12.98 08:12:50--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::addVetoableChangeListener(const OUString& PropertyName, const uno::Reference< beans::XVetoableChangeListener > & aListener) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException ) { DBG_WARNING("not implemented") } /*-- 11.12.98 08:12:51--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::removeVetoableChangeListener(const OUString& PropertyName, const uno::Reference< beans::XVetoableChangeListener > & aListener) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException ) { DBG_WARNING("not implemented") } //----------------------------------------------------------------------------- beans::PropertyState lcl_SwXParagraph_getPropertyState( SwUnoCrsr& rUnoCrsr, const SwAttrSet** ppSet, const SfxItemPropertyMap& rMap, sal_Bool &rAttrSetFetched ) throw( beans::UnknownPropertyException) { beans::PropertyState eRet = beans::PropertyState_DEFAULT_VALUE; if(!(*ppSet) && !rAttrSetFetched ) { SwNode& rTxtNode = rUnoCrsr.GetPoint()->nNode.GetNode(); (*ppSet) = ((SwTxtNode&)rTxtNode).GetpSwAttrSet(); rAttrSetFetched = sal_True; } switch( rMap.nWID ) { case FN_UNO_NUM_RULES: //wenn eine Numerierung gesetzt ist, dann hier herausreichen, sonst nichts tun SwUnoCursorHelper::getNumberingProperty( rUnoCrsr, eRet, NULL ); break; case FN_UNO_ANCHOR_TYPES: break; case RES_ANCHOR: if ( MID_SURROUND_SURROUNDTYPE != rMap.nMemberId ) goto lcl_SwXParagraph_getPropertyStateDEFAULT; break; case RES_SURROUND: if ( MID_ANCHOR_ANCHORTYPE != rMap.nMemberId ) goto lcl_SwXParagraph_getPropertyStateDEFAULT; break; case FN_UNO_PARA_STYLE: case FN_UNO_PARA_CONDITIONAL_STYLE_NAME: { SwFmtColl* pFmt = SwXTextCursor::GetCurTxtFmtColl( rUnoCrsr, rMap.nWID == FN_UNO_PARA_CONDITIONAL_STYLE_NAME); eRet = pFmt ? beans::PropertyState_DIRECT_VALUE : beans::PropertyState_AMBIGUOUS_VALUE; } break; case FN_UNO_PAGE_STYLE: { String sVal; SwUnoCursorHelper::GetCurPageStyle( rUnoCrsr, sVal ); eRet = sVal.Len() ? beans::PropertyState_DIRECT_VALUE : beans::PropertyState_AMBIGUOUS_VALUE; } break; lcl_SwXParagraph_getPropertyStateDEFAULT: default: if((*ppSet) && SFX_ITEM_SET == (*ppSet)->GetItemState(rMap.nWID, FALSE)) eRet = beans::PropertyState_DIRECT_VALUE; break; } return eRet; } /*-- 05.03.99 11:37:30--------------------------------------------------- -----------------------------------------------------------------------*/ beans::PropertyState SwXParagraph::getPropertyState(const OUString& rPropertyName) throw( beans::UnknownPropertyException, uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); beans::PropertyState eRet = beans::PropertyState_DEFAULT_VALUE; SwUnoCrsr* pUnoCrsr = ((SwXParagraph*)this)->GetCrsr(); if( pUnoCrsr ) { const SwAttrSet* pSet = 0; const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName ); if(!pMap) throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); sal_Bool bDummy = sal_False; eRet = lcl_SwXParagraph_getPropertyState( *pUnoCrsr, &pSet, *pMap, bDummy ); } else throw uno::RuntimeException(); return eRet; } /*-- 05.03.99 11:37:32--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Sequence< beans::PropertyState > SwXParagraph::getPropertyStates( const uno::Sequence< OUString >& PropertyNames) throw( beans::UnknownPropertyException, uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); const OUString* pNames = PropertyNames.getConstArray(); uno::Sequence< beans::PropertyState > aRet(PropertyNames.getLength()); beans::PropertyState* pStates = aRet.getArray(); SwUnoCrsr* pUnoCrsr = ((SwXParagraph*)this)->GetCrsr(); const SfxItemPropertyMap* pMap = aPropSet.getPropertyMap(); if( pUnoCrsr ) { const SwAttrSet* pSet = 0; sal_Bool bAttrSetFetched = sal_False; for(sal_Int32 i = 0, nEnd = PropertyNames.getLength(); i < nEnd; i++,++pStates,++pMap,++pNames ) { pMap = SfxItemPropertyMap::GetByName( pMap, *pNames ); if(!pMap) throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + *pNames, static_cast < cppu::OWeakObject * > ( this ) ); if (bAttrSetFetched && !pSet && pMap->nWID >= RES_CHRATR_BEGIN && pMap->nWID <= RES_UNKNOWNATR_END ) *pStates = beans::PropertyState_DEFAULT_VALUE; else *pStates = lcl_SwXParagraph_getPropertyState( *pUnoCrsr, &pSet,*pMap, bAttrSetFetched ); } } else throw uno::RuntimeException(); return aRet; } /*-- 05.03.99 11:37:33--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::setPropertyToDefault(const OUString& rPropertyName) throw( beans::UnknownPropertyException, uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); SwUnoCrsr* pUnoCrsr = GetCrsr(); if(pUnoCrsr) { if( rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_ANCHOR_TYPE)) || rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_ANCHOR_TYPES)) || rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_TEXT_WRAP))) return; // Absatz selektieren SwParaSelection aParaSel(pUnoCrsr); SwDoc* pDoc = pUnoCrsr->GetDoc(); const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName); if(pMap) { if ( pMap->nFlags & PropertyAttribute::READONLY) throw RuntimeException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only:" ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); if(pMap->nWID < RES_FRMATR_END) { SvUShortsSort aWhichIds; aWhichIds.Insert(pMap->nWID); if(pMap->nWID < RES_PARATR_BEGIN) pUnoCrsr->GetDoc()->ResetAttr(*pUnoCrsr, sal_True, &aWhichIds); else { //fuer Absatzattribute muss die Selektion jeweils auf //Absatzgrenzen erweitert werden SwPosition aStart = *pUnoCrsr->Start(); SwPosition aEnd = *pUnoCrsr->End(); SwUnoCrsr* pTemp = pUnoCrsr->GetDoc()->CreateUnoCrsr(aStart, sal_False); if(!SwUnoCursorHelper::IsStartOfPara(*pTemp)) { pTemp->MovePara(fnParaCurr, fnParaStart); } pTemp->SetMark(); *pTemp->GetPoint() = aEnd; //pTemp->Exchange(); SwXTextCursor::SelectPam(*pTemp, sal_True); if(!SwUnoCursorHelper::IsEndOfPara(*pTemp)) { pTemp->MovePara(fnParaCurr, fnParaEnd); } pTemp->GetDoc()->ResetAttr(*pTemp, sal_True, &aWhichIds); delete pTemp; } } else SwUnoCursorHelper::resetCrsrPropertyValue(pMap, *pUnoCrsr); } else throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); } else throw uno::RuntimeException(); } /*-- 05.03.99 11:37:33--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Any SwXParagraph::getPropertyDefault(const OUString& rPropertyName) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException ) { uno::Any aRet; SwUnoCrsr* pUnoCrsr = ((SwXParagraph*)this)->GetCrsr(); if(pUnoCrsr) { if(SwXParagraph::getDefaultTextContentValue(aRet, rPropertyName)) return aRet; SwDoc* pDoc = pUnoCrsr->GetDoc(); const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName); if(pMap) { if(pMap->nWID < RES_FRMATR_END) { const SfxPoolItem& rDefItem = pUnoCrsr->GetDoc()->GetAttrPool().GetDefaultItem(pMap->nWID); rDefItem.QueryValue(aRet, pMap->nMemberId); } } else throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); } else throw uno::RuntimeException(); return aRet; } /*-- 11.12.98 08:12:51--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::attach(const uno::Reference< XTextRange > & xTextRange) throw( lang::IllegalArgumentException, uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); // SwXParagraph will only created in order to be inserteb by // 'insertTextContentBefore' or 'insertTextContentAfter' therefore // they cannot be attached throw uno::RuntimeException(); } /*-- 11.12.98 08:12:51--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Reference< XTextRange > SwXParagraph::getAnchor(void) throw( uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); uno::Reference< XTextRange > aRet; SwUnoCrsr* pUnoCrsr = ((SwXParagraph*)this)->GetCrsr(); if(pUnoCrsr) { // Absatz selektieren SwParaSelection aSelection(pUnoCrsr); aRet = new SwXTextRange(*pUnoCrsr, xParentText); } else throw uno::RuntimeException(); return aRet; } /*-- 11.12.98 08:12:52--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::dispose(void) throw( uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); SwUnoCrsr* pUnoCrsr = ((SwXParagraph*)this)->GetCrsr(); if(pUnoCrsr) { // Absatz selektieren { SwParaSelection aSelection(pUnoCrsr); pUnoCrsr->GetDoc()->DelFullPara(*pUnoCrsr); } aLstnrCntnr.Disposing(); delete pUnoCrsr; } else throw uno::RuntimeException(); } /*-- 11.12.98 08:12:52--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::addEventListener(const uno::Reference< lang::XEventListener > & aListener) throw( uno::RuntimeException ) { if(!GetRegisteredIn()) throw uno::RuntimeException(); aLstnrCntnr.AddListener(aListener); } /*-- 11.12.98 08:12:53--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::removeEventListener(const uno::Reference< lang::XEventListener > & aListener) throw( uno::RuntimeException ) { if(!GetRegisteredIn() || !aLstnrCntnr.RemoveListener(aListener)) throw uno::RuntimeException(); } /*-- 11.12.98 08:12:53--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Reference< container::XEnumeration > SwXParagraph::createEnumeration(void) throw( uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); uno::Reference< container::XEnumeration > aRef; SwUnoCrsr* pUnoCrsr = GetCrsr(); if(pUnoCrsr) aRef = new SwXTextPortionEnumeration(*pUnoCrsr, xParentText, nSelectionStartPos, nSelectionEndPos); else throw uno::RuntimeException(); return aRef; } /*-- 11.12.98 08:12:54--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Type SwXParagraph::getElementType(void) throw( uno::RuntimeException ) { return ::getCppuType((uno::Reference<XTextRange>*)0); } /*-- 11.12.98 08:12:54--------------------------------------------------- -----------------------------------------------------------------------*/ sal_Bool SwXParagraph::hasElements(void) throw( uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); if(((SwXParagraph*)this)->GetCrsr()) return sal_True; else return sal_False; } /*-- 11.12.98 08:12:55--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Reference< XText > SwXParagraph::getText(void) throw( uno::RuntimeException ) { return xParentText; } /*-- 11.12.98 08:12:55--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Reference< XTextRange > SwXParagraph::getStart(void) throw( uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); uno::Reference< XTextRange > xRet; SwUnoCrsr* pUnoCrsr = GetCrsr(); if( pUnoCrsr) { SwParaSelection aSelection(pUnoCrsr); SwPaM aPam(*pUnoCrsr->Start()); uno::Reference< XText > xParent = getText(); xRet = new SwXTextRange(aPam, xParent); } else throw uno::RuntimeException(); return xRet; } /*-- 11.12.98 08:12:56--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Reference< XTextRange > SwXParagraph::getEnd(void) throw( uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); uno::Reference< XTextRange > xRet; SwUnoCrsr* pUnoCrsr = GetCrsr(); if( pUnoCrsr) { SwParaSelection aSelection(pUnoCrsr); SwPaM aPam(*pUnoCrsr->End()); uno::Reference< XText > xParent = getText(); xRet = new SwXTextRange(aPam, xParent); } else throw uno::RuntimeException(); return xRet; } /*-- 11.12.98 08:12:56--------------------------------------------------- -----------------------------------------------------------------------*/ OUString SwXParagraph::getString(void) throw( uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); OUString aRet; SwUnoCrsr* pUnoCrsr = GetCrsr(); if( pUnoCrsr) { SwParaSelection aSelection(pUnoCrsr); SwXTextCursor::getTextFromPam(*pUnoCrsr, aRet); } else if(IsDescriptor()) aRet = m_sText; else throw uno::RuntimeException(); return aRet; } /*-- 11.12.98 08:12:57--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::setString(const OUString& aString) throw( uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); SwUnoCrsr* pUnoCrsr = GetCrsr(); if(pUnoCrsr) { if(!SwUnoCursorHelper::IsStartOfPara(*pUnoCrsr)) pUnoCrsr->MovePara(fnParaCurr, fnParaStart); SwXTextCursor::SelectPam(*pUnoCrsr, sal_True); if(pUnoCrsr->GetNode()->GetTxtNode()->GetTxt().Len()) pUnoCrsr->MovePara(fnParaCurr, fnParaEnd); SwXTextCursor::SetString(*pUnoCrsr, aString); SwXTextCursor::SelectPam(*pUnoCrsr, sal_False); } else if(IsDescriptor()) m_sText = aString; else throw uno::RuntimeException(); } /* -----------------23.03.99 12:49------------------- * * --------------------------------------------------*/ uno::Reference< container::XEnumeration > SwXParagraph::createContentEnumeration(const OUString& rServiceName) throw( uno::RuntimeException ) { SwUnoCrsr* pUnoCrsr = GetCrsr(); if( !pUnoCrsr || COMPARE_EQUAL != rServiceName.compareToAscii("com.sun.star.text.TextContent") ) throw uno::RuntimeException(); uno::Reference< container::XEnumeration > xRet = new SwXParaFrameEnumeration(*pUnoCrsr, PARAFRAME_PORTION_PARAGRAPH); return xRet; } /* -----------------23.03.99 12:49------------------- * * --------------------------------------------------*/ uno::Sequence< OUString > SwXParagraph::getAvailableServiceNames(void) throw( uno::RuntimeException ) { uno::Sequence< OUString > aRet(1); OUString* pArray = aRet.getArray(); pArray[0] = C2U("com.sun.star.text.TextContent"); return aRet; } /*-- 11.12.98 08:12:58--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew) { ClientModify(this, pOld, pNew); if(!GetRegisteredIn()) aLstnrCntnr.Disposing(); } INTEGRATION: CWS fr8fix1 (1.29.588); FILE MERGED 2005/04/06 14:52:50 dvo 1.29.588.1: #i46786# fix XTolerantMultiPropertySet::getDirectPropertyValuesTolerant (previously this used the style's properties if the paragraph attr set was empty) /************************************************************************* * * $RCSfile: unoparagraph.cxx,v $ * * $Revision: 1.31 $ * * last change: $Author: obo $ $Date: 2005-04-18 15:12:11 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include <cmdid.h> #ifndef _UNOMID_H #include <unomid.h> #endif #ifndef _UNOOBJ_HXX #include <unoobj.hxx> #endif #ifndef _UNOMAP_HXX #include <unomap.hxx> #endif #ifndef _UNOCRSR_HXX #include <unocrsr.hxx> #endif #ifndef _UNOPRNMS_HXX #include <unoprnms.hxx> #endif #ifndef _UNOCRSRHELPER_HXX #include <unocrsrhelper.hxx> #endif #ifndef _DOC_HXX //autogen #include <doc.hxx> #endif #ifndef _NDTXT_HXX //autogen #include <ndtxt.hxx> #endif #ifndef _VOS_MUTEX_HXX_ //autogen #include <vos/mutex.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #define _SVSTDARR_USHORTS #define _SVSTDARR_USHORTSSORT #include <svtools/svstdarr.hxx> //#ifndef _COM_SUN_STAR_BEANS_SETPROPERTYTOLERANTFAILED_HPP_ //#include <com/sun/star/beans/SetPropertyTolerantFailed.hpp> //#endif //#ifndef _COM_SUN_STAR_BEANS_GETPROPERTYTOLERANTRESULT_HPP_ //#include <com/sun/star/beans/GetPropertyTolerantResult.hpp> //#endif //#ifndef _COM_SUN_STAR_BEANS_TOLERANTPROPERTYSETRESULTTYPE_HPP_ //#include <com/sun/star/beans/TolerantPropertySetResultType.hpp> //#endif #ifndef _COM_SUN_STAR_BEANS_PropertyAttribute_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_WRAPTEXTMODE_HPP_ #include <com/sun/star/text/WrapTextMode.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_TEXTCONTENTANCHORTYPE_HPP_ #include <com/sun/star/text/TextContentAnchorType.hpp> #endif using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::text; using namespace ::com::sun::star::container; using namespace ::com::sun::star::beans; //using namespace ::com::sun::star::drawing; using namespace ::rtl; /****************************************************************** * forward declarations ******************************************************************/ beans::PropertyState lcl_SwXParagraph_getPropertyState( SwUnoCrsr& rUnoCrsr, const SwAttrSet** ppSet, const SfxItemPropertyMap& rMap, sal_Bool &rAttrSetFetched ) throw( beans::UnknownPropertyException); /****************************************************************** * SwXParagraph ******************************************************************/ /* -----------------------------11.07.00 12:10-------------------------------- ---------------------------------------------------------------------------*/ SwXParagraph* SwXParagraph::GetImplementation(Reference< XInterface> xRef ) { uno::Reference<lang::XUnoTunnel> xParaTunnel( xRef, uno::UNO_QUERY); if(xParaTunnel.is()) return (SwXParagraph*)xParaTunnel->getSomething(SwXParagraph::getUnoTunnelId()); return 0; } /* -----------------------------13.03.00 12:15-------------------------------- ---------------------------------------------------------------------------*/ const uno::Sequence< sal_Int8 > & SwXParagraph::getUnoTunnelId() { static uno::Sequence< sal_Int8 > aSeq = ::CreateUnoTunnelId(); return aSeq; } /* -----------------------------10.03.00 18:04-------------------------------- ---------------------------------------------------------------------------*/ sal_Int64 SAL_CALL SwXParagraph::getSomething( const uno::Sequence< sal_Int8 >& rId ) throw(uno::RuntimeException) { if( rId.getLength() == 16 && 0 == rtl_compareMemory( getUnoTunnelId().getConstArray(), rId.getConstArray(), 16 ) ) { return (sal_Int64)this; } return 0; } /* -----------------------------06.04.00 16:37-------------------------------- ---------------------------------------------------------------------------*/ OUString SwXParagraph::getImplementationName(void) throw( RuntimeException ) { return C2U("SwXParagraph"); } /* -----------------------------06.04.00 16:37-------------------------------- ---------------------------------------------------------------------------*/ BOOL SwXParagraph::supportsService(const OUString& rServiceName) throw( RuntimeException ) { String sServiceName(rServiceName); return sServiceName.EqualsAscii("com.sun.star.text.TextContent") || sServiceName.EqualsAscii("com.sun.star.text.Paragraph") || sServiceName.EqualsAscii("com.sun.star.style.CharacterProperties")|| sServiceName.EqualsAscii("com.sun.star.style.CharacterPropertiesAsian")|| sServiceName.EqualsAscii("com.sun.star.style.CharacterPropertiesComplex")|| sServiceName.EqualsAscii("com.sun.star.style.ParagraphProperties") || sServiceName.EqualsAscii("com.sun.star.style.ParagraphPropertiesAsian") || sServiceName.EqualsAscii("com.sun.star.style.ParagraphPropertiesComplex"); } /* -----------------------------06.04.00 16:37-------------------------------- ---------------------------------------------------------------------------*/ Sequence< OUString > SwXParagraph::getSupportedServiceNames(void) throw( RuntimeException ) { Sequence< OUString > aRet(8); OUString* pArray = aRet.getArray(); pArray[0] = C2U("com.sun.star.text.Paragraph"); pArray[1] = C2U("com.sun.star.style.CharacterProperties"); pArray[2] = C2U("com.sun.star.style.CharacterPropertiesAsian"); pArray[3] = C2U("com.sun.star.style.CharacterPropertiesComplex"); pArray[4] = C2U("com.sun.star.style.ParagraphProperties"); pArray[5] = C2U("com.sun.star.style.ParagraphPropertiesAsian"); pArray[6] = C2U("com.sun.star.style.ParagraphPropertiesComplex"); pArray[7] = C2U("com.sun.star.text.TextContent"); return aRet; } /*-- 11.12.98 08:12:47--------------------------------------------------- -----------------------------------------------------------------------*/ SwXParagraph::SwXParagraph() : aLstnrCntnr( (XTextRange*)this), xParentText(0), aPropSet(aSwMapProvider.GetPropertyMap(PROPERTY_MAP_PARAGRAPH)), m_bIsDescriptor(TRUE), nSelectionStartPos(-1), nSelectionEndPos(-1) { } /*-- 11.12.98 08:12:47--------------------------------------------------- -----------------------------------------------------------------------*/ SwXParagraph::SwXParagraph(SwXText* pParent, SwUnoCrsr* pCrsr, sal_Int32 nSelStart, sal_Int32 nSelEnd) : SwClient(pCrsr), xParentText(pParent), aLstnrCntnr( (XTextRange*)this), aPropSet(aSwMapProvider.GetPropertyMap(PROPERTY_MAP_PARAGRAPH)), m_bIsDescriptor(FALSE), nSelectionStartPos(nSelStart), nSelectionEndPos(nSelEnd) { } /*-- 11.12.98 08:12:48--------------------------------------------------- -----------------------------------------------------------------------*/ SwXParagraph::~SwXParagraph() { SwUnoCrsr* pUnoCrsr = GetCrsr(); if(pUnoCrsr) delete pUnoCrsr; } /* -----------------------------11.07.00 14:48-------------------------------- ---------------------------------------------------------------------------*/ void SwXParagraph::attachToText(SwXText* pParent, SwUnoCrsr* pCrsr) { DBG_ASSERT(m_bIsDescriptor, "Paragraph is not a descriptor") if(m_bIsDescriptor) { m_bIsDescriptor = FALSE; pCrsr->Add(this); xParentText = pParent; if(m_sText.getLength()) { try { setString(m_sText); } catch(...){} m_sText = OUString(); } } } /*-- 11.12.98 08:12:49--------------------------------------------------- -----------------------------------------------------------------------*/ Reference< XPropertySetInfo > SwXParagraph::getPropertySetInfo(void) throw( RuntimeException ) { static Reference< XPropertySetInfo > xRef = aPropSet.getPropertySetInfo(); return xRef; } /*-- 11.12.98 08:12:49--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::setPropertyValue(const OUString& rPropertyName, const Any& aValue) throw( UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); Sequence<OUString> aPropertyNames(1); aPropertyNames.getArray()[0] = rPropertyName; Sequence<Any> aValues(1); aValues.getArray()[0] = aValue; SetPropertyValues_Impl( aPropertyNames, aValues ); } /*-- 11.12.98 08:12:49--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Any SwXParagraph::getPropertyValue(const OUString& rPropertyName) throw( UnknownPropertyException, WrappedTargetException, RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); Sequence<OUString> aPropertyNames(1); aPropertyNames.getArray()[0] = rPropertyName; Sequence< Any > aRet = GetPropertyValues_Impl(aPropertyNames ); return aRet.getConstArray()[0]; } /* -----------------------------02.04.01 11:43-------------------------------- ---------------------------------------------------------------------------*/ void SAL_CALL SwXParagraph::SetPropertyValues_Impl( const uno::Sequence< OUString >& rPropertyNames, const uno::Sequence< Any >& rValues ) throw( UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException) { SwUnoCrsr* pUnoCrsr = GetCrsr(); if(pUnoCrsr) { const OUString* pPropertyNames = rPropertyNames.getConstArray(); const Any* pValues = rValues.getConstArray(); const SfxItemPropertyMap* pMap = aPropSet.getPropertyMap(); OUString sTmp; SwParaSelection aParaSel(pUnoCrsr); for(sal_Int32 nProp = 0; nProp < rPropertyNames.getLength(); nProp++) { pMap = SfxItemPropertyMap::GetByName(pMap, pPropertyNames[nProp]); if(!pMap) throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + pPropertyNames[nProp], static_cast < cppu::OWeakObject * > ( this ) ); else { if ( pMap->nFlags & PropertyAttribute::READONLY) throw PropertyVetoException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only: " ) ) + pPropertyNames[nProp], static_cast < cppu::OWeakObject * > ( this ) ); SwXTextCursor::SetPropertyValue(*pUnoCrsr, aPropSet, sTmp, pValues[nProp], pMap); pMap++; } } } else throw uno::RuntimeException(); } void SwXParagraph::setPropertyValues( const Sequence< OUString >& rPropertyNames, const Sequence< Any >& rValues ) throw(PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException) { vos::OGuard aGuard(Application::GetSolarMutex()); // workaround for bad designed API try { SetPropertyValues_Impl( rPropertyNames, rValues ); } catch (UnknownPropertyException &rException) { // wrap the original (here not allowed) exception in // a WrappedTargetException that gets thrown instead. WrappedTargetException aWExc; aWExc.TargetException <<= rException; throw aWExc; } } /* -----------------------------02.04.01 11:43-------------------------------- ---------------------------------------------------------------------------*/ uno::Sequence< Any > SAL_CALL SwXParagraph::GetPropertyValues_Impl( const uno::Sequence< OUString > & rPropertyNames ) throw( UnknownPropertyException, WrappedTargetException, RuntimeException ) { Sequence< Any > aValues(rPropertyNames.getLength()); SwUnoCrsr* pUnoCrsr = ((SwXParagraph*)this)->GetCrsr(); if(pUnoCrsr) { Any* pValues = aValues.getArray(); const OUString* pPropertyNames = rPropertyNames.getConstArray(); const SfxItemPropertyMap* pMap = aPropSet.getPropertyMap(); SwNode& rTxtNode = pUnoCrsr->GetPoint()->nNode.GetNode(); SwAttrSet& rAttrSet = ((SwTxtNode&)rTxtNode).GetSwAttrSet(); for(sal_Int32 nProp = 0; nProp < rPropertyNames.getLength(); nProp++) { pMap = SfxItemPropertyMap::GetByName(pMap, pPropertyNames[nProp]); if(pMap) { if(!SwXParagraph::getDefaultTextContentValue( pValues[nProp], pPropertyNames[nProp], pMap->nWID)) { BOOL bDone = FALSE; PropertyState eTemp; bDone = SwUnoCursorHelper::getCrsrPropertyValue( pMap, *pUnoCrsr, &(pValues[nProp]), eTemp, rTxtNode.GetTxtNode() ); if(!bDone) pValues[nProp] = aPropSet.getPropertyValue(*pMap, rAttrSet); } ++pMap; } else throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + pPropertyNames[nProp], static_cast < cppu::OWeakObject * > ( this ) ); } } else throw RuntimeException(); return aValues; } /* -----------------------------04.11.03 11:43-------------------------------- ---------------------------------------------------------------------------*/ Sequence< Any > SwXParagraph::getPropertyValues( const Sequence< OUString >& rPropertyNames ) throw(RuntimeException) { vos::OGuard aGuard(Application::GetSolarMutex()); Sequence< Any > aValues; // workaround for bad designed API try { aValues = GetPropertyValues_Impl( rPropertyNames ); } catch (UnknownPropertyException &) { throw RuntimeException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property exception caught" ) ), static_cast < cppu::OWeakObject * > ( this ) ); } catch (WrappedTargetException &) { throw RuntimeException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "WrappedTargetException caught" ) ), static_cast < cppu::OWeakObject * > ( this ) ); } return aValues; } /* -----------------------------02.04.01 11:43-------------------------------- ---------------------------------------------------------------------------*/ void SwXParagraph::addPropertiesChangeListener( const Sequence< OUString >& aPropertyNames, const Reference< XPropertiesChangeListener >& xListener ) throw(RuntimeException) {} /* -----------------------------02.04.01 11:43-------------------------------- ---------------------------------------------------------------------------*/ void SwXParagraph::removePropertiesChangeListener( const Reference< XPropertiesChangeListener >& xListener ) throw(RuntimeException) {} /* -----------------------------02.04.01 11:43-------------------------------- ---------------------------------------------------------------------------*/ void SwXParagraph::firePropertiesChangeEvent( const Sequence< OUString >& aPropertyNames, const Reference< XPropertiesChangeListener >& xListener ) throw(RuntimeException) {} /* -----------------------------25.09.03 11:09-------------------------------- ---------------------------------------------------------------------------*/ /* disabled for #i46921# uno::Sequence< SetPropertyTolerantFailed > SAL_CALL SwXParagraph::setPropertyValuesTolerant( const uno::Sequence< OUString >& rPropertyNames, const uno::Sequence< Any >& rValues ) throw (lang::IllegalArgumentException, uno::RuntimeException) { vos::OGuard aGuard( Application::GetSolarMutex() ); if (rPropertyNames.getLength() != rValues.getLength()) throw IllegalArgumentException(); SwUnoCrsr* pUnoCrsr = ((SwXParagraph*)this)->GetCrsr(); if(!pUnoCrsr) throw RuntimeException(); SwNode& rTxtNode = pUnoCrsr->GetPoint()->nNode.GetNode(); SwAttrSet& rAttrSet = ((SwTxtNode&)rTxtNode).GetSwAttrSet(); USHORT nAttrCount = rAttrSet.Count(); sal_Int32 nProps = rPropertyNames.getLength(); const OUString *pProp = rPropertyNames.getConstArray(); sal_Int32 nVals = rValues.getLength(); const Any *pValue = rValues.getConstArray(); sal_Int32 nFailed = 0; uno::Sequence< SetPropertyTolerantFailed > aFailed( nProps ); SetPropertyTolerantFailed *pFailed = aFailed.getArray(); // get entry to start with const SfxItemPropertyMap* pStartEntry = aPropSet.getPropertyMap(); OUString sTmp; SwParaSelection aParaSel( pUnoCrsr ); for (sal_Int32 i = 0; i < nProps; ++i) { try { pFailed[ nFailed ].Name = pProp[i]; const SfxItemPropertyMap* pEntry = SfxItemPropertyMap::GetByName( pStartEntry, pProp[i] ); if (!pEntry) pFailed[ nFailed++ ].Result = TolerantPropertySetResultType::UNKNOWN_PROPERTY; else { // set property value // (compare to SwXParagraph::setPropertyValues) if (pEntry->nFlags & PropertyAttribute::READONLY) pFailed[ nFailed++ ].Result = TolerantPropertySetResultType::PROPERTY_VETO; else { SwXTextCursor::SetPropertyValue( *pUnoCrsr, aPropSet, sTmp, pValue[i], pEntry ); } // continue with search for next property after current entry // (property map and sequence of property names are sorted!) pStartEntry = ++pEntry; } } catch (UnknownPropertyException &) { // should not occur because property was searched for before DBG_ERROR( "unexpected exception catched" ); pFailed[ nFailed++ ].Result = TolerantPropertySetResultType::UNKNOWN_PROPERTY; } catch (IllegalArgumentException &) { pFailed[ nFailed++ ].Result = TolerantPropertySetResultType::ILLEGAL_ARGUMENT; } catch (PropertyVetoException &) { pFailed[ nFailed++ ].Result = TolerantPropertySetResultType::PROPERTY_VETO; } catch (WrappedTargetException &) { pFailed[ nFailed++ ].Result = TolerantPropertySetResultType::WRAPPED_TARGET; } } aFailed.realloc( nFailed ); return aFailed; } uno::Sequence< GetPropertyTolerantResult > SAL_CALL SwXParagraph::getPropertyValuesTolerant( const uno::Sequence< OUString >& rPropertyNames ) throw (uno::RuntimeException) { vos::OGuard aGuard( Application::GetSolarMutex() ); uno::Sequence< GetDirectPropertyTolerantResult > aTmpRes( GetPropertyValuesTolerant_Impl( rPropertyNames, sal_False ) ); const GetDirectPropertyTolerantResult *pTmpRes = aTmpRes.getConstArray(); // copy temporary result to final result type sal_Int32 nLen = aTmpRes.getLength(); uno::Sequence< GetPropertyTolerantResult > aRes( nLen ); GetPropertyTolerantResult *pRes = aRes.getArray(); for (sal_Int32 i = 0; i < nLen; i++) *pRes++ = *pTmpRes++; return aRes; } uno::Sequence< GetDirectPropertyTolerantResult > SAL_CALL SwXParagraph::getDirectPropertyValuesTolerant( const uno::Sequence< OUString >& rPropertyNames ) throw (uno::RuntimeException) { vos::OGuard aGuard( Application::GetSolarMutex() ); return GetPropertyValuesTolerant_Impl( rPropertyNames, sal_True ); } uno::Sequence< GetDirectPropertyTolerantResult > SAL_CALL SwXParagraph::GetPropertyValuesTolerant_Impl( const uno::Sequence< OUString >& rPropertyNames, sal_Bool bDirectValuesOnly ) throw (uno::RuntimeException) { vos::OGuard aGuard( Application::GetSolarMutex() ); SwUnoCrsr* pUnoCrsr = ((SwXParagraph*)this)->GetCrsr(); if (!pUnoCrsr) throw RuntimeException(); SwTxtNode* pTxtNode = pUnoCrsr->GetPoint()->nNode.GetNode().GetTxtNode(); DBG_ASSERT( pTxtNode != NULL, "need text node" ); // #i46786# Use SwAttrSet pointer for determining the state. // Use the value SwAttrSet (from the paragraph OR the style) // for determining the actual value(s). const SwAttrSet* pAttrSet = pTxtNode->GetpSwAttrSet(); const SwAttrSet& rValueAttrSet = pTxtNode->GetSwAttrSet(); sal_Int32 nProps = rPropertyNames.getLength(); const OUString *pProp = rPropertyNames.getConstArray(); uno::Sequence< GetDirectPropertyTolerantResult > aResult( nProps ); GetDirectPropertyTolerantResult *pResult = aResult.getArray(); sal_Int32 nIdx = 0; // get entry to start with const SfxItemPropertyMap *pStartEntry = aPropSet.getPropertyMap(); for (sal_Int32 i = 0; i < nProps; ++i) { DBG_ASSERT( nIdx < nProps, "index out ouf bounds" ); GetDirectPropertyTolerantResult &rResult = pResult[nIdx]; try { rResult.Name = pProp[i]; const SfxItemPropertyMap *pEntry = SfxItemPropertyMap::GetByName( pStartEntry, pProp[i] ); if (!pEntry) // property available? rResult.Result = TolerantPropertySetResultType::UNKNOWN_PROPERTY; else { // get property state // (compare to SwXParagraph::getPropertyState) sal_Bool bAttrSetFetched = sal_True; PropertyState eState = lcl_SwXParagraph_getPropertyState( *pUnoCrsr, &pAttrSet, *pEntry, bAttrSetFetched ); rResult.State = eState; // if (bDirectValuesOnly && PropertyState_DIRECT_VALUE != eState) // rResult.Result = TolerantPropertySetResultType::NO_DIRECT_VALUE; // else rResult.Result = TolerantPropertySetResultType::UNKNOWN_FAILURE; if (!bDirectValuesOnly || PropertyState_DIRECT_VALUE == eState) { // get property value // (compare to SwXParagraph::getPropertyValue(s)) Any aValue; if (!SwXParagraph::getDefaultTextContentValue( aValue, pProp[i], pEntry->nWID ) ) { // handle properties that are not part of the attribute // and thus only pretendend to be paragraph attributes BOOL bDone = FALSE; PropertyState eTemp; bDone = SwUnoCursorHelper::getCrsrPropertyValue( pEntry, *pUnoCrsr, &aValue, eTemp, pTxtNode ); // if not found try the real paragraph attributes... if (!bDone) aValue = aPropSet.getPropertyValue( *pEntry, rValueAttrSet ); } rResult.Value = aValue; rResult.Result = TolerantPropertySetResultType::SUCCESS; nIdx++; } // this assertion should never occur! DBG_ASSERT( nIdx < 1 || pResult[nIdx - 1].Result != TolerantPropertySetResultType::UNKNOWN_FAILURE, "unknown failure while retrieving property" ); // continue with search for next property after current entry // (property map and sequence of property names are sorted!) pStartEntry = ++pEntry; } } catch (UnknownPropertyException &) { // should not occur because property was searched for before DBG_ERROR( "unexpected exception catched" ); rResult.Result = TolerantPropertySetResultType::UNKNOWN_PROPERTY; } catch (IllegalArgumentException &) { rResult.Result = TolerantPropertySetResultType::ILLEGAL_ARGUMENT; } catch (PropertyVetoException &) { rResult.Result = TolerantPropertySetResultType::PROPERTY_VETO; } catch (WrappedTargetException &) { rResult.Result = TolerantPropertySetResultType::WRAPPED_TARGET; } } // resize to actually used size aResult.realloc( nIdx ); return aResult; } */ /* -----------------------------12.09.00 11:09-------------------------------- ---------------------------------------------------------------------------*/ BOOL SwXParagraph::getDefaultTextContentValue(Any& rAny, const OUString& rPropertyName, USHORT nWID) { if(!nWID) { if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_ANCHOR_TYPE))) nWID = FN_UNO_ANCHOR_TYPE; else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_ANCHOR_TYPES))) nWID = FN_UNO_ANCHOR_TYPES; else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_TEXT_WRAP))) nWID = FN_UNO_TEXT_WRAP; else return FALSE; } switch(nWID) { case FN_UNO_TEXT_WRAP: rAny <<= WrapTextMode_NONE; break; case FN_UNO_ANCHOR_TYPE: rAny <<= TextContentAnchorType_AT_PARAGRAPH; break; case FN_UNO_ANCHOR_TYPES: { Sequence<TextContentAnchorType> aTypes(1); TextContentAnchorType* pArray = aTypes.getArray(); pArray[0] = TextContentAnchorType_AT_PARAGRAPH; rAny.setValue(&aTypes, ::getCppuType((uno::Sequence<TextContentAnchorType>*)0)); } break; default: return FALSE; } return TRUE; } /*-- 11.12.98 08:12:50--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::addPropertyChangeListener( const OUString& PropertyName, const uno::Reference< beans::XPropertyChangeListener > & aListener) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException ) { DBG_WARNING("not implemented") } /*-- 11.12.98 08:12:50--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::removePropertyChangeListener(const OUString& PropertyName, const uno::Reference< beans::XPropertyChangeListener > & aListener) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException ) { DBG_WARNING("not implemented") } /*-- 11.12.98 08:12:50--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::addVetoableChangeListener(const OUString& PropertyName, const uno::Reference< beans::XVetoableChangeListener > & aListener) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException ) { DBG_WARNING("not implemented") } /*-- 11.12.98 08:12:51--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::removeVetoableChangeListener(const OUString& PropertyName, const uno::Reference< beans::XVetoableChangeListener > & aListener) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException ) { DBG_WARNING("not implemented") } //----------------------------------------------------------------------------- beans::PropertyState lcl_SwXParagraph_getPropertyState( SwUnoCrsr& rUnoCrsr, const SwAttrSet** ppSet, const SfxItemPropertyMap& rMap, sal_Bool &rAttrSetFetched ) throw( beans::UnknownPropertyException) { beans::PropertyState eRet = beans::PropertyState_DEFAULT_VALUE; if(!(*ppSet) && !rAttrSetFetched ) { SwNode& rTxtNode = rUnoCrsr.GetPoint()->nNode.GetNode(); (*ppSet) = ((SwTxtNode&)rTxtNode).GetpSwAttrSet(); rAttrSetFetched = sal_True; } switch( rMap.nWID ) { case FN_UNO_NUM_RULES: //wenn eine Numerierung gesetzt ist, dann hier herausreichen, sonst nichts tun SwUnoCursorHelper::getNumberingProperty( rUnoCrsr, eRet, NULL ); break; case FN_UNO_ANCHOR_TYPES: break; case RES_ANCHOR: if ( MID_SURROUND_SURROUNDTYPE != rMap.nMemberId ) goto lcl_SwXParagraph_getPropertyStateDEFAULT; break; case RES_SURROUND: if ( MID_ANCHOR_ANCHORTYPE != rMap.nMemberId ) goto lcl_SwXParagraph_getPropertyStateDEFAULT; break; case FN_UNO_PARA_STYLE: case FN_UNO_PARA_CONDITIONAL_STYLE_NAME: { SwFmtColl* pFmt = SwXTextCursor::GetCurTxtFmtColl( rUnoCrsr, rMap.nWID == FN_UNO_PARA_CONDITIONAL_STYLE_NAME); eRet = pFmt ? beans::PropertyState_DIRECT_VALUE : beans::PropertyState_AMBIGUOUS_VALUE; } break; case FN_UNO_PAGE_STYLE: { String sVal; SwUnoCursorHelper::GetCurPageStyle( rUnoCrsr, sVal ); eRet = sVal.Len() ? beans::PropertyState_DIRECT_VALUE : beans::PropertyState_AMBIGUOUS_VALUE; } break; lcl_SwXParagraph_getPropertyStateDEFAULT: default: if((*ppSet) && SFX_ITEM_SET == (*ppSet)->GetItemState(rMap.nWID, FALSE)) eRet = beans::PropertyState_DIRECT_VALUE; break; } return eRet; } /*-- 05.03.99 11:37:30--------------------------------------------------- -----------------------------------------------------------------------*/ beans::PropertyState SwXParagraph::getPropertyState(const OUString& rPropertyName) throw( beans::UnknownPropertyException, uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); beans::PropertyState eRet = beans::PropertyState_DEFAULT_VALUE; SwUnoCrsr* pUnoCrsr = ((SwXParagraph*)this)->GetCrsr(); if( pUnoCrsr ) { const SwAttrSet* pSet = 0; const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName ); if(!pMap) throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); sal_Bool bDummy = sal_False; eRet = lcl_SwXParagraph_getPropertyState( *pUnoCrsr, &pSet, *pMap, bDummy ); } else throw uno::RuntimeException(); return eRet; } /*-- 05.03.99 11:37:32--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Sequence< beans::PropertyState > SwXParagraph::getPropertyStates( const uno::Sequence< OUString >& PropertyNames) throw( beans::UnknownPropertyException, uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); const OUString* pNames = PropertyNames.getConstArray(); uno::Sequence< beans::PropertyState > aRet(PropertyNames.getLength()); beans::PropertyState* pStates = aRet.getArray(); SwUnoCrsr* pUnoCrsr = ((SwXParagraph*)this)->GetCrsr(); const SfxItemPropertyMap* pMap = aPropSet.getPropertyMap(); if( pUnoCrsr ) { const SwAttrSet* pSet = 0; sal_Bool bAttrSetFetched = sal_False; for(sal_Int32 i = 0, nEnd = PropertyNames.getLength(); i < nEnd; i++,++pStates,++pMap,++pNames ) { pMap = SfxItemPropertyMap::GetByName( pMap, *pNames ); if(!pMap) throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + *pNames, static_cast < cppu::OWeakObject * > ( this ) ); if (bAttrSetFetched && !pSet && pMap->nWID >= RES_CHRATR_BEGIN && pMap->nWID <= RES_UNKNOWNATR_END ) *pStates = beans::PropertyState_DEFAULT_VALUE; else *pStates = lcl_SwXParagraph_getPropertyState( *pUnoCrsr, &pSet,*pMap, bAttrSetFetched ); } } else throw uno::RuntimeException(); return aRet; } /*-- 05.03.99 11:37:33--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::setPropertyToDefault(const OUString& rPropertyName) throw( beans::UnknownPropertyException, uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); SwUnoCrsr* pUnoCrsr = GetCrsr(); if(pUnoCrsr) { if( rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_ANCHOR_TYPE)) || rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_ANCHOR_TYPES)) || rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_TEXT_WRAP))) return; // Absatz selektieren SwParaSelection aParaSel(pUnoCrsr); SwDoc* pDoc = pUnoCrsr->GetDoc(); const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName); if(pMap) { if ( pMap->nFlags & PropertyAttribute::READONLY) throw RuntimeException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only:" ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); if(pMap->nWID < RES_FRMATR_END) { SvUShortsSort aWhichIds; aWhichIds.Insert(pMap->nWID); if(pMap->nWID < RES_PARATR_BEGIN) pUnoCrsr->GetDoc()->ResetAttr(*pUnoCrsr, sal_True, &aWhichIds); else { //fuer Absatzattribute muss die Selektion jeweils auf //Absatzgrenzen erweitert werden SwPosition aStart = *pUnoCrsr->Start(); SwPosition aEnd = *pUnoCrsr->End(); SwUnoCrsr* pTemp = pUnoCrsr->GetDoc()->CreateUnoCrsr(aStart, sal_False); if(!SwUnoCursorHelper::IsStartOfPara(*pTemp)) { pTemp->MovePara(fnParaCurr, fnParaStart); } pTemp->SetMark(); *pTemp->GetPoint() = aEnd; //pTemp->Exchange(); SwXTextCursor::SelectPam(*pTemp, sal_True); if(!SwUnoCursorHelper::IsEndOfPara(*pTemp)) { pTemp->MovePara(fnParaCurr, fnParaEnd); } pTemp->GetDoc()->ResetAttr(*pTemp, sal_True, &aWhichIds); delete pTemp; } } else SwUnoCursorHelper::resetCrsrPropertyValue(pMap, *pUnoCrsr); } else throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); } else throw uno::RuntimeException(); } /*-- 05.03.99 11:37:33--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Any SwXParagraph::getPropertyDefault(const OUString& rPropertyName) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException ) { uno::Any aRet; SwUnoCrsr* pUnoCrsr = ((SwXParagraph*)this)->GetCrsr(); if(pUnoCrsr) { if(SwXParagraph::getDefaultTextContentValue(aRet, rPropertyName)) return aRet; SwDoc* pDoc = pUnoCrsr->GetDoc(); const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName); if(pMap) { if(pMap->nWID < RES_FRMATR_END) { const SfxPoolItem& rDefItem = pUnoCrsr->GetDoc()->GetAttrPool().GetDefaultItem(pMap->nWID); rDefItem.QueryValue(aRet, pMap->nMemberId); } } else throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); } else throw uno::RuntimeException(); return aRet; } /*-- 11.12.98 08:12:51--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::attach(const uno::Reference< XTextRange > & xTextRange) throw( lang::IllegalArgumentException, uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); // SwXParagraph will only created in order to be inserteb by // 'insertTextContentBefore' or 'insertTextContentAfter' therefore // they cannot be attached throw uno::RuntimeException(); } /*-- 11.12.98 08:12:51--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Reference< XTextRange > SwXParagraph::getAnchor(void) throw( uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); uno::Reference< XTextRange > aRet; SwUnoCrsr* pUnoCrsr = ((SwXParagraph*)this)->GetCrsr(); if(pUnoCrsr) { // Absatz selektieren SwParaSelection aSelection(pUnoCrsr); aRet = new SwXTextRange(*pUnoCrsr, xParentText); } else throw uno::RuntimeException(); return aRet; } /*-- 11.12.98 08:12:52--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::dispose(void) throw( uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); SwUnoCrsr* pUnoCrsr = ((SwXParagraph*)this)->GetCrsr(); if(pUnoCrsr) { // Absatz selektieren { SwParaSelection aSelection(pUnoCrsr); pUnoCrsr->GetDoc()->DelFullPara(*pUnoCrsr); } aLstnrCntnr.Disposing(); delete pUnoCrsr; } else throw uno::RuntimeException(); } /*-- 11.12.98 08:12:52--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::addEventListener(const uno::Reference< lang::XEventListener > & aListener) throw( uno::RuntimeException ) { if(!GetRegisteredIn()) throw uno::RuntimeException(); aLstnrCntnr.AddListener(aListener); } /*-- 11.12.98 08:12:53--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::removeEventListener(const uno::Reference< lang::XEventListener > & aListener) throw( uno::RuntimeException ) { if(!GetRegisteredIn() || !aLstnrCntnr.RemoveListener(aListener)) throw uno::RuntimeException(); } /*-- 11.12.98 08:12:53--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Reference< container::XEnumeration > SwXParagraph::createEnumeration(void) throw( uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); uno::Reference< container::XEnumeration > aRef; SwUnoCrsr* pUnoCrsr = GetCrsr(); if(pUnoCrsr) aRef = new SwXTextPortionEnumeration(*pUnoCrsr, xParentText, nSelectionStartPos, nSelectionEndPos); else throw uno::RuntimeException(); return aRef; } /*-- 11.12.98 08:12:54--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Type SwXParagraph::getElementType(void) throw( uno::RuntimeException ) { return ::getCppuType((uno::Reference<XTextRange>*)0); } /*-- 11.12.98 08:12:54--------------------------------------------------- -----------------------------------------------------------------------*/ sal_Bool SwXParagraph::hasElements(void) throw( uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); if(((SwXParagraph*)this)->GetCrsr()) return sal_True; else return sal_False; } /*-- 11.12.98 08:12:55--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Reference< XText > SwXParagraph::getText(void) throw( uno::RuntimeException ) { return xParentText; } /*-- 11.12.98 08:12:55--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Reference< XTextRange > SwXParagraph::getStart(void) throw( uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); uno::Reference< XTextRange > xRet; SwUnoCrsr* pUnoCrsr = GetCrsr(); if( pUnoCrsr) { SwParaSelection aSelection(pUnoCrsr); SwPaM aPam(*pUnoCrsr->Start()); uno::Reference< XText > xParent = getText(); xRet = new SwXTextRange(aPam, xParent); } else throw uno::RuntimeException(); return xRet; } /*-- 11.12.98 08:12:56--------------------------------------------------- -----------------------------------------------------------------------*/ uno::Reference< XTextRange > SwXParagraph::getEnd(void) throw( uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); uno::Reference< XTextRange > xRet; SwUnoCrsr* pUnoCrsr = GetCrsr(); if( pUnoCrsr) { SwParaSelection aSelection(pUnoCrsr); SwPaM aPam(*pUnoCrsr->End()); uno::Reference< XText > xParent = getText(); xRet = new SwXTextRange(aPam, xParent); } else throw uno::RuntimeException(); return xRet; } /*-- 11.12.98 08:12:56--------------------------------------------------- -----------------------------------------------------------------------*/ OUString SwXParagraph::getString(void) throw( uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); OUString aRet; SwUnoCrsr* pUnoCrsr = GetCrsr(); if( pUnoCrsr) { SwParaSelection aSelection(pUnoCrsr); SwXTextCursor::getTextFromPam(*pUnoCrsr, aRet); } else if(IsDescriptor()) aRet = m_sText; else throw uno::RuntimeException(); return aRet; } /*-- 11.12.98 08:12:57--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::setString(const OUString& aString) throw( uno::RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); SwUnoCrsr* pUnoCrsr = GetCrsr(); if(pUnoCrsr) { if(!SwUnoCursorHelper::IsStartOfPara(*pUnoCrsr)) pUnoCrsr->MovePara(fnParaCurr, fnParaStart); SwXTextCursor::SelectPam(*pUnoCrsr, sal_True); if(pUnoCrsr->GetNode()->GetTxtNode()->GetTxt().Len()) pUnoCrsr->MovePara(fnParaCurr, fnParaEnd); SwXTextCursor::SetString(*pUnoCrsr, aString); SwXTextCursor::SelectPam(*pUnoCrsr, sal_False); } else if(IsDescriptor()) m_sText = aString; else throw uno::RuntimeException(); } /* -----------------23.03.99 12:49------------------- * * --------------------------------------------------*/ uno::Reference< container::XEnumeration > SwXParagraph::createContentEnumeration(const OUString& rServiceName) throw( uno::RuntimeException ) { SwUnoCrsr* pUnoCrsr = GetCrsr(); if( !pUnoCrsr || COMPARE_EQUAL != rServiceName.compareToAscii("com.sun.star.text.TextContent") ) throw uno::RuntimeException(); uno::Reference< container::XEnumeration > xRet = new SwXParaFrameEnumeration(*pUnoCrsr, PARAFRAME_PORTION_PARAGRAPH); return xRet; } /* -----------------23.03.99 12:49------------------- * * --------------------------------------------------*/ uno::Sequence< OUString > SwXParagraph::getAvailableServiceNames(void) throw( uno::RuntimeException ) { uno::Sequence< OUString > aRet(1); OUString* pArray = aRet.getArray(); pArray[0] = C2U("com.sun.star.text.TextContent"); return aRet; } /*-- 11.12.98 08:12:58--------------------------------------------------- -----------------------------------------------------------------------*/ void SwXParagraph::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew) { ClientModify(this, pOld, pNew); if(!GetRegisteredIn()) aLstnrCntnr.Disposing(); }
#include "qhexcursor.h" #include "qhexdocument.h" #include <QWidget> #include <QPoint> #define currentDocument static_cast<QHexDocument*>(this->parent()) //#define currentContainer static_cast<QWidget*>(currentDocument->parent()) const int QHexCursor::CURSOR_BLINK_INTERVAL = 500; // 5ms QHexCursor::QHexCursor(QObject *parent) : QObject(parent), _selectedpart(QHexCursor::HexPart), _insertionmode(QHexCursor::OverwriteMode) { this->_cursorx = this->_cursory = 0; this->_selectionstart = this->_offset = this->_bitindex = 0; this->_timerid = this->startTimer(QHexCursor::CURSOR_BLINK_INTERVAL); } QHexCursor::~QHexCursor() { this->killTimer(this->_timerid); } QPoint QHexCursor::position() const { return QPoint(this->_cursorx, this->_cursory); } sinteger_t QHexCursor::cursorX() const { return this->_cursorx; } sinteger_t QHexCursor::cursorY() const { return this->_cursory; } integer_t QHexCursor::offset() const { return this->_offset; } integer_t QHexCursor::bitIndex() const { return this->_bitindex; } integer_t QHexCursor::selectionStart() const { return qMin(this->_offset, this->_selectionstart); } integer_t QHexCursor::selectionEnd() const { return qMax(this->_offset, this->_selectionstart); } integer_t QHexCursor::selectionLength() const { return this->selectionEnd() - this->selectionStart(); } QHexCursor::SelectedPart QHexCursor::selectedPart() const { return this->_selectedpart; } QHexCursor::InsertionMode QHexCursor::insertionMode() const { return this->_insertionmode; } bool QHexCursor::isAddressPartSelected() const { return this->_selectedpart == QHexCursor::AddressPart; } bool QHexCursor::isHexPartSelected() const { return this->_selectedpart == QHexCursor::HexPart; } bool QHexCursor::isAsciiPartSelected() const { return this->_selectedpart == QHexCursor::AsciiPart; } bool QHexCursor::isInsertMode() const { return this->_insertionmode == QHexCursor::InsertMode; } bool QHexCursor::isOverwriteMode() const { return this->_insertionmode == QHexCursor::OverwriteMode; } bool QHexCursor::hasSelection() const { return this->_offset != this->_selectionstart; } bool QHexCursor::blinking() const { return this->_blink; } bool QHexCursor::isSelected(integer_t offset) const { if(this->_offset == this->_selectionstart) return false; return (offset >= this->selectionStart()) && (offset < this->selectionEnd()); } void QHexCursor::selectStart() { this->setOffset(0); } void QHexCursor::selectEnd() { this->setOffset(currentDocument->length()); } void QHexCursor::selectAll() { this->setSelectionEnd(0); this->setOffset(currentDocument->length()); } void QHexCursor::setPosition(sinteger_t x, sinteger_t y) { if((this->_cursorx == x) && (this->_cursory == y)) return; this->_cursorx = x; this->_cursory = y; emit positionChanged(); } void QHexCursor::setOffset(integer_t offset) { this->setOffset(offset, 0); } void QHexCursor::setOffset(integer_t offset, integer_t bitindex) { offset = qMin(offset, currentDocument->length()); // Check EOF this->_selectionstart = offset; this->_bitindex = bitindex; this->setSelectionEnd(offset); } void QHexCursor::setSelectionEnd(integer_t offset) { offset = qMin(offset, currentDocument->length()); // Check EOF if(this->_selectionstart != this->_offset) emit selectionChanged(); this->_offset = offset; emit offsetChanged(); } void QHexCursor::setSelection(integer_t startoffset, integer_t endoffset) { this->setOffset(startoffset); this->setSelectionEnd(endoffset); } void QHexCursor::setSelectionRange(integer_t startoffset, integer_t length) { this->setSelection(startoffset, startoffset + length); } void QHexCursor::setSelectedPart(QHexCursor::SelectedPart sp) { if(sp == this->_selectedpart) return; this->_selectedpart = sp; emit selectedPartChanged(); } void QHexCursor::clearSelection() { if(this->_selectionstart == this->_offset) return; this->_selectionstart = this->_offset; emit selectionChanged(); } bool QHexCursor::removeSelection() { if(!this->hasSelection()) return false; currentDocument->remove(this->selectionStart(), this->selectionLength()); this->clearSelection(); return true; } void QHexCursor::moveOffset(sinteger_t c) { if(!c) return; integer_t offset = this->_offset + c; if(offset >= currentDocument->length()) offset = c > 0 ? currentDocument->length() : 0; this->setOffset(offset); } void QHexCursor::moveSelection(sinteger_t c) { if(!c) return; integer_t offset = this->_offset + c; if(offset >= currentDocument->length()) offset = c > 0 ? currentDocument->length() : 0; this->setSelectionEnd(offset); } void QHexCursor::blink(bool b) { this->_blink = b; emit blinkChanged(); } void QHexCursor::switchMode() { if(this->_insertionmode == QHexCursor::OverwriteMode) this->_insertionmode = QHexCursor::InsertMode; else this->_insertionmode = QHexCursor::OverwriteMode; emit insertionModeChanged(); } void QHexCursor::timerEvent(QTimerEvent *event) { Q_UNUSED(event); this->_blink = !this->_blink; emit blinkChanged(); } QHexCursor: Relax selectionChanged signal rules #include "qhexcursor.h" #include "qhexdocument.h" #include <QWidget> #include <QPoint> #define currentDocument static_cast<QHexDocument*>(this->parent()) //#define currentContainer static_cast<QWidget*>(currentDocument->parent()) const int QHexCursor::CURSOR_BLINK_INTERVAL = 500; // 5ms QHexCursor::QHexCursor(QObject *parent) : QObject(parent), _selectedpart(QHexCursor::HexPart), _insertionmode(QHexCursor::OverwriteMode) { this->_cursorx = this->_cursory = 0; this->_selectionstart = this->_offset = this->_bitindex = 0; this->_timerid = this->startTimer(QHexCursor::CURSOR_BLINK_INTERVAL); } QHexCursor::~QHexCursor() { this->killTimer(this->_timerid); } QPoint QHexCursor::position() const { return QPoint(this->_cursorx, this->_cursory); } sinteger_t QHexCursor::cursorX() const { return this->_cursorx; } sinteger_t QHexCursor::cursorY() const { return this->_cursory; } integer_t QHexCursor::offset() const { return this->_offset; } integer_t QHexCursor::bitIndex() const { return this->_bitindex; } integer_t QHexCursor::selectionStart() const { return qMin(this->_offset, this->_selectionstart); } integer_t QHexCursor::selectionEnd() const { return qMax(this->_offset, this->_selectionstart); } integer_t QHexCursor::selectionLength() const { return this->selectionEnd() - this->selectionStart(); } QHexCursor::SelectedPart QHexCursor::selectedPart() const { return this->_selectedpart; } QHexCursor::InsertionMode QHexCursor::insertionMode() const { return this->_insertionmode; } bool QHexCursor::isAddressPartSelected() const { return this->_selectedpart == QHexCursor::AddressPart; } bool QHexCursor::isHexPartSelected() const { return this->_selectedpart == QHexCursor::HexPart; } bool QHexCursor::isAsciiPartSelected() const { return this->_selectedpart == QHexCursor::AsciiPart; } bool QHexCursor::isInsertMode() const { return this->_insertionmode == QHexCursor::InsertMode; } bool QHexCursor::isOverwriteMode() const { return this->_insertionmode == QHexCursor::OverwriteMode; } bool QHexCursor::hasSelection() const { return this->_offset != this->_selectionstart; } bool QHexCursor::blinking() const { return this->_blink; } bool QHexCursor::isSelected(integer_t offset) const { if(this->_offset == this->_selectionstart) return false; return (offset >= this->selectionStart()) && (offset < this->selectionEnd()); } void QHexCursor::selectStart() { this->setOffset(0); } void QHexCursor::selectEnd() { this->setOffset(currentDocument->length()); } void QHexCursor::selectAll() { this->setSelectionEnd(0); this->setOffset(currentDocument->length()); } void QHexCursor::setPosition(sinteger_t x, sinteger_t y) { if((this->_cursorx == x) && (this->_cursory == y)) return; this->_cursorx = x; this->_cursory = y; emit positionChanged(); } void QHexCursor::setOffset(integer_t offset) { this->setOffset(offset, 0); } void QHexCursor::setOffset(integer_t offset, integer_t bitindex) { offset = qMin(offset, currentDocument->length()); // Check EOF this->_selectionstart = offset; this->_bitindex = bitindex; this->setSelectionEnd(offset); } void QHexCursor::setSelectionEnd(integer_t offset) { offset = qMin(offset, currentDocument->length()); // Check EOF emit selectionChanged(); this->_offset = offset; emit offsetChanged(); } void QHexCursor::setSelection(integer_t startoffset, integer_t endoffset) { this->setOffset(startoffset); this->setSelectionEnd(endoffset); } void QHexCursor::setSelectionRange(integer_t startoffset, integer_t length) { this->setSelection(startoffset, startoffset + length); } void QHexCursor::setSelectedPart(QHexCursor::SelectedPart sp) { if(sp == this->_selectedpart) return; this->_selectedpart = sp; emit selectedPartChanged(); } void QHexCursor::clearSelection() { if(this->_selectionstart == this->_offset) return; this->_selectionstart = this->_offset; emit selectionChanged(); } bool QHexCursor::removeSelection() { if(!this->hasSelection()) return false; currentDocument->remove(this->selectionStart(), this->selectionLength()); this->clearSelection(); return true; } void QHexCursor::moveOffset(sinteger_t c) { if(!c) return; integer_t offset = this->_offset + c; if(offset >= currentDocument->length()) offset = c > 0 ? currentDocument->length() : 0; this->setOffset(offset); } void QHexCursor::moveSelection(sinteger_t c) { if(!c) return; integer_t offset = this->_offset + c; if(offset >= currentDocument->length()) offset = c > 0 ? currentDocument->length() : 0; this->setSelectionEnd(offset); } void QHexCursor::blink(bool b) { this->_blink = b; emit blinkChanged(); } void QHexCursor::switchMode() { if(this->_insertionmode == QHexCursor::OverwriteMode) this->_insertionmode = QHexCursor::InsertMode; else this->_insertionmode = QHexCursor::OverwriteMode; emit insertionModeChanged(); } void QHexCursor::timerEvent(QTimerEvent *event) { Q_UNUSED(event); this->_blink = !this->_blink; emit blinkChanged(); }
/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */ /// @HTML #include <msfilter.hxx> # include "writerwordglue.hxx" #include <doc.hxx> # include "writerhelper.hxx" #include <algorithm> //std::find_if #include <functional> //std::unary_function #include <unicode/ubidi.h> //ubidi_getLogicalRun # include <tools/tenccvt.hxx> //GetExtendedTextEncoding # include <i18nutil/unicode.hxx> //unicode::getUnicodeScriptType #ifndef _COM_SUN_STAR_I18N_SCRIPTTYPE_HDL_ # include <com/sun/star/i18n/ScriptType.hdl> //ScriptType #endif #ifndef SV_FONTCVT_HXX # include <unotools/fontcvt.hxx> //GetSubsFontName #endif # include <editeng/paperinf.hxx> //lA0Width... # include <editeng/lrspitem.hxx> //SvxLRSpaceItem # include <editeng/ulspitem.hxx> //SvxULSpaceItem # include <editeng/boxitem.hxx> //SvxBoxItem # include <editeng/fontitem.hxx> //SvxFontItem # include <frmfmt.hxx> //SwFrmFmt # include <fmtclds.hxx> //SwFmtCol # include <hfspacingitem.hxx> //SwHeaderAndFooterEatSpacingItem # include <fmtfsize.hxx> //SwFmtFrmSize # include <swrect.hxx> //SwRect # include <fmthdft.hxx> //SwFmtHeader/SwFmtFooter # include <frmatr.hxx> //GetLRSpace... # include <ndtxt.hxx> //SwTxtNode # include <breakit.hxx> //pBreakIt #define ASSIGN_CONST_ASC(s) AssignAscii(RTL_CONSTASCII_STRINGPARAM(s)) namespace myImplHelpers { SwTwips CalcHdFtDist(const SwFrmFmt& rFmt, sal_uInt16 nSpacing) { /* #98506# The normal case for reexporting word docs is to have dynamic spacing, as this is word's only setting, and the reason for the existance of the dynamic spacing features. If we have dynamic spacing active then we can add its spacing to the value height of the h/f and get the wanted total size for word. Otherwise we have to get the real layout rendered height, which is totally nonoptimum, but the best we can do. */ long nDist=0; const SwFmtFrmSize& rSz = rFmt.GetFrmSize(); const SwHeaderAndFooterEatSpacingItem &rSpacingCtrl = sw::util::ItemGet<SwHeaderAndFooterEatSpacingItem> (rFmt, RES_HEADER_FOOTER_EAT_SPACING); if (rSpacingCtrl.GetValue()) nDist += rSz.GetHeight(); else { SwRect aRect(rFmt.FindLayoutRect(false)); if (aRect.Height()) nDist += aRect.Height(); else { const SwFmtFrmSize& rSize = rFmt.GetFrmSize(); if (ATT_VAR_SIZE != rSize.GetHeightSizeType()) nDist += rSize.GetHeight(); else { nDist += 274; // default for 12pt text nDist += nSpacing; } } } return nDist; } SwTwips CalcHdDist(const SwFrmFmt& rFmt) { return CalcHdFtDist(rFmt, rFmt.GetULSpace().GetUpper()); } SwTwips CalcFtDist(const SwFrmFmt& rFmt) { return CalcHdFtDist(rFmt, rFmt.GetULSpace().GetLower()); } /* SwTxtFmtColl and SwCharFmt are quite distinct types and how they are gotten is also distinct, but the algorithm to match word's eqivalents into them is the same, so we put the different stuff into two seperate helper implementations and a core template that uses the helpers that uses the same algorithm to do the work. We'll make the helpers specializations of a non existing template so I can let the compiler figure out the right one to use from a simple argument to the algorithm class */ template <class C> class MapperImpl; template<> class MapperImpl<SwTxtFmtColl> { private: SwDoc &mrDoc; public: MapperImpl(SwDoc &rDoc) : mrDoc(rDoc) {} SwTxtFmtColl* GetBuiltInStyle(ww::sti eSti); SwTxtFmtColl* GetStyle(const String &rName); SwTxtFmtColl* MakeStyle(const String &rName); }; SwTxtFmtColl* MapperImpl<SwTxtFmtColl>::GetBuiltInStyle(ww::sti eSti) { const RES_POOL_COLLFMT_TYPE RES_NONE = RES_POOLCOLL_DOC_END; static const RES_POOL_COLLFMT_TYPE aArr[]= { RES_POOLCOLL_STANDARD, RES_POOLCOLL_HEADLINE1, RES_POOLCOLL_HEADLINE2, RES_POOLCOLL_HEADLINE3, RES_POOLCOLL_HEADLINE4, RES_POOLCOLL_HEADLINE5, RES_POOLCOLL_HEADLINE6, RES_POOLCOLL_HEADLINE7, RES_POOLCOLL_HEADLINE8, RES_POOLCOLL_HEADLINE9, RES_POOLCOLL_TOX_IDX1, RES_POOLCOLL_TOX_IDX2, RES_POOLCOLL_TOX_IDX3, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_POOLCOLL_TOX_CNTNT1, RES_POOLCOLL_TOX_CNTNT2, RES_POOLCOLL_TOX_CNTNT3, RES_POOLCOLL_TOX_CNTNT4, RES_POOLCOLL_TOX_CNTNT5, RES_POOLCOLL_TOX_CNTNT6, RES_POOLCOLL_TOX_CNTNT7, RES_POOLCOLL_TOX_CNTNT8, RES_POOLCOLL_TOX_CNTNT9, RES_NONE, RES_POOLCOLL_FOOTNOTE, RES_NONE, RES_POOLCOLL_HEADER, RES_POOLCOLL_FOOTER, RES_POOLCOLL_TOX_IDXH, RES_NONE, RES_NONE, RES_POOLCOLL_JAKETADRESS, RES_POOLCOLL_SENDADRESS, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_POOLCOLL_ENDNOTE, RES_NONE, RES_NONE, RES_NONE, RES_POOLCOLL_LISTS_BEGIN, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_POOLCOLL_DOC_TITEL, RES_NONE, RES_POOLCOLL_SIGNATURE, RES_NONE, RES_POOLCOLL_TEXT, RES_POOLCOLL_TEXT_MOVE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_POOLCOLL_DOC_SUBTITEL }; const size_t nArrSize = (sizeof(aArr) / sizeof(aArr[0])); ASSERT(nArrSize == 75, "Style Array has false size"); SwTxtFmtColl* pRet = 0; //If this is a built-in word style that has a built-in writer //equivalent, then map it to one of our built in styles regardless //of its name if (sal::static_int_cast< size_t >(eSti) < nArrSize && aArr[eSti] != RES_NONE) pRet = mrDoc.GetTxtCollFromPool( static_cast< sal_uInt16 >(aArr[eSti]), false); return pRet; } SwTxtFmtColl* MapperImpl<SwTxtFmtColl>::GetStyle(const String &rName) { return sw::util::GetParaStyle(mrDoc, rName); } SwTxtFmtColl* MapperImpl<SwTxtFmtColl>::MakeStyle(const String &rName) { return mrDoc.MakeTxtFmtColl(rName, const_cast<SwTxtFmtColl *>(mrDoc.GetDfltTxtFmtColl())); } template<> class MapperImpl<SwCharFmt> { private: SwDoc &mrDoc; public: MapperImpl(SwDoc &rDoc) : mrDoc(rDoc) {} SwCharFmt* GetBuiltInStyle(ww::sti eSti); SwCharFmt* GetStyle(const String &rName); SwCharFmt* MakeStyle(const String &rName); }; SwCharFmt* MapperImpl<SwCharFmt>::GetBuiltInStyle(ww::sti eSti) { RES_POOL_CHRFMT_TYPE eLookup = RES_POOLCHR_NORMAL_END; switch (eSti) { case ww::stiFtnRef: eLookup = RES_POOLCHR_FOOTNOTE; break; case ww::stiLnn: eLookup = RES_POOLCHR_LINENUM; break; case ww::stiPgn: eLookup = RES_POOLCHR_PAGENO; break; case ww::stiEdnRef: eLookup = RES_POOLCHR_ENDNOTE; break; case ww::stiHyperlink: eLookup = RES_POOLCHR_INET_NORMAL; break; case ww::stiHyperlinkFollowed: eLookup = RES_POOLCHR_INET_VISIT; break; case ww::stiStrong: eLookup = RES_POOLCHR_HTML_STRONG; break; case ww::stiEmphasis: eLookup = RES_POOLCHR_HTML_EMPHASIS; break; default: eLookup = RES_POOLCHR_NORMAL_END; break; } SwCharFmt *pRet = 0; if (eLookup != RES_POOLCHR_NORMAL_END) pRet = mrDoc.GetCharFmtFromPool( static_cast< sal_uInt16 >(eLookup) ); return pRet; } SwCharFmt* MapperImpl<SwCharFmt>::GetStyle(const String &rName) { return sw::util::GetCharStyle(mrDoc, rName); } SwCharFmt* MapperImpl<SwCharFmt>::MakeStyle(const String &rName) { return mrDoc.MakeCharFmt(rName, mrDoc.GetDfltCharFmt()); } template<class C> class StyleMapperImpl { private: MapperImpl<C> maHelper; std::set<const C*> maUsedStyles; C* MakeNonCollidingStyle(const String& rName); public: typedef std::pair<C*, bool> StyleResult; StyleMapperImpl(SwDoc &rDoc) : maHelper(rDoc) {} StyleResult GetStyle(const String& rName, ww::sti eSti); }; template<class C> typename StyleMapperImpl<C>::StyleResult StyleMapperImpl<C>::GetStyle(const String& rName, ww::sti eSti) { C *pRet = maHelper.GetBuiltInStyle(eSti); //If we've used it once, don't reuse it if (pRet && (maUsedStyles.end() != maUsedStyles.find(pRet))) pRet = 0; if (!pRet) { pRet = maHelper.GetStyle(rName); //If we've used it once, don't reuse it if (pRet && (maUsedStyles.end() != maUsedStyles.find(pRet))) pRet = 0; } bool bStyExist = pRet ? true : false; if (!pRet) { String aName(rName); xub_StrLen nPos = aName.Search(','); // No commas allow in SW style names if (STRING_NOTFOUND != nPos) aName.Erase(nPos); pRet = MakeNonCollidingStyle(aName); } if (pRet) maUsedStyles.insert(pRet); return StyleResult(pRet, bStyExist); } template<class C> C* StyleMapperImpl<C>::MakeNonCollidingStyle(const String& rName) { String aName(rName); C* pColl = 0; if (0 != (pColl = maHelper.GetStyle(aName))) { //If the style collides first stick WW- in front of it, unless //it already has it and then successively add a larger and //larger number after it, its got to work at some stage! if (!aName.EqualsIgnoreCaseAscii("WW-", 0, 3)) aName.InsertAscii("WW-" , 0); sal_Int32 nI = 1; while ( 0 != (pColl = maHelper.GetStyle(aName)) && (nI < SAL_MAX_INT32) ) { aName += String::CreateFromInt32(nI++); } } return pColl ? 0 : maHelper.MakeStyle(aName); } String FindBestMSSubstituteFont(const String &rFont) { String sRet; if (sw::util::IsStarSymbol(rFont)) sRet.ASSIGN_CONST_ASC("Arial Unicode MS"); else sRet = GetSubsFontName(rFont, SUBSFONT_ONLYONE | SUBSFONT_MS); return sRet; } /* Utility to categorize unicode characters into the best fit windows charset range for exporting to ww6, or as a hint to non \u unicode token aware rtf readers */ rtl_TextEncoding getScriptClass(sal_Unicode cChar) { using namespace ::com::sun::star::i18n; static ScriptTypeList aScripts[] = { { UnicodeScript_kBasicLatin, UnicodeScript_kBasicLatin, RTL_TEXTENCODING_MS_1252}, { UnicodeScript_kLatin1Supplement, UnicodeScript_kLatin1Supplement, RTL_TEXTENCODING_MS_1252}, { UnicodeScript_kLatinExtendedA, UnicodeScript_kLatinExtendedA, RTL_TEXTENCODING_MS_1250}, { UnicodeScript_kLatinExtendedB, UnicodeScript_kLatinExtendedB, RTL_TEXTENCODING_MS_1257}, { UnicodeScript_kGreek, UnicodeScript_kGreek, RTL_TEXTENCODING_MS_1253}, { UnicodeScript_kCyrillic, UnicodeScript_kCyrillic, RTL_TEXTENCODING_MS_1251}, { UnicodeScript_kHebrew, UnicodeScript_kHebrew, RTL_TEXTENCODING_MS_1255}, { UnicodeScript_kArabic, UnicodeScript_kArabic, RTL_TEXTENCODING_MS_1256}, { UnicodeScript_kThai, UnicodeScript_kThai, RTL_TEXTENCODING_MS_1258}, { UnicodeScript_kScriptCount, UnicodeScript_kScriptCount, RTL_TEXTENCODING_MS_1252} }; return unicode::getUnicodeScriptType(cChar, aScripts, RTL_TEXTENCODING_MS_1252); } //Utility to remove entries before a given starting position class IfBeforeStart : public std::unary_function<const sw::util::CharRunEntry&, bool> { private: xub_StrLen mnStart; public: IfBeforeStart(xub_StrLen nStart) : mnStart(nStart) {} bool operator()(const sw::util::CharRunEntry &rEntry) const { return rEntry.mnEndPos < mnStart; } }; } namespace sw { namespace util { bool IsPlausableSingleWordSection(const SwFrmFmt &rTitleFmt, const SwFrmFmt &rFollowFmt) { bool bPlausableTitlePage = true; const SwFmtCol& rFirstCols = rTitleFmt.GetCol(); const SwFmtCol& rFollowCols = rFollowFmt.GetCol(); const SwColumns& rFirstColumns = rFirstCols.GetColumns(); const SwColumns& rFollowColumns = rFollowCols.GetColumns(); const SvxLRSpaceItem &rOneLR = rTitleFmt.GetLRSpace(); const SvxLRSpaceItem &rTwoLR= rFollowFmt.GetLRSpace(); if (rFirstColumns.Count() != rFollowColumns.Count()) { //e.g. #i4320# bPlausableTitlePage = false; } else if (rOneLR != rTwoLR) bPlausableTitlePage = false; else { HdFtDistanceGlue aOne(rTitleFmt.GetAttrSet()); HdFtDistanceGlue aTwo(rFollowFmt.GetAttrSet()); //e.g. #i14509# if (!aOne.EqualTopBottom(aTwo)) bPlausableTitlePage = false; } return bPlausableTitlePage; } HdFtDistanceGlue::HdFtDistanceGlue(const SfxItemSet &rPage) { if (const SvxBoxItem *pBox = HasItem<SvxBoxItem>(rPage, RES_BOX)) { dyaHdrTop = pBox->CalcLineSpace(BOX_LINE_TOP); dyaHdrBottom = pBox->CalcLineSpace(BOX_LINE_BOTTOM); } else { dyaHdrTop = dyaHdrBottom = 0; dyaHdrBottom = 0; } const SvxULSpaceItem &rUL = ItemGet<SvxULSpaceItem>(rPage, RES_UL_SPACE); dyaHdrTop = dyaHdrTop + rUL.GetUpper(); dyaHdrBottom = dyaHdrBottom + rUL.GetLower(); dyaTop = dyaHdrTop; dyaBottom = dyaHdrBottom; using sw::types::msword_cast; const SwFmtHeader *pHd = HasItem<SwFmtHeader>(rPage, RES_HEADER); if (pHd && pHd->IsActive() && pHd->GetHeaderFmt()) { mbHasHeader = true; dyaTop = dyaTop + static_cast< sal_uInt16 >( (myImplHelpers::CalcHdDist(*(pHd->GetHeaderFmt()))) ); } else mbHasHeader = false; const SwFmtFooter *pFt = HasItem<SwFmtFooter>(rPage, RES_FOOTER); if (pFt && pFt->IsActive() && pFt->GetFooterFmt()) { mbHasFooter = true; dyaBottom = dyaBottom + static_cast< sal_uInt16 >( (myImplHelpers::CalcFtDist(*(pFt->GetFooterFmt()))) ); } else mbHasFooter = false; } bool HdFtDistanceGlue::EqualTopBottom(const HdFtDistanceGlue &rOther) const { return (dyaTop == rOther.dyaTop && dyaBottom == rOther.dyaBottom); } ParaStyleMapper::ParaStyleMapper(SwDoc &rDoc) : mpImpl(new myImplHelpers::StyleMapperImpl<SwTxtFmtColl>(rDoc)) { } ParaStyleMapper::~ParaStyleMapper() { delete mpImpl; } ParaStyleMapper::StyleResult ParaStyleMapper::GetStyle( const String& rName, ww::sti eSti) { return mpImpl->GetStyle(rName, eSti); } CharStyleMapper::CharStyleMapper(SwDoc &rDoc) : mpImpl(new myImplHelpers::StyleMapperImpl<SwCharFmt>(rDoc)) { } CharStyleMapper::~CharStyleMapper() { delete mpImpl; } CharStyleMapper::StyleResult CharStyleMapper::GetStyle( const String& rName, ww::sti eSti) { return mpImpl->GetStyle(rName, eSti); } FontMapExport::FontMapExport(const String &rFamilyName) { msPrimary = GetFontToken(rFamilyName, 0); msSecondary = myImplHelpers::FindBestMSSubstituteFont(msPrimary); if (!msSecondary.Len()) msSecondary = GetFontToken(rFamilyName, 1); } bool FontMapExport::HasDistinctSecondary() const { if (msSecondary.Len() && msSecondary != msPrimary) return true; return false; } bool ItemSort::operator()(sal_uInt16 nA, sal_uInt16 nB) const { /* #i24291# All we want to do is ensure for now is that if a charfmt exist in the character properties that it rises to the top and is exported first. In the future we might find more ordering depandancies for export, in which case this is the place to do it */ if (nA == nB) return false; if (nA == RES_TXTATR_CHARFMT) return true; if (nB == RES_TXTATR_CHARFMT) return false; return nA < nB; } CharRuns GetPseudoCharRuns(const SwTxtNode& rTxtNd, xub_StrLen nTxtStart, bool bSplitOnCharSet) { const String &rTxt = rTxtNd.GetTxt(); bool bParaIsRTL = false; ASSERT(rTxtNd.GetDoc(), "No document for node?, suspicious"); if (rTxtNd.GetDoc()) { if (FRMDIR_HORI_RIGHT_TOP == rTxtNd.GetDoc()->GetTextDirection(SwPosition(rTxtNd))) { bParaIsRTL = true; } } using namespace ::com::sun::star::i18n; sal_uInt16 nScript = i18n::ScriptType::LATIN; if (rTxt.Len() && pBreakIt && pBreakIt->GetBreakIter().is()) nScript = pBreakIt->GetBreakIter()->getScriptType(rTxt, 0); rtl_TextEncoding eChrSet = ItemGet<SvxFontItem>(rTxtNd, GetWhichOfScript(RES_CHRATR_FONT, nScript)).GetCharSet(); eChrSet = GetExtendedTextEncoding(eChrSet); CharRuns aRunChanges; if (!rTxt.Len()) { aRunChanges.push_back(CharRunEntry(0, nScript, eChrSet, bParaIsRTL)); return aRunChanges; } typedef std::pair<int32_t, bool> DirEntry; typedef std::vector<DirEntry> DirChanges; typedef DirChanges::const_iterator cDirIter; typedef std::pair<xub_StrLen, sal_Int16> CharSetEntry; typedef std::vector<CharSetEntry> CharSetChanges; typedef CharSetChanges::const_iterator cCharSetIter; typedef std::pair<xub_StrLen, sal_uInt16> ScriptEntry; typedef std::vector<ScriptEntry> ScriptChanges; typedef ScriptChanges::const_iterator cScriptIter; DirChanges aDirChanges; CharSetChanges aCharSets; ScriptChanges aScripts; UBiDiDirection eDefaultDir = bParaIsRTL ? UBIDI_RTL : UBIDI_LTR; UErrorCode nError = U_ZERO_ERROR; UBiDi* pBidi = ubidi_openSized(rTxt.Len(), 0, &nError); ubidi_setPara(pBidi, reinterpret_cast<const UChar *>(rTxt.GetBuffer()), rTxt.Len(), static_cast< UBiDiLevel >(eDefaultDir), 0, &nError); sal_Int32 nCount = ubidi_countRuns(pBidi, &nError); aDirChanges.reserve(nCount); int32_t nStart = 0; int32_t nEnd; UBiDiLevel nCurrDir; for (sal_Int32 nIdx = 0; nIdx < nCount; ++nIdx) { ubidi_getLogicalRun(pBidi, nStart, &nEnd, &nCurrDir); /* UBiDiLevel is the type of the level values in this BiDi implementation. It holds an embedding level and indicates the visual direction by its bit 0 (even/odd value). The value for UBIDI_DEFAULT_LTR is even and the one for UBIDI_DEFAULT_RTL is odd */ aDirChanges.push_back(DirEntry(nEnd, nCurrDir & 0x1)); nStart = nEnd; } ubidi_close(pBidi); if (bSplitOnCharSet) { //Split unicode text into plausable 8bit ranges for export to //older non unicode aware format xub_StrLen nLen = rTxt.Len(); xub_StrLen nPos = 0; while (nPos != nLen) { rtl_TextEncoding ScriptType = myImplHelpers::getScriptClass(rTxt.GetChar(nPos++)); while ( (nPos != nLen) && (ScriptType == myImplHelpers::getScriptClass(rTxt.GetChar(nPos))) ) { ++nPos; } aCharSets.push_back(CharSetEntry(nPos, ScriptType)); } } using sw::types::writer_cast; if (pBreakIt && pBreakIt->GetBreakIter().is()) { xub_StrLen nLen = rTxt.Len(); xub_StrLen nPos = 0; while (nPos < nLen) { sal_Int32 nEnd2 = pBreakIt->GetBreakIter()->endOfScript(rTxt, nPos, nScript); if (nEnd2 < 0) break; // nPos = writer_cast<xub_StrLen>(nEnd2); nPos = static_cast< xub_StrLen >(nEnd2); aScripts.push_back(ScriptEntry(nPos, nScript)); nScript = pBreakIt->GetBreakIter()->getScriptType(rTxt, nPos); } } cDirIter aBiDiEnd = aDirChanges.end(); cCharSetIter aCharSetEnd = aCharSets.end(); cScriptIter aScriptEnd = aScripts.end(); cDirIter aBiDiIter = aDirChanges.begin(); cCharSetIter aCharSetIter = aCharSets.begin(); cScriptIter aScriptIter = aScripts.begin(); bool bCharIsRTL = bParaIsRTL; while ( aBiDiIter != aBiDiEnd || aCharSetIter != aCharSetEnd || aScriptIter != aScriptEnd ) { xub_StrLen nMinPos = rTxt.Len(); if (aBiDiIter != aBiDiEnd) { if (aBiDiIter->first < nMinPos) // nMinPos = writer_cast<xub_StrLen>(aBiDiIter->first); nMinPos = static_cast< xub_StrLen >(aBiDiIter->first); bCharIsRTL = aBiDiIter->second; } if (aCharSetIter != aCharSetEnd) { if (aCharSetIter->first < nMinPos) nMinPos = aCharSetIter->first; eChrSet = aCharSetIter->second; } if (aScriptIter != aScriptEnd) { if (aScriptIter->first < nMinPos) nMinPos = aScriptIter->first; nScript = aScriptIter->second; } aRunChanges.push_back( CharRunEntry(nMinPos, nScript, eChrSet, bCharIsRTL)); if (aBiDiIter != aBiDiEnd) { if (aBiDiIter->first == nMinPos) ++aBiDiIter; } if (aCharSetIter != aCharSetEnd) { if (aCharSetIter->first == nMinPos) ++aCharSetIter; } if (aScriptIter != aScriptEnd) { if (aScriptIter->first == nMinPos) ++aScriptIter; } } aRunChanges.erase(std::remove_if(aRunChanges.begin(), aRunChanges.end(), myImplHelpers::IfBeforeStart(nTxtStart)), aRunChanges.end()); return aRunChanges; } } namespace ms { sal_uInt8 rtl_TextEncodingToWinCharset(rtl_TextEncoding eTextEncoding) { sal_uInt8 nRet = rtl_getBestWindowsCharsetFromTextEncoding(eTextEncoding); switch (eTextEncoding) { case RTL_TEXTENCODING_DONTKNOW: case RTL_TEXTENCODING_UCS2: case RTL_TEXTENCODING_UTF7: case RTL_TEXTENCODING_UTF8: case RTL_TEXTENCODING_JAVA_UTF8: ASSERT(nRet != 0x80, "This method may be redundant"); nRet = 0x80; break; default: break; } return nRet; } long DateTime2DTTM( const DateTime& rDT ) { /* mint short :6 0000003F minutes (0-59) hr short :5 000007C0 hours (0-23) dom short :5 0000F800 days of month (1-31) mon short :4 000F0000 months (1-12) yr short :9 1FF00000 years (1900-2411)-1900 wdy short :3 E0000000 weekday(Sunday=0 Monday=1 ( wdy can be ignored ) Tuesday=2 Wednesday=3 Thursday=4 Friday=5 Saturday=6) */ if ( rDT.GetDate() == 0L ) return 0L; long nDT = ( rDT.GetDayOfWeek() + 1 ) % 7; nDT <<= 9; nDT += ( rDT.GetYear() - 1900 ) & 0x1ff; nDT <<= 4; nDT += rDT.GetMonth() & 0xf; nDT <<= 5; nDT += rDT.GetDay() & 0x1f; nDT <<= 5; nDT += rDT.GetHour() & 0x1f; nDT <<= 6; nDT += rDT.GetMin() & 0x3f; return nDT; } DateTime DTTM2DateTime( long lDTTM ) { /* mint short :6 0000003F minutes (0-59) hr short :5 000007C0 hours (0-23) dom short :5 0000F800 days of month (1-31) mon short :4 000F0000 months (1-12) yr short :9 1FF00000 years (1900-2411)-1900 wdy short :3 E0000000 weekday(Sunday=0 Monday=1 ( wdy can be ignored ) Tuesday=2 Wednesday=3 Thursday=4 Friday=5 Saturday=6) */ DateTime aDateTime(Date( 0 ), Time( 0 )); if( lDTTM ) { USHORT lMin = (USHORT)(lDTTM & 0x0000003F); lDTTM >>= 6; USHORT lHour= (USHORT)(lDTTM & 0x0000001F); lDTTM >>= 5; USHORT lDay = (USHORT)(lDTTM & 0x0000001F); lDTTM >>= 5; USHORT lMon = (USHORT)(lDTTM & 0x0000000F); lDTTM >>= 4; USHORT lYear= (USHORT)(lDTTM & 0x000001FF) + 1900; aDateTime = DateTime(Date(lDay, lMon, lYear), Time(lHour, lMin)); } return aDateTime; } ULONG MSDateTimeFormatToSwFormat(String& rParams, SvNumberFormatter *pFormatter, USHORT &rLang, bool bHijri) { // tell the Formatter about the new entry UINT16 nCheckPos = 0; short nType = NUMBERFORMAT_DEFINED; sal_uInt32 nKey = 0; SwapQuotesInField(rParams); //#102782#, #102815#, #108341# & #111944# have to work at the same time :-) bool bForceJapanese(false); bool bForceNatNum(false); xub_StrLen nLen = rParams.Len(); xub_StrLen nI = 0; while (nI < nLen) { if (rParams.GetChar(nI) == '\\') nI++; else if (rParams.GetChar(nI) == '\"') { ++nI; //While not at the end and not at an unescaped end quote while ((nI < nLen) && (!(rParams.GetChar(nI) == '\"') && (rParams.GetChar(nI-1) != '\\'))) ++nI; } else //normal unquoted section { sal_Unicode nChar = rParams.GetChar(nI); if (nChar == 'O') { rParams.SetChar(nI, 'M'); bForceNatNum = true; } else if (nChar == 'o') { rParams.SetChar(nI, 'm'); bForceNatNum = true; } else if ((nChar == 'A') && IsNotAM(rParams, nI)) { rParams.SetChar(nI, 'D'); bForceNatNum = true; } else if ((nChar == 'g') || (nChar == 'G')) bForceJapanese = true; else if ((nChar == 'a') && IsNotAM(rParams, nI)) bForceJapanese = true; else if (nChar == 'E') { if ((nI != nLen-1) && (rParams.GetChar(nI+1) == 'E')) { rParams.Replace(nI, 2, CREATE_CONST_ASC("YYYY")); nLen+=2; nI+=3; } bForceJapanese = true; } else if (nChar == 'e') { if ((nI != nLen-1) && (rParams.GetChar(nI+1) == 'e')) { rParams.Replace(nI, 2, CREATE_CONST_ASC("yyyy")); nLen+=2; nI+=3; } bForceJapanese = true; } else if (nChar == '/') { // MM We have to escape '/' in case it's used as a char rParams.Replace(nI, 1, CREATE_CONST_ASC("\\/")); // rParams.Insert( nI, '\\' ); nI++; nLen++; } // Deal with language differences in date format expression. // Should be made with i18n framework. // The list of the mappings and of those "special" locales is to be found at: // http://l10n.openoffice.org/i18n_framework/LocaleData.html switch ( rLang ) { case LANGUAGE_FINNISH: { if (nChar == 'y' || nChar == 'Y') rParams.SetChar (nI, 'V'); else if (nChar == 'm' || nChar == 'M') rParams.SetChar (nI, 'K'); else if (nChar == 'd' || nChar == 'D') rParams.SetChar (nI, 'P'); else if (nChar == 'h' || nChar == 'H') rParams.SetChar (nI, 'T'); } break; case LANGUAGE_DANISH: case LANGUAGE_NORWEGIAN: case LANGUAGE_NORWEGIAN_BOKMAL: case LANGUAGE_NORWEGIAN_NYNORSK: case LANGUAGE_SWEDISH: case LANGUAGE_SWEDISH_FINLAND: { if (nChar == 'h' || nChar == 'H') rParams.SetChar (nI, 'T'); } break; case LANGUAGE_PORTUGUESE: case LANGUAGE_PORTUGUESE_BRAZILIAN: case LANGUAGE_SPANISH_MODERN: case LANGUAGE_SPANISH_DATED: case LANGUAGE_SPANISH_MEXICAN: case LANGUAGE_SPANISH_GUATEMALA: case LANGUAGE_SPANISH_COSTARICA: case LANGUAGE_SPANISH_PANAMA: case LANGUAGE_SPANISH_DOMINICAN_REPUBLIC: case LANGUAGE_SPANISH_VENEZUELA: case LANGUAGE_SPANISH_COLOMBIA: case LANGUAGE_SPANISH_PERU: case LANGUAGE_SPANISH_ARGENTINA: case LANGUAGE_SPANISH_ECUADOR: case LANGUAGE_SPANISH_CHILE: case LANGUAGE_SPANISH_URUGUAY: case LANGUAGE_SPANISH_PARAGUAY: case LANGUAGE_SPANISH_BOLIVIA: case LANGUAGE_SPANISH_EL_SALVADOR: case LANGUAGE_SPANISH_HONDURAS: case LANGUAGE_SPANISH_NICARAGUA: case LANGUAGE_SPANISH_PUERTO_RICO: { if (nChar == 'a' || nChar == 'A') rParams.SetChar (nI, 'O'); else if (nChar == 'y' || nChar == 'Y') rParams.SetChar (nI, 'A'); } break; case LANGUAGE_DUTCH: case LANGUAGE_DUTCH_BELGIAN: { if (nChar == 'y' || nChar == 'Y') rParams.SetChar (nI, 'J'); else if (nChar == 'u' || nChar == 'U') rParams.SetChar (nI, 'H'); } break; case LANGUAGE_ITALIAN: case LANGUAGE_ITALIAN_SWISS: { if (nChar == 'a' || nChar == 'A') rParams.SetChar (nI, 'O'); else if (nChar == 'g' || nChar == 'G') rParams.SetChar (nI, 'X'); else if (nChar == 'y' || nChar == 'Y') rParams.SetChar(nI, 'A'); else if (nChar == 'd' || nChar == 'D') rParams.SetChar (nI, 'G'); } break; case LANGUAGE_GERMAN: case LANGUAGE_GERMAN_SWISS: case LANGUAGE_GERMAN_AUSTRIAN: case LANGUAGE_GERMAN_LUXEMBOURG: case LANGUAGE_GERMAN_LIECHTENSTEIN: { if (nChar == 'y' || nChar == 'Y') rParams.SetChar (nI, 'J'); else if (nChar == 'd' || nChar == 'D') rParams.SetChar (nI, 'T'); } break; case LANGUAGE_FRENCH: case LANGUAGE_FRENCH_BELGIAN: case LANGUAGE_FRENCH_CANADIAN: case LANGUAGE_FRENCH_SWISS: case LANGUAGE_FRENCH_LUXEMBOURG: case LANGUAGE_FRENCH_MONACO: { if (nChar == 'a' || nChar == 'A') rParams.SetChar (nI, 'O'); else if (nChar == 'y' || nChar == 'Y') rParams.SetChar (nI, 'A'); else if (nChar == 'd' || nChar == 'D') rParams.SetChar (nI, 'J'); } break; default: { ; // Nothing } } } ++nI; } if (bForceNatNum) bForceJapanese = true; if (bForceJapanese) rLang = LANGUAGE_JAPANESE; if (bForceNatNum) rParams.Insert(CREATE_CONST_ASC("[NatNum1][$-411]"),0); if (bHijri) rParams.Insert(CREATE_CONST_ASC("[~hijri]"), 0); pFormatter->PutEntry(rParams, nCheckPos, nType, nKey, rLang); return nKey; } bool IsNotAM(String& rParams, xub_StrLen nPos) { return ( (nPos == rParams.Len() - 1) || ( (rParams.GetChar(nPos+1) != 'M') && (rParams.GetChar(nPos+1) != 'm') ) ); } void SwapQuotesInField(String &rFmt) { //Swap unescaped " and ' with ' and " xub_StrLen nLen = rFmt.Len(); for (xub_StrLen nI = 0; nI < nLen; ++nI) { if ((rFmt.GetChar(nI) == '\"') && (!nI || rFmt.GetChar(nI-1) != '\\')) rFmt.SetChar(nI, '\''); else if ((rFmt.GetChar(nI) == '\'') && (!nI || rFmt.GetChar(nI-1) != '\\')) rFmt.SetChar(nI, '\"'); } } } } /* vi:set tabstop=4 shiftwidth=4 expandtab: */ sw-ww8-styles-import-fix.diff: wrong style import in french i#21939 /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */ /// @HTML #include <msfilter.hxx> # include "writerwordglue.hxx" #include <doc.hxx> # include "writerhelper.hxx" #include <algorithm> //std::find_if #include <functional> //std::unary_function #include <unicode/ubidi.h> //ubidi_getLogicalRun # include <tools/tenccvt.hxx> //GetExtendedTextEncoding # include <i18nutil/unicode.hxx> //unicode::getUnicodeScriptType #ifndef _COM_SUN_STAR_I18N_SCRIPTTYPE_HDL_ # include <com/sun/star/i18n/ScriptType.hdl> //ScriptType #endif #ifndef SV_FONTCVT_HXX # include <unotools/fontcvt.hxx> //GetSubsFontName #endif # include <editeng/paperinf.hxx> //lA0Width... # include <editeng/lrspitem.hxx> //SvxLRSpaceItem # include <editeng/ulspitem.hxx> //SvxULSpaceItem # include <editeng/boxitem.hxx> //SvxBoxItem # include <editeng/fontitem.hxx> //SvxFontItem # include <frmfmt.hxx> //SwFrmFmt # include <fmtclds.hxx> //SwFmtCol # include <hfspacingitem.hxx> //SwHeaderAndFooterEatSpacingItem # include <fmtfsize.hxx> //SwFmtFrmSize # include <swrect.hxx> //SwRect # include <fmthdft.hxx> //SwFmtHeader/SwFmtFooter # include <frmatr.hxx> //GetLRSpace... # include <ndtxt.hxx> //SwTxtNode # include <breakit.hxx> //pBreakIt #define ASSIGN_CONST_ASC(s) AssignAscii(RTL_CONSTASCII_STRINGPARAM(s)) namespace myImplHelpers { SwTwips CalcHdFtDist(const SwFrmFmt& rFmt, sal_uInt16 nSpacing) { /* #98506# The normal case for reexporting word docs is to have dynamic spacing, as this is word's only setting, and the reason for the existance of the dynamic spacing features. If we have dynamic spacing active then we can add its spacing to the value height of the h/f and get the wanted total size for word. Otherwise we have to get the real layout rendered height, which is totally nonoptimum, but the best we can do. */ long nDist=0; const SwFmtFrmSize& rSz = rFmt.GetFrmSize(); const SwHeaderAndFooterEatSpacingItem &rSpacingCtrl = sw::util::ItemGet<SwHeaderAndFooterEatSpacingItem> (rFmt, RES_HEADER_FOOTER_EAT_SPACING); if (rSpacingCtrl.GetValue()) nDist += rSz.GetHeight(); else { SwRect aRect(rFmt.FindLayoutRect(false)); if (aRect.Height()) nDist += aRect.Height(); else { const SwFmtFrmSize& rSize = rFmt.GetFrmSize(); if (ATT_VAR_SIZE != rSize.GetHeightSizeType()) nDist += rSize.GetHeight(); else { nDist += 274; // default for 12pt text nDist += nSpacing; } } } return nDist; } SwTwips CalcHdDist(const SwFrmFmt& rFmt) { return CalcHdFtDist(rFmt, rFmt.GetULSpace().GetUpper()); } SwTwips CalcFtDist(const SwFrmFmt& rFmt) { return CalcHdFtDist(rFmt, rFmt.GetULSpace().GetLower()); } /* SwTxtFmtColl and SwCharFmt are quite distinct types and how they are gotten is also distinct, but the algorithm to match word's eqivalents into them is the same, so we put the different stuff into two seperate helper implementations and a core template that uses the helpers that uses the same algorithm to do the work. We'll make the helpers specializations of a non existing template so I can let the compiler figure out the right one to use from a simple argument to the algorithm class */ template <class C> class MapperImpl; template<> class MapperImpl<SwTxtFmtColl> { private: SwDoc &mrDoc; public: MapperImpl(SwDoc &rDoc) : mrDoc(rDoc) {} SwTxtFmtColl* GetBuiltInStyle(ww::sti eSti); SwTxtFmtColl* GetStyle(const String &rName); SwTxtFmtColl* MakeStyle(const String &rName); }; SwTxtFmtColl* MapperImpl<SwTxtFmtColl>::GetBuiltInStyle(ww::sti eSti) { const RES_POOL_COLLFMT_TYPE RES_NONE = RES_POOLCOLL_DOC_END; static const RES_POOL_COLLFMT_TYPE aArr[]= { RES_POOLCOLL_STANDARD, RES_POOLCOLL_HEADLINE1, RES_POOLCOLL_HEADLINE2, RES_POOLCOLL_HEADLINE3, RES_POOLCOLL_HEADLINE4, RES_POOLCOLL_HEADLINE5, RES_POOLCOLL_HEADLINE6, RES_POOLCOLL_HEADLINE7, RES_POOLCOLL_HEADLINE8, RES_POOLCOLL_HEADLINE9, RES_POOLCOLL_TOX_IDX1, RES_POOLCOLL_TOX_IDX2, RES_POOLCOLL_TOX_IDX3, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_POOLCOLL_TOX_CNTNT1, RES_POOLCOLL_TOX_CNTNT2, RES_POOLCOLL_TOX_CNTNT3, RES_POOLCOLL_TOX_CNTNT4, RES_POOLCOLL_TOX_CNTNT5, RES_POOLCOLL_TOX_CNTNT6, RES_POOLCOLL_TOX_CNTNT7, RES_POOLCOLL_TOX_CNTNT8, RES_POOLCOLL_TOX_CNTNT9, RES_NONE, RES_POOLCOLL_FOOTNOTE, RES_NONE, RES_POOLCOLL_HEADER, RES_POOLCOLL_FOOTER, RES_POOLCOLL_TOX_IDXH, RES_NONE, RES_NONE, RES_POOLCOLL_JAKETADRESS, RES_POOLCOLL_SENDADRESS, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_POOLCOLL_ENDNOTE, RES_NONE, RES_NONE, RES_NONE, RES_POOLCOLL_LISTS_BEGIN, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_POOLCOLL_HEADLINE_BASE, RES_NONE, RES_POOLCOLL_SIGNATURE, RES_NONE, RES_POOLCOLL_TEXT, RES_POOLCOLL_TEXT_MOVE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_NONE, RES_POOLCOLL_DOC_SUBTITEL }; const size_t nArrSize = (sizeof(aArr) / sizeof(aArr[0])); ASSERT(nArrSize == 75, "Style Array has false size"); SwTxtFmtColl* pRet = 0; //If this is a built-in word style that has a built-in writer //equivalent, then map it to one of our built in styles regardless //of its name if (sal::static_int_cast< size_t >(eSti) < nArrSize && aArr[eSti] != RES_NONE) pRet = mrDoc.GetTxtCollFromPool( static_cast< sal_uInt16 >(aArr[eSti]), false); return pRet; } SwTxtFmtColl* MapperImpl<SwTxtFmtColl>::GetStyle(const String &rName) { return sw::util::GetParaStyle(mrDoc, rName); } SwTxtFmtColl* MapperImpl<SwTxtFmtColl>::MakeStyle(const String &rName) { return mrDoc.MakeTxtFmtColl(rName, const_cast<SwTxtFmtColl *>(mrDoc.GetDfltTxtFmtColl())); } template<> class MapperImpl<SwCharFmt> { private: SwDoc &mrDoc; public: MapperImpl(SwDoc &rDoc) : mrDoc(rDoc) {} SwCharFmt* GetBuiltInStyle(ww::sti eSti); SwCharFmt* GetStyle(const String &rName); SwCharFmt* MakeStyle(const String &rName); }; SwCharFmt* MapperImpl<SwCharFmt>::GetBuiltInStyle(ww::sti eSti) { RES_POOL_CHRFMT_TYPE eLookup = RES_POOLCHR_NORMAL_END; switch (eSti) { case ww::stiFtnRef: eLookup = RES_POOLCHR_FOOTNOTE; break; case ww::stiLnn: eLookup = RES_POOLCHR_LINENUM; break; case ww::stiPgn: eLookup = RES_POOLCHR_PAGENO; break; case ww::stiEdnRef: eLookup = RES_POOLCHR_ENDNOTE; break; case ww::stiHyperlink: eLookup = RES_POOLCHR_INET_NORMAL; break; case ww::stiHyperlinkFollowed: eLookup = RES_POOLCHR_INET_VISIT; break; case ww::stiStrong: eLookup = RES_POOLCHR_HTML_STRONG; break; case ww::stiEmphasis: eLookup = RES_POOLCHR_HTML_EMPHASIS; break; default: eLookup = RES_POOLCHR_NORMAL_END; break; } SwCharFmt *pRet = 0; if (eLookup != RES_POOLCHR_NORMAL_END) pRet = mrDoc.GetCharFmtFromPool( static_cast< sal_uInt16 >(eLookup) ); return pRet; } SwCharFmt* MapperImpl<SwCharFmt>::GetStyle(const String &rName) { return sw::util::GetCharStyle(mrDoc, rName); } SwCharFmt* MapperImpl<SwCharFmt>::MakeStyle(const String &rName) { return mrDoc.MakeCharFmt(rName, mrDoc.GetDfltCharFmt()); } template<class C> class StyleMapperImpl { private: MapperImpl<C> maHelper; std::set<const C*> maUsedStyles; C* MakeNonCollidingStyle(const String& rName); public: typedef std::pair<C*, bool> StyleResult; StyleMapperImpl(SwDoc &rDoc) : maHelper(rDoc) {} StyleResult GetStyle(const String& rName, ww::sti eSti); }; template<class C> typename StyleMapperImpl<C>::StyleResult StyleMapperImpl<C>::GetStyle(const String& rName, ww::sti eSti) { C *pRet = maHelper.GetBuiltInStyle(eSti); //If we've used it once, don't reuse it if (pRet && (maUsedStyles.end() != maUsedStyles.find(pRet))) pRet = 0; if (!pRet) { pRet = maHelper.GetStyle(rName); //If we've used it once, don't reuse it if (pRet && (maUsedStyles.end() != maUsedStyles.find(pRet))) pRet = 0; } bool bStyExist = pRet ? true : false; if (!pRet) { String aName(rName); xub_StrLen nPos = aName.Search(','); // No commas allow in SW style names if (STRING_NOTFOUND != nPos) aName.Erase(nPos); pRet = MakeNonCollidingStyle(aName); } if (pRet) maUsedStyles.insert(pRet); return StyleResult(pRet, bStyExist); } template<class C> C* StyleMapperImpl<C>::MakeNonCollidingStyle(const String& rName) { String aName(rName); C* pColl = 0; if (0 != (pColl = maHelper.GetStyle(aName))) { //If the style collides first stick WW- in front of it, unless //it already has it and then successively add a larger and //larger number after it, its got to work at some stage! if (!aName.EqualsIgnoreCaseAscii("WW-", 0, 3)) aName.InsertAscii("WW-" , 0); sal_Int32 nI = 1; while ( 0 != (pColl = maHelper.GetStyle(aName)) && (nI < SAL_MAX_INT32) ) { aName += String::CreateFromInt32(nI++); } } return pColl ? 0 : maHelper.MakeStyle(aName); } String FindBestMSSubstituteFont(const String &rFont) { String sRet; if (sw::util::IsStarSymbol(rFont)) sRet.ASSIGN_CONST_ASC("Arial Unicode MS"); else sRet = GetSubsFontName(rFont, SUBSFONT_ONLYONE | SUBSFONT_MS); return sRet; } /* Utility to categorize unicode characters into the best fit windows charset range for exporting to ww6, or as a hint to non \u unicode token aware rtf readers */ rtl_TextEncoding getScriptClass(sal_Unicode cChar) { using namespace ::com::sun::star::i18n; static ScriptTypeList aScripts[] = { { UnicodeScript_kBasicLatin, UnicodeScript_kBasicLatin, RTL_TEXTENCODING_MS_1252}, { UnicodeScript_kLatin1Supplement, UnicodeScript_kLatin1Supplement, RTL_TEXTENCODING_MS_1252}, { UnicodeScript_kLatinExtendedA, UnicodeScript_kLatinExtendedA, RTL_TEXTENCODING_MS_1250}, { UnicodeScript_kLatinExtendedB, UnicodeScript_kLatinExtendedB, RTL_TEXTENCODING_MS_1257}, { UnicodeScript_kGreek, UnicodeScript_kGreek, RTL_TEXTENCODING_MS_1253}, { UnicodeScript_kCyrillic, UnicodeScript_kCyrillic, RTL_TEXTENCODING_MS_1251}, { UnicodeScript_kHebrew, UnicodeScript_kHebrew, RTL_TEXTENCODING_MS_1255}, { UnicodeScript_kArabic, UnicodeScript_kArabic, RTL_TEXTENCODING_MS_1256}, { UnicodeScript_kThai, UnicodeScript_kThai, RTL_TEXTENCODING_MS_1258}, { UnicodeScript_kScriptCount, UnicodeScript_kScriptCount, RTL_TEXTENCODING_MS_1252} }; return unicode::getUnicodeScriptType(cChar, aScripts, RTL_TEXTENCODING_MS_1252); } //Utility to remove entries before a given starting position class IfBeforeStart : public std::unary_function<const sw::util::CharRunEntry&, bool> { private: xub_StrLen mnStart; public: IfBeforeStart(xub_StrLen nStart) : mnStart(nStart) {} bool operator()(const sw::util::CharRunEntry &rEntry) const { return rEntry.mnEndPos < mnStart; } }; } namespace sw { namespace util { bool IsPlausableSingleWordSection(const SwFrmFmt &rTitleFmt, const SwFrmFmt &rFollowFmt) { bool bPlausableTitlePage = true; const SwFmtCol& rFirstCols = rTitleFmt.GetCol(); const SwFmtCol& rFollowCols = rFollowFmt.GetCol(); const SwColumns& rFirstColumns = rFirstCols.GetColumns(); const SwColumns& rFollowColumns = rFollowCols.GetColumns(); const SvxLRSpaceItem &rOneLR = rTitleFmt.GetLRSpace(); const SvxLRSpaceItem &rTwoLR= rFollowFmt.GetLRSpace(); if (rFirstColumns.Count() != rFollowColumns.Count()) { //e.g. #i4320# bPlausableTitlePage = false; } else if (rOneLR != rTwoLR) bPlausableTitlePage = false; else { HdFtDistanceGlue aOne(rTitleFmt.GetAttrSet()); HdFtDistanceGlue aTwo(rFollowFmt.GetAttrSet()); //e.g. #i14509# if (!aOne.EqualTopBottom(aTwo)) bPlausableTitlePage = false; } return bPlausableTitlePage; } HdFtDistanceGlue::HdFtDistanceGlue(const SfxItemSet &rPage) { if (const SvxBoxItem *pBox = HasItem<SvxBoxItem>(rPage, RES_BOX)) { dyaHdrTop = pBox->CalcLineSpace(BOX_LINE_TOP); dyaHdrBottom = pBox->CalcLineSpace(BOX_LINE_BOTTOM); } else { dyaHdrTop = dyaHdrBottom = 0; dyaHdrBottom = 0; } const SvxULSpaceItem &rUL = ItemGet<SvxULSpaceItem>(rPage, RES_UL_SPACE); dyaHdrTop = dyaHdrTop + rUL.GetUpper(); dyaHdrBottom = dyaHdrBottom + rUL.GetLower(); dyaTop = dyaHdrTop; dyaBottom = dyaHdrBottom; using sw::types::msword_cast; const SwFmtHeader *pHd = HasItem<SwFmtHeader>(rPage, RES_HEADER); if (pHd && pHd->IsActive() && pHd->GetHeaderFmt()) { mbHasHeader = true; dyaTop = dyaTop + static_cast< sal_uInt16 >( (myImplHelpers::CalcHdDist(*(pHd->GetHeaderFmt()))) ); } else mbHasHeader = false; const SwFmtFooter *pFt = HasItem<SwFmtFooter>(rPage, RES_FOOTER); if (pFt && pFt->IsActive() && pFt->GetFooterFmt()) { mbHasFooter = true; dyaBottom = dyaBottom + static_cast< sal_uInt16 >( (myImplHelpers::CalcFtDist(*(pFt->GetFooterFmt()))) ); } else mbHasFooter = false; } bool HdFtDistanceGlue::EqualTopBottom(const HdFtDistanceGlue &rOther) const { return (dyaTop == rOther.dyaTop && dyaBottom == rOther.dyaBottom); } ParaStyleMapper::ParaStyleMapper(SwDoc &rDoc) : mpImpl(new myImplHelpers::StyleMapperImpl<SwTxtFmtColl>(rDoc)) { } ParaStyleMapper::~ParaStyleMapper() { delete mpImpl; } ParaStyleMapper::StyleResult ParaStyleMapper::GetStyle( const String& rName, ww::sti eSti) { return mpImpl->GetStyle(rName, eSti); } CharStyleMapper::CharStyleMapper(SwDoc &rDoc) : mpImpl(new myImplHelpers::StyleMapperImpl<SwCharFmt>(rDoc)) { } CharStyleMapper::~CharStyleMapper() { delete mpImpl; } CharStyleMapper::StyleResult CharStyleMapper::GetStyle( const String& rName, ww::sti eSti) { return mpImpl->GetStyle(rName, eSti); } FontMapExport::FontMapExport(const String &rFamilyName) { msPrimary = GetFontToken(rFamilyName, 0); msSecondary = myImplHelpers::FindBestMSSubstituteFont(msPrimary); if (!msSecondary.Len()) msSecondary = GetFontToken(rFamilyName, 1); } bool FontMapExport::HasDistinctSecondary() const { if (msSecondary.Len() && msSecondary != msPrimary) return true; return false; } bool ItemSort::operator()(sal_uInt16 nA, sal_uInt16 nB) const { /* #i24291# All we want to do is ensure for now is that if a charfmt exist in the character properties that it rises to the top and is exported first. In the future we might find more ordering depandancies for export, in which case this is the place to do it */ if (nA == nB) return false; if (nA == RES_TXTATR_CHARFMT) return true; if (nB == RES_TXTATR_CHARFMT) return false; return nA < nB; } CharRuns GetPseudoCharRuns(const SwTxtNode& rTxtNd, xub_StrLen nTxtStart, bool bSplitOnCharSet) { const String &rTxt = rTxtNd.GetTxt(); bool bParaIsRTL = false; ASSERT(rTxtNd.GetDoc(), "No document for node?, suspicious"); if (rTxtNd.GetDoc()) { if (FRMDIR_HORI_RIGHT_TOP == rTxtNd.GetDoc()->GetTextDirection(SwPosition(rTxtNd))) { bParaIsRTL = true; } } using namespace ::com::sun::star::i18n; sal_uInt16 nScript = i18n::ScriptType::LATIN; if (rTxt.Len() && pBreakIt && pBreakIt->GetBreakIter().is()) nScript = pBreakIt->GetBreakIter()->getScriptType(rTxt, 0); rtl_TextEncoding eChrSet = ItemGet<SvxFontItem>(rTxtNd, GetWhichOfScript(RES_CHRATR_FONT, nScript)).GetCharSet(); eChrSet = GetExtendedTextEncoding(eChrSet); CharRuns aRunChanges; if (!rTxt.Len()) { aRunChanges.push_back(CharRunEntry(0, nScript, eChrSet, bParaIsRTL)); return aRunChanges; } typedef std::pair<int32_t, bool> DirEntry; typedef std::vector<DirEntry> DirChanges; typedef DirChanges::const_iterator cDirIter; typedef std::pair<xub_StrLen, sal_Int16> CharSetEntry; typedef std::vector<CharSetEntry> CharSetChanges; typedef CharSetChanges::const_iterator cCharSetIter; typedef std::pair<xub_StrLen, sal_uInt16> ScriptEntry; typedef std::vector<ScriptEntry> ScriptChanges; typedef ScriptChanges::const_iterator cScriptIter; DirChanges aDirChanges; CharSetChanges aCharSets; ScriptChanges aScripts; UBiDiDirection eDefaultDir = bParaIsRTL ? UBIDI_RTL : UBIDI_LTR; UErrorCode nError = U_ZERO_ERROR; UBiDi* pBidi = ubidi_openSized(rTxt.Len(), 0, &nError); ubidi_setPara(pBidi, reinterpret_cast<const UChar *>(rTxt.GetBuffer()), rTxt.Len(), static_cast< UBiDiLevel >(eDefaultDir), 0, &nError); sal_Int32 nCount = ubidi_countRuns(pBidi, &nError); aDirChanges.reserve(nCount); int32_t nStart = 0; int32_t nEnd; UBiDiLevel nCurrDir; for (sal_Int32 nIdx = 0; nIdx < nCount; ++nIdx) { ubidi_getLogicalRun(pBidi, nStart, &nEnd, &nCurrDir); /* UBiDiLevel is the type of the level values in this BiDi implementation. It holds an embedding level and indicates the visual direction by its bit 0 (even/odd value). The value for UBIDI_DEFAULT_LTR is even and the one for UBIDI_DEFAULT_RTL is odd */ aDirChanges.push_back(DirEntry(nEnd, nCurrDir & 0x1)); nStart = nEnd; } ubidi_close(pBidi); if (bSplitOnCharSet) { //Split unicode text into plausable 8bit ranges for export to //older non unicode aware format xub_StrLen nLen = rTxt.Len(); xub_StrLen nPos = 0; while (nPos != nLen) { rtl_TextEncoding ScriptType = myImplHelpers::getScriptClass(rTxt.GetChar(nPos++)); while ( (nPos != nLen) && (ScriptType == myImplHelpers::getScriptClass(rTxt.GetChar(nPos))) ) { ++nPos; } aCharSets.push_back(CharSetEntry(nPos, ScriptType)); } } using sw::types::writer_cast; if (pBreakIt && pBreakIt->GetBreakIter().is()) { xub_StrLen nLen = rTxt.Len(); xub_StrLen nPos = 0; while (nPos < nLen) { sal_Int32 nEnd2 = pBreakIt->GetBreakIter()->endOfScript(rTxt, nPos, nScript); if (nEnd2 < 0) break; // nPos = writer_cast<xub_StrLen>(nEnd2); nPos = static_cast< xub_StrLen >(nEnd2); aScripts.push_back(ScriptEntry(nPos, nScript)); nScript = pBreakIt->GetBreakIter()->getScriptType(rTxt, nPos); } } cDirIter aBiDiEnd = aDirChanges.end(); cCharSetIter aCharSetEnd = aCharSets.end(); cScriptIter aScriptEnd = aScripts.end(); cDirIter aBiDiIter = aDirChanges.begin(); cCharSetIter aCharSetIter = aCharSets.begin(); cScriptIter aScriptIter = aScripts.begin(); bool bCharIsRTL = bParaIsRTL; while ( aBiDiIter != aBiDiEnd || aCharSetIter != aCharSetEnd || aScriptIter != aScriptEnd ) { xub_StrLen nMinPos = rTxt.Len(); if (aBiDiIter != aBiDiEnd) { if (aBiDiIter->first < nMinPos) // nMinPos = writer_cast<xub_StrLen>(aBiDiIter->first); nMinPos = static_cast< xub_StrLen >(aBiDiIter->first); bCharIsRTL = aBiDiIter->second; } if (aCharSetIter != aCharSetEnd) { if (aCharSetIter->first < nMinPos) nMinPos = aCharSetIter->first; eChrSet = aCharSetIter->second; } if (aScriptIter != aScriptEnd) { if (aScriptIter->first < nMinPos) nMinPos = aScriptIter->first; nScript = aScriptIter->second; } aRunChanges.push_back( CharRunEntry(nMinPos, nScript, eChrSet, bCharIsRTL)); if (aBiDiIter != aBiDiEnd) { if (aBiDiIter->first == nMinPos) ++aBiDiIter; } if (aCharSetIter != aCharSetEnd) { if (aCharSetIter->first == nMinPos) ++aCharSetIter; } if (aScriptIter != aScriptEnd) { if (aScriptIter->first == nMinPos) ++aScriptIter; } } aRunChanges.erase(std::remove_if(aRunChanges.begin(), aRunChanges.end(), myImplHelpers::IfBeforeStart(nTxtStart)), aRunChanges.end()); return aRunChanges; } } namespace ms { sal_uInt8 rtl_TextEncodingToWinCharset(rtl_TextEncoding eTextEncoding) { sal_uInt8 nRet = rtl_getBestWindowsCharsetFromTextEncoding(eTextEncoding); switch (eTextEncoding) { case RTL_TEXTENCODING_DONTKNOW: case RTL_TEXTENCODING_UCS2: case RTL_TEXTENCODING_UTF7: case RTL_TEXTENCODING_UTF8: case RTL_TEXTENCODING_JAVA_UTF8: ASSERT(nRet != 0x80, "This method may be redundant"); nRet = 0x80; break; default: break; } return nRet; } long DateTime2DTTM( const DateTime& rDT ) { /* mint short :6 0000003F minutes (0-59) hr short :5 000007C0 hours (0-23) dom short :5 0000F800 days of month (1-31) mon short :4 000F0000 months (1-12) yr short :9 1FF00000 years (1900-2411)-1900 wdy short :3 E0000000 weekday(Sunday=0 Monday=1 ( wdy can be ignored ) Tuesday=2 Wednesday=3 Thursday=4 Friday=5 Saturday=6) */ if ( rDT.GetDate() == 0L ) return 0L; long nDT = ( rDT.GetDayOfWeek() + 1 ) % 7; nDT <<= 9; nDT += ( rDT.GetYear() - 1900 ) & 0x1ff; nDT <<= 4; nDT += rDT.GetMonth() & 0xf; nDT <<= 5; nDT += rDT.GetDay() & 0x1f; nDT <<= 5; nDT += rDT.GetHour() & 0x1f; nDT <<= 6; nDT += rDT.GetMin() & 0x3f; return nDT; } DateTime DTTM2DateTime( long lDTTM ) { /* mint short :6 0000003F minutes (0-59) hr short :5 000007C0 hours (0-23) dom short :5 0000F800 days of month (1-31) mon short :4 000F0000 months (1-12) yr short :9 1FF00000 years (1900-2411)-1900 wdy short :3 E0000000 weekday(Sunday=0 Monday=1 ( wdy can be ignored ) Tuesday=2 Wednesday=3 Thursday=4 Friday=5 Saturday=6) */ DateTime aDateTime(Date( 0 ), Time( 0 )); if( lDTTM ) { USHORT lMin = (USHORT)(lDTTM & 0x0000003F); lDTTM >>= 6; USHORT lHour= (USHORT)(lDTTM & 0x0000001F); lDTTM >>= 5; USHORT lDay = (USHORT)(lDTTM & 0x0000001F); lDTTM >>= 5; USHORT lMon = (USHORT)(lDTTM & 0x0000000F); lDTTM >>= 4; USHORT lYear= (USHORT)(lDTTM & 0x000001FF) + 1900; aDateTime = DateTime(Date(lDay, lMon, lYear), Time(lHour, lMin)); } return aDateTime; } ULONG MSDateTimeFormatToSwFormat(String& rParams, SvNumberFormatter *pFormatter, USHORT &rLang, bool bHijri) { // tell the Formatter about the new entry UINT16 nCheckPos = 0; short nType = NUMBERFORMAT_DEFINED; sal_uInt32 nKey = 0; SwapQuotesInField(rParams); //#102782#, #102815#, #108341# & #111944# have to work at the same time :-) bool bForceJapanese(false); bool bForceNatNum(false); xub_StrLen nLen = rParams.Len(); xub_StrLen nI = 0; while (nI < nLen) { if (rParams.GetChar(nI) == '\\') nI++; else if (rParams.GetChar(nI) == '\"') { ++nI; //While not at the end and not at an unescaped end quote while ((nI < nLen) && (!(rParams.GetChar(nI) == '\"') && (rParams.GetChar(nI-1) != '\\'))) ++nI; } else //normal unquoted section { sal_Unicode nChar = rParams.GetChar(nI); if (nChar == 'O') { rParams.SetChar(nI, 'M'); bForceNatNum = true; } else if (nChar == 'o') { rParams.SetChar(nI, 'm'); bForceNatNum = true; } else if ((nChar == 'A') && IsNotAM(rParams, nI)) { rParams.SetChar(nI, 'D'); bForceNatNum = true; } else if ((nChar == 'g') || (nChar == 'G')) bForceJapanese = true; else if ((nChar == 'a') && IsNotAM(rParams, nI)) bForceJapanese = true; else if (nChar == 'E') { if ((nI != nLen-1) && (rParams.GetChar(nI+1) == 'E')) { rParams.Replace(nI, 2, CREATE_CONST_ASC("YYYY")); nLen+=2; nI+=3; } bForceJapanese = true; } else if (nChar == 'e') { if ((nI != nLen-1) && (rParams.GetChar(nI+1) == 'e')) { rParams.Replace(nI, 2, CREATE_CONST_ASC("yyyy")); nLen+=2; nI+=3; } bForceJapanese = true; } else if (nChar == '/') { // MM We have to escape '/' in case it's used as a char rParams.Replace(nI, 1, CREATE_CONST_ASC("\\/")); // rParams.Insert( nI, '\\' ); nI++; nLen++; } // Deal with language differences in date format expression. // Should be made with i18n framework. // The list of the mappings and of those "special" locales is to be found at: // http://l10n.openoffice.org/i18n_framework/LocaleData.html switch ( rLang ) { case LANGUAGE_FINNISH: { if (nChar == 'y' || nChar == 'Y') rParams.SetChar (nI, 'V'); else if (nChar == 'm' || nChar == 'M') rParams.SetChar (nI, 'K'); else if (nChar == 'd' || nChar == 'D') rParams.SetChar (nI, 'P'); else if (nChar == 'h' || nChar == 'H') rParams.SetChar (nI, 'T'); } break; case LANGUAGE_DANISH: case LANGUAGE_NORWEGIAN: case LANGUAGE_NORWEGIAN_BOKMAL: case LANGUAGE_NORWEGIAN_NYNORSK: case LANGUAGE_SWEDISH: case LANGUAGE_SWEDISH_FINLAND: { if (nChar == 'h' || nChar == 'H') rParams.SetChar (nI, 'T'); } break; case LANGUAGE_PORTUGUESE: case LANGUAGE_PORTUGUESE_BRAZILIAN: case LANGUAGE_SPANISH_MODERN: case LANGUAGE_SPANISH_DATED: case LANGUAGE_SPANISH_MEXICAN: case LANGUAGE_SPANISH_GUATEMALA: case LANGUAGE_SPANISH_COSTARICA: case LANGUAGE_SPANISH_PANAMA: case LANGUAGE_SPANISH_DOMINICAN_REPUBLIC: case LANGUAGE_SPANISH_VENEZUELA: case LANGUAGE_SPANISH_COLOMBIA: case LANGUAGE_SPANISH_PERU: case LANGUAGE_SPANISH_ARGENTINA: case LANGUAGE_SPANISH_ECUADOR: case LANGUAGE_SPANISH_CHILE: case LANGUAGE_SPANISH_URUGUAY: case LANGUAGE_SPANISH_PARAGUAY: case LANGUAGE_SPANISH_BOLIVIA: case LANGUAGE_SPANISH_EL_SALVADOR: case LANGUAGE_SPANISH_HONDURAS: case LANGUAGE_SPANISH_NICARAGUA: case LANGUAGE_SPANISH_PUERTO_RICO: { if (nChar == 'a' || nChar == 'A') rParams.SetChar (nI, 'O'); else if (nChar == 'y' || nChar == 'Y') rParams.SetChar (nI, 'A'); } break; case LANGUAGE_DUTCH: case LANGUAGE_DUTCH_BELGIAN: { if (nChar == 'y' || nChar == 'Y') rParams.SetChar (nI, 'J'); else if (nChar == 'u' || nChar == 'U') rParams.SetChar (nI, 'H'); } break; case LANGUAGE_ITALIAN: case LANGUAGE_ITALIAN_SWISS: { if (nChar == 'a' || nChar == 'A') rParams.SetChar (nI, 'O'); else if (nChar == 'g' || nChar == 'G') rParams.SetChar (nI, 'X'); else if (nChar == 'y' || nChar == 'Y') rParams.SetChar(nI, 'A'); else if (nChar == 'd' || nChar == 'D') rParams.SetChar (nI, 'G'); } break; case LANGUAGE_GERMAN: case LANGUAGE_GERMAN_SWISS: case LANGUAGE_GERMAN_AUSTRIAN: case LANGUAGE_GERMAN_LUXEMBOURG: case LANGUAGE_GERMAN_LIECHTENSTEIN: { if (nChar == 'y' || nChar == 'Y') rParams.SetChar (nI, 'J'); else if (nChar == 'd' || nChar == 'D') rParams.SetChar (nI, 'T'); } break; case LANGUAGE_FRENCH: case LANGUAGE_FRENCH_BELGIAN: case LANGUAGE_FRENCH_CANADIAN: case LANGUAGE_FRENCH_SWISS: case LANGUAGE_FRENCH_LUXEMBOURG: case LANGUAGE_FRENCH_MONACO: { if (nChar == 'a' || nChar == 'A') rParams.SetChar (nI, 'O'); else if (nChar == 'y' || nChar == 'Y') rParams.SetChar (nI, 'A'); else if (nChar == 'd' || nChar == 'D') rParams.SetChar (nI, 'J'); } break; default: { ; // Nothing } } } ++nI; } if (bForceNatNum) bForceJapanese = true; if (bForceJapanese) rLang = LANGUAGE_JAPANESE; if (bForceNatNum) rParams.Insert(CREATE_CONST_ASC("[NatNum1][$-411]"),0); if (bHijri) rParams.Insert(CREATE_CONST_ASC("[~hijri]"), 0); pFormatter->PutEntry(rParams, nCheckPos, nType, nKey, rLang); return nKey; } bool IsNotAM(String& rParams, xub_StrLen nPos) { return ( (nPos == rParams.Len() - 1) || ( (rParams.GetChar(nPos+1) != 'M') && (rParams.GetChar(nPos+1) != 'm') ) ); } void SwapQuotesInField(String &rFmt) { //Swap unescaped " and ' with ' and " xub_StrLen nLen = rFmt.Len(); for (xub_StrLen nI = 0; nI < nLen; ++nI) { if ((rFmt.GetChar(nI) == '\"') && (!nI || rFmt.GetChar(nI-1) != '\\')) rFmt.SetChar(nI, '\''); else if ((rFmt.GetChar(nI) == '\'') && (!nI || rFmt.GetChar(nI-1) != '\\')) rFmt.SetChar(nI, '\"'); } } } } /* vi:set tabstop=4 shiftwidth=4 expandtab: */
#pragma once #include "cql3/result_set.hh" #include "transport/event.hh" #include "core/shared_ptr.hh" #include "core/sstring.hh" namespace transport { namespace messages { class result_message { public: class visitor; virtual ~result_message() {} virtual void accept(visitor&) = 0; // // Message types: // class void_message; class set_keyspace; class prepared; class schema_change; class rows; }; class result_message::visitor { public: virtual void visit(const result_message::void_message&) = 0; virtual void visit(const result_message::set_keyspace&) = 0; virtual void visit(const result_message::prepared&) = 0; virtual void visit(const result_message::schema_change&) = 0; virtual void visit(const result_message::rows&) = 0; }; class result_message::void_message : public result_message { public: virtual void accept(result_message::visitor& v) override { v.visit(*this); } }; class result_message::set_keyspace : public result_message { private: sstring _keyspace; public: set_keyspace(const sstring& keyspace) : _keyspace{keyspace} { } const sstring& get_keyspace() const { return _keyspace; } virtual void accept(result_message::visitor& v) override { v.visit(*this); } }; class result_message::prepared : public result_message { private: bytes _id; ::shared_ptr<cql3::statements::parsed_statement::prepared> _prepared; public: prepared(const bytes& id, ::shared_ptr<cql3::statements::parsed_statement::prepared> prepared) : _id{id} , _prepared{prepared} { } const bytes& get_id() const { return _id; } const ::shared_ptr<cql3::statements::parsed_statement::prepared>& get_prepared() const { return _prepared; } virtual void accept(result_message::visitor& v) override { v.visit(*this); } }; class result_message::schema_change : public result_message { private: shared_ptr<event::schema_change> _change; public: schema_change(shared_ptr<event::schema_change> change) : _change{change} { } shared_ptr<event::schema_change> get_change() const { return _change; } virtual void accept(result_message::visitor& v) override { v.visit(*this); } }; class result_message::rows : public result_message { private: std::unique_ptr<cql3::result_set> _rs; public: rows(std::unique_ptr<cql3::result_set> rs) : _rs(std::move(rs)) {} const cql3::result_set& rs() const { return *_rs; } virtual void accept(result_message::visitor& v) override { v.visit(*this); } }; } } transport: Add missing include #pragma once #include "cql3/result_set.hh" #include "cql3/statements/parsed_statement.hh" #include "transport/event.hh" #include "core/shared_ptr.hh" #include "core/sstring.hh" namespace transport { namespace messages { class result_message { public: class visitor; virtual ~result_message() {} virtual void accept(visitor&) = 0; // // Message types: // class void_message; class set_keyspace; class prepared; class schema_change; class rows; }; class result_message::visitor { public: virtual void visit(const result_message::void_message&) = 0; virtual void visit(const result_message::set_keyspace&) = 0; virtual void visit(const result_message::prepared&) = 0; virtual void visit(const result_message::schema_change&) = 0; virtual void visit(const result_message::rows&) = 0; }; class result_message::void_message : public result_message { public: virtual void accept(result_message::visitor& v) override { v.visit(*this); } }; class result_message::set_keyspace : public result_message { private: sstring _keyspace; public: set_keyspace(const sstring& keyspace) : _keyspace{keyspace} { } const sstring& get_keyspace() const { return _keyspace; } virtual void accept(result_message::visitor& v) override { v.visit(*this); } }; class result_message::prepared : public result_message { private: bytes _id; ::shared_ptr<cql3::statements::parsed_statement::prepared> _prepared; public: prepared(const bytes& id, ::shared_ptr<cql3::statements::parsed_statement::prepared> prepared) : _id{id} , _prepared{prepared} { } const bytes& get_id() const { return _id; } const ::shared_ptr<cql3::statements::parsed_statement::prepared>& get_prepared() const { return _prepared; } virtual void accept(result_message::visitor& v) override { v.visit(*this); } }; class result_message::schema_change : public result_message { private: shared_ptr<event::schema_change> _change; public: schema_change(shared_ptr<event::schema_change> change) : _change{change} { } shared_ptr<event::schema_change> get_change() const { return _change; } virtual void accept(result_message::visitor& v) override { v.visit(*this); } }; class result_message::rows : public result_message { private: std::unique_ptr<cql3::result_set> _rs; public: rows(std::unique_ptr<cql3::result_set> rs) : _rs(std::move(rs)) {} const cql3::result_set& rs() const { return *_rs; } virtual void accept(result_message::visitor& v) override { v.visit(*this); } }; } }
#include "CharacterPropertiesMapping.h" namespace DocFileFormat { CharacterPropertiesMapping::CharacterPropertiesMapping( XmlUtils::CXmlWriter* writer, WordDocument* doc, RevisionData* rev, ParagraphPropertyExceptions* currentPapx, bool styleChpx, bool isRunStyleNeeded) : PropertiesMapping( writer ), _isRunStyleNeeded(isRunStyleNeeded), _isOwnRPr(true), _isRTL(false) { this->_doc = doc; this->_rPr = new XMLTools::XMLElement<wchar_t>( _T( "w:rPr" ) ); this->_revisionData = rev; this->_currentPapx = currentPapx; this->_styleChpx = styleChpx; this->_currentIstd = USHRT_MAX; } CharacterPropertiesMapping::CharacterPropertiesMapping( XMLTools::XMLElement<wchar_t>* rPr, WordDocument* doc, RevisionData* rev, ParagraphPropertyExceptions* currentPapx, bool styleChpx, bool isRunStyleNeeded ) : PropertiesMapping( NULL ), _isRunStyleNeeded(isRunStyleNeeded), _isOwnRPr(false), _isRTL(false) { this->_doc = doc; this->_rPr = rPr; this->_revisionData = rev; this->_currentPapx = currentPapx; this->_styleChpx = styleChpx; this->_currentIstd = USHRT_MAX; } CharacterPropertiesMapping::~CharacterPropertiesMapping() { if (_isOwnRPr) { RELEASEOBJECT(_rPr); } } } namespace DocFileFormat { void CharacterPropertiesMapping::Apply( IVisitable* chpx ) { //convert the normal SPRMS convertSprms( dynamic_cast<CharacterPropertyExceptions*>( chpx )->grpprl, this->_rPr ); // apend revision changes if (_revisionData->Type == Changed) { XMLTools::XMLElement<wchar_t> rPrChange( _T( "w:rPrChange" ) ); //!!!TODO!!! //date //_revisionData->Dttm.Convert( new DateMapping( rPrChange ) ); //author XMLTools::XMLAttribute<wchar_t> author( _T( "w:author" ), static_cast<WideString*>( this->_doc->RevisionAuthorTable->operator []( _revisionData->Isbt ) )->c_str() ); rPrChange.AppendAttribute( author ); //convert revision stack convertSprms( this->_revisionData->Changes, &rPrChange ); this->_rPr->AppendChild( rPrChange ); } //write properties if ( ( m_pXmlWriter != NULL ) && ( ( _rPr->GetChildCount() > 0 ) || ( _rPr->GetAttributeCount() > 0 ) ) ) { m_pXmlWriter->WriteString( _rPr->GetXMLString().c_str() ); } } /*========================================================================================================*/ bool CharacterPropertiesMapping::CheckIsSymbolFont() { //Todo fontManager // Google Docs, bullet Arial if (-1 != this->m_sAsciiFont.find (_T("Arial")) && -1 != this->m_sEastAsiaFont.find (_T("Arial")) && -1 != this->m_shAnsiFont.find (_T("Arial"))) return false; return true; } /*========================================================================================================*/ void CharacterPropertiesMapping::convertSprms( list<SinglePropertyModifier>* sprms, XMLTools::XMLElement<wchar_t>* parent ) { XMLTools::XMLElement<wchar_t> * rFonts = new XMLTools::XMLElement<wchar_t> ( _T( "w:rFonts" ) ); XMLTools::XMLElement<wchar_t> * color = new XMLTools::XMLElement<wchar_t> ( _T( "w:color" ) ); XMLTools::XMLAttribute<wchar_t> * colorVal = new XMLTools::XMLAttribute<wchar_t>( _T( "w:val" ) ); XMLTools::XMLElement<wchar_t> * lang = new XMLTools::XMLElement<wchar_t> ( _T( "w:lang" ) ); // - http://bugzserver/show_bug.cgi?id=13353 TODO : bool haveStyle = FALSE; std::list<SinglePropertyModifier>::iterator end = sprms->end(); for (std::list<SinglePropertyModifier>::iterator iter = sprms->begin(); iter != end; ++iter) { switch ( (int)( iter->OpCode ) ) { case 0x4A30 : // style id { if (_isRunStyleNeeded) { _currentIstd = FormatUtils::BytesToUInt16( iter->Arguments, 0, iter->argumentsSize ); appendValueElement( parent, _T( "rStyle" ), StyleSheetMapping::MakeStyleId( this->_doc->Styles->Styles->at( _currentIstd ) ).c_str(), true ); haveStyle = TRUE; } } break; case 0x085A : // Element flags appendFlagElement( parent, *iter, _T( "rtl" ), true ); this->_isRTL = true; break; case 0x0835 : appendFlagElement( parent, *iter, _T( "b" ), true ); break; case 0x085C : appendFlagElement( parent, *iter, _T( "bCs" ), true ); break; case 0x083B : appendFlagElement( parent, *iter, _T( "caps" ), true ); break; case 0x0882 : appendFlagElement( parent, *iter, _T( "cs" ), true ); break; case 0x2A53 : appendFlagElement( parent, *iter, _T( "dstrike" ), true ); break; case 0x0858 : appendFlagElement( parent, *iter, _T( "emboss" ), true ); break; case 0x0854 : appendFlagElement( parent, *iter, _T( "imprint" ), true ); break; case 0x0836 : appendFlagElement( parent, *iter, _T( "i" ), true ); break; case 0x085D: appendFlagElement( parent, *iter, _T( "iCs" ), true ); break; case 0x0875: appendFlagElement( parent, *iter, _T( "noProof" ), true ); break; case 0x0838: appendFlagElement( parent, *iter, _T( "outline" ), true ); break; case 0x0839: appendFlagElement( parent, *iter, _T( "shadow" ), true ); break; case 0x083A: appendFlagElement( parent, *iter, _T( "smallCaps" ), true ); break; case 0x0818: appendFlagElement( parent, *iter, _T( "specVanish" ), true ); break; case 0x0837: appendFlagElement( parent, *iter, _T( "strike" ), true ); break; case 0x083C: appendFlagElement( parent, *iter, _T( "vanish" ), true ); break; case 0x0811: appendFlagElement( parent, *iter, _T( "webHidden" ), true ); break; case 0x2A48: appendValueElement( parent, _T( "vertAlign" ), FormatUtils::MapValueToWideString( iter->Arguments[0], &SuperscriptIndex[0][0], 3, 12 ).c_str(), true ); break; //language case 0x486D: case 0x4873: { //latin LanguageId langid( FormatUtils::BytesToInt16( iter->Arguments, 0, iter->argumentsSize ) ); LanguageIdMapping* langIDMapping = new LanguageIdMapping( lang, Default ); langid.Convert( langIDMapping ); RELEASEOBJECT( langIDMapping ); } break; case 0x486E: case 0x4874: { //east asia LanguageId langid( FormatUtils::BytesToInt16( iter->Arguments, 0, iter->argumentsSize ) ); LanguageIdMapping* langIDMapping = new LanguageIdMapping( lang, EastAsian ); langid.Convert( langIDMapping ); RELEASEOBJECT( langIDMapping ); } break; case 0x485F: { //bidi LanguageId langid( FormatUtils::BytesToInt16( iter->Arguments, 0, iter->argumentsSize ) ); LanguageIdMapping* langIDMapping = new LanguageIdMapping( lang, Complex ); langid.Convert( langIDMapping ); RELEASEOBJECT( langIDMapping ); } break; //borders case 0x6865: case 0xCA72: { XMLTools::XMLElement<wchar_t> bdr( _T( "w:bdr" ) ); BorderCode bc( iter->Arguments, iter->argumentsSize ); appendBorderAttributes( &bc, &bdr ); parent->AppendChild( bdr ); } break; //shading case 0x4866: case 0xCA71: { ShadingDescriptor desc( iter->Arguments, iter->argumentsSize ); appendShading( parent, desc ); } break; //color case 0x2A42: case 0x4A60: colorVal->SetValue( FormatUtils::MapValueToWideString( iter->Arguments[0], &Global::ColorIdentifier[0][0], 17, 12 ).c_str() ); break; case 0x6870: { CString rgbColor; rgbColor.Format( _T( "%02x%02x%02x" ), /*R*/iter->Arguments[0], /*G*/iter->Arguments[1], /*B*/iter->Arguments[2] ); colorVal->SetValue( rgbColor.GetString() ); } break; //highlightning case 0x2A0C: appendValueElement( parent, _T( "highlight" ), FormatUtils::MapValueToWideString( iter->Arguments[0], &Global::ColorIdentifier[0][0], 17, 12 ).c_str(), true ); break; //spacing case 0x8840: { appendValueElement( parent, _T( "spacing" ), FormatUtils::IntToWideString( FormatUtils::BytesToInt16( iter->Arguments, 0, iter->argumentsSize ) ).c_str(), true ); } break; case sprmCFtcBi : { //SHORT fontIndex = FormatUtils::BytesToUInt16 (iter->Arguments, 0, iter->argumentsSize); //ATLTRACE ( _T("fontIndex : %d\n"), fontIndex); } break; case sprmCHpsBi : { //SHORT fontSize = FormatUtils::BytesToUInt16 (iter->Arguments, 0, iter->argumentsSize); //ATLTRACE ( _T("CHpsBi : %d\n"), fontSize); if (FALSE == haveStyle) { appendValueElement( parent, _T( "szCs" ), FormatUtils::IntToWideString( FormatUtils::BytesToInt16( iter->Arguments, 0, iter->argumentsSize ) ).c_str(), true ); } } break; case sprmCHps : // Font Size in points (2~3276) default 20-half-points { //SHORT fontSize = FormatUtils::BytesToUInt16 (iter->Arguments, 0, iter->argumentsSize); //ATLTRACE ( _T("CHps : %d\n"), fontSize); if (FALSE == haveStyle) { appendValueElement (parent, _T( "sz" ), FormatUtils::IntToWideString (FormatUtils::BytesToUInt16 (iter->Arguments, 0, iter->argumentsSize) ).c_str(), true ); } } break; case sprmCHpsPos: // The vertical position, in half-points, of text relative to the normal position. (MUST be between -3168 and 3168) { short nVertPos = FormatUtils::BytesToInt16(iter->Arguments, 0, iter->argumentsSize); appendValueElement (parent, _T("position"), nVertPos, true); } break; case sprmCHpsKern: { appendValueElement( parent, _T( "kern" ), FormatUtils::IntToWideString( FormatUtils::BytesToInt16( iter->Arguments, 0, iter->argumentsSize ) ).c_str(), true ); } break; case sprmCRgFtc0: // font family { int nIndex = FormatUtils::BytesToUInt16( iter->Arguments, 0, iter->argumentsSize ); if( nIndex < _doc->FontTable->cData ) { XMLTools::XMLAttribute<wchar_t>* ascii = new XMLTools::XMLAttribute<wchar_t>( _T( "w:ascii" ) ); FontFamilyName* ffn = static_cast<FontFamilyName*>( _doc->FontTable->operator [] ( nIndex ) ); this->m_sAsciiFont = ffn->xszFtn; ascii->SetValue( FormatUtils::XmlEncode(m_sAsciiFont).c_str() ); rFonts->AppendAttribute( *ascii ); RELEASEOBJECT( ascii ); } } break; case 0x4A50: { int nIndex = FormatUtils::BytesToUInt16( iter->Arguments, 0, iter->argumentsSize ); if( nIndex>=0 && nIndex < _doc->FontTable->cData ) { XMLTools::XMLAttribute<wchar_t>* eastAsia = new XMLTools::XMLAttribute<wchar_t>( _T( "w:eastAsia" ) ); FontFamilyName* ffn = static_cast<FontFamilyName*>( _doc->FontTable->operator [] ( nIndex ) ); this->m_sEastAsiaFont = ffn->xszFtn; eastAsia->SetValue( FormatUtils::XmlEncode(this->m_sEastAsiaFont).c_str() ); rFonts->AppendAttribute( *eastAsia ); RELEASEOBJECT( eastAsia ); } } break; case 0x4A51: { int nIndex = FormatUtils::BytesToUInt16( iter->Arguments, 0, iter->argumentsSize ); if( nIndex>=0 && nIndex < _doc->FontTable->cData ) { XMLTools::XMLAttribute<wchar_t>* ansi = new XMLTools::XMLAttribute<wchar_t>( _T( "w:hAnsi" ) ); FontFamilyName* ffn = static_cast<FontFamilyName*>( _doc->FontTable->operator [] ( nIndex ) ); this->m_shAnsiFont = ffn->xszFtn; ansi->SetValue( FormatUtils::XmlEncode(this->m_shAnsiFont).c_str() ); rFonts->AppendAttribute( *ansi ); RELEASEOBJECT( ansi ); } } break; //Underlining case 0x2A3E: { appendValueElement( parent, _T( "u" ), FormatUtils::MapValueToWideString( iter->Arguments[0], &Global::UnderlineCode[0][0], 56, 16 ).c_str(), true ); } break; //char width case 0x4852: { appendValueElement( parent, _T( "w" ), FormatUtils::IntToWideString( FormatUtils::BytesToInt16( iter->Arguments, 0, iter->argumentsSize ) ).c_str(), true ); } break; //animation case 0x2859: { appendValueElement( parent, _T( "effect" ), FormatUtils::MapValueToWideString( iter->Arguments[0], &Global::TextAnimation[0][0], 7, 16 ).c_str(), true ); } break; default: #ifdef _DEBUG // //ATLTRACE (_T("CharacterPropertiesMapping - UNKNOWN SPRM : 0x%x\n"), iter->OpCode); #endif break; } } //apend lang if ( lang->GetAttributeCount() > 0 ) { parent->AppendChild( *lang ); } //append fonts if ( rFonts->GetAttributeCount() > 0 ) { parent->AppendChild( *rFonts ); } //append color if ( colorVal->GetValue() != _T( "" ) ) { color->AppendAttribute( *colorVal ); parent->AppendChild( *color ); } RELEASEOBJECT( lang ); RELEASEOBJECT( colorVal ); RELEASEOBJECT( color ); RELEASEOBJECT( rFonts ); } /*========================================================================================================*/ /// CHPX flags are special flags because the can be 0,1,128 and 129, /// so this method overrides the appendFlagElement method. void CharacterPropertiesMapping::appendFlagElement( XMLTools::XMLElement<wchar_t>* node, const SinglePropertyModifier& sprm, const wchar_t* elementName, bool unique ) { unsigned char flag = sprm.Arguments[0]; if( flag != 128 ) { XMLTools::XMLElement<wchar_t>* ele = new XMLTools::XMLElement<wchar_t>( _T( "w" ), elementName ); XMLTools::XMLAttribute<wchar_t>* val = new XMLTools::XMLAttribute<wchar_t>( _T( "w:val" ) ); if ( unique ) { node->RemoveChild( *ele ); } if ( flag == 0 ) { val->SetValue( _T( "false" ) ); ele->AppendAttribute( *val ); node->AppendChild( *ele ); } else if (flag == 1) { //dont append attribute val //no attribute means true node->AppendChild( *ele ); } else if( flag == 129 ) { //Invert the value of the style //determine the style id of the current style unsigned short styleId = 0; if ( _currentIstd != USHRT_MAX ) { styleId = _currentIstd; } else if( _currentPapx != NULL ) { styleId = _currentPapx->istd; } //this chpx is the chpx of a style, //don't use the id of the chpx or the papx, use the baseOn style if ( _styleChpx ) { StyleSheetDescription* thisStyle = this->_doc->Styles->Styles->at( styleId ); styleId = (unsigned short)thisStyle->istdBase; } //build the style hierarchy this->_hierarchy = buildHierarchy( this->_doc->Styles, styleId ); //apply the toggle values to get the real value of the style bool stylesVal = applyToggleHierachy( sprm ); //invert it if ( stylesVal ) { val->SetValue( _T( "false" ) ); ele->AppendAttribute( *val ); } node->AppendChild( *ele ); } RELEASEOBJECT(ele); RELEASEOBJECT(val); } } /*========================================================================================================*/ list<CharacterPropertyExceptions*> CharacterPropertiesMapping::buildHierarchy( const StyleSheet* styleSheet, unsigned short istdStart ) { list<CharacterPropertyExceptions*> hierarchy; unsigned int istd = (unsigned int)istdStart; bool goOn = true; if ( ( styleSheet != NULL ) && ( styleSheet->Styles != NULL ) ) { while ( goOn ) { try { if ( istd < styleSheet->Styles->size() ) { CharacterPropertyExceptions* baseChpx = styleSheet->Styles->at( istd )->chpx; if ( baseChpx != NULL ) { hierarchy.push_back( baseChpx ); istd = (unsigned int)styleSheet->Styles->at( istd )->istdBase; } else { goOn = false; } } else { goOn = false; } } catch (...) { goOn = false; } } } return hierarchy; } /*========================================================================================================*/ bool CharacterPropertiesMapping::applyToggleHierachy( const SinglePropertyModifier& sprm ) { bool ret = false; std::list<CharacterPropertyExceptions*>::const_iterator end = _hierarchy.end(); for (std::list<CharacterPropertyExceptions*>::const_iterator iter = this->_hierarchy.begin(); iter != end; ++iter) { std::list<SinglePropertyModifier>::const_iterator end_grpprl = (*iter)->grpprl->end(); for (std::list<SinglePropertyModifier>::const_iterator grpprlIter = (*iter)->grpprl->begin(); grpprlIter != end_grpprl; ++grpprlIter) { if (grpprlIter->OpCode == sprm.OpCode) { unsigned char ancient = grpprlIter->Arguments[0]; ret = toogleValue(ret, ancient); break; } } } return ret; } /*========================================================================================================*/ bool CharacterPropertiesMapping::toogleValue(bool currentValue, unsigned char toggle) { if ( toggle == 1 ) { return true; } else if ( toggle == 129 ) { //invert the current value if ( currentValue ) { return false; } else { return true; } } else if ( toggle == 128 ) { //use the current value return currentValue; } else { return false; } } } DocFormat - fix файла с отсутствующим стилем git-svn-id: bd6e61130530ab01186c33a20f55445ba6f1e843@68191 954022d7-b5bf-4e40-9824-e11837661b57 #include "CharacterPropertiesMapping.h" namespace DocFileFormat { CharacterPropertiesMapping::CharacterPropertiesMapping( XmlUtils::CXmlWriter* writer, WordDocument* doc, RevisionData* rev, ParagraphPropertyExceptions* currentPapx, bool styleChpx, bool isRunStyleNeeded) : PropertiesMapping( writer ), _isRunStyleNeeded(isRunStyleNeeded), _isOwnRPr(true), _isRTL(false) { this->_doc = doc; this->_rPr = new XMLTools::XMLElement<wchar_t>( _T( "w:rPr" ) ); this->_revisionData = rev; this->_currentPapx = currentPapx; this->_styleChpx = styleChpx; this->_currentIstd = USHRT_MAX; } CharacterPropertiesMapping::CharacterPropertiesMapping( XMLTools::XMLElement<wchar_t>* rPr, WordDocument* doc, RevisionData* rev, ParagraphPropertyExceptions* currentPapx, bool styleChpx, bool isRunStyleNeeded ) : PropertiesMapping( NULL ), _isRunStyleNeeded(isRunStyleNeeded), _isOwnRPr(false), _isRTL(false) { this->_doc = doc; this->_rPr = rPr; this->_revisionData = rev; this->_currentPapx = currentPapx; this->_styleChpx = styleChpx; this->_currentIstd = USHRT_MAX; } CharacterPropertiesMapping::~CharacterPropertiesMapping() { if (_isOwnRPr) { RELEASEOBJECT(_rPr); } } } namespace DocFileFormat { void CharacterPropertiesMapping::Apply( IVisitable* chpx ) { //convert the normal SPRMS convertSprms( dynamic_cast<CharacterPropertyExceptions*>( chpx )->grpprl, this->_rPr ); // apend revision changes if (_revisionData->Type == Changed) { XMLTools::XMLElement<wchar_t> rPrChange( _T( "w:rPrChange" ) ); //!!!TODO!!! //date //_revisionData->Dttm.Convert( new DateMapping( rPrChange ) ); //author XMLTools::XMLAttribute<wchar_t> author( _T( "w:author" ), static_cast<WideString*>( this->_doc->RevisionAuthorTable->operator []( _revisionData->Isbt ) )->c_str() ); rPrChange.AppendAttribute( author ); //convert revision stack convertSprms( this->_revisionData->Changes, &rPrChange ); this->_rPr->AppendChild( rPrChange ); } //write properties if ( ( m_pXmlWriter != NULL ) && ( ( _rPr->GetChildCount() > 0 ) || ( _rPr->GetAttributeCount() > 0 ) ) ) { m_pXmlWriter->WriteString( _rPr->GetXMLString().c_str() ); } } /*========================================================================================================*/ bool CharacterPropertiesMapping::CheckIsSymbolFont() { //Todo fontManager // Google Docs, bullet Arial if (-1 != this->m_sAsciiFont.find (_T("Arial")) && -1 != this->m_sEastAsiaFont.find (_T("Arial")) && -1 != this->m_shAnsiFont.find (_T("Arial"))) return false; return true; } /*========================================================================================================*/ void CharacterPropertiesMapping::convertSprms( list<SinglePropertyModifier>* sprms, XMLTools::XMLElement<wchar_t>* parent ) { XMLTools::XMLElement<wchar_t> * rFonts = new XMLTools::XMLElement<wchar_t> ( _T( "w:rFonts" ) ); XMLTools::XMLElement<wchar_t> * color = new XMLTools::XMLElement<wchar_t> ( _T( "w:color" ) ); XMLTools::XMLAttribute<wchar_t> * colorVal = new XMLTools::XMLAttribute<wchar_t>( _T( "w:val" ) ); XMLTools::XMLElement<wchar_t> * lang = new XMLTools::XMLElement<wchar_t> ( _T( "w:lang" ) ); // - http://bugzserver/show_bug.cgi?id=13353 TODO : bool haveStyle = FALSE; std::list<SinglePropertyModifier>::iterator end = sprms->end(); for (std::list<SinglePropertyModifier>::iterator iter = sprms->begin(); iter != end; ++iter) { switch ( (int)( iter->OpCode ) ) { case 0x4A30 : // style id { if (_isRunStyleNeeded) { _currentIstd = FormatUtils::BytesToUInt16( iter->Arguments, 0, iter->argumentsSize ); if (_currentIstd < this->_doc->Styles->Styles->size()) { appendValueElement( parent, _T( "rStyle" ), StyleSheetMapping::MakeStyleId( this->_doc->Styles->Styles->at( _currentIstd ) ).c_str(), true ); haveStyle = TRUE; } } } break; case 0x085A : // Element flags appendFlagElement( parent, *iter, _T( "rtl" ), true ); this->_isRTL = true; break; case 0x0835 : appendFlagElement( parent, *iter, _T( "b" ), true ); break; case 0x085C : appendFlagElement( parent, *iter, _T( "bCs" ), true ); break; case 0x083B : appendFlagElement( parent, *iter, _T( "caps" ), true ); break; case 0x0882 : appendFlagElement( parent, *iter, _T( "cs" ), true ); break; case 0x2A53 : appendFlagElement( parent, *iter, _T( "dstrike" ), true ); break; case 0x0858 : appendFlagElement( parent, *iter, _T( "emboss" ), true ); break; case 0x0854 : appendFlagElement( parent, *iter, _T( "imprint" ), true ); break; case 0x0836 : appendFlagElement( parent, *iter, _T( "i" ), true ); break; case 0x085D: appendFlagElement( parent, *iter, _T( "iCs" ), true ); break; case 0x0875: appendFlagElement( parent, *iter, _T( "noProof" ), true ); break; case 0x0838: appendFlagElement( parent, *iter, _T( "outline" ), true ); break; case 0x0839: appendFlagElement( parent, *iter, _T( "shadow" ), true ); break; case 0x083A: appendFlagElement( parent, *iter, _T( "smallCaps" ), true ); break; case 0x0818: appendFlagElement( parent, *iter, _T( "specVanish" ), true ); break; case 0x0837: appendFlagElement( parent, *iter, _T( "strike" ), true ); break; case 0x083C: appendFlagElement( parent, *iter, _T( "vanish" ), true ); break; case 0x0811: appendFlagElement( parent, *iter, _T( "webHidden" ), true ); break; case 0x2A48: appendValueElement( parent, _T( "vertAlign" ), FormatUtils::MapValueToWideString( iter->Arguments[0], &SuperscriptIndex[0][0], 3, 12 ).c_str(), true ); break; //language case 0x486D: case 0x4873: { //latin LanguageId langid( FormatUtils::BytesToInt16( iter->Arguments, 0, iter->argumentsSize ) ); LanguageIdMapping* langIDMapping = new LanguageIdMapping( lang, Default ); langid.Convert( langIDMapping ); RELEASEOBJECT( langIDMapping ); } break; case 0x486E: case 0x4874: { //east asia LanguageId langid( FormatUtils::BytesToInt16( iter->Arguments, 0, iter->argumentsSize ) ); LanguageIdMapping* langIDMapping = new LanguageIdMapping( lang, EastAsian ); langid.Convert( langIDMapping ); RELEASEOBJECT( langIDMapping ); } break; case 0x485F: { //bidi LanguageId langid( FormatUtils::BytesToInt16( iter->Arguments, 0, iter->argumentsSize ) ); LanguageIdMapping* langIDMapping = new LanguageIdMapping( lang, Complex ); langid.Convert( langIDMapping ); RELEASEOBJECT( langIDMapping ); } break; //borders case 0x6865: case 0xCA72: { XMLTools::XMLElement<wchar_t> bdr( _T( "w:bdr" ) ); BorderCode bc( iter->Arguments, iter->argumentsSize ); appendBorderAttributes( &bc, &bdr ); parent->AppendChild( bdr ); } break; //shading case 0x4866: case 0xCA71: { ShadingDescriptor desc( iter->Arguments, iter->argumentsSize ); appendShading( parent, desc ); } break; //color case 0x2A42: case 0x4A60: colorVal->SetValue( FormatUtils::MapValueToWideString( iter->Arguments[0], &Global::ColorIdentifier[0][0], 17, 12 ).c_str() ); break; case 0x6870: { CString rgbColor; rgbColor.Format( _T( "%02x%02x%02x" ), /*R*/iter->Arguments[0], /*G*/iter->Arguments[1], /*B*/iter->Arguments[2] ); colorVal->SetValue( rgbColor.GetString() ); } break; //highlightning case 0x2A0C: appendValueElement( parent, _T( "highlight" ), FormatUtils::MapValueToWideString( iter->Arguments[0], &Global::ColorIdentifier[0][0], 17, 12 ).c_str(), true ); break; //spacing case 0x8840: { appendValueElement( parent, _T( "spacing" ), FormatUtils::IntToWideString( FormatUtils::BytesToInt16( iter->Arguments, 0, iter->argumentsSize ) ).c_str(), true ); } break; case sprmCFtcBi : { //SHORT fontIndex = FormatUtils::BytesToUInt16 (iter->Arguments, 0, iter->argumentsSize); //ATLTRACE ( _T("fontIndex : %d\n"), fontIndex); } break; case sprmCHpsBi : { //SHORT fontSize = FormatUtils::BytesToUInt16 (iter->Arguments, 0, iter->argumentsSize); //ATLTRACE ( _T("CHpsBi : %d\n"), fontSize); if (FALSE == haveStyle) { appendValueElement( parent, _T( "szCs" ), FormatUtils::IntToWideString( FormatUtils::BytesToInt16( iter->Arguments, 0, iter->argumentsSize ) ).c_str(), true ); } } break; case sprmCHps : // Font Size in points (2~3276) default 20-half-points { //SHORT fontSize = FormatUtils::BytesToUInt16 (iter->Arguments, 0, iter->argumentsSize); //ATLTRACE ( _T("CHps : %d\n"), fontSize); if (FALSE == haveStyle) { appendValueElement (parent, _T( "sz" ), FormatUtils::IntToWideString (FormatUtils::BytesToUInt16 (iter->Arguments, 0, iter->argumentsSize) ).c_str(), true ); } } break; case sprmCHpsPos: // The vertical position, in half-points, of text relative to the normal position. (MUST be between -3168 and 3168) { short nVertPos = FormatUtils::BytesToInt16(iter->Arguments, 0, iter->argumentsSize); appendValueElement (parent, _T("position"), nVertPos, true); } break; case sprmCHpsKern: { appendValueElement( parent, _T( "kern" ), FormatUtils::IntToWideString( FormatUtils::BytesToInt16( iter->Arguments, 0, iter->argumentsSize ) ).c_str(), true ); } break; case sprmCRgFtc0: // font family { int nIndex = FormatUtils::BytesToUInt16( iter->Arguments, 0, iter->argumentsSize ); if( nIndex < _doc->FontTable->cData ) { XMLTools::XMLAttribute<wchar_t>* ascii = new XMLTools::XMLAttribute<wchar_t>( _T( "w:ascii" ) ); FontFamilyName* ffn = static_cast<FontFamilyName*>( _doc->FontTable->operator [] ( nIndex ) ); this->m_sAsciiFont = ffn->xszFtn; ascii->SetValue( FormatUtils::XmlEncode(m_sAsciiFont).c_str() ); rFonts->AppendAttribute( *ascii ); RELEASEOBJECT( ascii ); } } break; case 0x4A50: { int nIndex = FormatUtils::BytesToUInt16( iter->Arguments, 0, iter->argumentsSize ); if( nIndex>=0 && nIndex < _doc->FontTable->cData ) { XMLTools::XMLAttribute<wchar_t>* eastAsia = new XMLTools::XMLAttribute<wchar_t>( _T( "w:eastAsia" ) ); FontFamilyName* ffn = static_cast<FontFamilyName*>( _doc->FontTable->operator [] ( nIndex ) ); this->m_sEastAsiaFont = ffn->xszFtn; eastAsia->SetValue( FormatUtils::XmlEncode(this->m_sEastAsiaFont).c_str() ); rFonts->AppendAttribute( *eastAsia ); RELEASEOBJECT( eastAsia ); } } break; case 0x4A51: { int nIndex = FormatUtils::BytesToUInt16( iter->Arguments, 0, iter->argumentsSize ); if( nIndex>=0 && nIndex < _doc->FontTable->cData ) { XMLTools::XMLAttribute<wchar_t>* ansi = new XMLTools::XMLAttribute<wchar_t>( _T( "w:hAnsi" ) ); FontFamilyName* ffn = static_cast<FontFamilyName*>( _doc->FontTable->operator [] ( nIndex ) ); this->m_shAnsiFont = ffn->xszFtn; ansi->SetValue( FormatUtils::XmlEncode(this->m_shAnsiFont).c_str() ); rFonts->AppendAttribute( *ansi ); RELEASEOBJECT( ansi ); } } break; //Underlining case 0x2A3E: { appendValueElement( parent, _T( "u" ), FormatUtils::MapValueToWideString( iter->Arguments[0], &Global::UnderlineCode[0][0], 56, 16 ).c_str(), true ); } break; //char width case 0x4852: { appendValueElement( parent, _T( "w" ), FormatUtils::IntToWideString( FormatUtils::BytesToInt16( iter->Arguments, 0, iter->argumentsSize ) ).c_str(), true ); } break; //animation case 0x2859: { appendValueElement( parent, _T( "effect" ), FormatUtils::MapValueToWideString( iter->Arguments[0], &Global::TextAnimation[0][0], 7, 16 ).c_str(), true ); } break; default: #ifdef _DEBUG // //ATLTRACE (_T("CharacterPropertiesMapping - UNKNOWN SPRM : 0x%x\n"), iter->OpCode); #endif break; } } //apend lang if ( lang->GetAttributeCount() > 0 ) { parent->AppendChild( *lang ); } //append fonts if ( rFonts->GetAttributeCount() > 0 ) { parent->AppendChild( *rFonts ); } //append color if ( colorVal->GetValue() != _T( "" ) ) { color->AppendAttribute( *colorVal ); parent->AppendChild( *color ); } RELEASEOBJECT( lang ); RELEASEOBJECT( colorVal ); RELEASEOBJECT( color ); RELEASEOBJECT( rFonts ); } /*========================================================================================================*/ /// CHPX flags are special flags because the can be 0,1,128 and 129, /// so this method overrides the appendFlagElement method. void CharacterPropertiesMapping::appendFlagElement( XMLTools::XMLElement<wchar_t>* node, const SinglePropertyModifier& sprm, const wchar_t* elementName, bool unique ) { unsigned char flag = sprm.Arguments[0]; if( flag != 128 ) { XMLTools::XMLElement<wchar_t>* ele = new XMLTools::XMLElement<wchar_t>( _T( "w" ), elementName ); XMLTools::XMLAttribute<wchar_t>* val = new XMLTools::XMLAttribute<wchar_t>( _T( "w:val" ) ); if ( unique ) { node->RemoveChild( *ele ); } if ( flag == 0 ) { val->SetValue( _T( "false" ) ); ele->AppendAttribute( *val ); node->AppendChild( *ele ); } else if (flag == 1) { //dont append attribute val //no attribute means true node->AppendChild( *ele ); } else if( flag == 129 ) { //Invert the value of the style //determine the style id of the current style unsigned short styleId = 0; if ( _currentIstd != USHRT_MAX ) { styleId = _currentIstd; } else if( _currentPapx != NULL ) { styleId = _currentPapx->istd; } //this chpx is the chpx of a style, //don't use the id of the chpx or the papx, use the baseOn style if ( _styleChpx ) { StyleSheetDescription* thisStyle = this->_doc->Styles->Styles->at( styleId ); styleId = (unsigned short)thisStyle->istdBase; } //build the style hierarchy this->_hierarchy = buildHierarchy( this->_doc->Styles, styleId ); //apply the toggle values to get the real value of the style bool stylesVal = applyToggleHierachy( sprm ); //invert it if ( stylesVal ) { val->SetValue( _T( "false" ) ); ele->AppendAttribute( *val ); } node->AppendChild( *ele ); } RELEASEOBJECT(ele); RELEASEOBJECT(val); } } /*========================================================================================================*/ list<CharacterPropertyExceptions*> CharacterPropertiesMapping::buildHierarchy( const StyleSheet* styleSheet, unsigned short istdStart ) { list<CharacterPropertyExceptions*> hierarchy; unsigned int istd = (unsigned int)istdStart; bool goOn = true; if ( ( styleSheet != NULL ) && ( styleSheet->Styles != NULL ) ) { while ( goOn ) { try { if ( istd < styleSheet->Styles->size() ) { CharacterPropertyExceptions* baseChpx = styleSheet->Styles->at( istd )->chpx; if ( baseChpx != NULL ) { hierarchy.push_back( baseChpx ); istd = (unsigned int)styleSheet->Styles->at( istd )->istdBase; } else { goOn = false; } } else { goOn = false; } } catch (...) { goOn = false; } } } return hierarchy; } /*========================================================================================================*/ bool CharacterPropertiesMapping::applyToggleHierachy( const SinglePropertyModifier& sprm ) { bool ret = false; std::list<CharacterPropertyExceptions*>::const_iterator end = _hierarchy.end(); for (std::list<CharacterPropertyExceptions*>::const_iterator iter = this->_hierarchy.begin(); iter != end; ++iter) { std::list<SinglePropertyModifier>::const_iterator end_grpprl = (*iter)->grpprl->end(); for (std::list<SinglePropertyModifier>::const_iterator grpprlIter = (*iter)->grpprl->begin(); grpprlIter != end_grpprl; ++grpprlIter) { if (grpprlIter->OpCode == sprm.OpCode) { unsigned char ancient = grpprlIter->Arguments[0]; ret = toogleValue(ret, ancient); break; } } } return ret; } /*========================================================================================================*/ bool CharacterPropertiesMapping::toogleValue(bool currentValue, unsigned char toggle) { if ( toggle == 1 ) { return true; } else if ( toggle == 129 ) { //invert the current value if ( currentValue ) { return false; } else { return true; } } else if ( toggle == 128 ) { //use the current value return currentValue; } else { return false; } } }
// @(#)root/treeplayer:$Id$ // Author: Rene Brun 19/01/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TROOT.h" #include "TTreeFormula.h" #include "TTree.h" #include "TBranch.h" #include "TBranchObject.h" #include "TFunction.h" #include "TClonesArray.h" #include "TLeafB.h" #include "TLeafC.h" #include "TLeafObject.h" #include "TDataMember.h" #include "TMethodCall.h" #include "TCutG.h" #include "TRandom.h" #include "TInterpreter.h" #include "TDataType.h" #include "TStreamerInfo.h" #include "TStreamerElement.h" #include "TBranchElement.h" #include "TLeafElement.h" #include "TArrayI.h" #include "TAxis.h" #include "TError.h" #include "TVirtualCollectionProxy.h" #include "TString.h" #include "TTimeStamp.h" #include "TMath.h" #include "TVirtualRefProxy.h" #include "TTreeFormulaManager.h" #include "TFormLeafInfo.h" #include "TMethod.h" #include "TBaseClass.h" #include "TFormLeafInfoReference.h" #include "TEntryList.h" #include <ctype.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <typeinfo> #include <algorithm> const Int_t kMaxLen = 1024; R__EXTERN TTree *gTree; ClassImp(TTreeFormula) //______________________________________________________________________________ // // TTreeFormula now relies on a variety of TFormLeafInfo classes to handle the // reading of the information. Here is the list of theses classes: // TFormLeafInfo // TFormLeafInfoDirect // TFormLeafInfoNumerical // TFormLeafInfoClones // TFormLeafInfoCollection // TFormLeafInfoPointer // TFormLeafInfoMethod // TFormLeafInfoMultiVarDim // TFormLeafInfoMultiVarDimDirect // TFormLeafInfoCast // // The following method are available from the TFormLeafInfo interface: // // AddOffset(Int_t offset, TStreamerElement* element) // GetCounterValue(TLeaf* leaf) : return the size of the array pointed to. // GetObjectAddress(TLeafElement* leaf) : Returns the the location of the object pointed to. // GetMultiplicity() : Returns info on the variability of the number of elements // GetNdata(TLeaf* leaf) : Returns the number of elements // GetNdata() : Used by GetNdata(TLeaf* leaf) // GetValue(TLeaf *leaf, Int_t instance = 0) : Return the value // GetValuePointer(TLeaf *leaf, Int_t instance = 0) : Returns the address of the value // GetLocalValuePointer(TLeaf *leaf, Int_t instance = 0) : Returns the address of the value of 'this' LeafInfo // IsString() // ReadValue(char *where, Int_t instance = 0) : Internal function to interpret the location 'where' // Update() : react to the possible loading of a shared library. // // //______________________________________________________________________________ inline static void R__LoadBranch(TBranch* br, Long64_t entry, Bool_t quickLoad) { if (!quickLoad || (br->GetReadEntry() != entry)) { br->GetEntry(entry); } } //______________________________________________________________________________ // // This class is a small helper class to help in keeping track of the array // dimensions encountered in the analysis of the expression. class TDimensionInfo : public TObject { public: Int_t fCode; // Location of the leaf in TTreeFormula::fCode Int_t fOper; // Location of the Operation using the leaf in TTreeFormula::fOper Int_t fSize; TFormLeafInfoMultiVarDim* fMultiDim; TDimensionInfo(Int_t code, Int_t oper, Int_t size, TFormLeafInfoMultiVarDim* multiDim) : fCode(code), fOper(oper), fSize(size), fMultiDim(multiDim) {}; ~TDimensionInfo() {}; }; //______________________________________________________________________________ // // A TreeFormula is used to pass a selection expression // to the Tree drawing routine. See TTree::Draw // // A TreeFormula can contain any arithmetic expression including // standard operators and mathematical functions separated by operators. // Examples of valid expression: // "x<y && sqrt(z)>3.2" // //______________________________________________________________________________ TTreeFormula::TTreeFormula(): TFormula(), fQuickLoad(kFALSE), fNeedLoading(kTRUE), fDidBooleanOptimization(kFALSE), fDimensionSetup(0) { // Tree Formula default constructor fTree = 0; fLookupType = 0; fNindex = 0; fNcodes = 0; fAxis = 0; fHasCast = 0; fManager = 0; fMultiplicity = 0; Int_t j,k; for (j=0; j<kMAXCODES; j++) { fNdimensions[j] = 0; fCodes[j] = 0; fNdata[j] = 1; fHasMultipleVarDim[j] = kFALSE; for (k = 0; k<kMAXFORMDIM; k++) { fIndexes[j][k] = -1; fCumulSizes[j][k] = 1; fVarIndexes[j][k] = 0; } } } //______________________________________________________________________________ TTreeFormula::TTreeFormula(const char *name,const char *expression, TTree *tree) :TFormula(), fTree(tree), fQuickLoad(kFALSE), fNeedLoading(kTRUE), fDidBooleanOptimization(kFALSE), fDimensionSetup(0) { // Normal TTree Formula Constuctor Init(name,expression); } //______________________________________________________________________________ TTreeFormula::TTreeFormula(const char *name,const char *expression, TTree *tree, const std::vector<std::string>& aliases) :TFormula(), fTree(tree), fQuickLoad(kFALSE), fNeedLoading(kTRUE), fDidBooleanOptimization(kFALSE), fDimensionSetup(0), fAliasesUsed(aliases) { // Constructor used during the expansion of an alias Init(name,expression); } //______________________________________________________________________________ void TTreeFormula::Init(const char*name, const char* expression) { // Initialiation called from the constructors. TDirectory *const savedir=gDirectory; fNindex = kMAXFOUND; fLookupType = new Int_t[fNindex]; fNcodes = 0; fMultiplicity = 0; fAxis = 0; fHasCast = 0; Int_t i,j,k; fManager = new TTreeFormulaManager; fManager->Add(this); for (j=0; j<kMAXCODES; j++) { fNdimensions[j] = 0; fLookupType[j] = kDirect; fCodes[j] = 0; fNdata[j] = 1; fHasMultipleVarDim[j] = kFALSE; for (k = 0; k<kMAXFORMDIM; k++) { fIndexes[j][k] = -1; fCumulSizes[j][k] = 1; fVarIndexes[j][k] = 0; } } fDimensionSetup = new TList; if (Compile(expression)) { fTree = 0; fNdim = 0; if(savedir) savedir->cd(); return; } if (fNcodes >= kMAXFOUND) { Warning("TTreeFormula","Too many items in expression:%s",expression); fNcodes = kMAXFOUND; } SetName(name); for (i=0;i<fNoper;i++) { if (GetAction(i)==kDefinedString) { Int_t string_code = GetActionParam(i); TLeaf *leafc = (TLeaf*)fLeaves.UncheckedAt(string_code); if (!leafc) continue; // We have a string used as a string // This dormant portion of code would be used if (when?) we allow the histogramming // of the integral content (as opposed to the string content) of strings // held in a variable size container delimited by a null (as opposed to // a fixed size container or variable size container whose size is controlled // by a variable). In GetNdata, we will then use strlen to grab the current length. //fCumulSizes[i][fNdimensions[i]-1] = 1; //fUsedSizes[fNdimensions[i]-1] = -TMath::Abs(fUsedSizes[fNdimensions[i]-1]); //fUsedSizes[0] = - TMath::Abs( fUsedSizes[0]); if (fNoper == 1) { // If the string is by itself, then it can safely be histogrammed as // in a string based axis. To histogram the number inside the string // just make it part of a useless expression (for example: mystring+0) SetBit(kIsCharacter); } continue; } if (GetAction(i)==kJump && GetActionParam(i)==(fNoper-1)) { // We have cond ? string1 : string2 if (IsString(fNoper-1)) SetBit(kIsCharacter); } } if (fNoper == 1 && GetAction(0)==kStringConst) { SetBit(kIsCharacter); } if (fNoper==1 && GetAction(0)==kAliasString) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); if (subform->IsString()) SetBit(kIsCharacter); } else if (fNoper==2 && GetAction(0)==kAlternateString) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); if (subform->IsString()) SetBit(kIsCharacter); } fManager->Sync(); // Let's verify the indexes and dies if we need to. Int_t k0,k1; for(k0 = 0; k0 < fNcodes; k0++) { for(k1 = 0; k1 < fNdimensions[k0]; k1++ ) { // fprintf(stderr,"Saw %d dim %d and index %d\n",k1, fFixedSizes[k0][k1], fIndexes[k0][k1]); if ( fIndexes[k0][k1]>=0 && fFixedSizes[k0][k1]>=0 && fIndexes[k0][k1]>=fFixedSizes[k0][k1]) { Error("TTreeFormula", "Index %d for dimension #%d in %s is too high (max is %d)", fIndexes[k0][k1],k1+1, expression,fFixedSizes[k0][k1]-1); fTree = 0; fNdim = 0; if(savedir) savedir->cd(); return; } } } // Create a list of uniques branches to load. for(k=0; k<fNcodes; k++) { TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(k); TBranch *branch = 0; if (leaf) { branch = leaf->GetBranch(); if (fBranches.FindObject(branch)) branch = 0; } fBranches.AddAtAndExpand(branch,k); } if (IsInteger(kFALSE)) SetBit(kIsInteger); if (TestBit(TTreeFormula::kNeedEntries)) { // Call TTree::GetEntries() to insure that it is already calculated. // This will need to be done anyway at the first iteration and insure // that it will not mess up the branch reading (because TTree::GetEntries // opens all the file in the chain and 'stays' on the last file. Long64_t readentry = fTree->GetReadEntry(); Int_t treenumber = fTree->GetTreeNumber(); fTree->GetEntries(); if (treenumber != fTree->GetTreeNumber()) { if (readentry >= 0) { fTree->LoadTree(readentry); } UpdateFormulaLeaves(); } else { if (readentry >= 0) { fTree->LoadTree(readentry); } } } if(savedir) savedir->cd(); } //______________________________________________________________________________ TTreeFormula::~TTreeFormula() { //*-*-*-*-*-*-*-*-*-*-*Tree Formula default destructor*-*-*-*-*-*-*-*-*-*-* //*-* ================================= if (fManager) { fManager->Remove(this); if (fManager->fFormulas.GetLast()<0) { delete fManager; fManager = 0; } } // Objects in fExternalCuts are not owned and should not be deleted // fExternalCuts.Clear(); fLeafNames.Delete(); fDataMembers.Delete(); fMethods.Delete(); fAliases.Delete(); if (fLookupType) delete [] fLookupType; for (int j=0; j<fNcodes; j++) { for (int k = 0; k<fNdimensions[j]; k++) { if (fVarIndexes[j][k]) delete fVarIndexes[j][k]; fVarIndexes[j][k] = 0; } } if (fDimensionSetup) { fDimensionSetup->Delete(); delete fDimensionSetup; } } //______________________________________________________________________________ void TTreeFormula::DefineDimensions(Int_t code, Int_t size, TFormLeafInfoMultiVarDim * info, Int_t& virt_dim) { // This method is used internally to decode the dimensions of the variables if (info) { fManager->EnableMultiVarDims(); //if (fIndexes[code][info->fDim]<0) { // removed because the index might be out of bounds! info->fVirtDim = virt_dim; fManager->AddVarDims(virt_dim); // if (!fVarDims[virt_dim]) fVarDims[virt_dim] = new TArrayI; //} } Int_t vsize = 0; if (fIndexes[code][fNdimensions[code]]==-2) { TTreeFormula *indexvar = fVarIndexes[code][fNdimensions[code]]; // ASSERT(indexvar!=0); Int_t index_multiplicity = indexvar->GetMultiplicity(); switch (index_multiplicity) { case -1: case 0: case 2: vsize = indexvar->GetNdata(); break; case 1: vsize = -1; break; }; } else vsize = size; fCumulSizes[code][fNdimensions[code]] = size; if ( fIndexes[code][fNdimensions[code]] < 0 ) { fManager->UpdateUsedSize(virt_dim, vsize); } fNdimensions[code] ++; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(const char *info, Int_t code) { // This method is used internally to decode the dimensions of the variables // We assume that there are NO white spaces in the info string const char * current; Int_t size, scanindex, vardim; current = info; vardim = 0; // the next value could be before the string but // that's okay because the next operation is ++ // (this is to avoid (?) a if statement at the end of the // loop) if (current[0] != '[') current--; while (current) { current++; scanindex = sscanf(current,"%d",&size); // if scanindex is 0 then we have a name index thus a variable // array (or TClonesArray!). if (scanindex==0) size = -1; vardim += RegisterDimensions(code, size); if (fNdimensions[code] >= kMAXFORMDIM) { // NOTE: test that fNdimensions[code] is NOT too big!! break; } current = (char*)strstr( current, "[" ); } return vardim; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(Int_t code, Int_t size, TFormLeafInfoMultiVarDim * multidim) { // This method stores the dimension information for later usage. TDimensionInfo * info = new TDimensionInfo(code,fNoper,size,multidim); fDimensionSetup->Add(info); fCumulSizes[code][fNdimensions[code]] = size; fNdimensions[code] ++; return (size==-1) ? 1 : 0; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(Int_t code, TFormLeafInfo *leafinfo, TFormLeafInfo * /* maininfo */, Bool_t useCollectionObject) { // This method is used internally to decode the dimensions of the variables Int_t ndim, size, current, vardim; vardim = 0; const TStreamerElement * elem = leafinfo->fElement; TClass* c = elem ? elem->GetClassPointer() : 0; TFormLeafInfoMultiVarDim * multi = dynamic_cast<TFormLeafInfoMultiVarDim * >(leafinfo); if (multi) { // We have a second variable dimensions fManager->EnableMultiVarDims(); multi->fDim = fNdimensions[code]; return RegisterDimensions(code, -1, multi); } if (elem->IsA() == TStreamerBasicPointer::Class()) { if (elem->GetArrayDim()>0) { ndim = elem->GetArrayDim(); size = elem->GetMaxIndex(0); vardim += RegisterDimensions(code, -1); } else { ndim = 1; size = -1; } TStreamerBasicPointer *array = (TStreamerBasicPointer*)elem; TClass *cl = leafinfo->fClass; Int_t offset; TStreamerElement* counter = ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(array->GetCountName(),offset); #if 1 leafinfo->fCounter = new TFormLeafInfo(cl,offset,counter); #else /* Code is not ready yet see revision 14078 */ if (maininfo==0 || maininfo==leafinfo || 1) { leafinfo->fCounter = new TFormLeafInfo(cl,offset,counter); } else { leafinfo->fCounter = maininfo->DeepCopy(); TFormLeafInfo *currentinfo = leafinfo->fCounter; while(currentinfo->fNext && currentinfo->fNext->fNext) currentinfo=currentinfo->fNext; delete currentinfo->fNext; currentinfo->fNext = new TFormLeafInfo(cl,offset,counter); } #endif } else if (!useCollectionObject && elem->GetClassPointer() == TClonesArray::Class() ) { ndim = 1; size = -1; TClass * clonesClass = TClonesArray::Class(); Int_t c_offset; TStreamerElement *counter = ((TStreamerInfo*)clonesClass->GetStreamerInfo())->GetStreamerElement("fLast",c_offset); leafinfo->fCounter = new TFormLeafInfo(clonesClass,c_offset,counter); } else if (!useCollectionObject && elem->GetClassPointer() && elem->GetClassPointer()->GetCollectionProxy() ) { if ( typeid(*leafinfo) == typeid(TFormLeafInfoCollection) ) { ndim = 1; size = -1; } else { R__ASSERT( fHasMultipleVarDim[code] ); ndim = 1; size = 1; } } else if ( c && c->GetReferenceProxy() && c->GetReferenceProxy()->HasCounter() ) { ndim = 1; size = -1; } else if (elem->GetArrayDim()>0) { ndim = elem->GetArrayDim(); size = elem->GetMaxIndex(0); } else if ( elem->GetNewType()== TStreamerInfo::kCharStar) { // When we implement being able to read the length from // strlen, we will have: // ndim = 1; // size = -1; // until then we more or so die: ndim = 1; size = 1; //NOTE: changed from 0 } else return 0; current = 0; do { vardim += RegisterDimensions(code, size); if (fNdimensions[code] >= kMAXFORMDIM) { // NOTE: test that fNdimensions[code] is NOT too big!! break; } current++; size = elem->GetMaxIndex(current); } while (current<ndim); return vardim; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(Int_t code, TBranchElement *branch) { // This method is used internally to decode the dimensions of the variables TBranchElement * leafcount2 = branch->GetBranchCount2(); if (leafcount2) { // With have a second variable dimensions TBranchElement *leafcount = dynamic_cast<TBranchElement*>(branch->GetBranchCount()); R__ASSERT(leafcount); // The function should only be called on a functional TBranchElement object fManager->EnableMultiVarDims(); TFormLeafInfoMultiVarDim * info = new TFormLeafInfoMultiVarDimDirect(); fDataMembers.AddAtAndExpand(info, code); fHasMultipleVarDim[code] = kTRUE; info->fCounter = new TFormLeafInfoDirect(leafcount); info->fCounter2 = new TFormLeafInfoDirect(leafcount2); info->fDim = fNdimensions[code]; //if (fIndexes[code][info->fDim]<0) { // info->fVirtDim = virt_dim; // if (!fVarDims[virt_dim]) fVarDims[virt_dim] = new TArrayI; //} return RegisterDimensions(code, -1, info); } return 0; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(Int_t code, TLeaf *leaf) { // This method is used internally to decode the dimensions of the variables Int_t numberOfVarDim = 0; // Let see if we can understand the structure of this branch. // Usually we have: leafname[fixed_array] leaftitle[var_array]\type // (with fixed_array that can be a multi-dimension array. const char *tname = leaf->GetTitle(); char *leaf_dim = (char*)strstr( tname, "[" ); const char *bname = leaf->GetBranch()->GetName(); char *branch_dim = (char*)strstr(bname,"["); if (branch_dim) branch_dim++; // skip the '[' Bool_t isString = kFALSE; if (leaf->IsA() == TLeafElement::Class()) { Int_t type =((TBranchElement*)leaf->GetBranch())->GetStreamerType(); isString = (type == TStreamerInfo::kOffsetL+TStreamerInfo::kChar) || (type == TStreamerInfo::kCharStar); } else { isString = (leaf->IsA() == TLeafC::Class()); } if (leaf_dim) { leaf_dim++; // skip the '[' if (!branch_dim || strncmp(branch_dim,leaf_dim,strlen(branch_dim))) { // then both are NOT the same so do the leaf title first: numberOfVarDim += RegisterDimensions( leaf_dim, code); } else if (branch_dim && strncmp(branch_dim,leaf_dim,strlen(branch_dim))==0 && strlen(leaf_dim)>strlen(branch_dim) && (leaf_dim+strlen(branch_dim))[0]=='[') { // we have extra info in the leaf title numberOfVarDim += RegisterDimensions( leaf_dim+strlen(branch_dim)+1, code); } } if (branch_dim) { // then both are NOT same so do the branch name next: if (isString) { numberOfVarDim += RegisterDimensions( code, 1); } else { numberOfVarDim += RegisterDimensions( branch_dim, code); } } if (leaf->IsA() == TLeafElement::Class()) { TBranchElement* branch = (TBranchElement*) leaf->GetBranch(); if (branch->GetBranchCount2()) { if (!branch->GetBranchCount()) { Warning("DefinedVariable", "Noticed an incorrect in-memory TBranchElement object (%s).\nIt has a BranchCount2 but no BranchCount!\nThe result might be incorrect!", branch->GetName()); return numberOfVarDim; } // Switch from old direct style to using a TLeafInfo if (fLookupType[code] == kDataMember) Warning("DefinedVariable", "Already in kDataMember mode when handling multiple variable dimensions"); fLookupType[code] = kDataMember; // Feed the information into the Dimensions system numberOfVarDim += RegisterDimensions( code, branch); } } return numberOfVarDim; } //______________________________________________________________________________ Int_t TTreeFormula::DefineAlternate(const char *expression) { // This method check for treat the case where expression contains $Atl and load up // both fAliases and fExpr. // We return // -1 in case of failure // 0 in case we did not find $Alt // the action number in case of success. static const char *altfunc = "Alt$("; static const char *minfunc = "MinIf$("; static const char *maxfunc = "MaxIf$("; Int_t action = 0; Int_t start = 0; if ( strncmp(expression,altfunc,strlen(altfunc))==0 && expression[strlen(expression)-1]==')' ) { action = kAlternate; start = strlen(altfunc); } if ( strncmp(expression,maxfunc,strlen(maxfunc))==0 && expression[strlen(expression)-1]==')' ) { action = kMaxIf; start = strlen(maxfunc); } if ( strncmp(expression,minfunc,strlen(minfunc))==0 && expression[strlen(expression)-1]==')' ) { action = kMinIf; start = strlen(minfunc); } if (action) { TString full = expression; TString part1; TString part2; int paran = 0; int instr = 0; int brack = 0; for(unsigned int i=start;i<strlen(expression);++i) { switch (expression[i]) { case '(': paran++; break; case ')': paran--; break; case '"': instr = instr ? 0 : 1; break; case '[': brack++; break; case ']': brack--; break; }; if (expression[i]==',' && paran==0 && instr==0 && brack==0) { part1 = full( start, i-start ); part2 = full( i+1, full.Length() -1 - (i+1) ); break; // out of the for loop } } if (part1.Length() && part2.Length()) { TTreeFormula *primary = new TTreeFormula("primary",part1,fTree); TTreeFormula *alternate = new TTreeFormula("alternate",part2,fTree); short isstring = 0; if (action == kAlternate) { if (alternate->GetManager()->GetMultiplicity() != 0 ) { Error("DefinedVariable","The 2nd arguments in %s can not be an array (%s,%d)!", expression,alternate->GetTitle(), alternate->GetManager()->GetMultiplicity()); return -1; } // Should check whether we have strings. if (primary->IsString()) { if (!alternate->IsString()) { Error("DefinedVariable", "The 2nd arguments in %s has to return the same type as the 1st argument (string)!", expression); return -1; } isstring = 1; } else if (alternate->IsString()) { Error("DefinedVariable", "The 2nd arguments in %s has to return the same type as the 1st argument (numerical type)!", expression); return -1; } } else { primary->GetManager()->Add( alternate ); primary->GetManager()->Sync(); if (primary->IsString() || alternate->IsString()) { if (!alternate->IsString()) { Error("DefinedVariable", "The arguments of %s can not be strings!", expression); return -1; } } } fAliases.AddAtAndExpand(primary,fNoper); fExpr[fNoper] = ""; SetAction(fNoper, (Int_t)action + isstring, 0 ); ++fNoper; fAliases.AddAtAndExpand(alternate,fNoper); return (Int_t)kAlias + isstring; } } return 0; } //______________________________________________________________________________ Int_t TTreeFormula::ParseWithLeaf(TLeaf* leaf, const char* subExpression, Bool_t final, UInt_t paran_level, TObjArray& castqueue, Bool_t useLeafCollectionObject, const char* fullExpression) { // Decompose 'expression' as pointing to something inside the leaf // Returns: // -2 Error: some information is missing (message already printed) // -1 Error: Syntax is incorrect (message already printed) // 0 // >0 the value returns is the action code. Int_t action = 0; Int_t numberOfVarDim = 0; char *current; char scratch[kMaxLen]; scratch[0] = '\0'; char work[kMaxLen]; work[0] = '\0'; const char *right = subExpression; TString name = fullExpression; TBranch *branch = leaf ? leaf->GetBranch() : 0; Long64_t readentry = fTree->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; Bool_t useLeafReferenceObject = false; Int_t code = fNcodes-1; // Make a check to prevent problem with some corrupted files (missing TStreamerInfo). if (leaf && leaf->IsA()==TLeafElement::Class()) { TBranchElement *br = 0; if( branch->IsA() == TBranchElement::Class() ) { br = ((TBranchElement*)branch); if ( br->GetInfo() == 0 ) { Error("DefinedVariable","Missing StreamerInfo for %s. We will be unable to read!", name.Data()); return -2; } } TBranch *bmom = branch->GetMother(); if( bmom->IsA() == TBranchElement::Class() ) { TBranchElement *mom = (TBranchElement*)br->GetMother(); if (mom!=br) { if (mom->GetInfo()==0) { Error("DefinedVariable","Missing StreamerInfo for %s." " We will be unable to read!", mom->GetName()); return -2; } if ((mom->GetType()) < -1 && !mom->GetAddress()) { Error("DefinedVariable", "Address not set when the type of the branch is negative for for %s. We will be unable to read!", mom->GetName()); return -2; } } } } // We need to record the location in the list of leaves because // the tree might actually be a chain and in that case the leaf will // change from tree to tree!. // Let's reconstruct the name of the leaf, including the possible friend alias TTree *realtree = fTree->GetTree(); const char* alias = 0; if (leaf) { if (realtree) alias = realtree->GetFriendAlias(leaf->GetBranch()->GetTree()); if (!alias && realtree!=fTree) { // Let's try on the chain alias = fTree->GetFriendAlias(leaf->GetBranch()->GetTree()); } } if (alias) snprintf(scratch,kMaxLen-1,"%s.%s",alias,leaf->GetName()); else if (leaf) strlcpy(scratch,leaf->GetName(),kMaxLen); TTree *tleaf = realtree; if (leaf) { tleaf = leaf->GetBranch()->GetTree(); fCodes[code] = tleaf->GetListOfLeaves()->IndexOf(leaf); const char *mother_name = leaf->GetBranch()->GetMother()->GetName(); TString br_extended_name; // Could do ( strlen(mother_name)+strlen( leaf->GetBranch()->GetName() ) + 2 ) if (leaf->GetBranch()!=leaf->GetBranch()->GetMother()) { if (mother_name[strlen(mother_name)-1]!='.') { br_extended_name = mother_name; br_extended_name.Append('.'); } } br_extended_name.Append( leaf->GetBranch()->GetName() ); Ssiz_t dim = br_extended_name.First('['); if (dim >= 0) br_extended_name.Remove(dim); TNamed *named = new TNamed(scratch,br_extended_name.Data()); fLeafNames.AddAtAndExpand(named,code); fLeaves.AddAtAndExpand(leaf,code); } // If the leaf belongs to a friend tree which has an index, we might // be in the case where some entry do not exist. if (tleaf != realtree && tleaf->GetTreeIndex()) { // reset the multiplicity if (fMultiplicity >= 0) fMultiplicity = 1; } // Analyze the content of 'right' // Try to find out the class (if any) of the object in the leaf. TClass * cl = 0; TFormLeafInfo *maininfo = 0; TFormLeafInfo *previnfo = 0; Bool_t unwindCollection = kFALSE; static TClassRef stdStringClass = TClass::GetClass("string"); if (leaf==0) { TNamed *names = (TNamed*)fLeafNames.UncheckedAt(code); fLeafNames.AddAt(0,code); TTree *what = (TTree*)fLeaves.UncheckedAt(code); fLeaves.AddAt(0,code); cl = what ? what->IsA() : TTree::Class(); maininfo = new TFormLeafInfoTTree(fTree,names->GetName(),what); previnfo = maininfo; delete names; } else if (leaf->InheritsFrom(TLeafObject::Class()) ) { TBranchObject *bobj = (TBranchObject*)leaf->GetBranch(); cl = TClass::GetClass(bobj->GetClassName()); } else if (leaf->InheritsFrom(TLeafElement::Class())) { TBranchElement *branchEl = (TBranchElement *)leaf->GetBranch(); branchEl->SetupAddresses(); TStreamerInfo *info = branchEl->GetInfo(); TStreamerElement *element = 0; Int_t type = branchEl->GetStreamerType(); switch(type) { case TStreamerInfo::kBase: case TStreamerInfo::kObject: case TStreamerInfo::kTString: case TStreamerInfo::kTNamed: case TStreamerInfo::kTObject: case TStreamerInfo::kAny: case TStreamerInfo::kAnyP: case TStreamerInfo::kAnyp: case TStreamerInfo::kSTL: case TStreamerInfo::kSTLp: case TStreamerInfo::kObjectp: case TStreamerInfo::kObjectP: { element = (TStreamerElement *)info->GetElems()[branchEl->GetID()]; if (element) cl = element->GetClassPointer(); } break; case TStreamerInfo::kOffsetL + TStreamerInfo::kSTL: case TStreamerInfo::kOffsetL + TStreamerInfo::kSTLp: case TStreamerInfo::kOffsetL + TStreamerInfo::kAny: case TStreamerInfo::kOffsetL + TStreamerInfo::kAnyp: case TStreamerInfo::kOffsetL + TStreamerInfo::kAnyP: case TStreamerInfo::kOffsetL + TStreamerInfo::kObjectp: case TStreamerInfo::kOffsetL + TStreamerInfo::kObjectP: case TStreamerInfo::kOffsetL + TStreamerInfo::kObject: { element = (TStreamerElement *)info->GetElems()[branchEl->GetID()]; if (element){ cl = element->GetClassPointer(); } } break; case -1: { cl = info->GetClass(); } break; } // If we got a class object, we need to verify whether it is on a // split TClonesArray sub branch. if (cl && branchEl->GetBranchCount()) { if (branchEl->GetType()==31) { // This is inside a TClonesArray. if (!element) { Warning("DefineVariable", "Missing TStreamerElement in object in TClonesArray section"); return -2; } TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(cl, 0, element, kTRUE); // The following code was commmented out because in THIS case // the dimension are actually handled by parsing the title and name of the leaf // and branch (see a little further) // The dimension needs to be handled! // numberOfVarDim += RegisterDimensions(code,clonesinfo); maininfo = clonesinfo; // We skip some cases because we can assume we have an object. Int_t offset=0; info->GetStreamerElement(element->GetName(),offset); if (type == TStreamerInfo::kObjectp || type == TStreamerInfo::kObjectP || type == TStreamerInfo::kOffsetL + TStreamerInfo::kObjectp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kObjectP || type == TStreamerInfo::kSTLp || type == TStreamerInfo::kAnyp || type == TStreamerInfo::kAnyP || type == TStreamerInfo::kOffsetL + TStreamerInfo::kSTLp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kAnyp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kAnyP) { previnfo = new TFormLeafInfoPointer(cl,offset+branchEl->GetOffset(),element); } else { previnfo = new TFormLeafInfo(cl,offset+branchEl->GetOffset(),element); } maininfo->fNext = previnfo; unwindCollection = kTRUE; } else if (branchEl->GetType()==41) { // This is inside a Collection if (!element) { Warning("DefineVariable","Missing TStreamerElement in object in Collection section"); return -2; } // First we need to recover the collection. TBranchElement *count = branchEl->GetBranchCount(); TFormLeafInfo* collectioninfo; if ( count->GetID() >= 0 ) { TStreamerElement *collectionElement = (TStreamerElement *)count->GetInfo()->GetElems()[count->GetID()]; TClass *collectionCl = collectionElement->GetClassPointer(); collectioninfo = new TFormLeafInfoCollection(collectionCl, 0, collectionElement, kTRUE); } else { TClass *collectionCl = TClass::GetClass(count->GetClassName()); collectioninfo = new TFormLeafInfoCollection(collectionCl, 0, collectionCl, kTRUE); } // The following code was commmented out because in THIS case // the dimension are actually handled by parsing the title and name of the leaf // and branch (see a little further) // The dimension needs to be handled! // numberOfVarDim += RegisterDimensions(code,clonesinfo); maininfo = collectioninfo; // We skip some cases because we can assume we have an object. Int_t offset=0; info->GetStreamerElement(element->GetName(),offset); if (type == TStreamerInfo::kObjectp || type == TStreamerInfo::kObjectP || type == TStreamerInfo::kOffsetL + TStreamerInfo::kObjectp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kObjectP || type == TStreamerInfo::kSTLp || type == TStreamerInfo::kAnyp || type == TStreamerInfo::kAnyP || type == TStreamerInfo::kOffsetL + TStreamerInfo::kSTLp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kAnyp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kAnyP) { previnfo = new TFormLeafInfoPointer(cl,offset+branchEl->GetOffset(),element); } else { previnfo = new TFormLeafInfo(cl,offset+branchEl->GetOffset(),element); } maininfo->fNext = previnfo; unwindCollection = kTRUE; } } else if ( branchEl->GetType()==3) { TFormLeafInfo* clonesinfo; if (useLeafCollectionObject) { clonesinfo = new TFormLeafInfoCollectionObject(cl); } else { clonesinfo = new TFormLeafInfoClones(cl, 0, kTRUE); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,clonesinfo,maininfo,useLeafCollectionObject); } maininfo = clonesinfo; previnfo = maininfo; } else if (!useLeafCollectionObject && branchEl->GetType()==4) { TFormLeafInfo* collectioninfo; if (useLeafCollectionObject) { collectioninfo = new TFormLeafInfoCollectionObject(cl); } else { collectioninfo = new TFormLeafInfoCollection(cl, 0, cl, kTRUE); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,useLeafCollectionObject); } maininfo = collectioninfo; previnfo = maininfo; } else if (branchEl->GetStreamerType()==-1 && cl && cl->GetCollectionProxy()) { if (useLeafCollectionObject) { TFormLeafInfo *collectioninfo = new TFormLeafInfoCollectionObject(cl); maininfo = collectioninfo; previnfo = collectioninfo; } else { TFormLeafInfo *collectioninfo = new TFormLeafInfoCollection(cl, 0, cl, kTRUE); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); maininfo = collectioninfo; previnfo = collectioninfo; if (cl->GetCollectionProxy()->GetValueClass()!=0 && cl->GetCollectionProxy()->GetValueClass()->GetCollectionProxy()!=0) { TFormLeafInfo *multi = new TFormLeafInfoMultiVarDimCollection(cl,0, cl->GetCollectionProxy()->GetValueClass(),collectioninfo); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,multi,maininfo,kFALSE); previnfo->fNext = multi; cl = cl->GetCollectionProxy()->GetValueClass(); multi->fNext = new TFormLeafInfoCollection(cl, 0, cl, false); previnfo = multi->fNext; } if (cl->GetCollectionProxy()->GetValueClass()==0 && cl->GetCollectionProxy()->GetType()>0) { previnfo->fNext = new TFormLeafInfoNumerical(cl->GetCollectionProxy()); previnfo = previnfo->fNext; } else { // nothing to do } } } else if (strlen(right)==0 && cl && element && final) { TClass *elemCl = element->GetClassPointer(); if (!useLeafCollectionObject && elemCl && elemCl->GetCollectionProxy() && elemCl->GetCollectionProxy()->GetValueClass() && elemCl->GetCollectionProxy()->GetValueClass()->GetCollectionProxy()) { TFormLeafInfo *collectioninfo = new TFormLeafInfoCollection(cl, 0, elemCl); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); maininfo = collectioninfo; previnfo = collectioninfo; TFormLeafInfo *multi = new TFormLeafInfoMultiVarDimCollection(elemCl, 0, elemCl->GetCollectionProxy()->GetValueClass(), collectioninfo); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,multi,maininfo,kFALSE); previnfo->fNext = multi; cl = elemCl->GetCollectionProxy()->GetValueClass(); multi->fNext = new TFormLeafInfoCollection(cl, 0, cl, false); previnfo = multi->fNext; if (cl->GetCollectionProxy()->GetValueClass()==0 && cl->GetCollectionProxy()->GetType()>0) { previnfo->fNext = new TFormLeafInfoNumerical(cl->GetCollectionProxy()); previnfo = previnfo->fNext; } } else if (!useLeafCollectionObject && elemCl && elemCl->GetCollectionProxy() && elemCl->GetCollectionProxy()->GetValueClass()==0 && elemCl->GetCollectionProxy()->GetType()>0) { // At this point we have an element which is inside a class (which is not // a collection) and this element of a collection of numerical type. // (Note: it is not possible to have more than one variable dimension // unless we were supporting variable size C-style array of collection). TFormLeafInfo* collectioninfo = new TFormLeafInfoCollection(cl, 0, elemCl); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); collectioninfo->fNext = new TFormLeafInfoNumerical(elemCl->GetCollectionProxy()); maininfo = collectioninfo; previnfo = maininfo->fNext; } else if (!useLeafCollectionObject && elemCl && elemCl->GetCollectionProxy()) { if (elemCl->GetCollectionProxy()->GetValueClass()==TString::Class()) { right = "Data()"; } else if (elemCl->GetCollectionProxy()->GetValueClass()==stdStringClass) { right = "c_str()"; } } else if (!element->IsaPointer()) { maininfo = new TFormLeafInfoDirect(branchEl); previnfo = maininfo; } } else if ( cl && cl->GetReferenceProxy() ) { if ( useLeafCollectionObject || fullExpression[0] == '@' || fullExpression[strlen(scratch)] == '@' ) { useLeafReferenceObject = true; } else { if ( !maininfo ) { maininfo = previnfo = new TFormLeafInfoReference(cl, element, 0); numberOfVarDim += RegisterDimensions(code,maininfo,maininfo,kFALSE); } TVirtualRefProxy *refproxy = cl->GetReferenceProxy(); for(Long64_t i=0; i<leaf->GetBranch()->GetEntries()-readentry; ++i) { R__LoadBranch(leaf->GetBranch(), readentry+i, fQuickLoad); void *refobj = maininfo->GetValuePointer(leaf,0); if (refobj) { cl = refproxy->GetValueClass(refobj); } if ( cl ) break; } if ( !cl ) { Error("DefinedVariable","Failed to access class type of reference target (%s)",element->GetName()); return -1; } } } } // Treat the dimension information in the leaf name, title and 2nd branch count if (leaf) numberOfVarDim += RegisterDimensions(code,leaf); if (cl) { if (unwindCollection) { // So far we should get here only if we encounter a split collection of a class that contains // directly a collection. R__ASSERT(numberOfVarDim==1 && maininfo); if (!useLeafCollectionObject && cl && cl->GetCollectionProxy()) { TFormLeafInfo *multi = new TFormLeafInfoMultiVarDimCollection(cl, 0, cl, maininfo); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,multi,maininfo,kFALSE); previnfo->fNext = multi; multi->fNext = new TFormLeafInfoCollection(cl, 0, cl, false); previnfo = multi->fNext; if (cl->GetCollectionProxy()->GetValueClass()==0 && cl->GetCollectionProxy()->GetType()>0) { previnfo->fNext = new TFormLeafInfoNumerical(cl->GetCollectionProxy()); previnfo = previnfo->fNext; } } else if (!useLeafCollectionObject && cl == TClonesArray::Class()) { TFormLeafInfo *multi = new TFormLeafInfoMultiVarDimClones(cl, 0, cl, maininfo); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,multi,maininfo,kFALSE); previnfo->fNext = multi; multi->fNext = new TFormLeafInfoClones(cl, 0, false); previnfo = multi->fNext; } } Int_t offset=0; if (cl == TString::Class() && strcmp(right,"fData")==0) { // For backward compatibility replace TString::fData which no longer exist // by a call to TString::Data() right = "Data()"; } Int_t nchname = strlen(right); TFormLeafInfo *leafinfo = 0; TStreamerElement* element = 0; // Let see if the leaf was attempted to be casted. // Since there would have been something like // ((cast_class*)leafname)->.... we need to use // paran_level+1 // Also we disable this functionality in case of TClonesArray // because it is not yet allowed to have 'inheritance' (or virtuality) // in play in a TClonesArray. { TClass * casted = (TClass*) castqueue.At(paran_level+1); if (casted && cl != TClonesArray::Class()) { if ( ! casted->InheritsFrom(cl) ) { Error("DefinedVariable","%s does not inherit from %s. Casting not possible!", casted->GetName(),cl->GetName()); return -2; } leafinfo = new TFormLeafInfoCast(cl,casted); fHasCast = kTRUE; if (maininfo==0) { maininfo = leafinfo; } if (previnfo==0) { previnfo = leafinfo; } else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = 0; cl = casted; castqueue.AddAt(0,paran_level); } } Int_t i; Bool_t prevUseCollectionObject = useLeafCollectionObject; Bool_t useCollectionObject = useLeafCollectionObject; Bool_t useReferenceObject = useLeafReferenceObject; Bool_t prevUseReferenceObject = useLeafReferenceObject; for (i=0, current = &(work[0]); i<=nchname;i++ ) { // We will treated the terminator as a token. if (right[i] == '(') { // Right now we do not allow nested paranthesis do { *current++ = right[i++]; } while(right[i]!=')' && right[i]); *current++ = right[i]; *current='\0'; char *params = strchr(work,'('); if (params) { *params = 0; params++; } else params = (char *) ")"; if (cl==0) { Error("DefinedVariable","Can not call '%s' with a class",work); return -1; } if (cl->GetClassInfo()==0 && !cl->GetCollectionProxy()) { Error("DefinedVariable","Class probably unavailable:%s",cl->GetName()); return -2; } if (!useCollectionObject && cl == TClonesArray::Class()) { // We are not interested in the ClonesArray object but only // in its contents. // We need to retrieve the class of its content. TBranch *clbranch = leaf->GetBranch(); R__LoadBranch(clbranch,readentry,fQuickLoad); TClonesArray * clones; if (previnfo) clones = (TClonesArray*)previnfo->GetLocalValuePointer(leaf,0); else { Bool_t top = (clbranch==((TBranchElement*)clbranch)->GetMother() || !leaf->IsOnTerminalBranch()); TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)clbranch)->GetInfo()->GetClass(); } TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(mother_cl, 0, top); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,clonesinfo,maininfo,kFALSE); previnfo = clonesinfo; maininfo = clonesinfo; clones = (TClonesArray*)clonesinfo->GetLocalValuePointer(leaf,0); } TClass * inside_cl = clones->GetClass(); cl = inside_cl; } else if (!useCollectionObject && cl && cl->GetCollectionProxy() ) { // We are NEVER (for now!) interested in the ClonesArray object but only // in its contents. // We need to retrieve the class of its content. if (previnfo==0) { Bool_t top = (branch==((TBranchElement*)branch)->GetMother() || !leaf->IsOnTerminalBranch()); TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)branch)->GetInfo()->GetClass(); } TFormLeafInfo* collectioninfo = new TFormLeafInfoCollection(mother_cl, 0,cl,top); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); previnfo = collectioninfo; maininfo = collectioninfo; } TClass * inside_cl = cl->GetCollectionProxy()->GetValueClass(); if (inside_cl) cl = inside_cl; else if (cl->GetCollectionProxy()->GetType()>0) { Warning("DefinedVariable","Can not call method on content of %s in %s\n", cl->GetName(),name.Data()); return -2; } } TMethodCall *method = 0; if (cl==0) { Error("DefinedVariable", "Could not discover the TClass corresponding to (%s)!", right); return -2; } else if (cl==TClonesArray::Class() && strcmp(work,"size")==0) { method = new TMethodCall(cl, "GetEntriesFast", ""); } else if (cl->GetCollectionProxy() && strcmp(work,"size")==0) { if (maininfo==0) { TFormLeafInfo* collectioninfo=0; if (useLeafCollectionObject) { Bool_t top = (branch==((TBranchElement*)branch)->GetMother() || !leaf->IsOnTerminalBranch()); collectioninfo = new TFormLeafInfoCollectionObject(cl,top); } maininfo=previnfo=collectioninfo; } leafinfo = new TFormLeafInfoCollectionSize(cl); cl = 0; } else { if (cl->GetClassInfo()==0) { Error("DefinedVariable", "Can not call method %s on class without dictionary (%s)!", right,cl->GetName()); return -2; } method = new TMethodCall(cl, work, params); } if (method) { if (!method->GetMethod()) { Error("DefinedVariable","Unknown method:%s in %s",right,cl->GetName()); return -1; } switch(method->ReturnType()) { case TMethodCall::kLong: leafinfo = new TFormLeafInfoMethod(cl,method); cl = 0; break; case TMethodCall::kDouble: leafinfo = new TFormLeafInfoMethod(cl,method); cl = 0; break; case TMethodCall::kString: leafinfo = new TFormLeafInfoMethod(cl,method); // 1 will be replaced by -1 when we know how to use strlen numberOfVarDim += RegisterDimensions(code,1); //NOTE: changed from 0 cl = 0; break; case TMethodCall::kOther: { TString return_type = gInterpreter->TypeName(method->GetMethod()->GetReturnTypeName()); leafinfo = new TFormLeafInfoMethod(cl,method); cl = (return_type == "void") ? 0 : TClass::GetClass(return_type.Data()); } break; default: Error("DefineVariable","Method %s from %s has an impossible return type %d", work,cl->GetName(),method->ReturnType()); return -2; } } if (maininfo==0) { maininfo = leafinfo; } if (previnfo==0) { previnfo = leafinfo; } else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = 0; current = &(work[0]); *current = 0; prevUseCollectionObject = kFALSE; prevUseReferenceObject = kFALSE; useCollectionObject = kFALSE; if (cl && cl->GetCollectionProxy()) { if (numberOfVarDim>1) { Warning("DefinedVariable","TTreeFormula support only 2 level of variables size collections. Assuming '@' notation for the collection %s.", cl->GetName()); leafinfo = new TFormLeafInfo(cl,0,0); useCollectionObject = kTRUE; } else if (numberOfVarDim==0) { R__ASSERT(maininfo); leafinfo = new TFormLeafInfoCollection(cl,0,cl); numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); } else if (numberOfVarDim==1) { R__ASSERT(maininfo); leafinfo = new TFormLeafInfoMultiVarDimCollection(cl,0, (TStreamerElement*)0,maininfo); previnfo->fNext = leafinfo; previnfo = leafinfo; leafinfo = new TFormLeafInfoCollection(cl,0,cl); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); } previnfo->fNext = leafinfo; previnfo = leafinfo; leafinfo = 0; } continue; } else if (right[i] == ')') { // We should have the end of a cast operator. Let's introduce a TFormLeafCast // in the chain. TClass * casted = (TClass*) ((int(--paran_level)>=0) ? castqueue.At(paran_level) : 0); if (casted) { leafinfo = new TFormLeafInfoCast(cl,casted); fHasCast = kTRUE; if (maininfo==0) { maininfo = leafinfo; } if (previnfo==0) { previnfo = leafinfo; } else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = 0; current = &(work[0]); *current = 0; cl = casted; continue; } } else if (i > 0 && (right[i] == '.' || right[i] == '[' || right[i] == '\0') ) { // A delimiter happened let's see if what we have seen // so far does point to a data member. Bool_t needClass = kTRUE; *current = '\0'; // skip it all if there is nothing to look at if (strlen(work)==0) continue; prevUseCollectionObject = useCollectionObject; prevUseReferenceObject = useReferenceObject; if (work[0]=='@') { useReferenceObject = kTRUE; useCollectionObject = kTRUE; Int_t l = 0; for(l=0;work[l+1]!=0;++l) work[l] = work[l+1]; work[l] = '\0'; } else if (work[strlen(work)-1]=='@') { useReferenceObject = kTRUE; useCollectionObject = kTRUE; work[strlen(work)-1] = '\0'; } else { useReferenceObject = kFALSE; useCollectionObject = kFALSE; } Bool_t mustderef = kFALSE; if ( !prevUseReferenceObject && cl && cl->GetReferenceProxy() ) { R__LoadBranch(leaf->GetBranch(), readentry, fQuickLoad); if ( !maininfo ) { maininfo = previnfo = new TFormLeafInfoReference(cl, element, offset); if ( cl->GetReferenceProxy()->HasCounter() ) { numberOfVarDim += RegisterDimensions(code,-1); } prevUseReferenceObject = kFALSE; } else { previnfo->fNext = new TFormLeafInfoReference(cl, element, offset); previnfo = previnfo->fNext; } TVirtualRefProxy *refproxy = cl->GetReferenceProxy(); cl = 0; for(Long64_t entry=0; entry<leaf->GetBranch()->GetEntries()-readentry; ++entry) { R__LoadBranch(leaf->GetBranch(), readentry+i, fQuickLoad); void *refobj = maininfo->GetValuePointer(leaf,0); if (refobj) { cl = refproxy->GetValueClass(refobj); } if ( cl ) break; } needClass = kFALSE; mustderef = kTRUE; } else if (!prevUseCollectionObject && cl == TClonesArray::Class()) { // We are not interested in the ClonesArray object but only // in its contents. // We need to retrieve the class of its content. TBranch *clbranch = leaf->GetBranch(); R__LoadBranch(clbranch,readentry,fQuickLoad); TClonesArray * clones; if (maininfo) { clones = (TClonesArray*)maininfo->GetValuePointer(leaf,0); } else { // we have a unsplit TClonesArray leaves // or we did not yet match any of the sub-branches! TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)clbranch)->GetInfo()->GetClass(); } TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(mother_cl, 0); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,clonesinfo,maininfo,kFALSE); mustderef = kTRUE; previnfo = clonesinfo; maininfo = clonesinfo; if (clbranch->GetListOfBranches()->GetLast()>=0) { if (clbranch->IsA() != TBranchElement::Class()) { Error("DefinedVariable","Unimplemented usage of ClonesArray"); return -2; } //clbranch = ((TBranchElement*)clbranch)->GetMother(); clones = (TClonesArray*)((TBranchElement*)clbranch)->GetObject(); } else clones = (TClonesArray*)clonesinfo->GetLocalValuePointer(leaf,0); } // NOTE clones can be zero! if (clones==0) { Warning("DefinedVariable", "TClonesArray object was not retrievable for %s!", name.Data()); return -1; } TClass * inside_cl = clones->GetClass(); #if 1 cl = inside_cl; #else /* Maybe we should make those test lead to warning messages */ if (1 || inside_cl) cl = inside_cl; // if inside_cl is nul ... we have a problem of inconsistency :( if (0 && strlen(work)==0) { // However in this case we have NO content :( // so let get the number of objects //strcpy(work,"fLast"); } #endif } else if (!prevUseCollectionObject && cl && cl->GetCollectionProxy() ) { // We are NEVER interested in the Collection object but only // in its contents. // We need to retrieve the class of its content. TBranch *clbranch = leaf->GetBranch(); R__LoadBranch(clbranch,readentry,fQuickLoad); if (maininfo==0) { // we have a unsplit Collection leaf // or we did not yet match any of the sub-branches! TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)clbranch)->GetInfo()->GetClass(); } TFormLeafInfo* collectioninfo = new TFormLeafInfoCollection(mother_cl, 0, cl); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); mustderef = kTRUE; previnfo = collectioninfo; maininfo = collectioninfo; } //else if (clbranch->GetStreamerType()==0) { //} TClass * inside_cl = cl->GetCollectionProxy()->GetValueClass(); if (!inside_cl && cl->GetCollectionProxy()->GetType() > 0) { Warning("DefinedVariable","No data member in content of %s in %s\n", cl->GetName(),name.Data()); } cl = inside_cl; // if inside_cl is nul ... we have a problem of inconsistency. } if (!cl) { Warning("DefinedVariable","Missing class for %s!",name.Data()); } else { element = ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(work,offset); } if (!element && !prevUseCollectionObject) { // We allow for looking for a data member inside a class inside // a TClonesArray without mentioning the TClonesArrays variable name TIter next( cl->GetStreamerInfo()->GetElements() ); TStreamerElement * curelem; while ((curelem = (TStreamerElement*)next())) { if (curelem->GetClassPointer() == TClonesArray::Class()) { Int_t clones_offset = 0; ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(curelem->GetName(),clones_offset); TFormLeafInfo* clonesinfo = new TFormLeafInfo(cl, clones_offset, curelem); TClonesArray * clones; R__LoadBranch(leaf->GetBranch(),readentry,fQuickLoad); if (previnfo) { previnfo->fNext = clonesinfo; clones = (TClonesArray*)maininfo->GetValuePointer(leaf,0); previnfo->fNext = 0; } else { clones = (TClonesArray*)clonesinfo->GetLocalValuePointer(leaf,0); } TClass *sub_cl = clones->GetClass(); if (sub_cl) element = ((TStreamerInfo*)sub_cl->GetStreamerInfo())->GetStreamerElement(work,offset); delete clonesinfo; if (element) { leafinfo = new TFormLeafInfoClones(cl,clones_offset,curelem); numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); if (maininfo==0) maininfo = leafinfo; if (previnfo==0) previnfo = leafinfo; else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = 0; cl = sub_cl; break; } } else if (curelem->GetClassPointer() && curelem->GetClassPointer()->GetCollectionProxy()) { Int_t coll_offset = 0; ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(curelem->GetName(),coll_offset); TClass *sub_cl = curelem->GetClassPointer()->GetCollectionProxy()->GetValueClass(); if (sub_cl) { element = ((TStreamerInfo*)sub_cl->GetStreamerInfo())->GetStreamerElement(work,offset); } if (element) { if (numberOfVarDim>1) { Warning("DefinedVariable","TTreeFormula support only 2 level of variables size collections. Assuming '@' notation for the collection %s.", curelem->GetName()); leafinfo = new TFormLeafInfo(cl,coll_offset,curelem); useCollectionObject = kTRUE; } else if (numberOfVarDim==1) { R__ASSERT(maininfo); leafinfo = new TFormLeafInfoMultiVarDimCollection(cl,coll_offset, curelem,maininfo); fHasMultipleVarDim[code] = kTRUE; leafinfo->fNext = new TFormLeafInfoCollection(cl,coll_offset,curelem); numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); } else { leafinfo = new TFormLeafInfoCollection(cl,coll_offset,curelem); numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); } if (maininfo==0) maininfo = leafinfo; if (previnfo==0) previnfo = leafinfo; else { previnfo->fNext = leafinfo; previnfo = leafinfo; } if (leafinfo->fNext) { previnfo = leafinfo->fNext; } leafinfo = 0; cl = sub_cl; break; } } } } if (element) { Int_t type = element->GetNewType(); if (type<60 && type!=0) { // This is a basic type ... if (numberOfVarDim>=1 && type>40) { // We have a variable array within a variable array! leafinfo = new TFormLeafInfoMultiVarDim(cl,offset,element,maininfo); fHasMultipleVarDim[code] = kTRUE; } else { if (leafinfo && type<=40 ) { leafinfo->AddOffset(offset,element); } else { leafinfo = new TFormLeafInfo(cl,offset,element); } } } else { Bool_t object = kFALSE; Bool_t pointer = kFALSE; Bool_t objarr = kFALSE; switch(type) { case TStreamerInfo::kObjectp: case TStreamerInfo::kObjectP: case TStreamerInfo::kSTLp: case TStreamerInfo::kAnyp: case TStreamerInfo::kAnyP: case TStreamerInfo::kOffsetL + TStreamerInfo::kObjectP: case TStreamerInfo::kOffsetL + TStreamerInfo::kSTLp: case TStreamerInfo::kOffsetL + TStreamerInfo::kAnyp: case TStreamerInfo::kOffsetL + TStreamerInfo::kObjectp: case TStreamerInfo::kOffsetL + TStreamerInfo::kAnyP: pointer = kTRUE; break; case TStreamerInfo::kBase: case TStreamerInfo::kAny : case TStreamerInfo::kSTL: case TStreamerInfo::kObject: case TStreamerInfo::kTString: case TStreamerInfo::kTNamed: case TStreamerInfo::kTObject: object = kTRUE; break; case TStreamerInfo::kOffsetL + TStreamerInfo::kAny: case TStreamerInfo::kOffsetL + TStreamerInfo::kSTL: case TStreamerInfo::kOffsetL + TStreamerInfo::kObject: objarr = kTRUE; break; case TStreamerInfo::kStreamer: case TStreamerInfo::kStreamLoop: // Unsupported case. Error("DefinedVariable", "%s is a datamember of %s BUT is not yet of a supported type (%d)", right,cl ? cl->GetName() : "unknown class",type); return -2; default: // Unknown and Unsupported case. Error("DefinedVariable", "%s is a datamember of %s BUT is not of a unknown type (%d)", right,cl ? cl->GetName() : "unknown class",type); return -2; } if (object && !useCollectionObject && ( element->GetClassPointer() == TClonesArray::Class() || element->GetClassPointer()->GetCollectionProxy() ) ) { object = kFALSE; } if (object && leafinfo) { leafinfo->AddOffset(offset,element); } else if (objarr) { // This is an embedded array of objects. We can not increase the offset. leafinfo = new TFormLeafInfo(cl,offset,element); mustderef = kTRUE; } else { if (!useCollectionObject && element->GetClassPointer() == TClonesArray::Class()) { leafinfo = new TFormLeafInfoClones(cl,offset,element); mustderef = kTRUE; } else if (!useCollectionObject && element->GetClassPointer() && element->GetClassPointer()->GetCollectionProxy()) { mustderef = kTRUE; if (numberOfVarDim>1) { Warning("DefinedVariable","TTreeFormula support only 2 level of variables size collections. Assuming '@' notation for the collection %s.", element->GetName()); leafinfo = new TFormLeafInfo(cl,offset,element); useCollectionObject = kTRUE; } else if (numberOfVarDim==1) { R__ASSERT(maininfo); leafinfo = new TFormLeafInfoMultiVarDimCollection(cl,offset,element,maininfo); fHasMultipleVarDim[code] = kTRUE; //numberOfVarDim += RegisterDimensions(code,leafinfo); //cl = cl->GetCollectionProxy()->GetValueClass(); //if (maininfo==0) maininfo = leafinfo; //if (previnfo==0) previnfo = leafinfo; //else { // previnfo->fNext = leafinfo; // previnfo = leafinfo; //} leafinfo->fNext = new TFormLeafInfoCollection(cl, offset, element); if (element->GetClassPointer()->GetCollectionProxy()->GetValueClass()==0) { TFormLeafInfo *info = new TFormLeafInfoNumerical( element->GetClassPointer()->GetCollectionProxy()); if (leafinfo->fNext) leafinfo->fNext->fNext = info; else leafinfo->fNext = info; } } else { leafinfo = new TFormLeafInfoCollection(cl, offset, element); TClass *elemCl = element->GetClassPointer(); TClass *valueCl = elemCl->GetCollectionProxy()->GetValueClass(); if (!maininfo) maininfo = leafinfo; if (valueCl!=0 && valueCl->GetCollectionProxy()!=0) { numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); if (previnfo==0) previnfo = leafinfo; else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = new TFormLeafInfoMultiVarDimCollection(elemCl,0, elemCl->GetCollectionProxy()->GetValueClass(),maininfo); //numberOfVarDim += RegisterDimensions(code,previnfo->fNext); fHasMultipleVarDim[code] = kTRUE; //previnfo = previnfo->fNext; leafinfo->fNext = new TFormLeafInfoCollection(elemCl,0, valueCl); elemCl = valueCl; } if (elemCl->GetCollectionProxy() && elemCl->GetCollectionProxy()->GetValueClass()==0) { TFormLeafInfo *info = new TFormLeafInfoNumerical(elemCl->GetCollectionProxy()); if (leafinfo->fNext) leafinfo->fNext->fNext = info; else leafinfo->fNext = info; } } } else if ( (object || pointer) && !useReferenceObject && element->GetClassPointer()->GetReferenceProxy() ) { TClass* c = element->GetClassPointer(); R__LoadBranch(leaf->GetBranch(),readentry,fQuickLoad); if ( object ) { leafinfo = new TFormLeafInfoReference(c, element, offset); } else { leafinfo = new TFormLeafInfoPointer(cl,offset,element); leafinfo->fNext = new TFormLeafInfoReference(c, element, 0); } //if ( c->GetReferenceProxy()->HasCounter() ) { // numberOfVarDim += RegisterDimensions(code,-1); //} prevUseReferenceObject = kFALSE; needClass = kFALSE; mustderef = kTRUE; } else if (pointer) { // this is a pointer to be followed. leafinfo = new TFormLeafInfoPointer(cl,offset,element); mustderef = kTRUE; } else { // this is an embedded object. R__ASSERT(object); leafinfo = new TFormLeafInfo(cl,offset,element); } } } } else { if (cl) Error("DefinedVariable","%s is not a datamember of %s",work,cl->GetName()); // no else, we warned earlier that the class was missing. return -1; } numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,useCollectionObject); // Note or useCollectionObject||prevUseColectionObject if (maininfo==0) { maininfo = leafinfo; } if (previnfo==0) { previnfo = leafinfo; } else if (previnfo!=leafinfo) { previnfo->fNext = leafinfo; previnfo = leafinfo; } while (previnfo->fNext) previnfo = previnfo->fNext; if ( right[i] != '\0' ) { if ( !needClass && mustderef ) { maininfo->SetBranch(leaf->GetBranch()); char *ptr = (char*)maininfo->GetValuePointer(leaf,0); TFormLeafInfoReference* refInfo = 0; if ( !maininfo->IsReference() ) { for( TFormLeafInfo* inf = maininfo->fNext; inf; inf = inf->fNext ) { if ( inf->IsReference() ) { refInfo = (TFormLeafInfoReference*)inf; } } } else { refInfo = (TFormLeafInfoReference*)maininfo; } if ( refInfo ) { cl = refInfo->GetValueClass(ptr); if ( !cl ) { Error("DefinedVariable","Failed to access class type of reference target (%s)",element->GetName()); return -1; } element = ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(work,offset); } else { Error("DefinedVariable","Failed to access class type of reference target (%s)",element->GetName()); return -1; } } else if ( needClass ) { cl = element->GetClassPointer(); } } if (mustderef) leafinfo = 0; current = &(work[0]); *current = 0; R__ASSERT(right[i] != '['); // We are supposed to have removed all dimensions already! if (cl == TString::Class() && strcmp(right+i+1,"fData") == 0) { // For backward compatibility replace TString::fData which no longer exist // by a call to TString::Data() right = ".Data()"; i = 0; nchname = strlen(right); } } else *current++ = right[i]; } if (maininfo) { fDataMembers.AddAtAndExpand(maininfo,code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } } if (strlen(work)!=0) { // We have something left to analyze. Let's make this an error case! return -1; } TClass *objClass = EvalClass(code); if (objClass && !useLeafCollectionObject && objClass->GetCollectionProxy() && objClass->GetCollectionProxy()->GetValueClass()) { TFormLeafInfo *last = 0; if ( SwitchToFormLeafInfo(code) ) { last = (TFormLeafInfo*)fDataMembers.At(code); if (!last) return action; while (last->fNext) { last = last->fNext; } } if (last && last->GetClass() != objClass) { TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)branch)->GetInfo()->GetClass(); } TFormLeafInfo* collectioninfo = new TFormLeafInfoCollection(mother_cl, 0, objClass, kFALSE); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); last->fNext = collectioninfo; } numberOfVarDim += RegisterDimensions(code,1); //NOTE: changed from 0 objClass = objClass->GetCollectionProxy()->GetValueClass(); } if (IsLeafString(code) || objClass == TString::Class() || objClass == stdStringClass) { TFormLeafInfo *last = 0; if ( SwitchToFormLeafInfo(code) ) { last = (TFormLeafInfo*)fDataMembers.At(code); if (!last) return action; while (last->fNext) { last = last->fNext; } } const char *funcname = 0; if (objClass == TString::Class()) { funcname = "Data"; //tobetested: numberOfVarDim += RegisterDimensions(code,1,0); // Register the dim of the implied char* } else if (objClass == stdStringClass) { funcname = "c_str"; //tobetested: numberOfVarDim += RegisterDimensions(code,1,0); // Register the dim of the implied char* } if (funcname) { TMethodCall *method = new TMethodCall(objClass, funcname, ""); if (last) { last->fNext = new TFormLeafInfoMethod(objClass,method); } else { fDataMembers.AddAtAndExpand(new TFormLeafInfoMethod(objClass,method),code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } } return kDefinedString; } if (objClass) { TMethodCall *method = new TMethodCall(objClass, "AsDouble", ""); if (method->IsValid() && (method->ReturnType() == TMethodCall::kLong || method->ReturnType() == TMethodCall::kDouble)) { TFormLeafInfo *last = 0; if (SwitchToFormLeafInfo(code)) { last = (TFormLeafInfo*)fDataMembers.At(code); // Improbable case if (!last) { delete method; return action; } while (last->fNext) { last = last->fNext; } } if (last) { last->fNext = new TFormLeafInfoMethod(objClass,method); } else { fDataMembers.AddAtAndExpand(new TFormLeafInfoMethod(objClass,method),code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } return kDefinedVariable; } delete method; method = new TMethodCall(objClass, "AsString", ""); if (method->IsValid() && method->ReturnType() == TMethodCall::kString) { TFormLeafInfo *last = 0; if (SwitchToFormLeafInfo(code)) { last = (TFormLeafInfo*)fDataMembers.At(code); // Improbable case if (!last) { delete method; return action; } while (last->fNext) { last = last->fNext; } } if (last) { last->fNext = new TFormLeafInfoMethod(objClass,method); } else { fDataMembers.AddAtAndExpand(new TFormLeafInfoMethod(objClass,method),code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } //tobetested: numberOfVarDim += RegisterDimensions(code,1,0); // Register the dim of the implied char* return kDefinedString; } if (method->IsValid() && method->ReturnType() == TMethodCall::kOther) { TClass *rcl = 0; TFunction *f = method->GetMethod(); if (f) rcl = TClass::GetClass(gInterpreter->TypeName(f->GetReturnTypeName())); if ((rcl == TString::Class() || rcl == stdStringClass) ) { TFormLeafInfo *last = 0; if (SwitchToFormLeafInfo(code)) { last = (TFormLeafInfo*)fDataMembers.At(code); // Improbable case if (!last) { delete method; return action; } while (last->fNext) { last = last->fNext; } } if (last) { last->fNext = new TFormLeafInfoMethod(objClass,method); last = last->fNext; } else { last = new TFormLeafInfoMethod(objClass,method); fDataMembers.AddAtAndExpand(last,code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } objClass = rcl; const char *funcname = 0; if (objClass == TString::Class()) { funcname = "Data"; } else if (objClass == stdStringClass) { funcname = "c_str"; } if (funcname) { method = new TMethodCall(objClass, funcname, ""); last->fNext = new TFormLeafInfoMethod(objClass,method); } return kDefinedString; } } delete method; } return action; } //______________________________________________________________________________ Int_t TTreeFormula::FindLeafForExpression(const char* expression, TLeaf*& leaf, TString& leftover, Bool_t& final, UInt_t& paran_level, TObjArray& castqueue, std::vector<std::string>& aliasUsed, Bool_t& useLeafCollectionObject, const char* fullExpression) { // Look for the leaf corresponding to the start of expression. // It returns the corresponding leaf if any. // It also modify the following arguments: // leftover: contain from expression that was not used to determine the leaf // final: // paran_level: number of un-matched open parenthesis // cast_queue: list of cast to be done // aliases: list of aliases used // Return <0 in case of failure // Return 0 if a leaf has been found // Return 2 if info about the TTree itself has been requested. // Later on we will need to read one entry, let's make sure // it is a real entry. if (fTree->GetTree()==0) { fTree->LoadTree(0); if (fTree->GetTree()==0) return -1; } Long64_t readentry = fTree->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; const char *cname = expression; char first[kMaxLen]; first[0] = '\0'; char second[kMaxLen]; second[0] = '\0'; char right[kMaxLen]; right[0] = '\0'; char work[kMaxLen]; work[0] = '\0'; char left[kMaxLen]; left[0] = '\0'; char scratch[kMaxLen]; char scratch2[kMaxLen]; std::string currentname; Int_t previousdot = 0; char *current; TLeaf *tmp_leaf=0; TBranch *branch=0, *tmp_branch=0; Int_t nchname = strlen(cname); Int_t i; Bool_t foundAtSign = kFALSE; for (i=0, current = &(work[0]); i<=nchname && !final;i++ ) { // We will treated the terminator as a token. *current++ = cname[i]; if (cname[i] == '(') { ++paran_level; if (current==work+1) { // If the expression starts with a paranthesis, we are likely // to have a cast operator inside. current--; } continue; //i++; //while( cname[i]!=')' && cname[i] ) { // *current++ = cname[i++]; //} //*current++ = cname[i]; ////*current = 0; //continue; } if (cname[i] == ')') { if (paran_level==0) { Error("DefinedVariable","Unmatched paranthesis in %s",fullExpression); return -1; } // Let's see if work is a classname. *(--current) = 0; paran_level--; TString cast_name = gInterpreter->TypeName(work); TClass *cast_cl = TClass::GetClass(cast_name); if (cast_cl) { // We must have a cast castqueue.AddAtAndExpand(cast_cl,paran_level); current = &(work[0]); *current = 0; // Warning("DefinedVariable","Found cast to %s",cast_fullExpression); continue; } else if (gROOT->GetType(cast_name)) { // We reset work current = &(work[0]); *current = 0; Warning("DefinedVariable", "Casting to primary types like \"%s\" is not supported yet",cast_name.Data()); continue; } *(current++)=')'; *current='\0'; char *params = strchr(work,'('); if (params) { *params = 0; params++; if (branch && !leaf) { // We have a branch but not a leaf. We are likely to have found // the top of split branch. if (BranchHasMethod(0, branch, work, params, readentry)) { //fprintf(stderr, "Does have a method %s for %s.\n", work, branch->GetName()); } } // What we have so far might be a member function of one of the // leaves that are not splitted (for example "GetNtrack" for the Event class). TIter next(fTree->GetIteratorOnAllLeaves()); TLeaf* leafcur = 0; while (!leaf && (leafcur = (TLeaf*) next())) { TBranch* br = leafcur->GetBranch(); Bool_t yes = BranchHasMethod(leafcur, br, work, params, readentry); if (yes) { leaf = leafcur; //fprintf(stderr, "Does have a method %s for %s found in leafcur %s.\n", work, leafcur->GetBranch()->GetName(), leafcur->GetName()); } } if (!leaf) { // Check for an alias. if (strlen(left) && left[strlen(left)-1]=='.') left[strlen(left)-1]=0; const char *aliasValue = fTree->GetAlias(left); if (aliasValue && strcspn(aliasValue,"+*/-%&!=<>|")==strlen(aliasValue)) { // First check whether we are using this alias recursively (this would // lead to an infinite recursion. if (find(aliasUsed.begin(), aliasUsed.end(), left) != aliasUsed.end()) { Error("DefinedVariable", "The substitution of the branch alias \"%s\" by \"%s\" in \"%s\" failed\n"\ "\tbecause \"%s\" is used [recursively] in its own definition!", left,aliasValue,fullExpression,left); return -3; } aliasUsed.push_back(left); TString newExpression = aliasValue; newExpression += (cname+strlen(left)); Int_t res = FindLeafForExpression(newExpression, leaf, leftover, final, paran_level, castqueue, aliasUsed, useLeafCollectionObject, fullExpression); if (res<0) { Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed.",left,aliasValue); return -3; } return res; } // This is actually not really any error, we probably received something // like "abs(some_val)", let TFormula decompose it first. return -1; } // if (!leaf->InheritsFrom(TLeafObject::Class()) ) { // If the leaf that we found so far is not a TLeafObject then there is // nothing we would be able to do. // Error("DefinedVariable","Need a TLeafObject to call a function!"); // return -1; //} // We need to recover the info not used. strlcpy(right,work,kMaxLen); strncat(right,"(",kMaxLen-1-strlen(right)); strncat(right,params,kMaxLen-1-strlen(right)); final = kTRUE; // we reset work current = &(work[0]); *current = 0; break; } } if (cname[i] == '.' || cname[i] == '\0' || cname[i] == ')') { // A delimiter happened let's see if what we have seen // so far does point to a leaf. *current = '\0'; Int_t len = strlen(work); if (work[0]=='@') { foundAtSign = kTRUE; Int_t l = 0; for(l=0;work[l+1]!=0;++l) work[l] = work[l+1]; work[l] = '\0'; --current; } else if (len>=2 && work[len-2]=='@') { foundAtSign = kTRUE; work[len-2] = cname[i]; work[len-1] = '\0'; --current; } else { foundAtSign = kFALSE; } if (left[0]==0) strlcpy(left,work,kMaxLen); if (!leaf && !branch) { // So far, we have not found a matching leaf or branch. strlcpy(first,work,kMaxLen); std::string treename(first); if (treename.size() && treename[treename.size()-1]=='.') { treename.erase(treename.size()-1); } if (treename== "This" /* || treename == fTree->GetName() */ ) { // Request info about the TTree object itself, TNamed *named = new TNamed(fTree->GetName(),fTree->GetName()); fLeafNames.AddAtAndExpand(named,fNcodes); fLeaves.AddAtAndExpand(fTree,fNcodes); if (cname[i]) leftover = &(cname[i+1]); return 2; } // The following would allow to access the friend by name // however, it would also prevent the access of the leaves // within the friend. We could use the '@' notation here // however this would not be aesthetically pleasing :( // What we need to do, is add the ability to look ahead to // the next 'token' to decide whether we to access the tree // or its leaf. //} else { // TTree *tfriend = fTree->GetFriend(treename.c_str()); // TTree *realtree = fTree->GetTree(); // if (!tfriend && realtree != fTree){ // // If it is a chain and we did not find a friend, // // let's try with the internal tree. // tfriend = realtree->GetFriend(treename.c_str()); // } // if (tfriend) { // TNamed *named = new TNamed(treename.c_str(),tfriend->GetName()); // fLeafNames.AddAtAndExpand(named,fNcodes); // fLeaves.AddAtAndExpand(tfriend,fNcodes); // if (cname[i]) leftover = &(cname[i+1]); // return 2; // } //} branch = fTree->FindBranch(first); leaf = fTree->FindLeaf(first); // Now look with the delimiter removed (we looked with it first // because a dot is allowed at the end of some branches). if (cname[i]) first[strlen(first)-1]='\0'; if (!branch) branch = fTree->FindBranch(first); if (!leaf) leaf = fTree->FindLeaf(first); TClass* cl = 0; if ( branch && branch->InheritsFrom(TBranchElement::Class()) ) { int offset=0; TBranchElement* bElt = (TBranchElement*)branch; TStreamerInfo* info = bElt->GetInfo(); TStreamerElement* element = info ? info->GetStreamerElement(first,offset) : 0; if (element) cl = element->GetClassPointer(); if ( cl && !cl->GetReferenceProxy() ) cl = 0; } if ( cl ) { // We have a reference class here.... final = kTRUE; useLeafCollectionObject = foundAtSign; // we reset work current = &(work[0]); *current = 0; } else if (branch && (foundAtSign || cname[i] != 0) ) { // Since we found a branch and there is more information in the name, // we do NOT look at the 'IsOnTerminalBranch' status of the leaf // we found ... yet! if (leaf==0) { // Note we do not know (yet?) what (if anything) to do // for a TBranchObject branch. if (branch->InheritsFrom(TBranchElement::Class()) ) { Int_t type = ((TBranchElement*)branch)->GetType(); if ( type == 3 || type ==4) { // We have a Collection branch. leaf = (TLeaf*)branch->GetListOfLeaves()->At(0); if (foundAtSign) { useLeafCollectionObject = foundAtSign; foundAtSign = kFALSE; current = &(work[0]); *current = 0; ++i; break; } } } } // we reset work useLeafCollectionObject = foundAtSign; foundAtSign = kFALSE; current = &(work[0]); *current = 0; } else if (leaf || branch) { if (leaf && branch) { // We found both a leaf and branch matching the request name // let's see which one is the proper one to use! (On annoying case // is that where the same name is repeated ( varname.varname ) // We always give priority to the branch // leaf = 0; } if (leaf && leaf->IsOnTerminalBranch()) { // This is a non-object leaf, it should NOT be specified more except for // dimensions. final = kTRUE; } // we reset work current = &(work[0]); *current = 0; } else { // What we have so far might be a data member of one of the // leaves that are not splitted (for example "fNtrack" for the Event class. TLeaf *leafcur = GetLeafWithDatamember(first,work,readentry); if (leafcur) { leaf = leafcur; branch = leaf->GetBranch(); if (leaf->IsOnTerminalBranch()) { final = kTRUE; strlcpy(right,first,kMaxLen); //We need to put the delimiter back! if (foundAtSign) strncat(right,"@",kMaxLen-1-strlen(right)); if (cname[i]=='.') strncat(right,".",kMaxLen-1-strlen(right)); // We reset work current = &(work[0]); *current = 0; }; } else if (cname[i] == '.') { // If we have a branch that match a name preceded by a dot // then we assume we are trying to drill down the branch // Let look if one of the top level branch has a branch with the name // we are looking for. TBranch *branchcur; TIter next( fTree->GetListOfBranches() ); while(!branch && (branchcur=(TBranch*)next()) ) { branch = branchcur->FindBranch(first); } if (branch) { // We reset work current = &(work[0]); *current = 0; } } } } else { // correspond to if (leaf || branch) if (final) { Error("DefinedVariable", "Unexpected control flow!"); return -1; } // No dot is allowed in subbranches and leaves, so // we always remove it in the present case. if (cname[i]) work[strlen(work)-1] = '\0'; snprintf(scratch,sizeof(scratch),"%s.%s",first,work); snprintf(scratch2,sizeof(scratch2),"%s.%s.%s",first,second,work); if (previousdot) { currentname = &(work[previousdot+1]); } // First look for the current 'word' in the list of // leaf of the if (branch) { tmp_leaf = branch->FindLeaf(work); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(scratch); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(scratch2); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(currentname.c_str()); } if (tmp_leaf && tmp_leaf->IsOnTerminalBranch() ) { // This is a non-object leaf, it should NOT be specified more except for // dimensions. final = kTRUE; } if (branch) { tmp_branch = branch->FindBranch(work); if (!tmp_branch) tmp_branch = branch->FindBranch(scratch); if (!tmp_branch) tmp_branch = branch->FindBranch(scratch2); if (!tmp_branch) tmp_branch = branch->FindBranch(currentname.c_str()); } if (tmp_branch) { branch=tmp_branch; // NOTE: Should we look for a leaf within here? if (!final) { tmp_leaf = branch->FindLeaf(work); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(scratch); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(scratch2); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(currentname.c_str()); if (tmp_leaf && tmp_leaf->IsOnTerminalBranch() ) { // This is a non-object leaf, it should NOT be specified // more except for dimensions. final = kTRUE; leaf = tmp_leaf; } } } if (tmp_leaf) { // Something was found. if (second[0]) strncat(second,".",kMaxLen-1-strlen(second)); strncat(second,work,kMaxLen-1-strlen(second)); leaf = tmp_leaf; useLeafCollectionObject = foundAtSign; foundAtSign = kFALSE; // we reset work current = &(work[0]); *current = 0; } else { //We need to put the delimiter back! if (strlen(work)) { if (foundAtSign) { Int_t where = strlen(work); work[where] = '@'; work[where+1] = cname[i]; ++current; previousdot = where+1; } else { previousdot = strlen(work); work[strlen(work)] = cname[i]; } } else --current; } } } } // Copy the left over for later use. if (strlen(work)) { strncat(right,work,kMaxLen-1-strlen(right)); } if (i<nchname) { if (strlen(right) && right[strlen(right)-1]!='.' && cname[i]!='.') { // In some cases we remove a little to fast the period, we add // it back if we need. It is assumed that 'right' and the rest of // the name was cut by a delimiter, so this should be safe. strncat(right,".",kMaxLen-1-strlen(right)); } strncat(right,&cname[i],kMaxLen-1-strlen(right)); } if (!final && branch) { if (!leaf) { leaf = (TLeaf*)branch->GetListOfLeaves()->UncheckedAt(0); if (!leaf) return -1; } final = leaf->IsOnTerminalBranch(); } if (leaf && leaf->InheritsFrom(TLeafObject::Class()) ) { if (strlen(right)==0) strlcpy(right,work,kMaxLen); } if (leaf==0 && left[0]!=0) { if (left[strlen(left)-1]=='.') left[strlen(left)-1]=0; // Check for an alias. const char *aliasValue = fTree->GetAlias(left); if (aliasValue && strcspn(aliasValue,"[]+*/-%&!=<>|")==strlen(aliasValue)) { // First check whether we are using this alias recursively (this would // lead to an infinite recursion). if (find(aliasUsed.begin(), aliasUsed.end(), left) != aliasUsed.end()) { Error("DefinedVariable", "The substitution of the branch alias \"%s\" by \"%s\" in \"%s\" failed\n"\ "\tbecause \"%s\" is used [recursively] in its own definition!", left,aliasValue,fullExpression,left); return -3; } aliasUsed.push_back(left); TString newExpression = aliasValue; newExpression += (cname+strlen(left)); Int_t res = FindLeafForExpression(newExpression, leaf, leftover, final, paran_level, castqueue, aliasUsed, useLeafCollectionObject, fullExpression); if (res<0) { Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed.",left,aliasValue); return -3; } return res; } } leftover = right; return 0; } //______________________________________________________________________________ Int_t TTreeFormula::DefinedVariable(TString &name, Int_t &action) { //*-*-*-*-*-*Check if name is in the list of Tree/Branch leaves*-*-*-*-* //*-* ================================================== // // This member function redefines the function in TFormula // If a leaf has a name corresponding to the argument name, then // returns a new code. // A TTreeFormula may contain more than one variable. // For each variable referenced, the pointers to the corresponding // branch and leaf is stored in the object arrays fBranches and fLeaves. // // name can be : // - Leaf_Name (simple variable or data member of a ClonesArray) // - Branch_Name.Leaf_Name // - Branch_Name.Method_Name // - Leaf_Name[index] // - Branch_Name.Leaf_Name[index] // - Branch_Name.Leaf_Name[index1] // - Branch_Name.Leaf_Name[][index2] // - Branch_Name.Leaf_Name[index1][index2] // New additions: // - Branch_Name.Leaf_Name[OtherLeaf_Name] // - Branch_Name.Datamember_Name // - '.' can be replaced by '->' // and // - Branch_Name[index1].Leaf_Name[index2] // - Leaf_name[index].Action().OtherAction(param) // - Leaf_name[index].Action()[val].OtherAction(param) // // The expected returns values are // -2 : the name has been recognized but won't be usable // -1 : the name has not been recognized // >=0 : the name has been recognized, return the internal code for this name. // action = kDefinedVariable; if (!fTree) return -1; fNpar = 0; if (name.Length() > kMaxLen) return -1; Int_t i,k; if (name == "Entry$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kIndexOfEntry; return code; } if (name == "LocalEntry$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kIndexOfLocalEntry; return code; } if (name == "Entries$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kEntries; SetBit(kNeedEntries); fManager->SetBit(kNeedEntries); return code; } if (name == "Iteration$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kIteration; return code; } if (name == "Length$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kLength; return code; } static const char *lenfunc = "Length$("; if (strncmp(name.Data(),"Length$(",strlen(lenfunc))==0 && name[name.Length()-1]==')') { TString subform = name.Data()+strlen(lenfunc); subform.Remove( subform.Length() - 1 ); TTreeFormula *lengthForm = new TTreeFormula("lengthForm",subform,fTree); fAliases.AddAtAndExpand(lengthForm,fNoper); Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kLengthFunc; return code; } static const char *minfunc = "Min$("; if (strncmp(name.Data(),"Min$(",strlen(minfunc))==0 && name[name.Length()-1]==')') { TString subform = name.Data()+strlen(minfunc); subform.Remove( subform.Length() - 1 ); TTreeFormula *minForm = new TTreeFormula("minForm",subform,fTree); fAliases.AddAtAndExpand(minForm,fNoper); Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kMin; return code; } static const char *maxfunc = "Max$("; if (strncmp(name.Data(),"Max$(",strlen(maxfunc))==0 && name[name.Length()-1]==')') { TString subform = name.Data()+strlen(maxfunc); subform.Remove( subform.Length() - 1 ); TTreeFormula *maxForm = new TTreeFormula("maxForm",subform,fTree); fAliases.AddAtAndExpand(maxForm,fNoper); Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kMax; return code; } static const char *sumfunc = "Sum$("; if (strncmp(name.Data(),"Sum$(",strlen(sumfunc))==0 && name[name.Length()-1]==')') { TString subform = name.Data()+strlen(sumfunc); subform.Remove( subform.Length() - 1 ); TTreeFormula *sumForm = new TTreeFormula("sumForm",subform,fTree); fAliases.AddAtAndExpand(sumForm,fNoper); Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kSum; return code; } // Check for $Alt(expression1,expression2) Int_t res = DefineAlternate(name.Data()); if (res!=0) { // There was either a syntax error or we found $Alt if (res<0) return res; action = res; return 0; } // Find the top level leaf and deal with dimensions char cname[kMaxLen]; strlcpy(cname,name.Data(),kMaxLen); char dims[kMaxLen]; dims[0] = '\0'; Bool_t final = kFALSE; UInt_t paran_level = 0; TObjArray castqueue; // First, it is easier to remove all dimensions information from 'cname' Int_t cnamelen = strlen(cname); for(i=0,k=0; i<cnamelen; ++i, ++k) { if (cname[i] == '[') { int bracket = i; int bracket_level = 1; int j; for (j=++i; j<cnamelen && (bracket_level>0 || cname[j]=='['); j++, i++) { if (cname[j]=='[') bracket_level++; else if (cname[j]==']') bracket_level--; } if (bracket_level != 0) { //Error("DefinedVariable","Bracket unbalanced"); return -1; } strncat(dims,&cname[bracket],j-bracket); //k += j-bracket; } if (i!=k) cname[k] = cname[i]; } cname[k]='\0'; Bool_t useLeafCollectionObject = kFALSE; TString leftover; TLeaf *leaf = 0; { std::vector<std::string> aliasSofar = fAliasesUsed; res = FindLeafForExpression(cname, leaf, leftover, final, paran_level, castqueue, aliasSofar, useLeafCollectionObject, name); } if (res<0) return res; if (!leaf && res!=2) { // Check for an alias. const char *aliasValue = fTree->GetAlias(cname); if (aliasValue) { // First check whether we are using this alias recursively (this would // lead to an infinite recursion. if (find(fAliasesUsed.begin(), fAliasesUsed.end(), cname) != fAliasesUsed.end()) { Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed\n"\ "\tbecause \"%s\" is recursively used in its own definition!", cname,aliasValue,cname); return -3; } if (strcspn(aliasValue,"+*/-%&!=<>|")!=strlen(aliasValue)) { // If the alias contains an operator, we need to use a nested formula // (since DefinedVariable must only add one entry to the operation's list). // Need to check the aliases used so far std::vector<std::string> aliasSofar = fAliasesUsed; aliasSofar.push_back( cname ); TString subValue( aliasValue ); if (dims[0]) { subValue += dims; } TTreeFormula *subform = new TTreeFormula(cname,subValue,fTree,aliasSofar); // Need to pass the aliases used so far. if (subform->GetNdim()==0) { delete subform; Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed.",cname,aliasValue); return -3; } fManager->Add(subform); fAliases.AddAtAndExpand(subform,fNoper); if (subform->IsString()) { action = kAliasString; return 0; } else { action = kAlias; return 0; } } else { /* assumes strcspn(aliasValue,"[]")!=strlen(aliasValue) */ TString thisAlias( aliasValue ); thisAlias += dims; Int_t aliasRes = DefinedVariable(thisAlias,action); if (aliasRes<0) { // We failed but DefinedVariable has not printed why yet. // and because we want thoses to be printed _before_ the notice // of the failure of the substitution, we need to print them here. if (aliasRes==-1) { Error("Compile", " Bad numerical expression : \"%s\"",thisAlias.Data()); } else if (aliasRes==-2) { Error("Compile", " Part of the Variable \"%s\" exists but some of it is not accessible or useable",thisAlias.Data()); } Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed.",cname,aliasValue); return -3; } return aliasRes; } } } if (leaf || res==2) { if (leaf && leaf->GetBranch() && leaf->GetBranch()->TestBit(kDoNotProcess)) { Error("DefinedVariable","the branch \"%s\" has to be enabled to be used",leaf->GetBranch()->GetName()); return -2; } Int_t code = fNcodes++; // If needed will now parse the indexes specified for // arrays. if (dims[0]) { char *current = &( dims[0] ); Int_t dim = 0; TString varindex; Int_t index; Int_t scanindex ; while (current) { current++; if (current[0] == ']') { fIndexes[code][dim] = -1; // Loop over all elements; } else { scanindex = sscanf(current,"%d",&index); if (scanindex) { fIndexes[code][dim] = index; } else { fIndexes[code][dim] = -2; // Index is calculated via a variable. varindex = current; char *end = (char*)(varindex.Data()); for(char bracket_level = 0;*end!=0;end++) { if (*end=='[') bracket_level++; if (bracket_level==0 && *end==']') break; if (*end==']') bracket_level--; } *end = '\0'; fVarIndexes[code][dim] = new TTreeFormula("index_var", varindex, fTree); current += strlen(varindex)+1; // move to the end of the index array } } dim ++; if (dim >= kMAXFORMDIM) { // NOTE: test that dim this is NOT too big!! break; } current = (char*)strstr( current, "[" ); } } // Now that we have cleaned-up the expression, let's compare it to the content // of the leaf! res = ParseWithLeaf(leaf,leftover,final,paran_level,castqueue,useLeafCollectionObject,name); if (res<0) return res; if (res>0) action = res; return code; } //*-*- May be a graphical cut ? TCutG *gcut = (TCutG*)gROOT->GetListOfSpecials()->FindObject(name.Data()); if (gcut) { if (gcut->GetObjectX()) { if(!gcut->GetObjectX()->InheritsFrom(TTreeFormula::Class())) { delete gcut->GetObjectX(); gcut->SetObjectX(0); } } if (gcut->GetObjectY()) { if(!gcut->GetObjectY()->InheritsFrom(TTreeFormula::Class())) { delete gcut->GetObjectY(); gcut->SetObjectY(0); } } Int_t code = fNcodes; if (strlen(gcut->GetVarX()) && strlen(gcut->GetVarY()) ) { TTreeFormula *fx = new TTreeFormula("f_x",gcut->GetVarX(),fTree); gcut->SetObjectX(fx); TTreeFormula *fy = new TTreeFormula("f_y",gcut->GetVarY(),fTree); gcut->SetObjectY(fy); fCodes[code] = -2; } else if (strlen(gcut->GetVarX())) { // Let's build the equivalent formula: // min(gcut->X) <= VarX <= max(gcut->Y) Double_t min = 0; Double_t max = 0; Int_t n = gcut->GetN(); Double_t *x = gcut->GetX(); min = max = x[0]; for(Int_t i2 = 1; i2<n; i2++) { if (x[i2] < min) min = x[i2]; if (x[i2] > max) max = x[i2]; } TString formula = "("; formula += min; formula += "<="; formula += gcut->GetVarX(); formula += " && "; formula += gcut->GetVarX(); formula += "<="; formula += max; formula += ")"; TTreeFormula *fx = new TTreeFormula("f_x",formula.Data(),fTree); gcut->SetObjectX(fx); fCodes[code] = -1; } else { Error("DefinedVariable","Found a TCutG without leaf information (%s)", gcut->GetName()); return -1; } fExternalCuts.AddAtAndExpand(gcut,code); fNcodes++; fLookupType[code] = -1; return code; } //may be an entrylist TEntryList *elist = dynamic_cast<TEntryList*> (gDirectory->Get(name.Data())); if (elist) { Int_t code = fNcodes; fCodes[code] = 0; fExternalCuts.AddAtAndExpand(elist, code); fNcodes++; fLookupType[code] = kEntryList; return code; } return -1; } //______________________________________________________________________________ TLeaf* TTreeFormula::GetLeafWithDatamember(const char* topchoice, const char* nextchoice, Long64_t readentry) const { // Return the leaf (if any) which contains an object containing // a data member which has the name provided in the arguments. TClass * cl = 0; TIter nextleaf (fTree->GetIteratorOnAllLeaves()); TFormLeafInfo* clonesinfo = 0; TLeaf *leafcur; while ((leafcur = (TLeaf*)nextleaf())) { // The following code is used somewhere else, we need to factor it out. // Here since we are interested in data member, we want to consider only // 'terminal' branch and leaf. cl = 0; if (leafcur->InheritsFrom(TLeafObject::Class()) && leafcur->GetBranch()->GetListOfBranches()->Last()==0) { TLeafObject *lobj = (TLeafObject*)leafcur; cl = lobj->GetClass(); } else if (leafcur->InheritsFrom(TLeafElement::Class()) && leafcur->IsOnTerminalBranch()) { TLeafElement * lElem = (TLeafElement*) leafcur; if (lElem->IsOnTerminalBranch()) { TBranchElement *branchEl = (TBranchElement *)leafcur->GetBranch(); Int_t type = branchEl->GetStreamerType(); if (type==-1) { cl = branchEl->GetInfo()->GetClass(); } else if (type>60 || type==0) { // Case of an object data member. Here we allow for the // variable name to be ommitted. Eg, for Event.root with split // level 1 or above Draw("GetXaxis") is the same as Draw("fH.GetXaxis()") TStreamerElement* element = (TStreamerElement*) branchEl->GetInfo()->GetElems()[branchEl->GetID()]; if (element) cl = element->GetClassPointer(); else cl = 0; } } } if (clonesinfo) { delete clonesinfo; clonesinfo = 0; } if (cl == TClonesArray::Class()) { // We have a unsplit TClonesArray leaves // In this case we assume that cl is the class in which the TClonesArray // belongs. R__LoadBranch(leafcur->GetBranch(),readentry,fQuickLoad); TClonesArray * clones; TBranch *branch = leafcur->GetBranch(); if ( branch->IsA()==TBranchElement::Class() && ((TBranchElement*)branch)->GetType()==31) { // We have an unsplit TClonesArray as part of a split TClonesArray! // Let's not dig any further. If the user really wants a data member // inside the nested TClonesArray, it has to specify it explicitly. continue; } else { Bool_t toplevel = (branch == branch->GetMother()); clonesinfo = new TFormLeafInfoClones(cl, 0, toplevel); clones = (TClonesArray*)clonesinfo->GetLocalValuePointer(leafcur,0); } if (clones) cl = clones->GetClass(); } else if (cl && cl->GetCollectionProxy()) { // We have a unsplit Collection leaves // In this case we assume that cl is the class in which the TClonesArray // belongs. TBranch *branch = leafcur->GetBranch(); if ( branch->IsA()==TBranchElement::Class() && ((TBranchElement*)branch)->GetType()==41) { // We have an unsplit Collection as part of a split Collection! // Let's not dig any further. If the user really wants a data member // inside the nested Collection, it has to specify it explicitly. continue; } else { clonesinfo = new TFormLeafInfoCollection(cl, 0); } cl = cl->GetCollectionProxy()->GetValueClass(); } if (cl) { // Now that we have the class, let's check if the topchoice is of its datamember // or if the nextchoice is a datamember of one of its datamember. Int_t offset; TStreamerInfo* info = (TStreamerInfo*)cl->GetStreamerInfo(); TStreamerElement* element = info?info->GetStreamerElement(topchoice,offset):0; if (!element) { TIter nextel( cl->GetStreamerInfo()->GetElements() ); TStreamerElement * curelem; while ((curelem = (TStreamerElement*)nextel())) { if (curelem->GetClassPointer() == TClonesArray::Class()) { // In case of a TClonesArray we need to load the data and read the // clonesArray object before being able to look into the class inside. // We need to do that because we are never interested in the TClonesArray // itself but only in the object inside. TBranch *branch = leafcur->GetBranch(); TFormLeafInfo *leafinfo = 0; if (clonesinfo) { leafinfo = clonesinfo; } else if (branch->IsA()==TBranchElement::Class() && ((TBranchElement*)branch)->GetType()==31) { // Case of a sub branch of a TClonesArray TBranchElement *branchEl = (TBranchElement*)branch; TStreamerInfo *bel_info = branchEl->GetInfo(); TClass * mother_cl = ((TBranchElement*)branch)->GetInfo()->GetClass(); TStreamerElement *bel_element = (TStreamerElement *)bel_info->GetElems()[branchEl->GetID()]; leafinfo = new TFormLeafInfoClones(mother_cl, 0, bel_element, kTRUE); } Int_t clones_offset = 0; ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(curelem->GetName(),clones_offset); TFormLeafInfo* sub_clonesinfo = new TFormLeafInfo(cl, clones_offset, curelem); if (leafinfo) if (leafinfo->fNext) leafinfo->fNext->fNext = sub_clonesinfo; else leafinfo->fNext = sub_clonesinfo; else leafinfo = sub_clonesinfo; R__LoadBranch(branch,readentry,fQuickLoad); TClonesArray * clones = (TClonesArray*)leafinfo->GetValuePointer(leafcur,0); delete leafinfo; clonesinfo = 0; // If TClonesArray object does not exist we have no information, so let go // on. This is a weakish test since the TClonesArray object might exist in // the next entry ... In other word, we ONLY rely on the information available // in entry #0. if (!clones) continue; TClass *sub_cl = clones->GetClass(); // Now that we finally have the inside class, let's query it. element = ((TStreamerInfo*)sub_cl->GetStreamerInfo())->GetStreamerElement(nextchoice,offset); if (element) break; } // if clones array else if (curelem->GetClassPointer() && curelem->GetClassPointer()->GetCollectionProxy()) { TClass *sub_cl = curelem->GetClassPointer()->GetCollectionProxy()->GetValueClass(); while(sub_cl && sub_cl->GetCollectionProxy()) sub_cl = sub_cl->GetCollectionProxy()->GetValueClass(); // Now that we finally have the inside class, let's query it. if (sub_cl) element = ((TStreamerInfo*)sub_cl->GetStreamerInfo())->GetStreamerElement(nextchoice,offset); if (element) break; } } // loop on elements } if (element) break; else cl = 0; } } delete clonesinfo; if (cl) { return leafcur; } else { return 0; } } //______________________________________________________________________________ Bool_t TTreeFormula::BranchHasMethod(TLeaf* leafcur, TBranch* branch, const char* method, const char* params, Long64_t readentry) const { // Return the leaf (if any) of the tree with contains an object of a class // having a method which has the name provided in the argument. TClass *cl = 0; TLeafObject* lobj = 0; // Since the user does not want this branch to be loaded anyway, we just // skip it. This prevents us from warning the user that the method might // be on a disabled branch. However, and more usefully, this allows the // user to avoid error messages from branches that cannot be currently // read without warnings/errors. if (branch->TestBit(kDoNotProcess)) { return kFALSE; } // FIXME: The following code is used somewhere else, we need to factor it out. if (branch->InheritsFrom(TBranchObject::Class())) { lobj = (TLeafObject*) branch->GetListOfLeaves()->At(0); cl = lobj->GetClass(); } else if (branch->InheritsFrom(TBranchElement::Class())) { TBranchElement* branchEl = (TBranchElement*) branch; Int_t type = branchEl->GetStreamerType(); if (type == -1) { cl = branchEl->GetInfo()->GetClass(); } else if (type > 60) { // Case of an object data member. Here we allow for the // variable name to be ommitted. Eg, for Event.root with split // level 1 or above Draw("GetXaxis") is the same as Draw("fH.GetXaxis()") TStreamerElement* element = (TStreamerElement*) branchEl->GetInfo()->GetElems()[branchEl->GetID()]; if (element) { cl = element->GetClassPointer(); } else { cl = 0; } if ((cl == TClonesArray::Class()) && (branchEl->GetType() == 31)) { // we have a TClonesArray inside a split TClonesArray, // Let's not dig any further. If the user really wants a data member // inside the nested TClonesArray, it has to specify it explicitly. cl = 0; } // NOTE do we need code for Collection here? } } if (cl == TClonesArray::Class()) { // We might be try to call a method of the top class inside a // TClonesArray. // Since the leaf was not terminal, we might have a split or // unsplit and/or top leaf/branch. TClonesArray* clones = 0; R__LoadBranch(branch, readentry, fQuickLoad); if (branch->InheritsFrom(TBranchObject::Class())) { clones = (TClonesArray*) lobj->GetObject(); } else if (branch->InheritsFrom(TBranchElement::Class())) { // We do not know exactly where the leaf of the TClonesArray is // in the hierachy but we still need to get the correct class // holder. TBranchElement* bc = (TBranchElement*) branch; if (bc == bc->GetMother()) { // Top level branch //clones = *((TClonesArray**) bc->GetAddress()); clones = (TClonesArray*) bc->GetObject(); } else if (!leafcur || !leafcur->IsOnTerminalBranch()) { TStreamerElement* element = (TStreamerElement*) bc->GetInfo()->GetElems()[bc->GetID()]; if (element->IsaPointer()) { clones = *((TClonesArray**) bc->GetAddress()); //clones = *((TClonesArray**) bc->GetObject()); } else { //clones = (TClonesArray*) bc->GetAddress(); clones = (TClonesArray*) bc->GetObject(); } } if (!clones) { R__LoadBranch(bc, readentry, fQuickLoad); TClass* mother_cl; mother_cl = bc->GetInfo()->GetClass(); TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(mother_cl, 0); // if (!leafcur) { leafcur = (TLeaf*) branch->GetListOfLeaves()->At(0); } clones = (TClonesArray*) clonesinfo->GetLocalValuePointer(leafcur, 0); // cl = clones->GetClass(); delete clonesinfo; } } else { Error("BranchHasMethod","A TClonesArray was stored in a branch type no yet support (i.e. neither TBranchObject nor TBranchElement): %s",branch->IsA()->GetName()); return kFALSE; } cl = clones ? clones->GetClass() : 0; } else if (cl && cl->GetCollectionProxy()) { cl = cl->GetCollectionProxy()->GetValueClass(); } if (cl) { if (cl->GetClassInfo()) { if (cl->GetMethodAllAny(method)) { // Let's try to see if the function we found belongs to the current // class. Note that this implementation currently can not work if // one the argument is another leaf or data member of the object. // (Anyway we do NOT support this case). TMethodCall* methodcall = new TMethodCall(cl, method, params); if (methodcall->GetMethod()) { // We have a method that works. // We will use it. return kTRUE; } delete methodcall; } } } return kFALSE; } //______________________________________________________________________________ Int_t TTreeFormula::GetRealInstance(Int_t instance, Int_t codeindex) { // Now let calculate what physical instance we really need. // Some redundant code is used to speed up the cases where // they are no dimensions. // We know that instance is less that fCumulUsedSize[0] so // we can skip the modulo when virt_dim is 0. Int_t real_instance = 0; Int_t virt_dim; Bool_t check = kFALSE; if (codeindex<0) { codeindex = 0; check = kTRUE; } TFormLeafInfo * info = 0; Int_t max_dim = fNdimensions[codeindex]; if ( max_dim ) { virt_dim = 0; max_dim--; if (!fManager->fMultiVarDim) { if (fIndexes[codeindex][0]>=0) { real_instance = fIndexes[codeindex][0] * fCumulSizes[codeindex][1]; } else { Int_t local_index; local_index = ( instance / fManager->fCumulUsedSizes[virt_dim+1]); if (fIndexes[codeindex][0]==-2) { // NOTE: Should we check that this is a valid index? if (check) { Int_t index_real_instance = fVarIndexes[codeindex][0]->GetRealInstance(local_index,-1); if (index_real_instance > fVarIndexes[codeindex][0]->fNdata[0]) { // out of bounds return fNdata[0]+1; } } if (fDidBooleanOptimization && local_index!=0) { // Force the loading of the index. fVarIndexes[codeindex][0]->LoadBranches(); } local_index = (Int_t)fVarIndexes[codeindex][0]->EvalInstance(local_index); if (local_index<0) { Error("EvalInstance","Index %s is out of bound (%d) in formula %s", fVarIndexes[codeindex][0]->GetTitle(), local_index, GetTitle()); return fNdata[0]+1; } } real_instance = local_index * fCumulSizes[codeindex][1]; virt_dim ++; } } else { // NOTE: We assume that ONLY the first dimension of a leaf can have a variable // size AND contain the index for the size of yet another sub-dimension. // I.e. a variable size array inside a variable size array can only have its // size vary with the VERY FIRST physical dimension of the leaf. // Thus once the index of the first dimension is found, all other dimensions // are fixed! // NOTE: We could unroll some of this loops to avoid a few tests. if (fHasMultipleVarDim[codeindex]) { info = (TFormLeafInfo *)(fDataMembers.At(codeindex)); // if (info && info->GetVarDim()==-1) info = 0; } Int_t local_index; switch (fIndexes[codeindex][0]) { case -2: if (fDidBooleanOptimization && instance!=0) { // Force the loading of the index. fVarIndexes[codeindex][0]->LoadBranches(); } local_index = (Int_t)fVarIndexes[codeindex][0]->EvalInstance(instance); if (local_index<0) { Error("EvalInstance","Index %s is out of bound (%d) in formula %s", fVarIndexes[codeindex][0]->GetTitle(), local_index, GetTitle()); local_index = 0; } break; case -1: { local_index = 0; Int_t virt_accum = 0; Int_t maxloop = fManager->fCumulUsedVarDims->GetSize(); if (maxloop == 0) { local_index--; instance = fNdata[0]+1; // out of bounds. if (check) return fNdata[0]+1; } else { do { virt_accum += fManager->fCumulUsedVarDims->GetArray()[local_index]; local_index++; } while( instance >= virt_accum && local_index<maxloop); if (local_index==maxloop && (instance >= virt_accum)) { local_index--; instance = fNdata[0]+1; // out of bounds. if (check) return fNdata[0]+1; } else { local_index--; if (fManager->fCumulUsedVarDims->At(local_index)) { instance -= (virt_accum - fManager->fCumulUsedVarDims->At(local_index)); } else { instance = fNdata[0]+1; // out of bounds. if (check) return fNdata[0]+1; } } } virt_dim ++; } break; default: local_index = fIndexes[codeindex][0]; } // Inform the (appropriate) MultiVarLeafInfo that the clones array index is // local_index. if (fManager->fVarDims[kMAXFORMDIM]) { fManager->fCumulUsedSizes[kMAXFORMDIM] = fManager->fVarDims[kMAXFORMDIM]->At(local_index); } else { fManager->fCumulUsedSizes[kMAXFORMDIM] = fManager->fUsedSizes[kMAXFORMDIM]; } for(Int_t d = kMAXFORMDIM-1; d>0; d--) { if (fManager->fVarDims[d]) { fManager->fCumulUsedSizes[d] = fManager->fCumulUsedSizes[d+1] * fManager->fVarDims[d]->At(local_index); } else { fManager->fCumulUsedSizes[d] = fManager->fCumulUsedSizes[d+1] * fManager->fUsedSizes[d]; } } if (info) { // When we have multiple variable dimensions, the LeafInfo only expect // the instance after the primary index has been set. info->SetPrimaryIndex(local_index); real_instance = 0; // Let's update fCumulSizes for the rest of the code. Int_t vdim = info->GetVarDim(); Int_t isize = info->GetSize(local_index); if (fIndexes[codeindex][vdim]>=0) { info->SetSecondaryIndex(fIndexes[codeindex][vdim]); } if (isize!=1 && fIndexes[codeindex][vdim]>isize) { // We are out of bounds! return fNdata[0]+1; } fCumulSizes[codeindex][vdim] = isize*fCumulSizes[codeindex][vdim+1]; for(Int_t k=vdim -1; k>0; --k) { fCumulSizes[codeindex][k] = fCumulSizes[codeindex][k+1]*fFixedSizes[codeindex][k]; } } else { real_instance = local_index * fCumulSizes[codeindex][1]; } } if (max_dim>0) { for (Int_t dim = 1; dim < max_dim; dim++) { if (fIndexes[codeindex][dim]>=0) { real_instance += fIndexes[codeindex][dim] * fCumulSizes[codeindex][dim+1]; } else { Int_t local_index; if (virt_dim && fManager->fCumulUsedSizes[virt_dim]>1) { local_index = ( ( instance % fManager->fCumulUsedSizes[virt_dim] ) / fManager->fCumulUsedSizes[virt_dim+1]); } else { local_index = ( instance / fManager->fCumulUsedSizes[virt_dim+1]); } if (fIndexes[codeindex][dim]==-2) { // NOTE: Should we check that this is a valid index? if (fDidBooleanOptimization && local_index!=0) { // Force the loading of the index. fVarIndexes[codeindex][dim]->LoadBranches(); } local_index = (Int_t)fVarIndexes[codeindex][dim]->EvalInstance(local_index); if (local_index<0 || local_index>=(fCumulSizes[codeindex][dim]/fCumulSizes[codeindex][dim+1])) { Error("EvalInstance","Index %s is out of bound (%d/%d) in formula %s", fVarIndexes[codeindex][dim]->GetTitle(), local_index, (fCumulSizes[codeindex][dim]/fCumulSizes[codeindex][dim+1]), GetTitle()); local_index = (fCumulSizes[codeindex][dim]/fCumulSizes[codeindex][dim+1])-1; } } real_instance += local_index * fCumulSizes[codeindex][dim+1]; virt_dim ++; } } if (fIndexes[codeindex][max_dim]>=0) { if (!info) real_instance += fIndexes[codeindex][max_dim]; } else { Int_t local_index; if (virt_dim && fManager->fCumulUsedSizes[virt_dim]>1) { local_index = instance % fManager->fCumulUsedSizes[virt_dim]; } else { local_index = instance; } if (info && local_index>=fCumulSizes[codeindex][max_dim]) { // We are out of bounds! [Multiple var dims, See same message a few line above] return fNdata[0]+1; } if (fIndexes[codeindex][max_dim]==-2) { if (fDidBooleanOptimization && local_index!=0) { // Force the loading of the index. fVarIndexes[codeindex][max_dim]->LoadBranches(); } local_index = (Int_t)fVarIndexes[codeindex][max_dim]->EvalInstance(local_index); if (local_index<0 || local_index>=fCumulSizes[codeindex][max_dim]) { Error("EvalInstance","Index %s is of out bound (%d/%d) in formula %s", fVarIndexes[codeindex][max_dim]->GetTitle(), local_index, fCumulSizes[codeindex][max_dim], GetTitle()); local_index = fCumulSizes[codeindex][max_dim]-1; } } real_instance += local_index; } } // if (max_dim-1>0) } // if (max_dim) return real_instance; } //______________________________________________________________________________ TClass* TTreeFormula::EvalClass() const { // Evaluate the class of this treeformula // // If the 'value' of this formula is a simple pointer to an object, // this function returns the TClass corresponding to its type. if (fNoper != 1 || fNcodes <=0 ) return 0; return EvalClass(0); } //______________________________________________________________________________ TClass* TTreeFormula::EvalClass(Int_t oper) const { // Evaluate the class of the operation oper // // If the 'value' in the requested operation is a simple pointer to an object, // this function returns the TClass corresponding to its type. TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(oper); switch(fLookupType[oper]) { case kDirect: { if (leaf->IsA()==TLeafObject::Class()) { return ((TLeafObject*)leaf)->GetClass(); } else if ( leaf->IsA()==TLeafElement::Class()) { TBranchElement * branch = (TBranchElement*)((TLeafElement*)leaf)->GetBranch(); TStreamerInfo * info = branch->GetInfo(); Int_t id = branch->GetID(); if (id>=0) { if (info==0 || info->GetElems()==0) { // we probably do not have a way to know the class of the object. return 0; } TStreamerElement* elem = (TStreamerElement*)info->GetElems()[id]; if (elem==0) { // we probably do not have a way to know the class of the object. return 0; } else { return elem->GetClass(); } } else return TClass::GetClass( branch->GetClassName() ); } else { return 0; } } case kMethod: return 0; // kMethod is deprecated so let's no waste time implementing this. case kTreeMember: case kDataMember: { TObject *obj = fDataMembers.UncheckedAt(oper); if (!obj) return 0; return ((TFormLeafInfo*)obj)->GetClass(); } default: return 0; } } //______________________________________________________________________________ void* TTreeFormula::EvalObject(int instance) { //*-*-*-*-*-*-*-*-*-*-*Evaluate this treeformula*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================= // // Return the address of the object pointed to by the formula. // Return 0 if the formula is not a single object // The object type can be retrieved using by call EvalClass(); if (fNoper != 1 || fNcodes <=0 ) return 0; switch (fLookupType[0]) { case kIndexOfEntry: case kIndexOfLocalEntry: case kEntries: case kLength: case kLengthFunc: case kIteration: case kEntryList: return 0; } TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); Int_t real_instance = GetRealInstance(instance,0); if (instance==0 || fNeedLoading) { fNeedLoading = kFALSE; R__LoadBranch(leaf->GetBranch(), leaf->GetBranch()->GetTree()->GetReadEntry(), fQuickLoad); } else if (real_instance>fNdata[0]) return 0; if (fAxis) { return 0; } switch(fLookupType[0]) { case kDirect: { if (real_instance) { Warning("EvalObject","Not yet implement for kDirect and arrays (for %s).\nPlease contact the developers",GetName()); } return leaf->GetValuePointer(); } case kMethod: return GetValuePointerFromMethod(0,leaf); case kTreeMember: case kDataMember: return ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->GetValuePointer(leaf,real_instance); default: return 0; } } //______________________________________________________________________________ const char* TTreeFormula::EvalStringInstance(Int_t instance) { // Eval the instance as a string. const Int_t kMAXSTRINGFOUND = 10; const char *stringStack[kMAXSTRINGFOUND]; if (fNoper==1 && fNcodes>0 && IsString()) { TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); Int_t real_instance = GetRealInstance(instance,0); if (instance==0 || fNeedLoading) { fNeedLoading = kFALSE; TBranch *branch = leaf->GetBranch(); R__LoadBranch(branch,branch->GetTree()->GetReadEntry(),fQuickLoad); } else if (real_instance>=fNdata[0]) { return 0; } if (fLookupType[0]==kDirect) { return (char*)leaf->GetValuePointer(); } else { return (char*)GetLeafInfo(0)->GetValuePointer(leaf,real_instance); } } EvalInstance(instance,stringStack); return stringStack[0]; } #define TT_EVAL_INIT \ TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); \ \ const Int_t real_instance = GetRealInstance(instance,0); \ \ if (instance==0) fNeedLoading = kTRUE; \ if (real_instance>fNdata[0]) return 0; \ \ /* Since the only operation in this formula is reading this branch, \ we are guaranteed that this function is first called with instance==0 and \ hence we are guaranteed that the branch is always properly read */ \ \ if (fNeedLoading) { \ fNeedLoading = kFALSE; \ TBranch *br = leaf->GetBranch(); \ Long64_t tentry = br->GetTree()->GetReadEntry(); \ R__LoadBranch(br,tentry,fQuickLoad); \ } \ \ if (fAxis) { \ char * label; \ /* This portion is a duplicate (for speed reason) of the code \ located in the main for loop at "a tree string" (and in EvalStringInstance) */ \ if (fLookupType[0]==kDirect) { \ label = (char*)leaf->GetValuePointer(); \ } else { \ label = (char*)GetLeafInfo(0)->GetValuePointer(leaf,instance); \ } \ Int_t bin = fAxis->FindBin(label); \ return bin-0.5; \ } #define TREE_EVAL_INIT \ const Int_t real_instance = GetRealInstance(instance,0); \ \ if (real_instance>fNdata[0]) return 0; \ \ if (fAxis) { \ char * label; \ /* This portion is a duplicate (for speed reason) of the code \ located in the main for loop at "a tree string" (and in EvalStringInstance) */ \ label = (char*)GetLeafInfo(0)->GetValuePointer((TLeaf*)0x0,instance); \ Int_t bin = fAxis->FindBin(label); \ return bin-0.5; \ } #define TT_EVAL_INIT_LOOP \ TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(code); \ \ /* Now let calculate what physical instance we really need. */ \ const Int_t real_instance = GetRealInstance(instance,code); \ \ if (willLoad) { \ TBranch *branch = (TBranch*)fBranches.UncheckedAt(code); \ if (branch) { \ Long64_t treeEntry = branch->GetTree()->GetReadEntry(); \ R__LoadBranch(branch,treeEntry,fQuickLoad); \ } else if (fDidBooleanOptimization) { \ branch = leaf->GetBranch(); \ Long64_t treeEntry = branch->GetTree()->GetReadEntry(); \ if (branch->GetReadEntry() != treeEntry) branch->GetEntry( treeEntry ); \ } \ } else { \ /* In the cases where we are behind (i.e. right of) a potential boolean optimization \ this tree variable reading may have not been executed with instance==0 which would \ result in the branch being potentially not read in. */ \ if (fDidBooleanOptimization) { \ TBranch *br = leaf->GetBranch(); \ Long64_t treeEntry = br->GetTree()->GetReadEntry(); \ if (br->GetReadEntry() != treeEntry) br->GetEntry( treeEntry ); \ } \ } \ if (real_instance>fNdata[code]) return 0; #define TREE_EVAL_INIT_LOOP \ /* Now let calculate what physical instance we really need. */ \ const Int_t real_instance = GetRealInstance(instance,code); \ \ if (real_instance>fNdata[code]) return 0; namespace { Double_t Summing(TTreeFormula *sum) { Int_t len = sum->GetNdata(); Double_t res = 0; for (int i=0; i<len; ++i) res += sum->EvalInstance(i); return res; } Double_t FindMin(TTreeFormula *arr) { Int_t len = arr->GetNdata(); Double_t res = 0; if (len) { res = arr->EvalInstance(0); for (int i=1; i<len; ++i) { Double_t val = arr->EvalInstance(i); if (val < res) { res = val; } } } return res; } Double_t FindMax(TTreeFormula *arr) { Int_t len = arr->GetNdata(); Double_t res = 0; if (len) { res = arr->EvalInstance(0); for (int i=1; i<len; ++i) { Double_t val = arr->EvalInstance(i); if (val > res) { res = val; } } } return res; } Double_t FindMin(TTreeFormula *arr, TTreeFormula *condition) { Int_t len = arr->GetNdata(); Double_t res = 0; if (len) { int i = 0; Double_t condval; do { condval = condition->EvalInstance(i); ++i; } while (!condval && i<len); if (i==len) { return 0; } if (i!=1) { // Insure the loading of the branch. arr->EvalInstance(0); } // Now we know that i>0 && i<len and cond==true res = arr->EvalInstance(i-1); for (; i<len; ++i) { condval = condition->EvalInstance(i); if (condval) { Double_t val = arr->EvalInstance(i); if (val < res) { res = val; } } } } return res; } Double_t FindMax(TTreeFormula *arr, TTreeFormula *condition) { Int_t len = arr->GetNdata(); Double_t res = 0; if (len) { int i = 0; Double_t condval; do { condval = condition->EvalInstance(i); ++i; } while (!condval && i<len); if (i==len) { return 0; } if (i!=1) { // Insure the loading of the branch. arr->EvalInstance(0); } // Now we know that i>0 && i<len and cond==true res = arr->EvalInstance(i-1); for (; i<len; ++i) { condval = condition->EvalInstance(i); if (condval) { Double_t val = arr->EvalInstance(i); if (val > res) { res = val; } } } } return res; } } //______________________________________________________________________________ Double_t TTreeFormula::EvalInstance(Int_t instance, const char *stringStackArg[]) { //*-*-*-*-*-*-*-*-*-*-*Evaluate this treeformula*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================= // // Note that the redundance and structure in this code is tailored to improve // efficiencies. if (TestBit(kMissingLeaf)) return 0; if (fNoper == 1 && fNcodes > 0) { switch (fLookupType[0]) { case kDirect: { TT_EVAL_INIT; Double_t result = leaf->GetValue(real_instance); return result; } case kMethod: { TT_EVAL_INIT; ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->SetBranch(leaf->GetBranch()); return GetValueFromMethod(0,leaf); } case kDataMember: { TT_EVAL_INIT; ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->SetBranch(leaf->GetBranch()); return ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->GetValue(leaf,real_instance); } case kTreeMember: { TREE_EVAL_INIT; return ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->GetValue((TLeaf*)0x0,real_instance); } case kIndexOfEntry: return (Double_t)fTree->GetReadEntry(); case kIndexOfLocalEntry: return (Double_t)fTree->GetTree()->GetReadEntry(); case kEntries: return (Double_t)fTree->GetEntries(); case kLength: return fManager->fNdata; case kLengthFunc: return ((TTreeFormula*)fAliases.UncheckedAt(0))->GetNdata(); case kIteration: return instance; case kSum: return Summing((TTreeFormula*)fAliases.UncheckedAt(0)); case kMin: return FindMin((TTreeFormula*)fAliases.UncheckedAt(0)); case kMax: return FindMax((TTreeFormula*)fAliases.UncheckedAt(0)); case kEntryList: { TEntryList *elist = (TEntryList*)fExternalCuts.At(0); return elist->Contains(fTree->GetTree()->GetReadEntry()); } case -1: break; } switch (fCodes[0]) { case -2: { TCutG *gcut = (TCutG*)fExternalCuts.At(0); TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); TTreeFormula *fy = (TTreeFormula *)gcut->GetObjectY(); Double_t xcut = fx->EvalInstance(instance); Double_t ycut = fy->EvalInstance(instance); return gcut->IsInside(xcut,ycut); } case -1: { TCutG *gcut = (TCutG*)fExternalCuts.At(0); TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); return fx->EvalInstance(instance); } default: return 0; } } Double_t tab[kMAXFOUND]; const Int_t kMAXSTRINGFOUND = 10; const char *stringStackLocal[kMAXSTRINGFOUND]; const char **stringStack = stringStackArg?stringStackArg:stringStackLocal; const Bool_t willLoad = (instance==0 || fNeedLoading); fNeedLoading = kFALSE; if (willLoad) fDidBooleanOptimization = kFALSE; Int_t pos = 0; Int_t pos2 = 0; for (Int_t i=0; i<fNoper ; ++i) { const Int_t oper = GetOper()[i]; const Int_t newaction = oper >> kTFOperShift; if (newaction<kDefinedVariable) { // TFormula operands. // one of the most used cases if (newaction==kConstant) { pos++; tab[pos-1] = fConst[(oper & kTFOperMask)]; continue; } switch(newaction) { case kEnd : return tab[0]; case kAdd : pos--; tab[pos-1] += tab[pos]; continue; case kSubstract : pos--; tab[pos-1] -= tab[pos]; continue; case kMultiply : pos--; tab[pos-1] *= tab[pos]; continue; case kDivide : pos--; if (tab[pos] == 0) tab[pos-1] = 0; // division by 0 else tab[pos-1] /= tab[pos]; continue; case kModulo : {pos--; Long64_t int1((Long64_t)tab[pos-1]); Long64_t int2((Long64_t)tab[pos]); tab[pos-1] = Double_t(int1%int2); continue;} case kcos : tab[pos-1] = TMath::Cos(tab[pos-1]); continue; case ksin : tab[pos-1] = TMath::Sin(tab[pos-1]); continue; case ktan : if (TMath::Cos(tab[pos-1]) == 0) {tab[pos-1] = 0;} // { tangente indeterminee } else tab[pos-1] = TMath::Tan(tab[pos-1]); continue; case kacos : if (TMath::Abs(tab[pos-1]) > 1) {tab[pos-1] = 0;} // indetermination else tab[pos-1] = TMath::ACos(tab[pos-1]); continue; case kasin : if (TMath::Abs(tab[pos-1]) > 1) {tab[pos-1] = 0;} // indetermination else tab[pos-1] = TMath::ASin(tab[pos-1]); continue; case katan : tab[pos-1] = TMath::ATan(tab[pos-1]); continue; case kcosh : tab[pos-1] = TMath::CosH(tab[pos-1]); continue; case ksinh : tab[pos-1] = TMath::SinH(tab[pos-1]); continue; case ktanh : if (TMath::CosH(tab[pos-1]) == 0) {tab[pos-1] = 0;} // { tangente indeterminee } else tab[pos-1] = TMath::TanH(tab[pos-1]); continue; case kacosh: if (tab[pos-1] < 1) {tab[pos-1] = 0;} // indetermination else tab[pos-1] = TMath::ACosH(tab[pos-1]); continue; case kasinh: tab[pos-1] = TMath::ASinH(tab[pos-1]); continue; case katanh: if (TMath::Abs(tab[pos-1]) > 1) {tab[pos-1] = 0;} // indetermination else tab[pos-1] = TMath::ATanH(tab[pos-1]); continue; case katan2: pos--; tab[pos-1] = TMath::ATan2(tab[pos-1],tab[pos]); continue; case kfmod : pos--; tab[pos-1] = fmod(tab[pos-1],tab[pos]); continue; case kpow : pos--; tab[pos-1] = TMath::Power(tab[pos-1],tab[pos]); continue; case ksq : tab[pos-1] = tab[pos-1]*tab[pos-1]; continue; case ksqrt : tab[pos-1] = TMath::Sqrt(TMath::Abs(tab[pos-1])); continue; case kstrstr : pos2 -= 2; pos++;if (strstr(stringStack[pos2],stringStack[pos2+1])) tab[pos-1]=1; else tab[pos-1]=0; continue; case kmin : pos--; tab[pos-1] = TMath::Min(tab[pos-1],tab[pos]); continue; case kmax : pos--; tab[pos-1] = TMath::Max(tab[pos-1],tab[pos]); continue; case klog : if (tab[pos-1] > 0) tab[pos-1] = TMath::Log(tab[pos-1]); else {tab[pos-1] = 0;} //{indetermination } continue; case kexp : { Double_t dexp = tab[pos-1]; if (dexp < -700) {tab[pos-1] = 0; continue;} if (dexp > 700) {tab[pos-1] = TMath::Exp(700); continue;} tab[pos-1] = TMath::Exp(dexp); continue; } case klog10: if (tab[pos-1] > 0) tab[pos-1] = TMath::Log10(tab[pos-1]); else {tab[pos-1] = 0;} //{indetermination } continue; case kpi : pos++; tab[pos-1] = TMath::ACos(-1); continue; case kabs : tab[pos-1] = TMath::Abs(tab[pos-1]); continue; case ksign : if (tab[pos-1] < 0) tab[pos-1] = -1; else tab[pos-1] = 1; continue; case kint : tab[pos-1] = Double_t(Int_t(tab[pos-1])); continue; case kSignInv: tab[pos-1] = -1 * tab[pos-1]; continue; case krndm : pos++; tab[pos-1] = gRandom->Rndm(1); continue; case kAnd : pos--; if (tab[pos-1]!=0 && tab[pos]!=0) tab[pos-1]=1; else tab[pos-1]=0; continue; case kOr : pos--; if (tab[pos-1]!=0 || tab[pos]!=0) tab[pos-1]=1; else tab[pos-1]=0; continue; case kEqual : pos--; tab[pos-1] = (tab[pos-1] == tab[pos]) ? 1 : 0; continue; case kNotEqual : pos--; tab[pos-1] = (tab[pos-1] != tab[pos]) ? 1 : 0; continue; case kLess : pos--; tab[pos-1] = (tab[pos-1] < tab[pos]) ? 1 : 0; continue; case kGreater : pos--; tab[pos-1] = (tab[pos-1] > tab[pos]) ? 1 : 0; continue; case kLessThan : pos--; tab[pos-1] = (tab[pos-1] <= tab[pos]) ? 1 : 0; continue; case kGreaterThan: pos--; tab[pos-1] = (tab[pos-1] >= tab[pos]) ? 1 : 0; continue; case kNot : tab[pos-1] = (tab[pos-1] != 0) ? 0 : 1; continue; case kStringEqual : pos2 -= 2; pos++; if (!strcmp(stringStack[pos2+1],stringStack[pos2])) tab[pos-1]=1; else tab[pos-1]=0; continue; case kStringNotEqual: pos2 -= 2; pos++;if (strcmp(stringStack[pos2+1],stringStack[pos2])) tab[pos-1]=1; else tab[pos-1]=0; continue; case kBitAnd : pos--; tab[pos-1]= ((Long64_t) tab[pos-1]) & ((Long64_t) tab[pos]); continue; case kBitOr : pos--; tab[pos-1]= ((Long64_t) tab[pos-1]) | ((Long64_t) tab[pos]); continue; case kLeftShift : pos--; tab[pos-1]= ((Long64_t) tab[pos-1]) <<((Long64_t) tab[pos]); continue; case kRightShift: pos--; tab[pos-1]= ((Long64_t) tab[pos-1]) >>((Long64_t) tab[pos]); continue; case kJump : i = (oper & kTFOperMask); continue; case kJumpIf : { pos--; if (!tab[pos]) { i = (oper & kTFOperMask); // If we skip the left (true) side of the if statement we may, // skip some of the branch loading (since we remove duplicate branch // request (in TTreeFormula constructor) and so we need to force the // loading here. if (willLoad) fDidBooleanOptimization = kTRUE; } continue; } case kStringConst: { // String pos2++; stringStack[pos2-1] = (char*)fExpr[i].Data(); if (fAxis) { // See TT_EVAL_INIT Int_t bin = fAxis->FindBin(stringStack[pos2-1]); \ return bin; } continue; } case kBoolOptimize: { // boolean operation optimizer int param = (oper & kTFOperMask); Bool_t skip = kFALSE; int op = param % 10; // 1 is && , 2 is || if (op == 1 && (!tab[pos-1]) ) { // &&: skip the right part if the left part is already false skip = kTRUE; // Preserve the existing behavior (i.e. the result of a&&b is // either 0 or 1) tab[pos-1] = 0; } else if (op == 2 && tab[pos-1] ) { // ||: skip the right part if the left part is already true skip = kTRUE; // Preserve the existing behavior (i.e. the result of a||b is // either 0 or 1) tab[pos-1] = 1; } if (skip) { int toskip = param / 10; i += toskip; if (willLoad) fDidBooleanOptimization = kTRUE; } continue; } case kFunctionCall: { // an external function call int param = (oper & kTFOperMask); int fno = param / 1000; int nargs = param % 1000; // Retrieve the function TMethodCall *method = (TMethodCall*)fFunctions.At(fno); // Set the arguments method->ResetParam(); if (nargs) { UInt_t argloc = pos-nargs; for(Int_t j=0;j<nargs;j++,argloc++,pos--) { method->SetParam( tab[argloc] ); } } pos++; Double_t ret = 0; method->Execute(ret); tab[pos-1] = ret; // check for the correct conversion! continue; } // case kParameter: { pos++; tab[pos-1] = fParams[(oper & kTFOperMask)]; continue; } } } else { // TTreeFormula operands. // a tree variable (the most used case). if (newaction == kDefinedVariable) { const Int_t code = (oper & kTFOperMask); const Int_t lookupType = fLookupType[code]; switch (lookupType) { case kIndexOfEntry: tab[pos++] = (Double_t)fTree->GetReadEntry(); continue; case kIndexOfLocalEntry: tab[pos++] = (Double_t)fTree->GetTree()->GetReadEntry(); continue; case kEntries: tab[pos++] = (Double_t)fTree->GetEntries(); continue; case kLength: tab[pos++] = fManager->fNdata; continue; case kLengthFunc: tab[pos++] = ((TTreeFormula*)fAliases.UncheckedAt(i))->GetNdata(); continue; case kIteration: tab[pos++] = instance; continue; case kSum: tab[pos++] = Summing((TTreeFormula*)fAliases.UncheckedAt(i)); continue; case kMin: tab[pos++] = FindMin((TTreeFormula*)fAliases.UncheckedAt(i)); continue; case kMax: tab[pos++] = FindMax((TTreeFormula*)fAliases.UncheckedAt(i)); continue; case kDirect: { TT_EVAL_INIT_LOOP; tab[pos++] = leaf->GetValue(real_instance); continue; } case kMethod: { TT_EVAL_INIT_LOOP; tab[pos++] = GetValueFromMethod(code,leaf); continue; } case kDataMember: { TT_EVAL_INIT_LOOP; tab[pos++] = ((TFormLeafInfo*)fDataMembers.UncheckedAt(code))-> GetValue(leaf,real_instance); continue; } case kTreeMember: { TREE_EVAL_INIT_LOOP; tab[pos++] = ((TFormLeafInfo*)fDataMembers.UncheckedAt(code))-> GetValue((TLeaf*)0x0,real_instance); continue; } case kEntryList: { TEntryList *elist = (TEntryList*)fExternalCuts.At(code); tab[pos++] = elist->Contains(fTree->GetReadEntry()); continue;} case -1: break; default: tab[pos++] = 0; continue; } switch (fCodes[code]) { case -2: { TCutG *gcut = (TCutG*)fExternalCuts.At(code); TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); TTreeFormula *fy = (TTreeFormula *)gcut->GetObjectY(); Double_t xcut = fx->EvalInstance(instance); Double_t ycut = fy->EvalInstance(instance); tab[pos++] = gcut->IsInside(xcut,ycut); continue; } case -1: { TCutG *gcut = (TCutG*)fExternalCuts.At(code); TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); tab[pos++] = fx->EvalInstance(instance); continue; } default: { tab[pos++] = 0; continue; } } } switch(newaction) { // a TTree Variable Alias (i.e. a sub-TTreeFormula) case kAlias: { int aliasN = i; TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(aliasN)); R__ASSERT(subform); Double_t param = subform->EvalInstance(instance); tab[pos] = param; pos++; continue; } // a TTree Variable Alias String (i.e. a sub-TTreeFormula) case kAliasString: { int aliasN = i; TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(aliasN)); R__ASSERT(subform); pos2++; stringStack[pos2-1] = subform->EvalStringInstance(instance); continue; } case kMinIf: { int alternateN = i; TTreeFormula *primary = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN)); TTreeFormula *condition = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN+1)); Double_t param = FindMin(primary,condition); ++i; // skip the place holder for the condition tab[pos] = param; pos++; continue; } case kMaxIf: { int alternateN = i; TTreeFormula *primary = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN)); TTreeFormula *condition = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN+1)); Double_t param = FindMax(primary,condition); ++i; // skip the place holder for the condition tab[pos] = param; pos++; continue; } // a TTree Variable Alternate (i.e. a sub-TTreeFormula) case kAlternate: { int alternateN = i; TTreeFormula *primary = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN)); // First check whether we are in range for the primary formula if (instance < primary->GetNdata()) { Double_t param = primary->EvalInstance(instance); ++i; // skip the alternate value. tab[pos] = param; pos++; } else { // The primary is not in rancge, we will calculate the alternate value // via the next operation (which will be a intentional). // kAlias no operations } continue; } case kAlternateString: { int alternateN = i; TTreeFormula *primary = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN)); // First check whether we are in range for the primary formula if (instance < primary->GetNdata()) { pos2++; stringStack[pos2-1] = primary->EvalStringInstance(instance); ++i; // skip the alternate value. } else { // The primary is not in rancge, we will calculate the alternate value // via the next operation (which will be a kAlias). // intentional no operations } continue; } // a tree string case kDefinedString: { Int_t string_code = (oper & kTFOperMask); TLeaf *leafc = (TLeaf*)fLeaves.UncheckedAt(string_code); // Now let calculate what physical instance we really need. const Int_t real_instance = GetRealInstance(instance,string_code); if (instance==0 || fNeedLoading) { fNeedLoading = kFALSE; TBranch *branch = leafc->GetBranch(); Long64_t readentry = branch->GetTree()->GetReadEntry(); R__LoadBranch(branch,readentry,fQuickLoad); } else { // In the cases where we are behind (i.e. right of) a potential boolean optimization // this tree variable reading may have not been executed with instance==0 which would // result in the branch being potentially not read in. if (fDidBooleanOptimization) { TBranch *br = leafc->GetBranch(); Long64_t treeEntry = br->GetTree()->GetReadEntry(); R__LoadBranch(br,treeEntry,kTRUE); } if (real_instance>fNdata[string_code]) return 0; } pos2++; if (fLookupType[string_code]==kDirect) { stringStack[pos2-1] = (char*)leafc->GetValuePointer(); } else { stringStack[pos2-1] = (char*)GetLeafInfo(string_code)->GetValuePointer(leafc,real_instance); } continue; } } } R__ASSERT(i<fNoper); } Double_t result = tab[0]; return result; } //______________________________________________________________________________ TFormLeafInfo *TTreeFormula::GetLeafInfo(Int_t code) const { //*-*-*-*-*-*-*-*Return DataMember corresponding to code*-*-*-*-*-* //*-* ======================================= // // function called by TLeafObject::GetValue // with the value of fLookupType computed in TTreeFormula::DefinedVariable return (TFormLeafInfo *)fDataMembers.UncheckedAt(code); } //______________________________________________________________________________ TLeaf *TTreeFormula::GetLeaf(Int_t n) const { //*-*-*-*-*-*-*-*Return leaf corresponding to serial number n*-*-*-*-*-* //*-* ============================================ // return (TLeaf*)fLeaves.UncheckedAt(n); } //______________________________________________________________________________ TMethodCall *TTreeFormula::GetMethodCall(Int_t code) const { //*-*-*-*-*-*-*-*Return methodcall corresponding to code*-*-*-*-*-* //*-* ======================================= // // function called by TLeafObject::GetValue // with the value of fLookupType computed in TTreeFormula::DefinedVariable return (TMethodCall *)fMethods.UncheckedAt(code); } //______________________________________________________________________________ Int_t TTreeFormula::GetNdata() { //*-*-*-*-*-*-*-*Return number of available instances in the formula-*-*-*-*-*-* //*-* =================================================== // return fManager->GetNdata(); } //______________________________________________________________________________ Double_t TTreeFormula::GetValueFromMethod(Int_t i, TLeaf* leaf) const { // Return result of a leafobject method. TMethodCall* m = GetMethodCall(i); if (!m) { return 0.0; } void* thisobj = 0; if (leaf->InheritsFrom(TLeafObject::Class())) { thisobj = ((TLeafObject*) leaf)->GetObject(); } else { TBranchElement* branch = (TBranchElement*) ((TLeafElement*) leaf)->GetBranch(); Int_t id = branch->GetID(); // FIXME: This is wrong for a top-level branch. Int_t offset = 0; if (id > -1) { TStreamerInfo* info = branch->GetInfo(); if (info) { offset = info->GetOffsets()[id]; } else { Warning("GetValueFromMethod", "No streamer info for branch %s.", branch->GetName()); } } if (id < 0) { char* address = branch->GetObject(); thisobj = address; } else { //char* address = branch->GetAddress(); char* address = branch->GetObject(); if (address) { thisobj = *((char**) (address + offset)); } else { // FIXME: If the address is not set, the object won't be either! thisobj = branch->GetObject(); } } } TMethodCall::EReturnType r = m->ReturnType(); if (r == TMethodCall::kLong) { Long_t l = 0; m->Execute(thisobj, l); return (Double_t) l; } if (r == TMethodCall::kDouble) { Double_t d = 0.0; m->Execute(thisobj, d); return d; } m->Execute(thisobj); return 0; } //______________________________________________________________________________ void* TTreeFormula::GetValuePointerFromMethod(Int_t i, TLeaf* leaf) const { // Return result of a leafobject method. TMethodCall* m = GetMethodCall(i); if (!m) { return 0; } void* thisobj; if (leaf->InheritsFrom(TLeafObject::Class())) { thisobj = ((TLeafObject*) leaf)->GetObject(); } else { TBranchElement* branch = (TBranchElement*) ((TLeafElement*) leaf)->GetBranch(); Int_t id = branch->GetID(); Int_t offset = 0; if (id > -1) { TStreamerInfo* info = branch->GetInfo(); if (info) { offset = info->GetOffsets()[id]; } else { Warning("GetValuePointerFromMethod", "No streamer info for branch %s.", branch->GetName()); } } if (id < 0) { char* address = branch->GetObject(); thisobj = address; } else { //char* address = branch->GetAddress(); char* address = branch->GetObject(); if (address) { thisobj = *((char**) (address + offset)); } else { // FIXME: If the address is not set, the object won't be either! thisobj = branch->GetObject(); } } } TMethodCall::EReturnType r = m->ReturnType(); if (r == TMethodCall::kLong) { Long_t l = 0; m->Execute(thisobj, l); return 0; } if (r == TMethodCall::kDouble) { Double_t d = 0.0; m->Execute(thisobj, d); return 0; } if (r == TMethodCall::kOther) { char* c = 0; m->Execute(thisobj, &c); return c; } m->Execute(thisobj); return 0; } //______________________________________________________________________________ Bool_t TTreeFormula::IsInteger(Bool_t fast) const { // return TRUE if the formula corresponds to one single Tree leaf // and this leaf is short, int or unsigned short, int // When a leaf is of type integer or string, the generated histogram is forced // to have an integer bin width if (fast) { if (TestBit(kIsInteger)) return kTRUE; else return kFALSE; } if (fNoper==2 && GetAction(0)==kAlternate) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); return subform->IsInteger(kFALSE); } if (GetAction(0)==kMinIf || GetAction(0)==kMaxIf) { return kFALSE; } if (fNoper > 1) return kFALSE; if (GetAction(0)==kAlias) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); return subform->IsInteger(kFALSE); } if (fLeaves.GetEntries() != 1) { switch (fLookupType[0]) { case kIndexOfEntry: case kIndexOfLocalEntry: case kEntries: case kLength: case kLengthFunc: case kIteration: return kTRUE; case kSum: case kMin: case kMax: case kEntryList: default: return kFALSE; } } if (EvalClass()==TBits::Class()) return kTRUE; if (IsLeafInteger(0) || IsLeafString(0)) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TTreeFormula::IsLeafInteger(Int_t code) const { // return TRUE if the leaf corresponding to code is short, int or unsigned // short, int When a leaf is of type integer, the generated histogram is // forced to have an integer bin width TLeaf *leaf = (TLeaf*)fLeaves.At(code); if (!leaf) { switch (fLookupType[code]) { case kIndexOfEntry: case kIndexOfLocalEntry: case kEntries: case kLength: case kLengthFunc: case kIteration: return kTRUE; case kSum: case kMin: case kMax: case kEntryList: default: return kFALSE; } } if (fAxis) return kTRUE; TFormLeafInfo * info; switch (fLookupType[code]) { case kMethod: case kTreeMember: case kDataMember: info = GetLeafInfo(code); return info->IsInteger(); case kDirect: break; } if (!strcmp(leaf->GetTypeName(),"Int_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"Short_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"UInt_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"UShort_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"Bool_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"Char_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"UChar_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"string")) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TTreeFormula::IsString() const { // return TRUE if the formula is a string // See TTreeFormula::Init for the setting of kIsCharacter. return TestBit(kIsCharacter); } //______________________________________________________________________________ Bool_t TTreeFormula::IsString(Int_t oper) const { // (fOper[i]>=105000 && fOper[i]<110000) || fOper[i] == kStrings) // return true if the expression at the index 'oper' is to be treated as // as string if (TFormula::IsString(oper)) return kTRUE; if (GetAction(oper)==kDefinedString) return kTRUE; if (GetAction(oper)==kAliasString) return kTRUE; if (GetAction(oper)==kAlternateString) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TTreeFormula::IsLeafString(Int_t code) const { // return TRUE if the leaf or data member corresponding to code is a string TLeaf *leaf = (TLeaf*)fLeaves.At(code); TFormLeafInfo * info; if (fLookupType[code]==kTreeMember) { info = GetLeafInfo(code); return info->IsString(); } switch(fLookupType[code]) { case kDirect: if ( !leaf->IsUnsigned() && (leaf->InheritsFrom(TLeafC::Class()) || leaf->InheritsFrom(TLeafB::Class()) ) ) { // Need to find out if it is an 'array' or a pointer. if (leaf->GetLenStatic() > 1) return kTRUE; // Now we need to differantiate between a variable length array and // a TClonesArray. if (leaf->GetLeafCount()) { const char* indexname = leaf->GetLeafCount()->GetName(); if (indexname[strlen(indexname)-1] == '_' ) { // This in a clones array return kFALSE; } else { // this is a variable length char array return kTRUE; } } return kFALSE; } else if (leaf->InheritsFrom(TLeafElement::Class())) { TBranchElement * br = (TBranchElement*)leaf->GetBranch(); Int_t bid = br->GetID(); if (bid < 0) return kFALSE; if (br->GetInfo()==0 || br->GetInfo()->GetElems()==0) { // Case where the file is corrupted is some ways. // We can not get to the actual type of the data // let's assume it is NOT a string. return kFALSE; } TStreamerElement * elem = (TStreamerElement*) br->GetInfo()->GetElems()[bid]; if (!elem) { // Case where the file is corrupted is some ways. // We can not get to the actual type of the data // let's assume it is NOT a string. return kFALSE; } if (elem->GetNewType()== TStreamerInfo::kOffsetL +kChar_t) { // Check whether a specific element of the string is specified! if (fIndexes[code][fNdimensions[code]-1] != -1) return kFALSE; return kTRUE; } if ( elem->GetNewType()== TStreamerInfo::kCharStar) { // Check whether a specific element of the string is specified! if (fNdimensions[code] && fIndexes[code][fNdimensions[code]-1] != -1) return kFALSE; return kTRUE; } return kFALSE; } else { return kFALSE; } case kMethod: //TMethodCall *m = GetMethodCall(code); //TMethodCall::EReturnType r = m->ReturnType(); return kFALSE; case kDataMember: info = GetLeafInfo(code); return info->IsString(); default: return kFALSE; } } //______________________________________________________________________________ char *TTreeFormula::PrintValue(Int_t mode) const { // Return value of variable as a string // // mode = -2 : Print line with *** // mode = -1 : Print column names // mode = 0 : Print column values return PrintValue(mode,0); } //______________________________________________________________________________ char *TTreeFormula::PrintValue(Int_t mode, Int_t instance, const char *decform) const { // Return value of variable as a string // // mode = -2 : Print line with *** // mode = -1 : Print column names // mode = 0 : Print column values // decform contains the requested format (with the same convention as printf). // const int kMAXLENGTH = 1024; static char value[kMAXLENGTH]; if (mode == -2) { for (int i = 0; i < kMAXLENGTH-1; i++) value[i] = '*'; value[kMAXLENGTH-1] = 0; } else if (mode == -1) { snprintf(value, kMAXLENGTH-1, "%s", GetTitle()); } else if (mode == 0) { if ( (fNstring && fNval==0 && fNoper==1) || IsString() ) { const char * val = 0; if (GetAction(0)==kStringConst) { val = fExpr[0].Data(); } else if (instance<fNdata[0]) { if (fNoper == 1) { if (fLookupType[0]==kTreeMember) { val = (char*)GetLeafInfo(0)->GetValuePointer((TLeaf*)0x0,instance); } else { TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); TBranch *branch = leaf->GetBranch(); Long64_t readentry = branch->GetTree()->GetReadEntry(); R__LoadBranch(branch,readentry,fQuickLoad); if (fLookupType[0]==kDirect && fNoper==1) { val = (const char*)leaf->GetValuePointer(); } else { val = ((TTreeFormula*)this)->EvalStringInstance(instance); } } } else { val = ((TTreeFormula*)this)->EvalStringInstance(instance); } } if (val) { strlcpy(value, val, kMAXLENGTH); } else { value[0] = '\0'; } value[kMAXLENGTH-1] = 0; } else { //NOTE: This is terrible form ... but is forced upon us by the fact that we can not //use the mutable keyword AND we should keep PrintValue const. Int_t real_instance = ((TTreeFormula*)this)->GetRealInstance(instance,-1); if (real_instance<fNdata[0]) { Ssiz_t len = strlen(decform); Char_t outputSizeLevel = 1; char *expo = 0; if (len>2) { switch (decform[len-2]) { case 'l': case 'L': { outputSizeLevel = 2; if (len>3 && tolower(decform[len-3])=='l') { outputSizeLevel = 3; } break; } case 'h': outputSizeLevel = 0; break; } } switch(decform[len-1]) { case 'c': case 'd': case 'i': { switch (outputSizeLevel) { case 0: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(Short_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 2: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(Long_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 3: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(Long64_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 1: default: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(Int_t)((TTreeFormula*)this)->EvalInstance(instance)); break; } break; } case 'o': case 'x': case 'X': case 'u': { switch (outputSizeLevel) { case 0: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(UShort_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 2: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(ULong_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 3: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(ULong64_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 1: default: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(UInt_t)((TTreeFormula*)this)->EvalInstance(instance)); break; } break; } case 'f': case 'e': case 'E': case 'g': case 'G': { switch (outputSizeLevel) { case 2: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(long double)((TTreeFormula*)this)->EvalInstance(instance)); break; case 1: default: snprintf(value,kMAXLENGTH,Form("%%%s",decform),((TTreeFormula*)this)->EvalInstance(instance)); break; } expo = strchr(value,'e'); break; } default: snprintf(value,kMAXLENGTH,Form("%%%sg",decform),((TTreeFormula*)this)->EvalInstance(instance)); expo = strchr(value,'e'); } if (expo) { // If there is an exponent we may be longer than planned. // so let's trim off the excess precission! UInt_t declen = atoi(decform); if (strlen(value)>declen) { UInt_t off = strlen(value)-declen; char *start = expo - off; UInt_t vlen = strlen(expo); for(UInt_t z=0;z<=vlen;++z) { start[z] = expo[z]; } //strcpy(expo-off,expo); } } } else { if (isalpha(decform[strlen(decform)-1])) { TString short_decform(decform); short_decform.Remove(short_decform.Length()-1); snprintf(value,kMAXLENGTH,Form(" %%%sc",short_decform.Data()),' '); } else { snprintf(value,kMAXLENGTH,Form(" %%%sc",decform),' '); } } } } return &value[0]; } //______________________________________________________________________________ void TTreeFormula::ResetLoading() { // Tell the formula that we are going to request a new entry. fNeedLoading = kTRUE; fDidBooleanOptimization = kFALSE; for(Int_t i=0; i<fNcodes; ++i) { UInt_t max_dim = fNdimensions[i]; for(UInt_t dim=0; dim<max_dim ;++dim) { if (fVarIndexes[i][dim]) { fVarIndexes[i][dim]->ResetLoading(); } } } Int_t n = fAliases.GetLast(); if ( fNoper < n ) { n = fNoper; } for(Int_t k=0; k <= n; ++k) { TTreeFormula *f = static_cast<TTreeFormula*>(fAliases.UncheckedAt(k)); if (f) { f->ResetLoading(); } } } //______________________________________________________________________________ void TTreeFormula::SetAxis(TAxis *axis) { // Set the axis (in particular get the type). if (!axis) {fAxis = 0; return;} if (IsString()) { fAxis = axis; if (fNoper==1 && GetAction(0)==kAliasString){ TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); subform->SetAxis(axis); } else if (fNoper==2 && GetAction(0)==kAlternateString){ TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); subform->SetAxis(axis); } // Since the bin are corresponding to 'string', we currently must also set // the axis to align the bins exactly on integer boundaries. axis->SetBit(TAxis::kIsInteger); } else if (IsInteger()) { axis->SetBit(TAxis::kIsInteger); } } //______________________________________________________________________________ void TTreeFormula::Streamer(TBuffer &R__b) { // Stream an object of class TTreeFormula. if (R__b.IsReading()) { UInt_t R__s, R__c; Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v > 2) { R__b.ReadClassBuffer(TTreeFormula::Class(), this, R__v, R__s, R__c); return; } //====process old versions before automatic schema evolution TFormula::Streamer(R__b); R__b >> fTree; R__b >> fNcodes; R__b.ReadFastArray(fCodes, fNcodes); R__b >> fMultiplicity; Int_t instance; R__b >> instance; //data member removed R__b >> fNindex; if (fNindex) { fLookupType = new Int_t[fNindex]; R__b.ReadFastArray(fLookupType, fNindex); } fMethods.Streamer(R__b); //====end of old versions } else { R__b.WriteClassBuffer(TTreeFormula::Class(),this); } } //______________________________________________________________________________ Bool_t TTreeFormula::StringToNumber(Int_t oper) { // Try to 'demote' a string into an array bytes. If this is not possible, // return false. Int_t code = GetActionParam(oper); if (GetAction(oper)==kDefinedString && fLookupType[code]==kDirect) { if (oper>0 && GetAction(oper-1)==kJump) { // We are the second hand of a ternary operator, let's not do the fixing. return kFALSE; } TLeaf *leaf = (TLeaf*)fLeaves.At(code); if (leaf && (leaf->InheritsFrom(TLeafC::Class()) || leaf->InheritsFrom(TLeafB::Class()) ) ) { SetAction(oper, kDefinedVariable, code ); fNval++; fNstring--; return kTRUE; } } return kFALSE; } //______________________________________________________________________________ void TTreeFormula::UpdateFormulaLeaves() { // this function is called TTreePlayer::UpdateFormulaLeaves, itself // called by TChain::LoadTree when a new Tree is loaded. // Because Trees in a TChain may have a different list of leaves, one // must update the leaves numbers in the TTreeFormula used by the TreePlayer. // A safer alternative would be to recompile the whole thing .... However // currently compile HAS TO be called from the constructor! Int_t nleaves = fLeafNames.GetEntriesFast(); ResetBit( kMissingLeaf ); for (Int_t i=0;i<nleaves;i++) { if (!fTree) break; if (!fLeafNames[i]) continue; TLeaf *leaf = fTree->GetLeaf(fLeafNames[i]->GetTitle(),fLeafNames[i]->GetName()); fLeaves[i] = leaf; if (fBranches[i] && leaf) { fBranches[i] = leaf->GetBranch(); // Since sometimes we might no read all the branches for all the entries, we // might sometimes only read the branch count and thus reset the colleciton // but might not read the data branches, to insure that a subsequent read // from TTreeFormula will properly load the data branches even if fQuickLoad is true, // we reset the entry of all branches in the TTree. ((TBranch*)fBranches[i])->ResetReadEntry(); } if (leaf==0) SetBit( kMissingLeaf ); } for (Int_t j=0; j<kMAXCODES; j++) { for (Int_t k = 0; k<kMAXFORMDIM; k++) { if (fVarIndexes[j][k]) { fVarIndexes[j][k]->UpdateFormulaLeaves(); } } if (fLookupType[j]==kDataMember || fLookupType[j]==kTreeMember) GetLeafInfo(j)->Update(); if (j<fNval && fCodes[j]<0) { TCutG *gcut = (TCutG*)fExternalCuts.At(j); if (gcut) { TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); TTreeFormula *fy = (TTreeFormula *)gcut->GetObjectY(); if (fx) fx->UpdateFormulaLeaves(); if (fy) fy->UpdateFormulaLeaves(); } } } for(Int_t k=0;k<fNoper;k++) { const Int_t oper = GetOper()[k]; switch(oper >> kTFOperShift) { case kAlias: case kAliasString: case kAlternate: case kAlternateString: case kMinIf: case kMaxIf: { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(k)); R__ASSERT(subform); subform->UpdateFormulaLeaves(); break; } case kDefinedVariable: { Int_t code = GetActionParam(k); if (fCodes[code]==0) switch(fLookupType[code]) { case kLengthFunc: case kSum: case kMin: case kMax: { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(k)); R__ASSERT(subform); subform->UpdateFormulaLeaves(); break; } default: break; } } default: break; } } } //______________________________________________________________________________ void TTreeFormula::ResetDimensions() { // Populate the TTreeFormulaManager with the dimension information. Int_t i,k; // Now that we saw all the expressions and variables AND that // we know whether arrays of chars are treated as string or // not, we can properly setup the dimensions. TIter next(fDimensionSetup); Int_t last_code = -1; Int_t virt_dim = 0; for(TDimensionInfo * info; (info = (TDimensionInfo*)next()); ) { if (last_code!=info->fCode) { // We know that the list is ordered by code number then by // dimension. Thus a different code means that we need to // restart at the lowest dimensions. virt_dim = 0; last_code = info->fCode; fNdimensions[last_code] = 0; } if (GetAction(info->fOper)==kDefinedString) { // We have a string used as a string (and not an array of number) // We need to determine which is the last dimension and skip it. TDimensionInfo *nextinfo = (TDimensionInfo*)next(); while(nextinfo && nextinfo->fCode==info->fCode) { DefineDimensions(info->fCode,info->fSize, info->fMultiDim, virt_dim); nextinfo = (TDimensionInfo*)next(); } if (!nextinfo) break; info = nextinfo; virt_dim = 0; last_code = info->fCode; fNdimensions[last_code] = 0; info->fSize = 1; // Maybe this should actually do nothing! } DefineDimensions(info->fCode,info->fSize, info->fMultiDim, virt_dim); } fMultiplicity = 0; for(i=0;i<fNoper;i++) { Int_t action = GetAction(i); if (action==kMinIf || action==kMaxIf) { // Skip/Ignore the 2nd args ++i; continue; } if (action==kAlias || action==kAliasString) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(i)); R__ASSERT(subform); switch(subform->GetMultiplicity()) { case 0: break; case 1: fMultiplicity = 1; break; case 2: if (fMultiplicity!=1) fMultiplicity = 2; break; } fManager->Add(subform); // since we are addint to this manager 'subform->ResetDimensions();' // will be called a little latter continue; } if (action==kDefinedString) { //if (fOper[i] >= 105000 && fOper[i]<110000) { // We have a string used as a string // This dormant portion of code would be used if (when?) we allow the histogramming // of the integral content (as opposed to the string content) of strings // held in a variable size container delimited by a null (as opposed to // a fixed size container or variable size container whose size is controlled // by a variable). In GetNdata, we will then use strlen to grab the current length. //fCumulSizes[i][fNdimensions[i]-1] = 1; //fUsedSizes[fNdimensions[i]-1] = -TMath::Abs(fUsedSizes[fNdimensions[i]-1]); //fUsedSizes[0] = - TMath::Abs( fUsedSizes[0]); //continue; } } for (i=0;i<fNcodes;i++) { if (fCodes[i] < 0) { TCutG *gcut = (TCutG*)fExternalCuts.At(i); if (!gcut) continue; TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); TTreeFormula *fy = (TTreeFormula *)gcut->GetObjectY(); if (fx) { switch(fx->GetMultiplicity()) { case 0: break; case 1: fMultiplicity = 1; break; case 2: if (fMultiplicity!=1) fMultiplicity = 2; break; } fManager->Add(fx); } if (fy) { switch(fy->GetMultiplicity()) { case 0: break; case 1: fMultiplicity = 1; break; case 2: if (fMultiplicity!=1) fMultiplicity = 2; break; } fManager->Add(fy); } continue; } if (fLookupType[i]==kIteration) { fMultiplicity = 1; continue; } TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(i); if (!leaf) continue; // Reminder of the meaning of fMultiplicity: // -1: Only one or 0 element per entry but contains variable length // -array! (Only used for TTreeFormulaManager) // 0: Only one element per entry, no variable length array // 1: loop over the elements of a variable length array // 2: loop over elements of fixed length array (nData is the same for all entry) if (leaf->GetLeafCount()) { // We assume only one possible variable length dimension (the left most) fMultiplicity = 1; } else if (fLookupType[i]==kDataMember) { TFormLeafInfo * leafinfo = GetLeafInfo(i); TStreamerElement * elem = leafinfo->fElement; if (fMultiplicity!=1) { if (leafinfo->HasCounter() ) fMultiplicity = 1; else if (elem && elem->GetArrayDim()>0) fMultiplicity = 2; else if (leaf->GetLenStatic()>1) fMultiplicity = 2; } } else { if (leaf->GetLenStatic()>1 && fMultiplicity!=1) fMultiplicity = 2; } if (fMultiplicity!=1) { // If the leaf belongs to a friend tree which has an index, we might // be in the case where some entry do not exist. TTree *realtree = fTree ? fTree->GetTree() : 0; TTree *tleaf = leaf->GetBranch()->GetTree(); if (tleaf && tleaf != realtree && tleaf->GetTreeIndex()) { // Reset the multiplicity if we have a friend tree with an index. fMultiplicity = 1; } } Int_t virt_dim2 = 0; for (k = 0; k < fNdimensions[i]; k++) { // At this point fCumulSizes[i][k] actually contain the physical // dimension of the k-th dimensions. if ( (fCumulSizes[i][k]>=0) && (fIndexes[i][k] >= fCumulSizes[i][k]) ) { // unreacheable element requested: fManager->CancelDimension(virt_dim2); // fCumulUsedSizes[virt_dim2] = 0; } if ( fIndexes[i][k] < 0 ) virt_dim2++; fFixedSizes[i][k] = fCumulSizes[i][k]; } // Add up the cumulative size for (k = fNdimensions[i]; (k > 0); k--) { // NOTE: When support for inside variable dimension is added this // will become inacurate (since one of the value in the middle of the chain // is unknown until GetNdata is called. fCumulSizes[i][k-1] *= TMath::Abs(fCumulSizes[i][k]); } // NOTE: We assume that the inside variable dimensions are dictated by the // first index. if (fCumulSizes[i][0]>0) fNdata[i] = fCumulSizes[i][0]; //for (k = 0; k<kMAXFORMDIM; k++) { // if (fVarIndexes[i][k]) fManager->Add(fVarIndexes[i][k]); //} } } //______________________________________________________________________________ void TTreeFormula::LoadBranches() { // Make sure that all the branches have been loaded properly. Int_t i; for (i=0; i<fNoper ; ++i) { TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(i); if (leaf==0) continue; TBranch *br = leaf->GetBranch(); Long64_t treeEntry = br->GetTree()->GetReadEntry(); R__LoadBranch(br,treeEntry,kTRUE); TTreeFormula *alias = (TTreeFormula*)fAliases.UncheckedAt(i); if (alias) alias->LoadBranches(); Int_t max_dim = fNdimensions[i]; for (Int_t dim = 0; dim < max_dim; ++dim) { if (fVarIndexes[i][dim]) fVarIndexes[i][dim]->LoadBranches(); } } } //______________________________________________________________________________ Bool_t TTreeFormula::LoadCurrentDim() { // Calculate the actual dimension for the current entry. Int_t size; Bool_t outofbounds = kFALSE; for (Int_t i=0;i<fNcodes;i++) { if (fCodes[i] < 0) continue; // NOTE: Currently only the leafcount can indicates a dimension that // is physically variable. So only the left-most dimension is variable. // When an API is introduced to be able to determine a variable inside dimensions // one would need to add a way to recalculate the values of fCumulSizes for this // leaf. This would probably require the addition of a new data member // fSizes[kMAXCODES][kMAXFORMDIM]; // Also note that EvalInstance expect all the values (but the very first one) // of fCumulSizes to be positive. So indicating that a physical dimension is // variable (expected for the first one) can NOT be done via negative values of // fCumulSizes. TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(i); if (!leaf) { switch(fLookupType[i]) { case kDirect: case kMethod: case kTreeMember: case kDataMember: fNdata[i] = 0; outofbounds = kTRUE; } continue; } TTree *realtree = fTree->GetTree(); TTree *tleaf = leaf->GetBranch()->GetTree(); if (tleaf && tleaf != realtree && tleaf->GetTreeIndex()) { if (tleaf->GetReadEntry() < 0) { fNdata[i] = 0; outofbounds = kTRUE; continue; } else { fNdata[i] = fCumulSizes[i][0]; } } Bool_t hasBranchCount2 = kFALSE; if (leaf->GetLeafCount()) { TLeaf* leafcount = leaf->GetLeafCount(); TBranch *branchcount = leafcount->GetBranch(); TFormLeafInfo * info = 0; if (leaf->IsA() == TLeafElement::Class()) { //if branchcount address not yet set, GetEntry will set the address // read branchcount value Long64_t readentry = leaf->GetBranch()->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; if (!branchcount->GetAddress()) { R__LoadBranch(branchcount, readentry, fQuickLoad); } else { // Since we do not read the full branch let's reset the read entry number // so that a subsequent read from TTreeFormula will properly load the full // object even if fQuickLoad is true. branchcount->TBranch::GetEntry(readentry); branchcount->ResetReadEntry(); } size = ((TBranchElement*)branchcount)->GetNdata(); // Reading the size as above is correct only when the branchcount // is of streamer type kCounter which require the underlying data // member to be signed integral type. TBranchElement* branch = (TBranchElement*) leaf->GetBranch(); // NOTE: could be sped up if (fHasMultipleVarDim[i]) {// info && info->GetVarDim()>=0) { info = (TFormLeafInfo* )fDataMembers.At(i); if (branch->GetBranchCount2()) R__LoadBranch(branch->GetBranchCount2(),readentry,fQuickLoad); else R__LoadBranch(branch,readentry,fQuickLoad); // Here we need to add the code to take in consideration the // double variable length // We fill up the array of sizes in the TLeafInfo: info->LoadSizes(branch); hasBranchCount2 = kTRUE; if (info->GetVirtVarDim()>=0) info->UpdateSizes(fManager->fVarDims[info->GetVirtVarDim()]); // Refresh the fCumulSizes[i] to have '1' for the // double variable dimensions Int_t vdim = info->GetVarDim(); fCumulSizes[i][vdim] = fCumulSizes[i][vdim+1]; for(Int_t k=vdim -1; k>=0; k--) { fCumulSizes[i][k] = fCumulSizes[i][k+1]*fFixedSizes[i][k]; } // Update fCumulUsedSizes // UpdateMultiVarSizes(vdim,info,i) //Int_t fixed = fCumulSizes[i][vdim+1]; //for(Int_t k=vdim - 1; k>=0; k++) { // Int_t fixed *= fFixedSizes[i][k]; // for(Int_t l=0;l<size; l++) { // fCumulSizes[i][k] += info->GetSize(l) * fixed; //} } } else { Long64_t readentry = leaf->GetBranch()->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; R__LoadBranch(branchcount,readentry,fQuickLoad); size = leaf->GetLen() / leaf->GetLenStatic(); } if (hasBranchCount2) { // We assume that fCumulSizes[i][1] contains the product of the fixed sizes fNdata[i] = fCumulSizes[i][1] * ((TFormLeafInfo *)fDataMembers.At(i))->GetSumOfSizes(); } else { fNdata[i] = size * fCumulSizes[i][1]; } if (fIndexes[i][0]==-1) { // Case where the index is not specified AND the 1st dimension has a variable // size. if (fManager->fUsedSizes[0]==1 || (size<fManager->fUsedSizes[0]) ) fManager->fUsedSizes[0] = size; if (info && fIndexes[i][info->GetVarDim()]>=0) { for(Int_t j=0; j<size; j++) { if (fIndexes[i][info->GetVarDim()] >= info->GetSize(j)) { info->SetSize(j,0); if (size>fManager->fCumulUsedVarDims->GetSize()) fManager->fCumulUsedVarDims->Set(size); fManager->fCumulUsedVarDims->AddAt(-1,j); } else if (fIndexes[i][info->GetVarDim()]>=0) { // There is an index and it is not too large info->SetSize(j,1); if (size>fManager->fCumulUsedVarDims->GetSize()) fManager->fCumulUsedVarDims->Set(size); fManager->fCumulUsedVarDims->AddAt(1,j); } } } } else if (fIndexes[i][0] >= size) { // unreacheable element requested: fManager->fUsedSizes[0] = 0; fNdata[i] = 0; outofbounds = kTRUE; } else if (hasBranchCount2) { TFormLeafInfo *info2; info2 = (TFormLeafInfo *)fDataMembers.At(i); if (fIndexes[i][0]<0 || fIndexes[i][info2->GetVarDim()] >= info2->GetSize(fIndexes[i][0])) { // unreacheable element requested: fManager->fUsedSizes[0] = 0; fNdata[i] = 0; outofbounds = kTRUE; } } } else if (fLookupType[i]==kDataMember) { TFormLeafInfo *leafinfo = (TFormLeafInfo*)fDataMembers.UncheckedAt(i); if (leafinfo->HasCounter()) { TBranch *branch = leaf->GetBranch(); Long64_t readentry = branch->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; R__LoadBranch(branch,readentry,fQuickLoad); size = (Int_t) leafinfo->GetCounterValue(leaf); if (fIndexes[i][0]==-1) { // Case where the index is not specified AND the 1st dimension has a variable // size. if (fManager->fUsedSizes[0]==1 || (size<fManager->fUsedSizes[0]) ) { fManager->fUsedSizes[0] = size; } } else if (fIndexes[i][0] >= size) { // unreacheable element requested: fManager->fUsedSizes[0] = 0; fNdata[i] = 0; outofbounds = kTRUE; } else { fNdata[i] = size*fCumulSizes[i][1]; } Int_t vdim = leafinfo->GetVarDim(); if (vdim>=0) { // Here we need to add the code to take in consideration the // double variable length // We fill up the array of sizes in the TLeafInfo: // here we can assume that branch is a TBranch element because the other style does NOT support this type // of complexity. leafinfo->LoadSizes(branch); hasBranchCount2 = kTRUE; if (fIndexes[i][0]==-1&&fIndexes[i][vdim] >= 0) { for(int z=0; z<size; ++z) { if (fIndexes[i][vdim] >= leafinfo->GetSize(z)) { leafinfo->SetSize(z,0); // --fManager->fUsedSizes[0]; } else if (fIndexes[i][vdim] >= 0 ) { leafinfo->SetSize(z,1); } } } leafinfo->UpdateSizes(fManager->fVarDims[vdim]); // Refresh the fCumulSizes[i] to have '1' for the // double variable dimensions fCumulSizes[i][vdim] = fCumulSizes[i][vdim+1]; for(Int_t k=vdim -1; k>=0; k--) { fCumulSizes[i][k] = fCumulSizes[i][k+1]*fFixedSizes[i][k]; } fNdata[i] = fCumulSizes[i][1] * leafinfo->GetSumOfSizes(); } else { fNdata[i] = size * fCumulSizes[i][1]; } } else if (leafinfo->GetMultiplicity()==-1) { TBranch *branch = leaf->GetBranch(); Long64_t readentry = branch->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; R__LoadBranch(branch,readentry,fQuickLoad); if (leafinfo->GetNdata(leaf)==0) { outofbounds = kTRUE; } } } // However we allow several dimensions that virtually vary via the size of their // index variables. So we have code to recalculate fCumulUsedSizes. Int_t index; TFormLeafInfo * info = 0; if (fLookupType[i]!=kDirect) { info = (TFormLeafInfo *)fDataMembers.At(i); } for(Int_t k=0, virt_dim=0; k < fNdimensions[i]; k++) { if (fIndexes[i][k]<0) { if (fIndexes[i][k]==-2 && fManager->fVirtUsedSizes[virt_dim]<0) { // if fVirtUsedSize[virt_dim] is positive then VarIndexes[i][k]->GetNdata() // is always the same and has already been factored in fUsedSize[virt_dim] index = fVarIndexes[i][k]->GetNdata(); if (index==1) { // We could either have a variable size array which is currently of size one // or a single element that might or not might not be present (and is currently present!) if (fVarIndexes[i][k]->GetManager()->GetMultiplicity()==1) { if (index<fManager->fUsedSizes[virt_dim]) fManager->fUsedSizes[virt_dim] = index; } } else if (fManager->fUsedSizes[virt_dim]==-fManager->fVirtUsedSizes[virt_dim] || index<fManager->fUsedSizes[virt_dim]) { fManager->fUsedSizes[virt_dim] = index; } } else if (hasBranchCount2 && info && k==info->GetVarDim()) { // NOTE: We assume the indexing of variable sizes on the first index! if (fIndexes[i][0]>=0) { index = info->GetSize(fIndexes[i][0]); if (fManager->fUsedSizes[virt_dim]==1 || (index!=1 && index<fManager->fUsedSizes[virt_dim]) ) fManager->fUsedSizes[virt_dim] = index; } } virt_dim++; } else if (hasBranchCount2 && info && k==info->GetVarDim()) { // nothing to do, at some point I thought this might be useful: // if (fIndexes[i][k]>=0) { // index = info->GetSize(fIndexes[i][k]); // if (fManager->fUsedSizes[virt_dim]==1 || (index!=1 && index<fManager->fUsedSizes[virt_dim]) ) // fManager->fUsedSizes[virt_dim] = index; // virt_dim++; // } } } } return ! outofbounds; } void TTreeFormula::Convert(UInt_t oldversion) { // Convert the fOper of a TTTreeFormula version fromVersion to the current in memory version enum { kOldAlias = /*TFormula::kVariable*/ 100000+10000+1, kOldAliasString = kOldAlias+1, kOldAlternate = kOldAlias+2, kOldAlternateString = kOldAliasString+2 }; for (int k=0; k<fNoper; k++) { // First hide from TFormula convertion Int_t action = GetOper()[k]; switch (action) { case kOldAlias: GetOper()[k] = -kOldAlias; break; case kOldAliasString: GetOper()[k] = -kOldAliasString; break; case kOldAlternate: GetOper()[k] = -kOldAlternate; break; case kOldAlternateString: GetOper()[k] = -kOldAlternateString; break; } } TFormula::Convert(oldversion); for (int i=0,offset=0; i<fNoper; i++) { Int_t action = GetOper()[i+offset]; switch (action) { case -kOldAlias: SetAction(i, kAlias, 0); break; case -kOldAliasString: SetAction(i, kAliasString, 0); break; case -kOldAlternate: SetAction(i, kAlternate, 0); break; case -kOldAlternateString: SetAction(i, kAlternateString, 0); break; } } } //______________________________________________________________________________ Bool_t TTreeFormula::SwitchToFormLeafInfo(Int_t code) { // Convert the underlying lookup method from the direct technique // (dereferencing the address held by the branch) to the method using // TFormLeafInfo. This is in particular usefull in the case where we // need to append an additional TFormLeafInfo (for example to call a // method). // Return false if the switch was unsuccessfull (basically in the // case of an old style split tree). TFormLeafInfo *last = 0; TLeaf *leaf = (TLeaf*)fLeaves.At(code); if (!leaf) return kFALSE; if (fLookupType[code]==kDirect) { if (leaf->InheritsFrom(TLeafElement::Class())) { TBranchElement * br = (TBranchElement*)leaf->GetBranch(); if (br->GetType()==31) { // sub branch of a TClonesArray TStreamerInfo *info = br->GetInfo(); TClass* cl = info->GetClass(); TStreamerElement *element = (TStreamerElement *)info->GetElems()[br->GetID()]; TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(cl, 0, element, kTRUE); Int_t offset; info->GetStreamerElement(element->GetName(),offset); clonesinfo->fNext = new TFormLeafInfo(cl,offset+br->GetOffset(),element); last = clonesinfo->fNext; fDataMembers.AddAtAndExpand(clonesinfo,code); fLookupType[code]=kDataMember; } else if (br->GetType()==41) { // sub branch of a Collection TBranchElement *count = br->GetBranchCount(); TFormLeafInfo* collectioninfo; if ( count->GetID() >= 0 ) { TStreamerElement *collectionElement = (TStreamerElement *)count->GetInfo()->GetElems()[count->GetID()]; TClass *collectionCl = collectionElement->GetClassPointer(); collectioninfo = new TFormLeafInfoCollection(collectionCl, 0, collectionElement, kTRUE); } else { TClass *collectionCl = TClass::GetClass(count->GetClassName()); collectioninfo = new TFormLeafInfoCollection(collectionCl, 0, collectionCl, kTRUE); } TStreamerInfo *info = br->GetInfo(); TClass* cl = info->GetClass(); TStreamerElement *element = (TStreamerElement *)info->GetElems()[br->GetID()]; Int_t offset; info->GetStreamerElement(element->GetName(),offset); collectioninfo->fNext = new TFormLeafInfo(cl,offset+br->GetOffset(),element); last = collectioninfo->fNext; fDataMembers.AddAtAndExpand(collectioninfo,code); fLookupType[code]=kDataMember; } else if (br->GetID()<0) { return kFALSE; } else { last = new TFormLeafInfoDirect(br); fDataMembers.AddAtAndExpand(last,code); fLookupType[code]=kDataMember; } } else { //last = new TFormLeafInfoDirect(br); //fDataMembers.AddAtAndExpand(last,code); //fLookupType[code]=kDataMember; return kFALSE; } } return kTRUE; } Import revision 48963 from the v5-34-00 patch branch: Record the consumption of a function arguments and closing paranthesis to avoid adding them a second time later on git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@48964 27541ba8-7e3a-0410-8455-c3a389f83636 // @(#)root/treeplayer:$Id$ // Author: Rene Brun 19/01/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TROOT.h" #include "TTreeFormula.h" #include "TTree.h" #include "TBranch.h" #include "TBranchObject.h" #include "TFunction.h" #include "TClonesArray.h" #include "TLeafB.h" #include "TLeafC.h" #include "TLeafObject.h" #include "TDataMember.h" #include "TMethodCall.h" #include "TCutG.h" #include "TRandom.h" #include "TInterpreter.h" #include "TDataType.h" #include "TStreamerInfo.h" #include "TStreamerElement.h" #include "TBranchElement.h" #include "TLeafElement.h" #include "TArrayI.h" #include "TAxis.h" #include "TError.h" #include "TVirtualCollectionProxy.h" #include "TString.h" #include "TTimeStamp.h" #include "TMath.h" #include "TVirtualRefProxy.h" #include "TTreeFormulaManager.h" #include "TFormLeafInfo.h" #include "TMethod.h" #include "TBaseClass.h" #include "TFormLeafInfoReference.h" #include "TEntryList.h" #include <ctype.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <typeinfo> #include <algorithm> const Int_t kMaxLen = 1024; R__EXTERN TTree *gTree; ClassImp(TTreeFormula) //______________________________________________________________________________ // // TTreeFormula now relies on a variety of TFormLeafInfo classes to handle the // reading of the information. Here is the list of theses classes: // TFormLeafInfo // TFormLeafInfoDirect // TFormLeafInfoNumerical // TFormLeafInfoClones // TFormLeafInfoCollection // TFormLeafInfoPointer // TFormLeafInfoMethod // TFormLeafInfoMultiVarDim // TFormLeafInfoMultiVarDimDirect // TFormLeafInfoCast // // The following method are available from the TFormLeafInfo interface: // // AddOffset(Int_t offset, TStreamerElement* element) // GetCounterValue(TLeaf* leaf) : return the size of the array pointed to. // GetObjectAddress(TLeafElement* leaf) : Returns the the location of the object pointed to. // GetMultiplicity() : Returns info on the variability of the number of elements // GetNdata(TLeaf* leaf) : Returns the number of elements // GetNdata() : Used by GetNdata(TLeaf* leaf) // GetValue(TLeaf *leaf, Int_t instance = 0) : Return the value // GetValuePointer(TLeaf *leaf, Int_t instance = 0) : Returns the address of the value // GetLocalValuePointer(TLeaf *leaf, Int_t instance = 0) : Returns the address of the value of 'this' LeafInfo // IsString() // ReadValue(char *where, Int_t instance = 0) : Internal function to interpret the location 'where' // Update() : react to the possible loading of a shared library. // // //______________________________________________________________________________ inline static void R__LoadBranch(TBranch* br, Long64_t entry, Bool_t quickLoad) { if (!quickLoad || (br->GetReadEntry() != entry)) { br->GetEntry(entry); } } //______________________________________________________________________________ // // This class is a small helper class to help in keeping track of the array // dimensions encountered in the analysis of the expression. class TDimensionInfo : public TObject { public: Int_t fCode; // Location of the leaf in TTreeFormula::fCode Int_t fOper; // Location of the Operation using the leaf in TTreeFormula::fOper Int_t fSize; TFormLeafInfoMultiVarDim* fMultiDim; TDimensionInfo(Int_t code, Int_t oper, Int_t size, TFormLeafInfoMultiVarDim* multiDim) : fCode(code), fOper(oper), fSize(size), fMultiDim(multiDim) {}; ~TDimensionInfo() {}; }; //______________________________________________________________________________ // // A TreeFormula is used to pass a selection expression // to the Tree drawing routine. See TTree::Draw // // A TreeFormula can contain any arithmetic expression including // standard operators and mathematical functions separated by operators. // Examples of valid expression: // "x<y && sqrt(z)>3.2" // //______________________________________________________________________________ TTreeFormula::TTreeFormula(): TFormula(), fQuickLoad(kFALSE), fNeedLoading(kTRUE), fDidBooleanOptimization(kFALSE), fDimensionSetup(0) { // Tree Formula default constructor fTree = 0; fLookupType = 0; fNindex = 0; fNcodes = 0; fAxis = 0; fHasCast = 0; fManager = 0; fMultiplicity = 0; Int_t j,k; for (j=0; j<kMAXCODES; j++) { fNdimensions[j] = 0; fCodes[j] = 0; fNdata[j] = 1; fHasMultipleVarDim[j] = kFALSE; for (k = 0; k<kMAXFORMDIM; k++) { fIndexes[j][k] = -1; fCumulSizes[j][k] = 1; fVarIndexes[j][k] = 0; } } } //______________________________________________________________________________ TTreeFormula::TTreeFormula(const char *name,const char *expression, TTree *tree) :TFormula(), fTree(tree), fQuickLoad(kFALSE), fNeedLoading(kTRUE), fDidBooleanOptimization(kFALSE), fDimensionSetup(0) { // Normal TTree Formula Constuctor Init(name,expression); } //______________________________________________________________________________ TTreeFormula::TTreeFormula(const char *name,const char *expression, TTree *tree, const std::vector<std::string>& aliases) :TFormula(), fTree(tree), fQuickLoad(kFALSE), fNeedLoading(kTRUE), fDidBooleanOptimization(kFALSE), fDimensionSetup(0), fAliasesUsed(aliases) { // Constructor used during the expansion of an alias Init(name,expression); } //______________________________________________________________________________ void TTreeFormula::Init(const char*name, const char* expression) { // Initialiation called from the constructors. TDirectory *const savedir=gDirectory; fNindex = kMAXFOUND; fLookupType = new Int_t[fNindex]; fNcodes = 0; fMultiplicity = 0; fAxis = 0; fHasCast = 0; Int_t i,j,k; fManager = new TTreeFormulaManager; fManager->Add(this); for (j=0; j<kMAXCODES; j++) { fNdimensions[j] = 0; fLookupType[j] = kDirect; fCodes[j] = 0; fNdata[j] = 1; fHasMultipleVarDim[j] = kFALSE; for (k = 0; k<kMAXFORMDIM; k++) { fIndexes[j][k] = -1; fCumulSizes[j][k] = 1; fVarIndexes[j][k] = 0; } } fDimensionSetup = new TList; if (Compile(expression)) { fTree = 0; fNdim = 0; if(savedir) savedir->cd(); return; } if (fNcodes >= kMAXFOUND) { Warning("TTreeFormula","Too many items in expression:%s",expression); fNcodes = kMAXFOUND; } SetName(name); for (i=0;i<fNoper;i++) { if (GetAction(i)==kDefinedString) { Int_t string_code = GetActionParam(i); TLeaf *leafc = (TLeaf*)fLeaves.UncheckedAt(string_code); if (!leafc) continue; // We have a string used as a string // This dormant portion of code would be used if (when?) we allow the histogramming // of the integral content (as opposed to the string content) of strings // held in a variable size container delimited by a null (as opposed to // a fixed size container or variable size container whose size is controlled // by a variable). In GetNdata, we will then use strlen to grab the current length. //fCumulSizes[i][fNdimensions[i]-1] = 1; //fUsedSizes[fNdimensions[i]-1] = -TMath::Abs(fUsedSizes[fNdimensions[i]-1]); //fUsedSizes[0] = - TMath::Abs( fUsedSizes[0]); if (fNoper == 1) { // If the string is by itself, then it can safely be histogrammed as // in a string based axis. To histogram the number inside the string // just make it part of a useless expression (for example: mystring+0) SetBit(kIsCharacter); } continue; } if (GetAction(i)==kJump && GetActionParam(i)==(fNoper-1)) { // We have cond ? string1 : string2 if (IsString(fNoper-1)) SetBit(kIsCharacter); } } if (fNoper == 1 && GetAction(0)==kStringConst) { SetBit(kIsCharacter); } if (fNoper==1 && GetAction(0)==kAliasString) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); if (subform->IsString()) SetBit(kIsCharacter); } else if (fNoper==2 && GetAction(0)==kAlternateString) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); if (subform->IsString()) SetBit(kIsCharacter); } fManager->Sync(); // Let's verify the indexes and dies if we need to. Int_t k0,k1; for(k0 = 0; k0 < fNcodes; k0++) { for(k1 = 0; k1 < fNdimensions[k0]; k1++ ) { // fprintf(stderr,"Saw %d dim %d and index %d\n",k1, fFixedSizes[k0][k1], fIndexes[k0][k1]); if ( fIndexes[k0][k1]>=0 && fFixedSizes[k0][k1]>=0 && fIndexes[k0][k1]>=fFixedSizes[k0][k1]) { Error("TTreeFormula", "Index %d for dimension #%d in %s is too high (max is %d)", fIndexes[k0][k1],k1+1, expression,fFixedSizes[k0][k1]-1); fTree = 0; fNdim = 0; if(savedir) savedir->cd(); return; } } } // Create a list of uniques branches to load. for(k=0; k<fNcodes; k++) { TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(k); TBranch *branch = 0; if (leaf) { branch = leaf->GetBranch(); if (fBranches.FindObject(branch)) branch = 0; } fBranches.AddAtAndExpand(branch,k); } if (IsInteger(kFALSE)) SetBit(kIsInteger); if (TestBit(TTreeFormula::kNeedEntries)) { // Call TTree::GetEntries() to insure that it is already calculated. // This will need to be done anyway at the first iteration and insure // that it will not mess up the branch reading (because TTree::GetEntries // opens all the file in the chain and 'stays' on the last file. Long64_t readentry = fTree->GetReadEntry(); Int_t treenumber = fTree->GetTreeNumber(); fTree->GetEntries(); if (treenumber != fTree->GetTreeNumber()) { if (readentry >= 0) { fTree->LoadTree(readentry); } UpdateFormulaLeaves(); } else { if (readentry >= 0) { fTree->LoadTree(readentry); } } } if(savedir) savedir->cd(); } //______________________________________________________________________________ TTreeFormula::~TTreeFormula() { //*-*-*-*-*-*-*-*-*-*-*Tree Formula default destructor*-*-*-*-*-*-*-*-*-*-* //*-* ================================= if (fManager) { fManager->Remove(this); if (fManager->fFormulas.GetLast()<0) { delete fManager; fManager = 0; } } // Objects in fExternalCuts are not owned and should not be deleted // fExternalCuts.Clear(); fLeafNames.Delete(); fDataMembers.Delete(); fMethods.Delete(); fAliases.Delete(); if (fLookupType) delete [] fLookupType; for (int j=0; j<fNcodes; j++) { for (int k = 0; k<fNdimensions[j]; k++) { if (fVarIndexes[j][k]) delete fVarIndexes[j][k]; fVarIndexes[j][k] = 0; } } if (fDimensionSetup) { fDimensionSetup->Delete(); delete fDimensionSetup; } } //______________________________________________________________________________ void TTreeFormula::DefineDimensions(Int_t code, Int_t size, TFormLeafInfoMultiVarDim * info, Int_t& virt_dim) { // This method is used internally to decode the dimensions of the variables if (info) { fManager->EnableMultiVarDims(); //if (fIndexes[code][info->fDim]<0) { // removed because the index might be out of bounds! info->fVirtDim = virt_dim; fManager->AddVarDims(virt_dim); // if (!fVarDims[virt_dim]) fVarDims[virt_dim] = new TArrayI; //} } Int_t vsize = 0; if (fIndexes[code][fNdimensions[code]]==-2) { TTreeFormula *indexvar = fVarIndexes[code][fNdimensions[code]]; // ASSERT(indexvar!=0); Int_t index_multiplicity = indexvar->GetMultiplicity(); switch (index_multiplicity) { case -1: case 0: case 2: vsize = indexvar->GetNdata(); break; case 1: vsize = -1; break; }; } else vsize = size; fCumulSizes[code][fNdimensions[code]] = size; if ( fIndexes[code][fNdimensions[code]] < 0 ) { fManager->UpdateUsedSize(virt_dim, vsize); } fNdimensions[code] ++; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(const char *info, Int_t code) { // This method is used internally to decode the dimensions of the variables // We assume that there are NO white spaces in the info string const char * current; Int_t size, scanindex, vardim; current = info; vardim = 0; // the next value could be before the string but // that's okay because the next operation is ++ // (this is to avoid (?) a if statement at the end of the // loop) if (current[0] != '[') current--; while (current) { current++; scanindex = sscanf(current,"%d",&size); // if scanindex is 0 then we have a name index thus a variable // array (or TClonesArray!). if (scanindex==0) size = -1; vardim += RegisterDimensions(code, size); if (fNdimensions[code] >= kMAXFORMDIM) { // NOTE: test that fNdimensions[code] is NOT too big!! break; } current = (char*)strstr( current, "[" ); } return vardim; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(Int_t code, Int_t size, TFormLeafInfoMultiVarDim * multidim) { // This method stores the dimension information for later usage. TDimensionInfo * info = new TDimensionInfo(code,fNoper,size,multidim); fDimensionSetup->Add(info); fCumulSizes[code][fNdimensions[code]] = size; fNdimensions[code] ++; return (size==-1) ? 1 : 0; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(Int_t code, TFormLeafInfo *leafinfo, TFormLeafInfo * /* maininfo */, Bool_t useCollectionObject) { // This method is used internally to decode the dimensions of the variables Int_t ndim, size, current, vardim; vardim = 0; const TStreamerElement * elem = leafinfo->fElement; TClass* c = elem ? elem->GetClassPointer() : 0; TFormLeafInfoMultiVarDim * multi = dynamic_cast<TFormLeafInfoMultiVarDim * >(leafinfo); if (multi) { // We have a second variable dimensions fManager->EnableMultiVarDims(); multi->fDim = fNdimensions[code]; return RegisterDimensions(code, -1, multi); } if (elem->IsA() == TStreamerBasicPointer::Class()) { if (elem->GetArrayDim()>0) { ndim = elem->GetArrayDim(); size = elem->GetMaxIndex(0); vardim += RegisterDimensions(code, -1); } else { ndim = 1; size = -1; } TStreamerBasicPointer *array = (TStreamerBasicPointer*)elem; TClass *cl = leafinfo->fClass; Int_t offset; TStreamerElement* counter = ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(array->GetCountName(),offset); #if 1 leafinfo->fCounter = new TFormLeafInfo(cl,offset,counter); #else /* Code is not ready yet see revision 14078 */ if (maininfo==0 || maininfo==leafinfo || 1) { leafinfo->fCounter = new TFormLeafInfo(cl,offset,counter); } else { leafinfo->fCounter = maininfo->DeepCopy(); TFormLeafInfo *currentinfo = leafinfo->fCounter; while(currentinfo->fNext && currentinfo->fNext->fNext) currentinfo=currentinfo->fNext; delete currentinfo->fNext; currentinfo->fNext = new TFormLeafInfo(cl,offset,counter); } #endif } else if (!useCollectionObject && elem->GetClassPointer() == TClonesArray::Class() ) { ndim = 1; size = -1; TClass * clonesClass = TClonesArray::Class(); Int_t c_offset; TStreamerElement *counter = ((TStreamerInfo*)clonesClass->GetStreamerInfo())->GetStreamerElement("fLast",c_offset); leafinfo->fCounter = new TFormLeafInfo(clonesClass,c_offset,counter); } else if (!useCollectionObject && elem->GetClassPointer() && elem->GetClassPointer()->GetCollectionProxy() ) { if ( typeid(*leafinfo) == typeid(TFormLeafInfoCollection) ) { ndim = 1; size = -1; } else { R__ASSERT( fHasMultipleVarDim[code] ); ndim = 1; size = 1; } } else if ( c && c->GetReferenceProxy() && c->GetReferenceProxy()->HasCounter() ) { ndim = 1; size = -1; } else if (elem->GetArrayDim()>0) { ndim = elem->GetArrayDim(); size = elem->GetMaxIndex(0); } else if ( elem->GetNewType()== TStreamerInfo::kCharStar) { // When we implement being able to read the length from // strlen, we will have: // ndim = 1; // size = -1; // until then we more or so die: ndim = 1; size = 1; //NOTE: changed from 0 } else return 0; current = 0; do { vardim += RegisterDimensions(code, size); if (fNdimensions[code] >= kMAXFORMDIM) { // NOTE: test that fNdimensions[code] is NOT too big!! break; } current++; size = elem->GetMaxIndex(current); } while (current<ndim); return vardim; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(Int_t code, TBranchElement *branch) { // This method is used internally to decode the dimensions of the variables TBranchElement * leafcount2 = branch->GetBranchCount2(); if (leafcount2) { // With have a second variable dimensions TBranchElement *leafcount = dynamic_cast<TBranchElement*>(branch->GetBranchCount()); R__ASSERT(leafcount); // The function should only be called on a functional TBranchElement object fManager->EnableMultiVarDims(); TFormLeafInfoMultiVarDim * info = new TFormLeafInfoMultiVarDimDirect(); fDataMembers.AddAtAndExpand(info, code); fHasMultipleVarDim[code] = kTRUE; info->fCounter = new TFormLeafInfoDirect(leafcount); info->fCounter2 = new TFormLeafInfoDirect(leafcount2); info->fDim = fNdimensions[code]; //if (fIndexes[code][info->fDim]<0) { // info->fVirtDim = virt_dim; // if (!fVarDims[virt_dim]) fVarDims[virt_dim] = new TArrayI; //} return RegisterDimensions(code, -1, info); } return 0; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(Int_t code, TLeaf *leaf) { // This method is used internally to decode the dimensions of the variables Int_t numberOfVarDim = 0; // Let see if we can understand the structure of this branch. // Usually we have: leafname[fixed_array] leaftitle[var_array]\type // (with fixed_array that can be a multi-dimension array. const char *tname = leaf->GetTitle(); char *leaf_dim = (char*)strstr( tname, "[" ); const char *bname = leaf->GetBranch()->GetName(); char *branch_dim = (char*)strstr(bname,"["); if (branch_dim) branch_dim++; // skip the '[' Bool_t isString = kFALSE; if (leaf->IsA() == TLeafElement::Class()) { Int_t type =((TBranchElement*)leaf->GetBranch())->GetStreamerType(); isString = (type == TStreamerInfo::kOffsetL+TStreamerInfo::kChar) || (type == TStreamerInfo::kCharStar); } else { isString = (leaf->IsA() == TLeafC::Class()); } if (leaf_dim) { leaf_dim++; // skip the '[' if (!branch_dim || strncmp(branch_dim,leaf_dim,strlen(branch_dim))) { // then both are NOT the same so do the leaf title first: numberOfVarDim += RegisterDimensions( leaf_dim, code); } else if (branch_dim && strncmp(branch_dim,leaf_dim,strlen(branch_dim))==0 && strlen(leaf_dim)>strlen(branch_dim) && (leaf_dim+strlen(branch_dim))[0]=='[') { // we have extra info in the leaf title numberOfVarDim += RegisterDimensions( leaf_dim+strlen(branch_dim)+1, code); } } if (branch_dim) { // then both are NOT same so do the branch name next: if (isString) { numberOfVarDim += RegisterDimensions( code, 1); } else { numberOfVarDim += RegisterDimensions( branch_dim, code); } } if (leaf->IsA() == TLeafElement::Class()) { TBranchElement* branch = (TBranchElement*) leaf->GetBranch(); if (branch->GetBranchCount2()) { if (!branch->GetBranchCount()) { Warning("DefinedVariable", "Noticed an incorrect in-memory TBranchElement object (%s).\nIt has a BranchCount2 but no BranchCount!\nThe result might be incorrect!", branch->GetName()); return numberOfVarDim; } // Switch from old direct style to using a TLeafInfo if (fLookupType[code] == kDataMember) Warning("DefinedVariable", "Already in kDataMember mode when handling multiple variable dimensions"); fLookupType[code] = kDataMember; // Feed the information into the Dimensions system numberOfVarDim += RegisterDimensions( code, branch); } } return numberOfVarDim; } //______________________________________________________________________________ Int_t TTreeFormula::DefineAlternate(const char *expression) { // This method check for treat the case where expression contains $Atl and load up // both fAliases and fExpr. // We return // -1 in case of failure // 0 in case we did not find $Alt // the action number in case of success. static const char *altfunc = "Alt$("; static const char *minfunc = "MinIf$("; static const char *maxfunc = "MaxIf$("; Int_t action = 0; Int_t start = 0; if ( strncmp(expression,altfunc,strlen(altfunc))==0 && expression[strlen(expression)-1]==')' ) { action = kAlternate; start = strlen(altfunc); } if ( strncmp(expression,maxfunc,strlen(maxfunc))==0 && expression[strlen(expression)-1]==')' ) { action = kMaxIf; start = strlen(maxfunc); } if ( strncmp(expression,minfunc,strlen(minfunc))==0 && expression[strlen(expression)-1]==')' ) { action = kMinIf; start = strlen(minfunc); } if (action) { TString full = expression; TString part1; TString part2; int paran = 0; int instr = 0; int brack = 0; for(unsigned int i=start;i<strlen(expression);++i) { switch (expression[i]) { case '(': paran++; break; case ')': paran--; break; case '"': instr = instr ? 0 : 1; break; case '[': brack++; break; case ']': brack--; break; }; if (expression[i]==',' && paran==0 && instr==0 && brack==0) { part1 = full( start, i-start ); part2 = full( i+1, full.Length() -1 - (i+1) ); break; // out of the for loop } } if (part1.Length() && part2.Length()) { TTreeFormula *primary = new TTreeFormula("primary",part1,fTree); TTreeFormula *alternate = new TTreeFormula("alternate",part2,fTree); short isstring = 0; if (action == kAlternate) { if (alternate->GetManager()->GetMultiplicity() != 0 ) { Error("DefinedVariable","The 2nd arguments in %s can not be an array (%s,%d)!", expression,alternate->GetTitle(), alternate->GetManager()->GetMultiplicity()); return -1; } // Should check whether we have strings. if (primary->IsString()) { if (!alternate->IsString()) { Error("DefinedVariable", "The 2nd arguments in %s has to return the same type as the 1st argument (string)!", expression); return -1; } isstring = 1; } else if (alternate->IsString()) { Error("DefinedVariable", "The 2nd arguments in %s has to return the same type as the 1st argument (numerical type)!", expression); return -1; } } else { primary->GetManager()->Add( alternate ); primary->GetManager()->Sync(); if (primary->IsString() || alternate->IsString()) { if (!alternate->IsString()) { Error("DefinedVariable", "The arguments of %s can not be strings!", expression); return -1; } } } fAliases.AddAtAndExpand(primary,fNoper); fExpr[fNoper] = ""; SetAction(fNoper, (Int_t)action + isstring, 0 ); ++fNoper; fAliases.AddAtAndExpand(alternate,fNoper); return (Int_t)kAlias + isstring; } } return 0; } //______________________________________________________________________________ Int_t TTreeFormula::ParseWithLeaf(TLeaf* leaf, const char* subExpression, Bool_t final, UInt_t paran_level, TObjArray& castqueue, Bool_t useLeafCollectionObject, const char* fullExpression) { // Decompose 'expression' as pointing to something inside the leaf // Returns: // -2 Error: some information is missing (message already printed) // -1 Error: Syntax is incorrect (message already printed) // 0 // >0 the value returns is the action code. Int_t action = 0; Int_t numberOfVarDim = 0; char *current; char scratch[kMaxLen]; scratch[0] = '\0'; char work[kMaxLen]; work[0] = '\0'; const char *right = subExpression; TString name = fullExpression; TBranch *branch = leaf ? leaf->GetBranch() : 0; Long64_t readentry = fTree->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; Bool_t useLeafReferenceObject = false; Int_t code = fNcodes-1; // Make a check to prevent problem with some corrupted files (missing TStreamerInfo). if (leaf && leaf->IsA()==TLeafElement::Class()) { TBranchElement *br = 0; if( branch->IsA() == TBranchElement::Class() ) { br = ((TBranchElement*)branch); if ( br->GetInfo() == 0 ) { Error("DefinedVariable","Missing StreamerInfo for %s. We will be unable to read!", name.Data()); return -2; } } TBranch *bmom = branch->GetMother(); if( bmom->IsA() == TBranchElement::Class() ) { TBranchElement *mom = (TBranchElement*)br->GetMother(); if (mom!=br) { if (mom->GetInfo()==0) { Error("DefinedVariable","Missing StreamerInfo for %s." " We will be unable to read!", mom->GetName()); return -2; } if ((mom->GetType()) < -1 && !mom->GetAddress()) { Error("DefinedVariable", "Address not set when the type of the branch is negative for for %s. We will be unable to read!", mom->GetName()); return -2; } } } } // We need to record the location in the list of leaves because // the tree might actually be a chain and in that case the leaf will // change from tree to tree!. // Let's reconstruct the name of the leaf, including the possible friend alias TTree *realtree = fTree->GetTree(); const char* alias = 0; if (leaf) { if (realtree) alias = realtree->GetFriendAlias(leaf->GetBranch()->GetTree()); if (!alias && realtree!=fTree) { // Let's try on the chain alias = fTree->GetFriendAlias(leaf->GetBranch()->GetTree()); } } if (alias) snprintf(scratch,kMaxLen-1,"%s.%s",alias,leaf->GetName()); else if (leaf) strlcpy(scratch,leaf->GetName(),kMaxLen); TTree *tleaf = realtree; if (leaf) { tleaf = leaf->GetBranch()->GetTree(); fCodes[code] = tleaf->GetListOfLeaves()->IndexOf(leaf); const char *mother_name = leaf->GetBranch()->GetMother()->GetName(); TString br_extended_name; // Could do ( strlen(mother_name)+strlen( leaf->GetBranch()->GetName() ) + 2 ) if (leaf->GetBranch()!=leaf->GetBranch()->GetMother()) { if (mother_name[strlen(mother_name)-1]!='.') { br_extended_name = mother_name; br_extended_name.Append('.'); } } br_extended_name.Append( leaf->GetBranch()->GetName() ); Ssiz_t dim = br_extended_name.First('['); if (dim >= 0) br_extended_name.Remove(dim); TNamed *named = new TNamed(scratch,br_extended_name.Data()); fLeafNames.AddAtAndExpand(named,code); fLeaves.AddAtAndExpand(leaf,code); } // If the leaf belongs to a friend tree which has an index, we might // be in the case where some entry do not exist. if (tleaf != realtree && tleaf->GetTreeIndex()) { // reset the multiplicity if (fMultiplicity >= 0) fMultiplicity = 1; } // Analyze the content of 'right' // Try to find out the class (if any) of the object in the leaf. TClass * cl = 0; TFormLeafInfo *maininfo = 0; TFormLeafInfo *previnfo = 0; Bool_t unwindCollection = kFALSE; static TClassRef stdStringClass = TClass::GetClass("string"); if (leaf==0) { TNamed *names = (TNamed*)fLeafNames.UncheckedAt(code); fLeafNames.AddAt(0,code); TTree *what = (TTree*)fLeaves.UncheckedAt(code); fLeaves.AddAt(0,code); cl = what ? what->IsA() : TTree::Class(); maininfo = new TFormLeafInfoTTree(fTree,names->GetName(),what); previnfo = maininfo; delete names; } else if (leaf->InheritsFrom(TLeafObject::Class()) ) { TBranchObject *bobj = (TBranchObject*)leaf->GetBranch(); cl = TClass::GetClass(bobj->GetClassName()); } else if (leaf->InheritsFrom(TLeafElement::Class())) { TBranchElement *branchEl = (TBranchElement *)leaf->GetBranch(); branchEl->SetupAddresses(); TStreamerInfo *info = branchEl->GetInfo(); TStreamerElement *element = 0; Int_t type = branchEl->GetStreamerType(); switch(type) { case TStreamerInfo::kBase: case TStreamerInfo::kObject: case TStreamerInfo::kTString: case TStreamerInfo::kTNamed: case TStreamerInfo::kTObject: case TStreamerInfo::kAny: case TStreamerInfo::kAnyP: case TStreamerInfo::kAnyp: case TStreamerInfo::kSTL: case TStreamerInfo::kSTLp: case TStreamerInfo::kObjectp: case TStreamerInfo::kObjectP: { element = (TStreamerElement *)info->GetElems()[branchEl->GetID()]; if (element) cl = element->GetClassPointer(); } break; case TStreamerInfo::kOffsetL + TStreamerInfo::kSTL: case TStreamerInfo::kOffsetL + TStreamerInfo::kSTLp: case TStreamerInfo::kOffsetL + TStreamerInfo::kAny: case TStreamerInfo::kOffsetL + TStreamerInfo::kAnyp: case TStreamerInfo::kOffsetL + TStreamerInfo::kAnyP: case TStreamerInfo::kOffsetL + TStreamerInfo::kObjectp: case TStreamerInfo::kOffsetL + TStreamerInfo::kObjectP: case TStreamerInfo::kOffsetL + TStreamerInfo::kObject: { element = (TStreamerElement *)info->GetElems()[branchEl->GetID()]; if (element){ cl = element->GetClassPointer(); } } break; case -1: { cl = info->GetClass(); } break; } // If we got a class object, we need to verify whether it is on a // split TClonesArray sub branch. if (cl && branchEl->GetBranchCount()) { if (branchEl->GetType()==31) { // This is inside a TClonesArray. if (!element) { Warning("DefineVariable", "Missing TStreamerElement in object in TClonesArray section"); return -2; } TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(cl, 0, element, kTRUE); // The following code was commmented out because in THIS case // the dimension are actually handled by parsing the title and name of the leaf // and branch (see a little further) // The dimension needs to be handled! // numberOfVarDim += RegisterDimensions(code,clonesinfo); maininfo = clonesinfo; // We skip some cases because we can assume we have an object. Int_t offset=0; info->GetStreamerElement(element->GetName(),offset); if (type == TStreamerInfo::kObjectp || type == TStreamerInfo::kObjectP || type == TStreamerInfo::kOffsetL + TStreamerInfo::kObjectp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kObjectP || type == TStreamerInfo::kSTLp || type == TStreamerInfo::kAnyp || type == TStreamerInfo::kAnyP || type == TStreamerInfo::kOffsetL + TStreamerInfo::kSTLp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kAnyp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kAnyP) { previnfo = new TFormLeafInfoPointer(cl,offset+branchEl->GetOffset(),element); } else { previnfo = new TFormLeafInfo(cl,offset+branchEl->GetOffset(),element); } maininfo->fNext = previnfo; unwindCollection = kTRUE; } else if (branchEl->GetType()==41) { // This is inside a Collection if (!element) { Warning("DefineVariable","Missing TStreamerElement in object in Collection section"); return -2; } // First we need to recover the collection. TBranchElement *count = branchEl->GetBranchCount(); TFormLeafInfo* collectioninfo; if ( count->GetID() >= 0 ) { TStreamerElement *collectionElement = (TStreamerElement *)count->GetInfo()->GetElems()[count->GetID()]; TClass *collectionCl = collectionElement->GetClassPointer(); collectioninfo = new TFormLeafInfoCollection(collectionCl, 0, collectionElement, kTRUE); } else { TClass *collectionCl = TClass::GetClass(count->GetClassName()); collectioninfo = new TFormLeafInfoCollection(collectionCl, 0, collectionCl, kTRUE); } // The following code was commmented out because in THIS case // the dimension are actually handled by parsing the title and name of the leaf // and branch (see a little further) // The dimension needs to be handled! // numberOfVarDim += RegisterDimensions(code,clonesinfo); maininfo = collectioninfo; // We skip some cases because we can assume we have an object. Int_t offset=0; info->GetStreamerElement(element->GetName(),offset); if (type == TStreamerInfo::kObjectp || type == TStreamerInfo::kObjectP || type == TStreamerInfo::kOffsetL + TStreamerInfo::kObjectp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kObjectP || type == TStreamerInfo::kSTLp || type == TStreamerInfo::kAnyp || type == TStreamerInfo::kAnyP || type == TStreamerInfo::kOffsetL + TStreamerInfo::kSTLp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kAnyp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kAnyP) { previnfo = new TFormLeafInfoPointer(cl,offset+branchEl->GetOffset(),element); } else { previnfo = new TFormLeafInfo(cl,offset+branchEl->GetOffset(),element); } maininfo->fNext = previnfo; unwindCollection = kTRUE; } } else if ( branchEl->GetType()==3) { TFormLeafInfo* clonesinfo; if (useLeafCollectionObject) { clonesinfo = new TFormLeafInfoCollectionObject(cl); } else { clonesinfo = new TFormLeafInfoClones(cl, 0, kTRUE); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,clonesinfo,maininfo,useLeafCollectionObject); } maininfo = clonesinfo; previnfo = maininfo; } else if (!useLeafCollectionObject && branchEl->GetType()==4) { TFormLeafInfo* collectioninfo; if (useLeafCollectionObject) { collectioninfo = new TFormLeafInfoCollectionObject(cl); } else { collectioninfo = new TFormLeafInfoCollection(cl, 0, cl, kTRUE); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,useLeafCollectionObject); } maininfo = collectioninfo; previnfo = maininfo; } else if (branchEl->GetStreamerType()==-1 && cl && cl->GetCollectionProxy()) { if (useLeafCollectionObject) { TFormLeafInfo *collectioninfo = new TFormLeafInfoCollectionObject(cl); maininfo = collectioninfo; previnfo = collectioninfo; } else { TFormLeafInfo *collectioninfo = new TFormLeafInfoCollection(cl, 0, cl, kTRUE); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); maininfo = collectioninfo; previnfo = collectioninfo; if (cl->GetCollectionProxy()->GetValueClass()!=0 && cl->GetCollectionProxy()->GetValueClass()->GetCollectionProxy()!=0) { TFormLeafInfo *multi = new TFormLeafInfoMultiVarDimCollection(cl,0, cl->GetCollectionProxy()->GetValueClass(),collectioninfo); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,multi,maininfo,kFALSE); previnfo->fNext = multi; cl = cl->GetCollectionProxy()->GetValueClass(); multi->fNext = new TFormLeafInfoCollection(cl, 0, cl, false); previnfo = multi->fNext; } if (cl->GetCollectionProxy()->GetValueClass()==0 && cl->GetCollectionProxy()->GetType()>0) { previnfo->fNext = new TFormLeafInfoNumerical(cl->GetCollectionProxy()); previnfo = previnfo->fNext; } else { // nothing to do } } } else if (strlen(right)==0 && cl && element && final) { TClass *elemCl = element->GetClassPointer(); if (!useLeafCollectionObject && elemCl && elemCl->GetCollectionProxy() && elemCl->GetCollectionProxy()->GetValueClass() && elemCl->GetCollectionProxy()->GetValueClass()->GetCollectionProxy()) { TFormLeafInfo *collectioninfo = new TFormLeafInfoCollection(cl, 0, elemCl); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); maininfo = collectioninfo; previnfo = collectioninfo; TFormLeafInfo *multi = new TFormLeafInfoMultiVarDimCollection(elemCl, 0, elemCl->GetCollectionProxy()->GetValueClass(), collectioninfo); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,multi,maininfo,kFALSE); previnfo->fNext = multi; cl = elemCl->GetCollectionProxy()->GetValueClass(); multi->fNext = new TFormLeafInfoCollection(cl, 0, cl, false); previnfo = multi->fNext; if (cl->GetCollectionProxy()->GetValueClass()==0 && cl->GetCollectionProxy()->GetType()>0) { previnfo->fNext = new TFormLeafInfoNumerical(cl->GetCollectionProxy()); previnfo = previnfo->fNext; } } else if (!useLeafCollectionObject && elemCl && elemCl->GetCollectionProxy() && elemCl->GetCollectionProxy()->GetValueClass()==0 && elemCl->GetCollectionProxy()->GetType()>0) { // At this point we have an element which is inside a class (which is not // a collection) and this element of a collection of numerical type. // (Note: it is not possible to have more than one variable dimension // unless we were supporting variable size C-style array of collection). TFormLeafInfo* collectioninfo = new TFormLeafInfoCollection(cl, 0, elemCl); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); collectioninfo->fNext = new TFormLeafInfoNumerical(elemCl->GetCollectionProxy()); maininfo = collectioninfo; previnfo = maininfo->fNext; } else if (!useLeafCollectionObject && elemCl && elemCl->GetCollectionProxy()) { if (elemCl->GetCollectionProxy()->GetValueClass()==TString::Class()) { right = "Data()"; } else if (elemCl->GetCollectionProxy()->GetValueClass()==stdStringClass) { right = "c_str()"; } } else if (!element->IsaPointer()) { maininfo = new TFormLeafInfoDirect(branchEl); previnfo = maininfo; } } else if ( cl && cl->GetReferenceProxy() ) { if ( useLeafCollectionObject || fullExpression[0] == '@' || fullExpression[strlen(scratch)] == '@' ) { useLeafReferenceObject = true; } else { if ( !maininfo ) { maininfo = previnfo = new TFormLeafInfoReference(cl, element, 0); numberOfVarDim += RegisterDimensions(code,maininfo,maininfo,kFALSE); } TVirtualRefProxy *refproxy = cl->GetReferenceProxy(); for(Long64_t i=0; i<leaf->GetBranch()->GetEntries()-readentry; ++i) { R__LoadBranch(leaf->GetBranch(), readentry+i, fQuickLoad); void *refobj = maininfo->GetValuePointer(leaf,0); if (refobj) { cl = refproxy->GetValueClass(refobj); } if ( cl ) break; } if ( !cl ) { Error("DefinedVariable","Failed to access class type of reference target (%s)",element->GetName()); return -1; } } } } // Treat the dimension information in the leaf name, title and 2nd branch count if (leaf) numberOfVarDim += RegisterDimensions(code,leaf); if (cl) { if (unwindCollection) { // So far we should get here only if we encounter a split collection of a class that contains // directly a collection. R__ASSERT(numberOfVarDim==1 && maininfo); if (!useLeafCollectionObject && cl && cl->GetCollectionProxy()) { TFormLeafInfo *multi = new TFormLeafInfoMultiVarDimCollection(cl, 0, cl, maininfo); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,multi,maininfo,kFALSE); previnfo->fNext = multi; multi->fNext = new TFormLeafInfoCollection(cl, 0, cl, false); previnfo = multi->fNext; if (cl->GetCollectionProxy()->GetValueClass()==0 && cl->GetCollectionProxy()->GetType()>0) { previnfo->fNext = new TFormLeafInfoNumerical(cl->GetCollectionProxy()); previnfo = previnfo->fNext; } } else if (!useLeafCollectionObject && cl == TClonesArray::Class()) { TFormLeafInfo *multi = new TFormLeafInfoMultiVarDimClones(cl, 0, cl, maininfo); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,multi,maininfo,kFALSE); previnfo->fNext = multi; multi->fNext = new TFormLeafInfoClones(cl, 0, false); previnfo = multi->fNext; } } Int_t offset=0; if (cl == TString::Class() && strcmp(right,"fData")==0) { // For backward compatibility replace TString::fData which no longer exist // by a call to TString::Data() right = "Data()"; } Int_t nchname = strlen(right); TFormLeafInfo *leafinfo = 0; TStreamerElement* element = 0; // Let see if the leaf was attempted to be casted. // Since there would have been something like // ((cast_class*)leafname)->.... we need to use // paran_level+1 // Also we disable this functionality in case of TClonesArray // because it is not yet allowed to have 'inheritance' (or virtuality) // in play in a TClonesArray. { TClass * casted = (TClass*) castqueue.At(paran_level+1); if (casted && cl != TClonesArray::Class()) { if ( ! casted->InheritsFrom(cl) ) { Error("DefinedVariable","%s does not inherit from %s. Casting not possible!", casted->GetName(),cl->GetName()); return -2; } leafinfo = new TFormLeafInfoCast(cl,casted); fHasCast = kTRUE; if (maininfo==0) { maininfo = leafinfo; } if (previnfo==0) { previnfo = leafinfo; } else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = 0; cl = casted; castqueue.AddAt(0,paran_level); } } Int_t i; Bool_t prevUseCollectionObject = useLeafCollectionObject; Bool_t useCollectionObject = useLeafCollectionObject; Bool_t useReferenceObject = useLeafReferenceObject; Bool_t prevUseReferenceObject = useLeafReferenceObject; for (i=0, current = &(work[0]); i<=nchname;i++ ) { // We will treated the terminator as a token. if (right[i] == '(') { // Right now we do not allow nested paranthesis do { *current++ = right[i++]; } while(right[i]!=')' && right[i]); *current++ = right[i]; *current='\0'; char *params = strchr(work,'('); if (params) { *params = 0; params++; } else params = (char *) ")"; if (cl==0) { Error("DefinedVariable","Can not call '%s' with a class",work); return -1; } if (cl->GetClassInfo()==0 && !cl->GetCollectionProxy()) { Error("DefinedVariable","Class probably unavailable:%s",cl->GetName()); return -2; } if (!useCollectionObject && cl == TClonesArray::Class()) { // We are not interested in the ClonesArray object but only // in its contents. // We need to retrieve the class of its content. TBranch *clbranch = leaf->GetBranch(); R__LoadBranch(clbranch,readentry,fQuickLoad); TClonesArray * clones; if (previnfo) clones = (TClonesArray*)previnfo->GetLocalValuePointer(leaf,0); else { Bool_t top = (clbranch==((TBranchElement*)clbranch)->GetMother() || !leaf->IsOnTerminalBranch()); TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)clbranch)->GetInfo()->GetClass(); } TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(mother_cl, 0, top); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,clonesinfo,maininfo,kFALSE); previnfo = clonesinfo; maininfo = clonesinfo; clones = (TClonesArray*)clonesinfo->GetLocalValuePointer(leaf,0); } TClass * inside_cl = clones->GetClass(); cl = inside_cl; } else if (!useCollectionObject && cl && cl->GetCollectionProxy() ) { // We are NEVER (for now!) interested in the ClonesArray object but only // in its contents. // We need to retrieve the class of its content. if (previnfo==0) { Bool_t top = (branch==((TBranchElement*)branch)->GetMother() || !leaf->IsOnTerminalBranch()); TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)branch)->GetInfo()->GetClass(); } TFormLeafInfo* collectioninfo = new TFormLeafInfoCollection(mother_cl, 0,cl,top); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); previnfo = collectioninfo; maininfo = collectioninfo; } TClass * inside_cl = cl->GetCollectionProxy()->GetValueClass(); if (inside_cl) cl = inside_cl; else if (cl->GetCollectionProxy()->GetType()>0) { Warning("DefinedVariable","Can not call method on content of %s in %s\n", cl->GetName(),name.Data()); return -2; } } TMethodCall *method = 0; if (cl==0) { Error("DefinedVariable", "Could not discover the TClass corresponding to (%s)!", right); return -2; } else if (cl==TClonesArray::Class() && strcmp(work,"size")==0) { method = new TMethodCall(cl, "GetEntriesFast", ""); } else if (cl->GetCollectionProxy() && strcmp(work,"size")==0) { if (maininfo==0) { TFormLeafInfo* collectioninfo=0; if (useLeafCollectionObject) { Bool_t top = (branch==((TBranchElement*)branch)->GetMother() || !leaf->IsOnTerminalBranch()); collectioninfo = new TFormLeafInfoCollectionObject(cl,top); } maininfo=previnfo=collectioninfo; } leafinfo = new TFormLeafInfoCollectionSize(cl); cl = 0; } else { if (cl->GetClassInfo()==0) { Error("DefinedVariable", "Can not call method %s on class without dictionary (%s)!", right,cl->GetName()); return -2; } method = new TMethodCall(cl, work, params); } if (method) { if (!method->GetMethod()) { Error("DefinedVariable","Unknown method:%s in %s",right,cl->GetName()); return -1; } switch(method->ReturnType()) { case TMethodCall::kLong: leafinfo = new TFormLeafInfoMethod(cl,method); cl = 0; break; case TMethodCall::kDouble: leafinfo = new TFormLeafInfoMethod(cl,method); cl = 0; break; case TMethodCall::kString: leafinfo = new TFormLeafInfoMethod(cl,method); // 1 will be replaced by -1 when we know how to use strlen numberOfVarDim += RegisterDimensions(code,1); //NOTE: changed from 0 cl = 0; break; case TMethodCall::kOther: { TString return_type = gInterpreter->TypeName(method->GetMethod()->GetReturnTypeName()); leafinfo = new TFormLeafInfoMethod(cl,method); cl = (return_type == "void") ? 0 : TClass::GetClass(return_type.Data()); } break; default: Error("DefineVariable","Method %s from %s has an impossible return type %d", work,cl->GetName(),method->ReturnType()); return -2; } } if (maininfo==0) { maininfo = leafinfo; } if (previnfo==0) { previnfo = leafinfo; } else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = 0; current = &(work[0]); *current = 0; prevUseCollectionObject = kFALSE; prevUseReferenceObject = kFALSE; useCollectionObject = kFALSE; if (cl && cl->GetCollectionProxy()) { if (numberOfVarDim>1) { Warning("DefinedVariable","TTreeFormula support only 2 level of variables size collections. Assuming '@' notation for the collection %s.", cl->GetName()); leafinfo = new TFormLeafInfo(cl,0,0); useCollectionObject = kTRUE; } else if (numberOfVarDim==0) { R__ASSERT(maininfo); leafinfo = new TFormLeafInfoCollection(cl,0,cl); numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); } else if (numberOfVarDim==1) { R__ASSERT(maininfo); leafinfo = new TFormLeafInfoMultiVarDimCollection(cl,0, (TStreamerElement*)0,maininfo); previnfo->fNext = leafinfo; previnfo = leafinfo; leafinfo = new TFormLeafInfoCollection(cl,0,cl); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); } previnfo->fNext = leafinfo; previnfo = leafinfo; leafinfo = 0; } continue; } else if (right[i] == ')') { // We should have the end of a cast operator. Let's introduce a TFormLeafCast // in the chain. TClass * casted = (TClass*) ((int(--paran_level)>=0) ? castqueue.At(paran_level) : 0); if (casted) { leafinfo = new TFormLeafInfoCast(cl,casted); fHasCast = kTRUE; if (maininfo==0) { maininfo = leafinfo; } if (previnfo==0) { previnfo = leafinfo; } else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = 0; current = &(work[0]); *current = 0; cl = casted; continue; } } else if (i > 0 && (right[i] == '.' || right[i] == '[' || right[i] == '\0') ) { // A delimiter happened let's see if what we have seen // so far does point to a data member. Bool_t needClass = kTRUE; *current = '\0'; // skip it all if there is nothing to look at if (strlen(work)==0) continue; prevUseCollectionObject = useCollectionObject; prevUseReferenceObject = useReferenceObject; if (work[0]=='@') { useReferenceObject = kTRUE; useCollectionObject = kTRUE; Int_t l = 0; for(l=0;work[l+1]!=0;++l) work[l] = work[l+1]; work[l] = '\0'; } else if (work[strlen(work)-1]=='@') { useReferenceObject = kTRUE; useCollectionObject = kTRUE; work[strlen(work)-1] = '\0'; } else { useReferenceObject = kFALSE; useCollectionObject = kFALSE; } Bool_t mustderef = kFALSE; if ( !prevUseReferenceObject && cl && cl->GetReferenceProxy() ) { R__LoadBranch(leaf->GetBranch(), readentry, fQuickLoad); if ( !maininfo ) { maininfo = previnfo = new TFormLeafInfoReference(cl, element, offset); if ( cl->GetReferenceProxy()->HasCounter() ) { numberOfVarDim += RegisterDimensions(code,-1); } prevUseReferenceObject = kFALSE; } else { previnfo->fNext = new TFormLeafInfoReference(cl, element, offset); previnfo = previnfo->fNext; } TVirtualRefProxy *refproxy = cl->GetReferenceProxy(); cl = 0; for(Long64_t entry=0; entry<leaf->GetBranch()->GetEntries()-readentry; ++entry) { R__LoadBranch(leaf->GetBranch(), readentry+i, fQuickLoad); void *refobj = maininfo->GetValuePointer(leaf,0); if (refobj) { cl = refproxy->GetValueClass(refobj); } if ( cl ) break; } needClass = kFALSE; mustderef = kTRUE; } else if (!prevUseCollectionObject && cl == TClonesArray::Class()) { // We are not interested in the ClonesArray object but only // in its contents. // We need to retrieve the class of its content. TBranch *clbranch = leaf->GetBranch(); R__LoadBranch(clbranch,readentry,fQuickLoad); TClonesArray * clones; if (maininfo) { clones = (TClonesArray*)maininfo->GetValuePointer(leaf,0); } else { // we have a unsplit TClonesArray leaves // or we did not yet match any of the sub-branches! TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)clbranch)->GetInfo()->GetClass(); } TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(mother_cl, 0); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,clonesinfo,maininfo,kFALSE); mustderef = kTRUE; previnfo = clonesinfo; maininfo = clonesinfo; if (clbranch->GetListOfBranches()->GetLast()>=0) { if (clbranch->IsA() != TBranchElement::Class()) { Error("DefinedVariable","Unimplemented usage of ClonesArray"); return -2; } //clbranch = ((TBranchElement*)clbranch)->GetMother(); clones = (TClonesArray*)((TBranchElement*)clbranch)->GetObject(); } else clones = (TClonesArray*)clonesinfo->GetLocalValuePointer(leaf,0); } // NOTE clones can be zero! if (clones==0) { Warning("DefinedVariable", "TClonesArray object was not retrievable for %s!", name.Data()); return -1; } TClass * inside_cl = clones->GetClass(); #if 1 cl = inside_cl; #else /* Maybe we should make those test lead to warning messages */ if (1 || inside_cl) cl = inside_cl; // if inside_cl is nul ... we have a problem of inconsistency :( if (0 && strlen(work)==0) { // However in this case we have NO content :( // so let get the number of objects //strcpy(work,"fLast"); } #endif } else if (!prevUseCollectionObject && cl && cl->GetCollectionProxy() ) { // We are NEVER interested in the Collection object but only // in its contents. // We need to retrieve the class of its content. TBranch *clbranch = leaf->GetBranch(); R__LoadBranch(clbranch,readentry,fQuickLoad); if (maininfo==0) { // we have a unsplit Collection leaf // or we did not yet match any of the sub-branches! TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)clbranch)->GetInfo()->GetClass(); } TFormLeafInfo* collectioninfo = new TFormLeafInfoCollection(mother_cl, 0, cl); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); mustderef = kTRUE; previnfo = collectioninfo; maininfo = collectioninfo; } //else if (clbranch->GetStreamerType()==0) { //} TClass * inside_cl = cl->GetCollectionProxy()->GetValueClass(); if (!inside_cl && cl->GetCollectionProxy()->GetType() > 0) { Warning("DefinedVariable","No data member in content of %s in %s\n", cl->GetName(),name.Data()); } cl = inside_cl; // if inside_cl is nul ... we have a problem of inconsistency. } if (!cl) { Warning("DefinedVariable","Missing class for %s!",name.Data()); } else { element = ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(work,offset); } if (!element && !prevUseCollectionObject) { // We allow for looking for a data member inside a class inside // a TClonesArray without mentioning the TClonesArrays variable name TIter next( cl->GetStreamerInfo()->GetElements() ); TStreamerElement * curelem; while ((curelem = (TStreamerElement*)next())) { if (curelem->GetClassPointer() == TClonesArray::Class()) { Int_t clones_offset = 0; ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(curelem->GetName(),clones_offset); TFormLeafInfo* clonesinfo = new TFormLeafInfo(cl, clones_offset, curelem); TClonesArray * clones; R__LoadBranch(leaf->GetBranch(),readentry,fQuickLoad); if (previnfo) { previnfo->fNext = clonesinfo; clones = (TClonesArray*)maininfo->GetValuePointer(leaf,0); previnfo->fNext = 0; } else { clones = (TClonesArray*)clonesinfo->GetLocalValuePointer(leaf,0); } TClass *sub_cl = clones->GetClass(); if (sub_cl) element = ((TStreamerInfo*)sub_cl->GetStreamerInfo())->GetStreamerElement(work,offset); delete clonesinfo; if (element) { leafinfo = new TFormLeafInfoClones(cl,clones_offset,curelem); numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); if (maininfo==0) maininfo = leafinfo; if (previnfo==0) previnfo = leafinfo; else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = 0; cl = sub_cl; break; } } else if (curelem->GetClassPointer() && curelem->GetClassPointer()->GetCollectionProxy()) { Int_t coll_offset = 0; ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(curelem->GetName(),coll_offset); TClass *sub_cl = curelem->GetClassPointer()->GetCollectionProxy()->GetValueClass(); if (sub_cl) { element = ((TStreamerInfo*)sub_cl->GetStreamerInfo())->GetStreamerElement(work,offset); } if (element) { if (numberOfVarDim>1) { Warning("DefinedVariable","TTreeFormula support only 2 level of variables size collections. Assuming '@' notation for the collection %s.", curelem->GetName()); leafinfo = new TFormLeafInfo(cl,coll_offset,curelem); useCollectionObject = kTRUE; } else if (numberOfVarDim==1) { R__ASSERT(maininfo); leafinfo = new TFormLeafInfoMultiVarDimCollection(cl,coll_offset, curelem,maininfo); fHasMultipleVarDim[code] = kTRUE; leafinfo->fNext = new TFormLeafInfoCollection(cl,coll_offset,curelem); numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); } else { leafinfo = new TFormLeafInfoCollection(cl,coll_offset,curelem); numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); } if (maininfo==0) maininfo = leafinfo; if (previnfo==0) previnfo = leafinfo; else { previnfo->fNext = leafinfo; previnfo = leafinfo; } if (leafinfo->fNext) { previnfo = leafinfo->fNext; } leafinfo = 0; cl = sub_cl; break; } } } } if (element) { Int_t type = element->GetNewType(); if (type<60 && type!=0) { // This is a basic type ... if (numberOfVarDim>=1 && type>40) { // We have a variable array within a variable array! leafinfo = new TFormLeafInfoMultiVarDim(cl,offset,element,maininfo); fHasMultipleVarDim[code] = kTRUE; } else { if (leafinfo && type<=40 ) { leafinfo->AddOffset(offset,element); } else { leafinfo = new TFormLeafInfo(cl,offset,element); } } } else { Bool_t object = kFALSE; Bool_t pointer = kFALSE; Bool_t objarr = kFALSE; switch(type) { case TStreamerInfo::kObjectp: case TStreamerInfo::kObjectP: case TStreamerInfo::kSTLp: case TStreamerInfo::kAnyp: case TStreamerInfo::kAnyP: case TStreamerInfo::kOffsetL + TStreamerInfo::kObjectP: case TStreamerInfo::kOffsetL + TStreamerInfo::kSTLp: case TStreamerInfo::kOffsetL + TStreamerInfo::kAnyp: case TStreamerInfo::kOffsetL + TStreamerInfo::kObjectp: case TStreamerInfo::kOffsetL + TStreamerInfo::kAnyP: pointer = kTRUE; break; case TStreamerInfo::kBase: case TStreamerInfo::kAny : case TStreamerInfo::kSTL: case TStreamerInfo::kObject: case TStreamerInfo::kTString: case TStreamerInfo::kTNamed: case TStreamerInfo::kTObject: object = kTRUE; break; case TStreamerInfo::kOffsetL + TStreamerInfo::kAny: case TStreamerInfo::kOffsetL + TStreamerInfo::kSTL: case TStreamerInfo::kOffsetL + TStreamerInfo::kObject: objarr = kTRUE; break; case TStreamerInfo::kStreamer: case TStreamerInfo::kStreamLoop: // Unsupported case. Error("DefinedVariable", "%s is a datamember of %s BUT is not yet of a supported type (%d)", right,cl ? cl->GetName() : "unknown class",type); return -2; default: // Unknown and Unsupported case. Error("DefinedVariable", "%s is a datamember of %s BUT is not of a unknown type (%d)", right,cl ? cl->GetName() : "unknown class",type); return -2; } if (object && !useCollectionObject && ( element->GetClassPointer() == TClonesArray::Class() || element->GetClassPointer()->GetCollectionProxy() ) ) { object = kFALSE; } if (object && leafinfo) { leafinfo->AddOffset(offset,element); } else if (objarr) { // This is an embedded array of objects. We can not increase the offset. leafinfo = new TFormLeafInfo(cl,offset,element); mustderef = kTRUE; } else { if (!useCollectionObject && element->GetClassPointer() == TClonesArray::Class()) { leafinfo = new TFormLeafInfoClones(cl,offset,element); mustderef = kTRUE; } else if (!useCollectionObject && element->GetClassPointer() && element->GetClassPointer()->GetCollectionProxy()) { mustderef = kTRUE; if (numberOfVarDim>1) { Warning("DefinedVariable","TTreeFormula support only 2 level of variables size collections. Assuming '@' notation for the collection %s.", element->GetName()); leafinfo = new TFormLeafInfo(cl,offset,element); useCollectionObject = kTRUE; } else if (numberOfVarDim==1) { R__ASSERT(maininfo); leafinfo = new TFormLeafInfoMultiVarDimCollection(cl,offset,element,maininfo); fHasMultipleVarDim[code] = kTRUE; //numberOfVarDim += RegisterDimensions(code,leafinfo); //cl = cl->GetCollectionProxy()->GetValueClass(); //if (maininfo==0) maininfo = leafinfo; //if (previnfo==0) previnfo = leafinfo; //else { // previnfo->fNext = leafinfo; // previnfo = leafinfo; //} leafinfo->fNext = new TFormLeafInfoCollection(cl, offset, element); if (element->GetClassPointer()->GetCollectionProxy()->GetValueClass()==0) { TFormLeafInfo *info = new TFormLeafInfoNumerical( element->GetClassPointer()->GetCollectionProxy()); if (leafinfo->fNext) leafinfo->fNext->fNext = info; else leafinfo->fNext = info; } } else { leafinfo = new TFormLeafInfoCollection(cl, offset, element); TClass *elemCl = element->GetClassPointer(); TClass *valueCl = elemCl->GetCollectionProxy()->GetValueClass(); if (!maininfo) maininfo = leafinfo; if (valueCl!=0 && valueCl->GetCollectionProxy()!=0) { numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); if (previnfo==0) previnfo = leafinfo; else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = new TFormLeafInfoMultiVarDimCollection(elemCl,0, elemCl->GetCollectionProxy()->GetValueClass(),maininfo); //numberOfVarDim += RegisterDimensions(code,previnfo->fNext); fHasMultipleVarDim[code] = kTRUE; //previnfo = previnfo->fNext; leafinfo->fNext = new TFormLeafInfoCollection(elemCl,0, valueCl); elemCl = valueCl; } if (elemCl->GetCollectionProxy() && elemCl->GetCollectionProxy()->GetValueClass()==0) { TFormLeafInfo *info = new TFormLeafInfoNumerical(elemCl->GetCollectionProxy()); if (leafinfo->fNext) leafinfo->fNext->fNext = info; else leafinfo->fNext = info; } } } else if ( (object || pointer) && !useReferenceObject && element->GetClassPointer()->GetReferenceProxy() ) { TClass* c = element->GetClassPointer(); R__LoadBranch(leaf->GetBranch(),readentry,fQuickLoad); if ( object ) { leafinfo = new TFormLeafInfoReference(c, element, offset); } else { leafinfo = new TFormLeafInfoPointer(cl,offset,element); leafinfo->fNext = new TFormLeafInfoReference(c, element, 0); } //if ( c->GetReferenceProxy()->HasCounter() ) { // numberOfVarDim += RegisterDimensions(code,-1); //} prevUseReferenceObject = kFALSE; needClass = kFALSE; mustderef = kTRUE; } else if (pointer) { // this is a pointer to be followed. leafinfo = new TFormLeafInfoPointer(cl,offset,element); mustderef = kTRUE; } else { // this is an embedded object. R__ASSERT(object); leafinfo = new TFormLeafInfo(cl,offset,element); } } } } else { if (cl) Error("DefinedVariable","%s is not a datamember of %s",work,cl->GetName()); // no else, we warned earlier that the class was missing. return -1; } numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,useCollectionObject); // Note or useCollectionObject||prevUseColectionObject if (maininfo==0) { maininfo = leafinfo; } if (previnfo==0) { previnfo = leafinfo; } else if (previnfo!=leafinfo) { previnfo->fNext = leafinfo; previnfo = leafinfo; } while (previnfo->fNext) previnfo = previnfo->fNext; if ( right[i] != '\0' ) { if ( !needClass && mustderef ) { maininfo->SetBranch(leaf->GetBranch()); char *ptr = (char*)maininfo->GetValuePointer(leaf,0); TFormLeafInfoReference* refInfo = 0; if ( !maininfo->IsReference() ) { for( TFormLeafInfo* inf = maininfo->fNext; inf; inf = inf->fNext ) { if ( inf->IsReference() ) { refInfo = (TFormLeafInfoReference*)inf; } } } else { refInfo = (TFormLeafInfoReference*)maininfo; } if ( refInfo ) { cl = refInfo->GetValueClass(ptr); if ( !cl ) { Error("DefinedVariable","Failed to access class type of reference target (%s)",element->GetName()); return -1; } element = ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(work,offset); } else { Error("DefinedVariable","Failed to access class type of reference target (%s)",element->GetName()); return -1; } } else if ( needClass ) { cl = element->GetClassPointer(); } } if (mustderef) leafinfo = 0; current = &(work[0]); *current = 0; R__ASSERT(right[i] != '['); // We are supposed to have removed all dimensions already! if (cl == TString::Class() && strcmp(right+i+1,"fData") == 0) { // For backward compatibility replace TString::fData which no longer exist // by a call to TString::Data() right = ".Data()"; i = 0; nchname = strlen(right); } } else *current++ = right[i]; } if (maininfo) { fDataMembers.AddAtAndExpand(maininfo,code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } } if (strlen(work)!=0) { // We have something left to analyze. Let's make this an error case! return -1; } TClass *objClass = EvalClass(code); if (objClass && !useLeafCollectionObject && objClass->GetCollectionProxy() && objClass->GetCollectionProxy()->GetValueClass()) { TFormLeafInfo *last = 0; if ( SwitchToFormLeafInfo(code) ) { last = (TFormLeafInfo*)fDataMembers.At(code); if (!last) return action; while (last->fNext) { last = last->fNext; } } if (last && last->GetClass() != objClass) { TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)branch)->GetInfo()->GetClass(); } TFormLeafInfo* collectioninfo = new TFormLeafInfoCollection(mother_cl, 0, objClass, kFALSE); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); last->fNext = collectioninfo; } numberOfVarDim += RegisterDimensions(code,1); //NOTE: changed from 0 objClass = objClass->GetCollectionProxy()->GetValueClass(); } if (IsLeafString(code) || objClass == TString::Class() || objClass == stdStringClass) { TFormLeafInfo *last = 0; if ( SwitchToFormLeafInfo(code) ) { last = (TFormLeafInfo*)fDataMembers.At(code); if (!last) return action; while (last->fNext) { last = last->fNext; } } const char *funcname = 0; if (objClass == TString::Class()) { funcname = "Data"; //tobetested: numberOfVarDim += RegisterDimensions(code,1,0); // Register the dim of the implied char* } else if (objClass == stdStringClass) { funcname = "c_str"; //tobetested: numberOfVarDim += RegisterDimensions(code,1,0); // Register the dim of the implied char* } if (funcname) { TMethodCall *method = new TMethodCall(objClass, funcname, ""); if (last) { last->fNext = new TFormLeafInfoMethod(objClass,method); } else { fDataMembers.AddAtAndExpand(new TFormLeafInfoMethod(objClass,method),code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } } return kDefinedString; } if (objClass) { TMethodCall *method = new TMethodCall(objClass, "AsDouble", ""); if (method->IsValid() && (method->ReturnType() == TMethodCall::kLong || method->ReturnType() == TMethodCall::kDouble)) { TFormLeafInfo *last = 0; if (SwitchToFormLeafInfo(code)) { last = (TFormLeafInfo*)fDataMembers.At(code); // Improbable case if (!last) { delete method; return action; } while (last->fNext) { last = last->fNext; } } if (last) { last->fNext = new TFormLeafInfoMethod(objClass,method); } else { fDataMembers.AddAtAndExpand(new TFormLeafInfoMethod(objClass,method),code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } return kDefinedVariable; } delete method; method = new TMethodCall(objClass, "AsString", ""); if (method->IsValid() && method->ReturnType() == TMethodCall::kString) { TFormLeafInfo *last = 0; if (SwitchToFormLeafInfo(code)) { last = (TFormLeafInfo*)fDataMembers.At(code); // Improbable case if (!last) { delete method; return action; } while (last->fNext) { last = last->fNext; } } if (last) { last->fNext = new TFormLeafInfoMethod(objClass,method); } else { fDataMembers.AddAtAndExpand(new TFormLeafInfoMethod(objClass,method),code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } //tobetested: numberOfVarDim += RegisterDimensions(code,1,0); // Register the dim of the implied char* return kDefinedString; } if (method->IsValid() && method->ReturnType() == TMethodCall::kOther) { TClass *rcl = 0; TFunction *f = method->GetMethod(); if (f) rcl = TClass::GetClass(gInterpreter->TypeName(f->GetReturnTypeName())); if ((rcl == TString::Class() || rcl == stdStringClass) ) { TFormLeafInfo *last = 0; if (SwitchToFormLeafInfo(code)) { last = (TFormLeafInfo*)fDataMembers.At(code); // Improbable case if (!last) { delete method; return action; } while (last->fNext) { last = last->fNext; } } if (last) { last->fNext = new TFormLeafInfoMethod(objClass,method); last = last->fNext; } else { last = new TFormLeafInfoMethod(objClass,method); fDataMembers.AddAtAndExpand(last,code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } objClass = rcl; const char *funcname = 0; if (objClass == TString::Class()) { funcname = "Data"; } else if (objClass == stdStringClass) { funcname = "c_str"; } if (funcname) { method = new TMethodCall(objClass, funcname, ""); last->fNext = new TFormLeafInfoMethod(objClass,method); } return kDefinedString; } } delete method; } return action; } //______________________________________________________________________________ Int_t TTreeFormula::FindLeafForExpression(const char* expression, TLeaf*& leaf, TString& leftover, Bool_t& final, UInt_t& paran_level, TObjArray& castqueue, std::vector<std::string>& aliasUsed, Bool_t& useLeafCollectionObject, const char* fullExpression) { // Look for the leaf corresponding to the start of expression. // It returns the corresponding leaf if any. // It also modify the following arguments: // leftover: contain from expression that was not used to determine the leaf // final: // paran_level: number of un-matched open parenthesis // cast_queue: list of cast to be done // aliases: list of aliases used // Return <0 in case of failure // Return 0 if a leaf has been found // Return 2 if info about the TTree itself has been requested. // Later on we will need to read one entry, let's make sure // it is a real entry. if (fTree->GetTree()==0) { fTree->LoadTree(0); if (fTree->GetTree()==0) return -1; } Long64_t readentry = fTree->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; const char *cname = expression; char first[kMaxLen]; first[0] = '\0'; char second[kMaxLen]; second[0] = '\0'; char right[kMaxLen]; right[0] = '\0'; char work[kMaxLen]; work[0] = '\0'; char left[kMaxLen]; left[0] = '\0'; char scratch[kMaxLen]; char scratch2[kMaxLen]; std::string currentname; Int_t previousdot = 0; char *current; TLeaf *tmp_leaf=0; TBranch *branch=0, *tmp_branch=0; Int_t nchname = strlen(cname); Int_t i; Bool_t foundAtSign = kFALSE; for (i=0, current = &(work[0]); i<=nchname && !final;i++ ) { // We will treated the terminator as a token. *current++ = cname[i]; if (cname[i] == '(') { ++paran_level; if (current==work+1) { // If the expression starts with a paranthesis, we are likely // to have a cast operator inside. current--; } continue; //i++; //while( cname[i]!=')' && cname[i] ) { // *current++ = cname[i++]; //} //*current++ = cname[i]; ////*current = 0; //continue; } if (cname[i] == ')') { if (paran_level==0) { Error("DefinedVariable","Unmatched paranthesis in %s",fullExpression); return -1; } // Let's see if work is a classname. *(--current) = 0; paran_level--; TString cast_name = gInterpreter->TypeName(work); TClass *cast_cl = TClass::GetClass(cast_name); if (cast_cl) { // We must have a cast castqueue.AddAtAndExpand(cast_cl,paran_level); current = &(work[0]); *current = 0; // Warning("DefinedVariable","Found cast to %s",cast_fullExpression); continue; } else if (gROOT->GetType(cast_name)) { // We reset work current = &(work[0]); *current = 0; Warning("DefinedVariable", "Casting to primary types like \"%s\" is not supported yet",cast_name.Data()); continue; } *(current++)=')'; *current='\0'; char *params = strchr(work,'('); if (params) { *params = 0; params++; if (branch && !leaf) { // We have a branch but not a leaf. We are likely to have found // the top of split branch. if (BranchHasMethod(0, branch, work, params, readentry)) { //fprintf(stderr, "Does have a method %s for %s.\n", work, branch->GetName()); } } // What we have so far might be a member function of one of the // leaves that are not splitted (for example "GetNtrack" for the Event class). TIter next(fTree->GetIteratorOnAllLeaves()); TLeaf* leafcur = 0; while (!leaf && (leafcur = (TLeaf*) next())) { TBranch* br = leafcur->GetBranch(); Bool_t yes = BranchHasMethod(leafcur, br, work, params, readentry); if (yes) { leaf = leafcur; //fprintf(stderr, "Does have a method %s for %s found in leafcur %s.\n", work, leafcur->GetBranch()->GetName(), leafcur->GetName()); } } if (!leaf) { // Check for an alias. if (strlen(left) && left[strlen(left)-1]=='.') left[strlen(left)-1]=0; const char *aliasValue = fTree->GetAlias(left); if (aliasValue && strcspn(aliasValue,"+*/-%&!=<>|")==strlen(aliasValue)) { // First check whether we are using this alias recursively (this would // lead to an infinite recursion. if (find(aliasUsed.begin(), aliasUsed.end(), left) != aliasUsed.end()) { Error("DefinedVariable", "The substitution of the branch alias \"%s\" by \"%s\" in \"%s\" failed\n"\ "\tbecause \"%s\" is used [recursively] in its own definition!", left,aliasValue,fullExpression,left); return -3; } aliasUsed.push_back(left); TString newExpression = aliasValue; newExpression += (cname+strlen(left)); Int_t res = FindLeafForExpression(newExpression, leaf, leftover, final, paran_level, castqueue, aliasUsed, useLeafCollectionObject, fullExpression); if (res<0) { Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed.",left,aliasValue); return -3; } return res; } // This is actually not really any error, we probably received something // like "abs(some_val)", let TFormula decompose it first. return -1; } // if (!leaf->InheritsFrom(TLeafObject::Class()) ) { // If the leaf that we found so far is not a TLeafObject then there is // nothing we would be able to do. // Error("DefinedVariable","Need a TLeafObject to call a function!"); // return -1; //} // We need to recover the info not used. strlcpy(right,work,kMaxLen); strncat(right,"(",kMaxLen-1-strlen(right)); strncat(right,params,kMaxLen-1-strlen(right)); final = kTRUE; // Record in 'i' what we consumed i += strlen(params); // we reset work current = &(work[0]); *current = 0; break; } } if (cname[i] == '.' || cname[i] == '\0' || cname[i] == ')') { // A delimiter happened let's see if what we have seen // so far does point to a leaf. *current = '\0'; Int_t len = strlen(work); if (work[0]=='@') { foundAtSign = kTRUE; Int_t l = 0; for(l=0;work[l+1]!=0;++l) work[l] = work[l+1]; work[l] = '\0'; --current; } else if (len>=2 && work[len-2]=='@') { foundAtSign = kTRUE; work[len-2] = cname[i]; work[len-1] = '\0'; --current; } else { foundAtSign = kFALSE; } if (left[0]==0) strlcpy(left,work,kMaxLen); if (!leaf && !branch) { // So far, we have not found a matching leaf or branch. strlcpy(first,work,kMaxLen); std::string treename(first); if (treename.size() && treename[treename.size()-1]=='.') { treename.erase(treename.size()-1); } if (treename== "This" /* || treename == fTree->GetName() */ ) { // Request info about the TTree object itself, TNamed *named = new TNamed(fTree->GetName(),fTree->GetName()); fLeafNames.AddAtAndExpand(named,fNcodes); fLeaves.AddAtAndExpand(fTree,fNcodes); if (cname[i]) leftover = &(cname[i+1]); return 2; } // The following would allow to access the friend by name // however, it would also prevent the access of the leaves // within the friend. We could use the '@' notation here // however this would not be aesthetically pleasing :( // What we need to do, is add the ability to look ahead to // the next 'token' to decide whether we to access the tree // or its leaf. //} else { // TTree *tfriend = fTree->GetFriend(treename.c_str()); // TTree *realtree = fTree->GetTree(); // if (!tfriend && realtree != fTree){ // // If it is a chain and we did not find a friend, // // let's try with the internal tree. // tfriend = realtree->GetFriend(treename.c_str()); // } // if (tfriend) { // TNamed *named = new TNamed(treename.c_str(),tfriend->GetName()); // fLeafNames.AddAtAndExpand(named,fNcodes); // fLeaves.AddAtAndExpand(tfriend,fNcodes); // if (cname[i]) leftover = &(cname[i+1]); // return 2; // } //} branch = fTree->FindBranch(first); leaf = fTree->FindLeaf(first); // Now look with the delimiter removed (we looked with it first // because a dot is allowed at the end of some branches). if (cname[i]) first[strlen(first)-1]='\0'; if (!branch) branch = fTree->FindBranch(first); if (!leaf) leaf = fTree->FindLeaf(first); TClass* cl = 0; if ( branch && branch->InheritsFrom(TBranchElement::Class()) ) { int offset=0; TBranchElement* bElt = (TBranchElement*)branch; TStreamerInfo* info = bElt->GetInfo(); TStreamerElement* element = info ? info->GetStreamerElement(first,offset) : 0; if (element) cl = element->GetClassPointer(); if ( cl && !cl->GetReferenceProxy() ) cl = 0; } if ( cl ) { // We have a reference class here.... final = kTRUE; useLeafCollectionObject = foundAtSign; // we reset work current = &(work[0]); *current = 0; } else if (branch && (foundAtSign || cname[i] != 0) ) { // Since we found a branch and there is more information in the name, // we do NOT look at the 'IsOnTerminalBranch' status of the leaf // we found ... yet! if (leaf==0) { // Note we do not know (yet?) what (if anything) to do // for a TBranchObject branch. if (branch->InheritsFrom(TBranchElement::Class()) ) { Int_t type = ((TBranchElement*)branch)->GetType(); if ( type == 3 || type ==4) { // We have a Collection branch. leaf = (TLeaf*)branch->GetListOfLeaves()->At(0); if (foundAtSign) { useLeafCollectionObject = foundAtSign; foundAtSign = kFALSE; current = &(work[0]); *current = 0; ++i; break; } } } } // we reset work useLeafCollectionObject = foundAtSign; foundAtSign = kFALSE; current = &(work[0]); *current = 0; } else if (leaf || branch) { if (leaf && branch) { // We found both a leaf and branch matching the request name // let's see which one is the proper one to use! (On annoying case // is that where the same name is repeated ( varname.varname ) // We always give priority to the branch // leaf = 0; } if (leaf && leaf->IsOnTerminalBranch()) { // This is a non-object leaf, it should NOT be specified more except for // dimensions. final = kTRUE; } // we reset work current = &(work[0]); *current = 0; } else { // What we have so far might be a data member of one of the // leaves that are not splitted (for example "fNtrack" for the Event class. TLeaf *leafcur = GetLeafWithDatamember(first,work,readentry); if (leafcur) { leaf = leafcur; branch = leaf->GetBranch(); if (leaf->IsOnTerminalBranch()) { final = kTRUE; strlcpy(right,first,kMaxLen); //We need to put the delimiter back! if (foundAtSign) strncat(right,"@",kMaxLen-1-strlen(right)); if (cname[i]=='.') strncat(right,".",kMaxLen-1-strlen(right)); // We reset work current = &(work[0]); *current = 0; }; } else if (cname[i] == '.') { // If we have a branch that match a name preceded by a dot // then we assume we are trying to drill down the branch // Let look if one of the top level branch has a branch with the name // we are looking for. TBranch *branchcur; TIter next( fTree->GetListOfBranches() ); while(!branch && (branchcur=(TBranch*)next()) ) { branch = branchcur->FindBranch(first); } if (branch) { // We reset work current = &(work[0]); *current = 0; } } } } else { // correspond to if (leaf || branch) if (final) { Error("DefinedVariable", "Unexpected control flow!"); return -1; } // No dot is allowed in subbranches and leaves, so // we always remove it in the present case. if (cname[i]) work[strlen(work)-1] = '\0'; snprintf(scratch,sizeof(scratch),"%s.%s",first,work); snprintf(scratch2,sizeof(scratch2),"%s.%s.%s",first,second,work); if (previousdot) { currentname = &(work[previousdot+1]); } // First look for the current 'word' in the list of // leaf of the if (branch) { tmp_leaf = branch->FindLeaf(work); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(scratch); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(scratch2); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(currentname.c_str()); } if (tmp_leaf && tmp_leaf->IsOnTerminalBranch() ) { // This is a non-object leaf, it should NOT be specified more except for // dimensions. final = kTRUE; } if (branch) { tmp_branch = branch->FindBranch(work); if (!tmp_branch) tmp_branch = branch->FindBranch(scratch); if (!tmp_branch) tmp_branch = branch->FindBranch(scratch2); if (!tmp_branch) tmp_branch = branch->FindBranch(currentname.c_str()); } if (tmp_branch) { branch=tmp_branch; // NOTE: Should we look for a leaf within here? if (!final) { tmp_leaf = branch->FindLeaf(work); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(scratch); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(scratch2); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(currentname.c_str()); if (tmp_leaf && tmp_leaf->IsOnTerminalBranch() ) { // This is a non-object leaf, it should NOT be specified // more except for dimensions. final = kTRUE; leaf = tmp_leaf; } } } if (tmp_leaf) { // Something was found. if (second[0]) strncat(second,".",kMaxLen-1-strlen(second)); strncat(second,work,kMaxLen-1-strlen(second)); leaf = tmp_leaf; useLeafCollectionObject = foundAtSign; foundAtSign = kFALSE; // we reset work current = &(work[0]); *current = 0; } else { //We need to put the delimiter back! if (strlen(work)) { if (foundAtSign) { Int_t where = strlen(work); work[where] = '@'; work[where+1] = cname[i]; ++current; previousdot = where+1; } else { previousdot = strlen(work); work[strlen(work)] = cname[i]; } } else --current; } } } } // Copy the left over for later use. if (strlen(work)) { strncat(right,work,kMaxLen-1-strlen(right)); } if (i<nchname) { if (strlen(right) && right[strlen(right)-1]!='.' && cname[i]!='.') { // In some cases we remove a little to fast the period, we add // it back if we need. It is assumed that 'right' and the rest of // the name was cut by a delimiter, so this should be safe. strncat(right,".",kMaxLen-1-strlen(right)); } strncat(right,&cname[i],kMaxLen-1-strlen(right)); } if (!final && branch) { if (!leaf) { leaf = (TLeaf*)branch->GetListOfLeaves()->UncheckedAt(0); if (!leaf) return -1; } final = leaf->IsOnTerminalBranch(); } if (leaf && leaf->InheritsFrom(TLeafObject::Class()) ) { if (strlen(right)==0) strlcpy(right,work,kMaxLen); } if (leaf==0 && left[0]!=0) { if (left[strlen(left)-1]=='.') left[strlen(left)-1]=0; // Check for an alias. const char *aliasValue = fTree->GetAlias(left); if (aliasValue && strcspn(aliasValue,"[]+*/-%&!=<>|")==strlen(aliasValue)) { // First check whether we are using this alias recursively (this would // lead to an infinite recursion). if (find(aliasUsed.begin(), aliasUsed.end(), left) != aliasUsed.end()) { Error("DefinedVariable", "The substitution of the branch alias \"%s\" by \"%s\" in \"%s\" failed\n"\ "\tbecause \"%s\" is used [recursively] in its own definition!", left,aliasValue,fullExpression,left); return -3; } aliasUsed.push_back(left); TString newExpression = aliasValue; newExpression += (cname+strlen(left)); Int_t res = FindLeafForExpression(newExpression, leaf, leftover, final, paran_level, castqueue, aliasUsed, useLeafCollectionObject, fullExpression); if (res<0) { Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed.",left,aliasValue); return -3; } return res; } } leftover = right; return 0; } //______________________________________________________________________________ Int_t TTreeFormula::DefinedVariable(TString &name, Int_t &action) { //*-*-*-*-*-*Check if name is in the list of Tree/Branch leaves*-*-*-*-* //*-* ================================================== // // This member function redefines the function in TFormula // If a leaf has a name corresponding to the argument name, then // returns a new code. // A TTreeFormula may contain more than one variable. // For each variable referenced, the pointers to the corresponding // branch and leaf is stored in the object arrays fBranches and fLeaves. // // name can be : // - Leaf_Name (simple variable or data member of a ClonesArray) // - Branch_Name.Leaf_Name // - Branch_Name.Method_Name // - Leaf_Name[index] // - Branch_Name.Leaf_Name[index] // - Branch_Name.Leaf_Name[index1] // - Branch_Name.Leaf_Name[][index2] // - Branch_Name.Leaf_Name[index1][index2] // New additions: // - Branch_Name.Leaf_Name[OtherLeaf_Name] // - Branch_Name.Datamember_Name // - '.' can be replaced by '->' // and // - Branch_Name[index1].Leaf_Name[index2] // - Leaf_name[index].Action().OtherAction(param) // - Leaf_name[index].Action()[val].OtherAction(param) // // The expected returns values are // -2 : the name has been recognized but won't be usable // -1 : the name has not been recognized // >=0 : the name has been recognized, return the internal code for this name. // action = kDefinedVariable; if (!fTree) return -1; fNpar = 0; if (name.Length() > kMaxLen) return -1; Int_t i,k; if (name == "Entry$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kIndexOfEntry; return code; } if (name == "LocalEntry$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kIndexOfLocalEntry; return code; } if (name == "Entries$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kEntries; SetBit(kNeedEntries); fManager->SetBit(kNeedEntries); return code; } if (name == "Iteration$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kIteration; return code; } if (name == "Length$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kLength; return code; } static const char *lenfunc = "Length$("; if (strncmp(name.Data(),"Length$(",strlen(lenfunc))==0 && name[name.Length()-1]==')') { TString subform = name.Data()+strlen(lenfunc); subform.Remove( subform.Length() - 1 ); TTreeFormula *lengthForm = new TTreeFormula("lengthForm",subform,fTree); fAliases.AddAtAndExpand(lengthForm,fNoper); Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kLengthFunc; return code; } static const char *minfunc = "Min$("; if (strncmp(name.Data(),"Min$(",strlen(minfunc))==0 && name[name.Length()-1]==')') { TString subform = name.Data()+strlen(minfunc); subform.Remove( subform.Length() - 1 ); TTreeFormula *minForm = new TTreeFormula("minForm",subform,fTree); fAliases.AddAtAndExpand(minForm,fNoper); Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kMin; return code; } static const char *maxfunc = "Max$("; if (strncmp(name.Data(),"Max$(",strlen(maxfunc))==0 && name[name.Length()-1]==')') { TString subform = name.Data()+strlen(maxfunc); subform.Remove( subform.Length() - 1 ); TTreeFormula *maxForm = new TTreeFormula("maxForm",subform,fTree); fAliases.AddAtAndExpand(maxForm,fNoper); Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kMax; return code; } static const char *sumfunc = "Sum$("; if (strncmp(name.Data(),"Sum$(",strlen(sumfunc))==0 && name[name.Length()-1]==')') { TString subform = name.Data()+strlen(sumfunc); subform.Remove( subform.Length() - 1 ); TTreeFormula *sumForm = new TTreeFormula("sumForm",subform,fTree); fAliases.AddAtAndExpand(sumForm,fNoper); Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kSum; return code; } // Check for $Alt(expression1,expression2) Int_t res = DefineAlternate(name.Data()); if (res!=0) { // There was either a syntax error or we found $Alt if (res<0) return res; action = res; return 0; } // Find the top level leaf and deal with dimensions char cname[kMaxLen]; strlcpy(cname,name.Data(),kMaxLen); char dims[kMaxLen]; dims[0] = '\0'; Bool_t final = kFALSE; UInt_t paran_level = 0; TObjArray castqueue; // First, it is easier to remove all dimensions information from 'cname' Int_t cnamelen = strlen(cname); for(i=0,k=0; i<cnamelen; ++i, ++k) { if (cname[i] == '[') { int bracket = i; int bracket_level = 1; int j; for (j=++i; j<cnamelen && (bracket_level>0 || cname[j]=='['); j++, i++) { if (cname[j]=='[') bracket_level++; else if (cname[j]==']') bracket_level--; } if (bracket_level != 0) { //Error("DefinedVariable","Bracket unbalanced"); return -1; } strncat(dims,&cname[bracket],j-bracket); //k += j-bracket; } if (i!=k) cname[k] = cname[i]; } cname[k]='\0'; Bool_t useLeafCollectionObject = kFALSE; TString leftover; TLeaf *leaf = 0; { std::vector<std::string> aliasSofar = fAliasesUsed; res = FindLeafForExpression(cname, leaf, leftover, final, paran_level, castqueue, aliasSofar, useLeafCollectionObject, name); } if (res<0) return res; if (!leaf && res!=2) { // Check for an alias. const char *aliasValue = fTree->GetAlias(cname); if (aliasValue) { // First check whether we are using this alias recursively (this would // lead to an infinite recursion. if (find(fAliasesUsed.begin(), fAliasesUsed.end(), cname) != fAliasesUsed.end()) { Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed\n"\ "\tbecause \"%s\" is recursively used in its own definition!", cname,aliasValue,cname); return -3; } if (strcspn(aliasValue,"+*/-%&!=<>|")!=strlen(aliasValue)) { // If the alias contains an operator, we need to use a nested formula // (since DefinedVariable must only add one entry to the operation's list). // Need to check the aliases used so far std::vector<std::string> aliasSofar = fAliasesUsed; aliasSofar.push_back( cname ); TString subValue( aliasValue ); if (dims[0]) { subValue += dims; } TTreeFormula *subform = new TTreeFormula(cname,subValue,fTree,aliasSofar); // Need to pass the aliases used so far. if (subform->GetNdim()==0) { delete subform; Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed.",cname,aliasValue); return -3; } fManager->Add(subform); fAliases.AddAtAndExpand(subform,fNoper); if (subform->IsString()) { action = kAliasString; return 0; } else { action = kAlias; return 0; } } else { /* assumes strcspn(aliasValue,"[]")!=strlen(aliasValue) */ TString thisAlias( aliasValue ); thisAlias += dims; Int_t aliasRes = DefinedVariable(thisAlias,action); if (aliasRes<0) { // We failed but DefinedVariable has not printed why yet. // and because we want thoses to be printed _before_ the notice // of the failure of the substitution, we need to print them here. if (aliasRes==-1) { Error("Compile", " Bad numerical expression : \"%s\"",thisAlias.Data()); } else if (aliasRes==-2) { Error("Compile", " Part of the Variable \"%s\" exists but some of it is not accessible or useable",thisAlias.Data()); } Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed.",cname,aliasValue); return -3; } return aliasRes; } } } if (leaf || res==2) { if (leaf && leaf->GetBranch() && leaf->GetBranch()->TestBit(kDoNotProcess)) { Error("DefinedVariable","the branch \"%s\" has to be enabled to be used",leaf->GetBranch()->GetName()); return -2; } Int_t code = fNcodes++; // If needed will now parse the indexes specified for // arrays. if (dims[0]) { char *current = &( dims[0] ); Int_t dim = 0; TString varindex; Int_t index; Int_t scanindex ; while (current) { current++; if (current[0] == ']') { fIndexes[code][dim] = -1; // Loop over all elements; } else { scanindex = sscanf(current,"%d",&index); if (scanindex) { fIndexes[code][dim] = index; } else { fIndexes[code][dim] = -2; // Index is calculated via a variable. varindex = current; char *end = (char*)(varindex.Data()); for(char bracket_level = 0;*end!=0;end++) { if (*end=='[') bracket_level++; if (bracket_level==0 && *end==']') break; if (*end==']') bracket_level--; } *end = '\0'; fVarIndexes[code][dim] = new TTreeFormula("index_var", varindex, fTree); current += strlen(varindex)+1; // move to the end of the index array } } dim ++; if (dim >= kMAXFORMDIM) { // NOTE: test that dim this is NOT too big!! break; } current = (char*)strstr( current, "[" ); } } // Now that we have cleaned-up the expression, let's compare it to the content // of the leaf! res = ParseWithLeaf(leaf,leftover,final,paran_level,castqueue,useLeafCollectionObject,name); if (res<0) return res; if (res>0) action = res; return code; } //*-*- May be a graphical cut ? TCutG *gcut = (TCutG*)gROOT->GetListOfSpecials()->FindObject(name.Data()); if (gcut) { if (gcut->GetObjectX()) { if(!gcut->GetObjectX()->InheritsFrom(TTreeFormula::Class())) { delete gcut->GetObjectX(); gcut->SetObjectX(0); } } if (gcut->GetObjectY()) { if(!gcut->GetObjectY()->InheritsFrom(TTreeFormula::Class())) { delete gcut->GetObjectY(); gcut->SetObjectY(0); } } Int_t code = fNcodes; if (strlen(gcut->GetVarX()) && strlen(gcut->GetVarY()) ) { TTreeFormula *fx = new TTreeFormula("f_x",gcut->GetVarX(),fTree); gcut->SetObjectX(fx); TTreeFormula *fy = new TTreeFormula("f_y",gcut->GetVarY(),fTree); gcut->SetObjectY(fy); fCodes[code] = -2; } else if (strlen(gcut->GetVarX())) { // Let's build the equivalent formula: // min(gcut->X) <= VarX <= max(gcut->Y) Double_t min = 0; Double_t max = 0; Int_t n = gcut->GetN(); Double_t *x = gcut->GetX(); min = max = x[0]; for(Int_t i2 = 1; i2<n; i2++) { if (x[i2] < min) min = x[i2]; if (x[i2] > max) max = x[i2]; } TString formula = "("; formula += min; formula += "<="; formula += gcut->GetVarX(); formula += " && "; formula += gcut->GetVarX(); formula += "<="; formula += max; formula += ")"; TTreeFormula *fx = new TTreeFormula("f_x",formula.Data(),fTree); gcut->SetObjectX(fx); fCodes[code] = -1; } else { Error("DefinedVariable","Found a TCutG without leaf information (%s)", gcut->GetName()); return -1; } fExternalCuts.AddAtAndExpand(gcut,code); fNcodes++; fLookupType[code] = -1; return code; } //may be an entrylist TEntryList *elist = dynamic_cast<TEntryList*> (gDirectory->Get(name.Data())); if (elist) { Int_t code = fNcodes; fCodes[code] = 0; fExternalCuts.AddAtAndExpand(elist, code); fNcodes++; fLookupType[code] = kEntryList; return code; } return -1; } //______________________________________________________________________________ TLeaf* TTreeFormula::GetLeafWithDatamember(const char* topchoice, const char* nextchoice, Long64_t readentry) const { // Return the leaf (if any) which contains an object containing // a data member which has the name provided in the arguments. TClass * cl = 0; TIter nextleaf (fTree->GetIteratorOnAllLeaves()); TFormLeafInfo* clonesinfo = 0; TLeaf *leafcur; while ((leafcur = (TLeaf*)nextleaf())) { // The following code is used somewhere else, we need to factor it out. // Here since we are interested in data member, we want to consider only // 'terminal' branch and leaf. cl = 0; if (leafcur->InheritsFrom(TLeafObject::Class()) && leafcur->GetBranch()->GetListOfBranches()->Last()==0) { TLeafObject *lobj = (TLeafObject*)leafcur; cl = lobj->GetClass(); } else if (leafcur->InheritsFrom(TLeafElement::Class()) && leafcur->IsOnTerminalBranch()) { TLeafElement * lElem = (TLeafElement*) leafcur; if (lElem->IsOnTerminalBranch()) { TBranchElement *branchEl = (TBranchElement *)leafcur->GetBranch(); Int_t type = branchEl->GetStreamerType(); if (type==-1) { cl = branchEl->GetInfo()->GetClass(); } else if (type>60 || type==0) { // Case of an object data member. Here we allow for the // variable name to be ommitted. Eg, for Event.root with split // level 1 or above Draw("GetXaxis") is the same as Draw("fH.GetXaxis()") TStreamerElement* element = (TStreamerElement*) branchEl->GetInfo()->GetElems()[branchEl->GetID()]; if (element) cl = element->GetClassPointer(); else cl = 0; } } } if (clonesinfo) { delete clonesinfo; clonesinfo = 0; } if (cl == TClonesArray::Class()) { // We have a unsplit TClonesArray leaves // In this case we assume that cl is the class in which the TClonesArray // belongs. R__LoadBranch(leafcur->GetBranch(),readentry,fQuickLoad); TClonesArray * clones; TBranch *branch = leafcur->GetBranch(); if ( branch->IsA()==TBranchElement::Class() && ((TBranchElement*)branch)->GetType()==31) { // We have an unsplit TClonesArray as part of a split TClonesArray! // Let's not dig any further. If the user really wants a data member // inside the nested TClonesArray, it has to specify it explicitly. continue; } else { Bool_t toplevel = (branch == branch->GetMother()); clonesinfo = new TFormLeafInfoClones(cl, 0, toplevel); clones = (TClonesArray*)clonesinfo->GetLocalValuePointer(leafcur,0); } if (clones) cl = clones->GetClass(); } else if (cl && cl->GetCollectionProxy()) { // We have a unsplit Collection leaves // In this case we assume that cl is the class in which the TClonesArray // belongs. TBranch *branch = leafcur->GetBranch(); if ( branch->IsA()==TBranchElement::Class() && ((TBranchElement*)branch)->GetType()==41) { // We have an unsplit Collection as part of a split Collection! // Let's not dig any further. If the user really wants a data member // inside the nested Collection, it has to specify it explicitly. continue; } else { clonesinfo = new TFormLeafInfoCollection(cl, 0); } cl = cl->GetCollectionProxy()->GetValueClass(); } if (cl) { // Now that we have the class, let's check if the topchoice is of its datamember // or if the nextchoice is a datamember of one of its datamember. Int_t offset; TStreamerInfo* info = (TStreamerInfo*)cl->GetStreamerInfo(); TStreamerElement* element = info?info->GetStreamerElement(topchoice,offset):0; if (!element) { TIter nextel( cl->GetStreamerInfo()->GetElements() ); TStreamerElement * curelem; while ((curelem = (TStreamerElement*)nextel())) { if (curelem->GetClassPointer() == TClonesArray::Class()) { // In case of a TClonesArray we need to load the data and read the // clonesArray object before being able to look into the class inside. // We need to do that because we are never interested in the TClonesArray // itself but only in the object inside. TBranch *branch = leafcur->GetBranch(); TFormLeafInfo *leafinfo = 0; if (clonesinfo) { leafinfo = clonesinfo; } else if (branch->IsA()==TBranchElement::Class() && ((TBranchElement*)branch)->GetType()==31) { // Case of a sub branch of a TClonesArray TBranchElement *branchEl = (TBranchElement*)branch; TStreamerInfo *bel_info = branchEl->GetInfo(); TClass * mother_cl = ((TBranchElement*)branch)->GetInfo()->GetClass(); TStreamerElement *bel_element = (TStreamerElement *)bel_info->GetElems()[branchEl->GetID()]; leafinfo = new TFormLeafInfoClones(mother_cl, 0, bel_element, kTRUE); } Int_t clones_offset = 0; ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(curelem->GetName(),clones_offset); TFormLeafInfo* sub_clonesinfo = new TFormLeafInfo(cl, clones_offset, curelem); if (leafinfo) if (leafinfo->fNext) leafinfo->fNext->fNext = sub_clonesinfo; else leafinfo->fNext = sub_clonesinfo; else leafinfo = sub_clonesinfo; R__LoadBranch(branch,readentry,fQuickLoad); TClonesArray * clones = (TClonesArray*)leafinfo->GetValuePointer(leafcur,0); delete leafinfo; clonesinfo = 0; // If TClonesArray object does not exist we have no information, so let go // on. This is a weakish test since the TClonesArray object might exist in // the next entry ... In other word, we ONLY rely on the information available // in entry #0. if (!clones) continue; TClass *sub_cl = clones->GetClass(); // Now that we finally have the inside class, let's query it. element = ((TStreamerInfo*)sub_cl->GetStreamerInfo())->GetStreamerElement(nextchoice,offset); if (element) break; } // if clones array else if (curelem->GetClassPointer() && curelem->GetClassPointer()->GetCollectionProxy()) { TClass *sub_cl = curelem->GetClassPointer()->GetCollectionProxy()->GetValueClass(); while(sub_cl && sub_cl->GetCollectionProxy()) sub_cl = sub_cl->GetCollectionProxy()->GetValueClass(); // Now that we finally have the inside class, let's query it. if (sub_cl) element = ((TStreamerInfo*)sub_cl->GetStreamerInfo())->GetStreamerElement(nextchoice,offset); if (element) break; } } // loop on elements } if (element) break; else cl = 0; } } delete clonesinfo; if (cl) { return leafcur; } else { return 0; } } //______________________________________________________________________________ Bool_t TTreeFormula::BranchHasMethod(TLeaf* leafcur, TBranch* branch, const char* method, const char* params, Long64_t readentry) const { // Return the leaf (if any) of the tree with contains an object of a class // having a method which has the name provided in the argument. TClass *cl = 0; TLeafObject* lobj = 0; // Since the user does not want this branch to be loaded anyway, we just // skip it. This prevents us from warning the user that the method might // be on a disabled branch. However, and more usefully, this allows the // user to avoid error messages from branches that cannot be currently // read without warnings/errors. if (branch->TestBit(kDoNotProcess)) { return kFALSE; } // FIXME: The following code is used somewhere else, we need to factor it out. if (branch->InheritsFrom(TBranchObject::Class())) { lobj = (TLeafObject*) branch->GetListOfLeaves()->At(0); cl = lobj->GetClass(); } else if (branch->InheritsFrom(TBranchElement::Class())) { TBranchElement* branchEl = (TBranchElement*) branch; Int_t type = branchEl->GetStreamerType(); if (type == -1) { cl = branchEl->GetInfo()->GetClass(); } else if (type > 60) { // Case of an object data member. Here we allow for the // variable name to be ommitted. Eg, for Event.root with split // level 1 or above Draw("GetXaxis") is the same as Draw("fH.GetXaxis()") TStreamerElement* element = (TStreamerElement*) branchEl->GetInfo()->GetElems()[branchEl->GetID()]; if (element) { cl = element->GetClassPointer(); } else { cl = 0; } if ((cl == TClonesArray::Class()) && (branchEl->GetType() == 31)) { // we have a TClonesArray inside a split TClonesArray, // Let's not dig any further. If the user really wants a data member // inside the nested TClonesArray, it has to specify it explicitly. cl = 0; } // NOTE do we need code for Collection here? } } if (cl == TClonesArray::Class()) { // We might be try to call a method of the top class inside a // TClonesArray. // Since the leaf was not terminal, we might have a split or // unsplit and/or top leaf/branch. TClonesArray* clones = 0; R__LoadBranch(branch, readentry, fQuickLoad); if (branch->InheritsFrom(TBranchObject::Class())) { clones = (TClonesArray*) lobj->GetObject(); } else if (branch->InheritsFrom(TBranchElement::Class())) { // We do not know exactly where the leaf of the TClonesArray is // in the hierachy but we still need to get the correct class // holder. TBranchElement* bc = (TBranchElement*) branch; if (bc == bc->GetMother()) { // Top level branch //clones = *((TClonesArray**) bc->GetAddress()); clones = (TClonesArray*) bc->GetObject(); } else if (!leafcur || !leafcur->IsOnTerminalBranch()) { TStreamerElement* element = (TStreamerElement*) bc->GetInfo()->GetElems()[bc->GetID()]; if (element->IsaPointer()) { clones = *((TClonesArray**) bc->GetAddress()); //clones = *((TClonesArray**) bc->GetObject()); } else { //clones = (TClonesArray*) bc->GetAddress(); clones = (TClonesArray*) bc->GetObject(); } } if (!clones) { R__LoadBranch(bc, readentry, fQuickLoad); TClass* mother_cl; mother_cl = bc->GetInfo()->GetClass(); TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(mother_cl, 0); // if (!leafcur) { leafcur = (TLeaf*) branch->GetListOfLeaves()->At(0); } clones = (TClonesArray*) clonesinfo->GetLocalValuePointer(leafcur, 0); // cl = clones->GetClass(); delete clonesinfo; } } else { Error("BranchHasMethod","A TClonesArray was stored in a branch type no yet support (i.e. neither TBranchObject nor TBranchElement): %s",branch->IsA()->GetName()); return kFALSE; } cl = clones ? clones->GetClass() : 0; } else if (cl && cl->GetCollectionProxy()) { cl = cl->GetCollectionProxy()->GetValueClass(); } if (cl) { if (cl->GetClassInfo()) { if (cl->GetMethodAllAny(method)) { // Let's try to see if the function we found belongs to the current // class. Note that this implementation currently can not work if // one the argument is another leaf or data member of the object. // (Anyway we do NOT support this case). TMethodCall* methodcall = new TMethodCall(cl, method, params); if (methodcall->GetMethod()) { // We have a method that works. // We will use it. return kTRUE; } delete methodcall; } } } return kFALSE; } //______________________________________________________________________________ Int_t TTreeFormula::GetRealInstance(Int_t instance, Int_t codeindex) { // Now let calculate what physical instance we really need. // Some redundant code is used to speed up the cases where // they are no dimensions. // We know that instance is less that fCumulUsedSize[0] so // we can skip the modulo when virt_dim is 0. Int_t real_instance = 0; Int_t virt_dim; Bool_t check = kFALSE; if (codeindex<0) { codeindex = 0; check = kTRUE; } TFormLeafInfo * info = 0; Int_t max_dim = fNdimensions[codeindex]; if ( max_dim ) { virt_dim = 0; max_dim--; if (!fManager->fMultiVarDim) { if (fIndexes[codeindex][0]>=0) { real_instance = fIndexes[codeindex][0] * fCumulSizes[codeindex][1]; } else { Int_t local_index; local_index = ( instance / fManager->fCumulUsedSizes[virt_dim+1]); if (fIndexes[codeindex][0]==-2) { // NOTE: Should we check that this is a valid index? if (check) { Int_t index_real_instance = fVarIndexes[codeindex][0]->GetRealInstance(local_index,-1); if (index_real_instance > fVarIndexes[codeindex][0]->fNdata[0]) { // out of bounds return fNdata[0]+1; } } if (fDidBooleanOptimization && local_index!=0) { // Force the loading of the index. fVarIndexes[codeindex][0]->LoadBranches(); } local_index = (Int_t)fVarIndexes[codeindex][0]->EvalInstance(local_index); if (local_index<0) { Error("EvalInstance","Index %s is out of bound (%d) in formula %s", fVarIndexes[codeindex][0]->GetTitle(), local_index, GetTitle()); return fNdata[0]+1; } } real_instance = local_index * fCumulSizes[codeindex][1]; virt_dim ++; } } else { // NOTE: We assume that ONLY the first dimension of a leaf can have a variable // size AND contain the index for the size of yet another sub-dimension. // I.e. a variable size array inside a variable size array can only have its // size vary with the VERY FIRST physical dimension of the leaf. // Thus once the index of the first dimension is found, all other dimensions // are fixed! // NOTE: We could unroll some of this loops to avoid a few tests. if (fHasMultipleVarDim[codeindex]) { info = (TFormLeafInfo *)(fDataMembers.At(codeindex)); // if (info && info->GetVarDim()==-1) info = 0; } Int_t local_index; switch (fIndexes[codeindex][0]) { case -2: if (fDidBooleanOptimization && instance!=0) { // Force the loading of the index. fVarIndexes[codeindex][0]->LoadBranches(); } local_index = (Int_t)fVarIndexes[codeindex][0]->EvalInstance(instance); if (local_index<0) { Error("EvalInstance","Index %s is out of bound (%d) in formula %s", fVarIndexes[codeindex][0]->GetTitle(), local_index, GetTitle()); local_index = 0; } break; case -1: { local_index = 0; Int_t virt_accum = 0; Int_t maxloop = fManager->fCumulUsedVarDims->GetSize(); if (maxloop == 0) { local_index--; instance = fNdata[0]+1; // out of bounds. if (check) return fNdata[0]+1; } else { do { virt_accum += fManager->fCumulUsedVarDims->GetArray()[local_index]; local_index++; } while( instance >= virt_accum && local_index<maxloop); if (local_index==maxloop && (instance >= virt_accum)) { local_index--; instance = fNdata[0]+1; // out of bounds. if (check) return fNdata[0]+1; } else { local_index--; if (fManager->fCumulUsedVarDims->At(local_index)) { instance -= (virt_accum - fManager->fCumulUsedVarDims->At(local_index)); } else { instance = fNdata[0]+1; // out of bounds. if (check) return fNdata[0]+1; } } } virt_dim ++; } break; default: local_index = fIndexes[codeindex][0]; } // Inform the (appropriate) MultiVarLeafInfo that the clones array index is // local_index. if (fManager->fVarDims[kMAXFORMDIM]) { fManager->fCumulUsedSizes[kMAXFORMDIM] = fManager->fVarDims[kMAXFORMDIM]->At(local_index); } else { fManager->fCumulUsedSizes[kMAXFORMDIM] = fManager->fUsedSizes[kMAXFORMDIM]; } for(Int_t d = kMAXFORMDIM-1; d>0; d--) { if (fManager->fVarDims[d]) { fManager->fCumulUsedSizes[d] = fManager->fCumulUsedSizes[d+1] * fManager->fVarDims[d]->At(local_index); } else { fManager->fCumulUsedSizes[d] = fManager->fCumulUsedSizes[d+1] * fManager->fUsedSizes[d]; } } if (info) { // When we have multiple variable dimensions, the LeafInfo only expect // the instance after the primary index has been set. info->SetPrimaryIndex(local_index); real_instance = 0; // Let's update fCumulSizes for the rest of the code. Int_t vdim = info->GetVarDim(); Int_t isize = info->GetSize(local_index); if (fIndexes[codeindex][vdim]>=0) { info->SetSecondaryIndex(fIndexes[codeindex][vdim]); } if (isize!=1 && fIndexes[codeindex][vdim]>isize) { // We are out of bounds! return fNdata[0]+1; } fCumulSizes[codeindex][vdim] = isize*fCumulSizes[codeindex][vdim+1]; for(Int_t k=vdim -1; k>0; --k) { fCumulSizes[codeindex][k] = fCumulSizes[codeindex][k+1]*fFixedSizes[codeindex][k]; } } else { real_instance = local_index * fCumulSizes[codeindex][1]; } } if (max_dim>0) { for (Int_t dim = 1; dim < max_dim; dim++) { if (fIndexes[codeindex][dim]>=0) { real_instance += fIndexes[codeindex][dim] * fCumulSizes[codeindex][dim+1]; } else { Int_t local_index; if (virt_dim && fManager->fCumulUsedSizes[virt_dim]>1) { local_index = ( ( instance % fManager->fCumulUsedSizes[virt_dim] ) / fManager->fCumulUsedSizes[virt_dim+1]); } else { local_index = ( instance / fManager->fCumulUsedSizes[virt_dim+1]); } if (fIndexes[codeindex][dim]==-2) { // NOTE: Should we check that this is a valid index? if (fDidBooleanOptimization && local_index!=0) { // Force the loading of the index. fVarIndexes[codeindex][dim]->LoadBranches(); } local_index = (Int_t)fVarIndexes[codeindex][dim]->EvalInstance(local_index); if (local_index<0 || local_index>=(fCumulSizes[codeindex][dim]/fCumulSizes[codeindex][dim+1])) { Error("EvalInstance","Index %s is out of bound (%d/%d) in formula %s", fVarIndexes[codeindex][dim]->GetTitle(), local_index, (fCumulSizes[codeindex][dim]/fCumulSizes[codeindex][dim+1]), GetTitle()); local_index = (fCumulSizes[codeindex][dim]/fCumulSizes[codeindex][dim+1])-1; } } real_instance += local_index * fCumulSizes[codeindex][dim+1]; virt_dim ++; } } if (fIndexes[codeindex][max_dim]>=0) { if (!info) real_instance += fIndexes[codeindex][max_dim]; } else { Int_t local_index; if (virt_dim && fManager->fCumulUsedSizes[virt_dim]>1) { local_index = instance % fManager->fCumulUsedSizes[virt_dim]; } else { local_index = instance; } if (info && local_index>=fCumulSizes[codeindex][max_dim]) { // We are out of bounds! [Multiple var dims, See same message a few line above] return fNdata[0]+1; } if (fIndexes[codeindex][max_dim]==-2) { if (fDidBooleanOptimization && local_index!=0) { // Force the loading of the index. fVarIndexes[codeindex][max_dim]->LoadBranches(); } local_index = (Int_t)fVarIndexes[codeindex][max_dim]->EvalInstance(local_index); if (local_index<0 || local_index>=fCumulSizes[codeindex][max_dim]) { Error("EvalInstance","Index %s is of out bound (%d/%d) in formula %s", fVarIndexes[codeindex][max_dim]->GetTitle(), local_index, fCumulSizes[codeindex][max_dim], GetTitle()); local_index = fCumulSizes[codeindex][max_dim]-1; } } real_instance += local_index; } } // if (max_dim-1>0) } // if (max_dim) return real_instance; } //______________________________________________________________________________ TClass* TTreeFormula::EvalClass() const { // Evaluate the class of this treeformula // // If the 'value' of this formula is a simple pointer to an object, // this function returns the TClass corresponding to its type. if (fNoper != 1 || fNcodes <=0 ) return 0; return EvalClass(0); } //______________________________________________________________________________ TClass* TTreeFormula::EvalClass(Int_t oper) const { // Evaluate the class of the operation oper // // If the 'value' in the requested operation is a simple pointer to an object, // this function returns the TClass corresponding to its type. TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(oper); switch(fLookupType[oper]) { case kDirect: { if (leaf->IsA()==TLeafObject::Class()) { return ((TLeafObject*)leaf)->GetClass(); } else if ( leaf->IsA()==TLeafElement::Class()) { TBranchElement * branch = (TBranchElement*)((TLeafElement*)leaf)->GetBranch(); TStreamerInfo * info = branch->GetInfo(); Int_t id = branch->GetID(); if (id>=0) { if (info==0 || info->GetElems()==0) { // we probably do not have a way to know the class of the object. return 0; } TStreamerElement* elem = (TStreamerElement*)info->GetElems()[id]; if (elem==0) { // we probably do not have a way to know the class of the object. return 0; } else { return elem->GetClass(); } } else return TClass::GetClass( branch->GetClassName() ); } else { return 0; } } case kMethod: return 0; // kMethod is deprecated so let's no waste time implementing this. case kTreeMember: case kDataMember: { TObject *obj = fDataMembers.UncheckedAt(oper); if (!obj) return 0; return ((TFormLeafInfo*)obj)->GetClass(); } default: return 0; } } //______________________________________________________________________________ void* TTreeFormula::EvalObject(int instance) { //*-*-*-*-*-*-*-*-*-*-*Evaluate this treeformula*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================= // // Return the address of the object pointed to by the formula. // Return 0 if the formula is not a single object // The object type can be retrieved using by call EvalClass(); if (fNoper != 1 || fNcodes <=0 ) return 0; switch (fLookupType[0]) { case kIndexOfEntry: case kIndexOfLocalEntry: case kEntries: case kLength: case kLengthFunc: case kIteration: case kEntryList: return 0; } TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); Int_t real_instance = GetRealInstance(instance,0); if (instance==0 || fNeedLoading) { fNeedLoading = kFALSE; R__LoadBranch(leaf->GetBranch(), leaf->GetBranch()->GetTree()->GetReadEntry(), fQuickLoad); } else if (real_instance>fNdata[0]) return 0; if (fAxis) { return 0; } switch(fLookupType[0]) { case kDirect: { if (real_instance) { Warning("EvalObject","Not yet implement for kDirect and arrays (for %s).\nPlease contact the developers",GetName()); } return leaf->GetValuePointer(); } case kMethod: return GetValuePointerFromMethod(0,leaf); case kTreeMember: case kDataMember: return ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->GetValuePointer(leaf,real_instance); default: return 0; } } //______________________________________________________________________________ const char* TTreeFormula::EvalStringInstance(Int_t instance) { // Eval the instance as a string. const Int_t kMAXSTRINGFOUND = 10; const char *stringStack[kMAXSTRINGFOUND]; if (fNoper==1 && fNcodes>0 && IsString()) { TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); Int_t real_instance = GetRealInstance(instance,0); if (instance==0 || fNeedLoading) { fNeedLoading = kFALSE; TBranch *branch = leaf->GetBranch(); R__LoadBranch(branch,branch->GetTree()->GetReadEntry(),fQuickLoad); } else if (real_instance>=fNdata[0]) { return 0; } if (fLookupType[0]==kDirect) { return (char*)leaf->GetValuePointer(); } else { return (char*)GetLeafInfo(0)->GetValuePointer(leaf,real_instance); } } EvalInstance(instance,stringStack); return stringStack[0]; } #define TT_EVAL_INIT \ TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); \ \ const Int_t real_instance = GetRealInstance(instance,0); \ \ if (instance==0) fNeedLoading = kTRUE; \ if (real_instance>fNdata[0]) return 0; \ \ /* Since the only operation in this formula is reading this branch, \ we are guaranteed that this function is first called with instance==0 and \ hence we are guaranteed that the branch is always properly read */ \ \ if (fNeedLoading) { \ fNeedLoading = kFALSE; \ TBranch *br = leaf->GetBranch(); \ Long64_t tentry = br->GetTree()->GetReadEntry(); \ R__LoadBranch(br,tentry,fQuickLoad); \ } \ \ if (fAxis) { \ char * label; \ /* This portion is a duplicate (for speed reason) of the code \ located in the main for loop at "a tree string" (and in EvalStringInstance) */ \ if (fLookupType[0]==kDirect) { \ label = (char*)leaf->GetValuePointer(); \ } else { \ label = (char*)GetLeafInfo(0)->GetValuePointer(leaf,instance); \ } \ Int_t bin = fAxis->FindBin(label); \ return bin-0.5; \ } #define TREE_EVAL_INIT \ const Int_t real_instance = GetRealInstance(instance,0); \ \ if (real_instance>fNdata[0]) return 0; \ \ if (fAxis) { \ char * label; \ /* This portion is a duplicate (for speed reason) of the code \ located in the main for loop at "a tree string" (and in EvalStringInstance) */ \ label = (char*)GetLeafInfo(0)->GetValuePointer((TLeaf*)0x0,instance); \ Int_t bin = fAxis->FindBin(label); \ return bin-0.5; \ } #define TT_EVAL_INIT_LOOP \ TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(code); \ \ /* Now let calculate what physical instance we really need. */ \ const Int_t real_instance = GetRealInstance(instance,code); \ \ if (willLoad) { \ TBranch *branch = (TBranch*)fBranches.UncheckedAt(code); \ if (branch) { \ Long64_t treeEntry = branch->GetTree()->GetReadEntry(); \ R__LoadBranch(branch,treeEntry,fQuickLoad); \ } else if (fDidBooleanOptimization) { \ branch = leaf->GetBranch(); \ Long64_t treeEntry = branch->GetTree()->GetReadEntry(); \ if (branch->GetReadEntry() != treeEntry) branch->GetEntry( treeEntry ); \ } \ } else { \ /* In the cases where we are behind (i.e. right of) a potential boolean optimization \ this tree variable reading may have not been executed with instance==0 which would \ result in the branch being potentially not read in. */ \ if (fDidBooleanOptimization) { \ TBranch *br = leaf->GetBranch(); \ Long64_t treeEntry = br->GetTree()->GetReadEntry(); \ if (br->GetReadEntry() != treeEntry) br->GetEntry( treeEntry ); \ } \ } \ if (real_instance>fNdata[code]) return 0; #define TREE_EVAL_INIT_LOOP \ /* Now let calculate what physical instance we really need. */ \ const Int_t real_instance = GetRealInstance(instance,code); \ \ if (real_instance>fNdata[code]) return 0; namespace { Double_t Summing(TTreeFormula *sum) { Int_t len = sum->GetNdata(); Double_t res = 0; for (int i=0; i<len; ++i) res += sum->EvalInstance(i); return res; } Double_t FindMin(TTreeFormula *arr) { Int_t len = arr->GetNdata(); Double_t res = 0; if (len) { res = arr->EvalInstance(0); for (int i=1; i<len; ++i) { Double_t val = arr->EvalInstance(i); if (val < res) { res = val; } } } return res; } Double_t FindMax(TTreeFormula *arr) { Int_t len = arr->GetNdata(); Double_t res = 0; if (len) { res = arr->EvalInstance(0); for (int i=1; i<len; ++i) { Double_t val = arr->EvalInstance(i); if (val > res) { res = val; } } } return res; } Double_t FindMin(TTreeFormula *arr, TTreeFormula *condition) { Int_t len = arr->GetNdata(); Double_t res = 0; if (len) { int i = 0; Double_t condval; do { condval = condition->EvalInstance(i); ++i; } while (!condval && i<len); if (i==len) { return 0; } if (i!=1) { // Insure the loading of the branch. arr->EvalInstance(0); } // Now we know that i>0 && i<len and cond==true res = arr->EvalInstance(i-1); for (; i<len; ++i) { condval = condition->EvalInstance(i); if (condval) { Double_t val = arr->EvalInstance(i); if (val < res) { res = val; } } } } return res; } Double_t FindMax(TTreeFormula *arr, TTreeFormula *condition) { Int_t len = arr->GetNdata(); Double_t res = 0; if (len) { int i = 0; Double_t condval; do { condval = condition->EvalInstance(i); ++i; } while (!condval && i<len); if (i==len) { return 0; } if (i!=1) { // Insure the loading of the branch. arr->EvalInstance(0); } // Now we know that i>0 && i<len and cond==true res = arr->EvalInstance(i-1); for (; i<len; ++i) { condval = condition->EvalInstance(i); if (condval) { Double_t val = arr->EvalInstance(i); if (val > res) { res = val; } } } } return res; } } //______________________________________________________________________________ Double_t TTreeFormula::EvalInstance(Int_t instance, const char *stringStackArg[]) { //*-*-*-*-*-*-*-*-*-*-*Evaluate this treeformula*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================= // // Note that the redundance and structure in this code is tailored to improve // efficiencies. if (TestBit(kMissingLeaf)) return 0; if (fNoper == 1 && fNcodes > 0) { switch (fLookupType[0]) { case kDirect: { TT_EVAL_INIT; Double_t result = leaf->GetValue(real_instance); return result; } case kMethod: { TT_EVAL_INIT; ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->SetBranch(leaf->GetBranch()); return GetValueFromMethod(0,leaf); } case kDataMember: { TT_EVAL_INIT; ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->SetBranch(leaf->GetBranch()); return ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->GetValue(leaf,real_instance); } case kTreeMember: { TREE_EVAL_INIT; return ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->GetValue((TLeaf*)0x0,real_instance); } case kIndexOfEntry: return (Double_t)fTree->GetReadEntry(); case kIndexOfLocalEntry: return (Double_t)fTree->GetTree()->GetReadEntry(); case kEntries: return (Double_t)fTree->GetEntries(); case kLength: return fManager->fNdata; case kLengthFunc: return ((TTreeFormula*)fAliases.UncheckedAt(0))->GetNdata(); case kIteration: return instance; case kSum: return Summing((TTreeFormula*)fAliases.UncheckedAt(0)); case kMin: return FindMin((TTreeFormula*)fAliases.UncheckedAt(0)); case kMax: return FindMax((TTreeFormula*)fAliases.UncheckedAt(0)); case kEntryList: { TEntryList *elist = (TEntryList*)fExternalCuts.At(0); return elist->Contains(fTree->GetTree()->GetReadEntry()); } case -1: break; } switch (fCodes[0]) { case -2: { TCutG *gcut = (TCutG*)fExternalCuts.At(0); TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); TTreeFormula *fy = (TTreeFormula *)gcut->GetObjectY(); Double_t xcut = fx->EvalInstance(instance); Double_t ycut = fy->EvalInstance(instance); return gcut->IsInside(xcut,ycut); } case -1: { TCutG *gcut = (TCutG*)fExternalCuts.At(0); TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); return fx->EvalInstance(instance); } default: return 0; } } Double_t tab[kMAXFOUND]; const Int_t kMAXSTRINGFOUND = 10; const char *stringStackLocal[kMAXSTRINGFOUND]; const char **stringStack = stringStackArg?stringStackArg:stringStackLocal; const Bool_t willLoad = (instance==0 || fNeedLoading); fNeedLoading = kFALSE; if (willLoad) fDidBooleanOptimization = kFALSE; Int_t pos = 0; Int_t pos2 = 0; for (Int_t i=0; i<fNoper ; ++i) { const Int_t oper = GetOper()[i]; const Int_t newaction = oper >> kTFOperShift; if (newaction<kDefinedVariable) { // TFormula operands. // one of the most used cases if (newaction==kConstant) { pos++; tab[pos-1] = fConst[(oper & kTFOperMask)]; continue; } switch(newaction) { case kEnd : return tab[0]; case kAdd : pos--; tab[pos-1] += tab[pos]; continue; case kSubstract : pos--; tab[pos-1] -= tab[pos]; continue; case kMultiply : pos--; tab[pos-1] *= tab[pos]; continue; case kDivide : pos--; if (tab[pos] == 0) tab[pos-1] = 0; // division by 0 else tab[pos-1] /= tab[pos]; continue; case kModulo : {pos--; Long64_t int1((Long64_t)tab[pos-1]); Long64_t int2((Long64_t)tab[pos]); tab[pos-1] = Double_t(int1%int2); continue;} case kcos : tab[pos-1] = TMath::Cos(tab[pos-1]); continue; case ksin : tab[pos-1] = TMath::Sin(tab[pos-1]); continue; case ktan : if (TMath::Cos(tab[pos-1]) == 0) {tab[pos-1] = 0;} // { tangente indeterminee } else tab[pos-1] = TMath::Tan(tab[pos-1]); continue; case kacos : if (TMath::Abs(tab[pos-1]) > 1) {tab[pos-1] = 0;} // indetermination else tab[pos-1] = TMath::ACos(tab[pos-1]); continue; case kasin : if (TMath::Abs(tab[pos-1]) > 1) {tab[pos-1] = 0;} // indetermination else tab[pos-1] = TMath::ASin(tab[pos-1]); continue; case katan : tab[pos-1] = TMath::ATan(tab[pos-1]); continue; case kcosh : tab[pos-1] = TMath::CosH(tab[pos-1]); continue; case ksinh : tab[pos-1] = TMath::SinH(tab[pos-1]); continue; case ktanh : if (TMath::CosH(tab[pos-1]) == 0) {tab[pos-1] = 0;} // { tangente indeterminee } else tab[pos-1] = TMath::TanH(tab[pos-1]); continue; case kacosh: if (tab[pos-1] < 1) {tab[pos-1] = 0;} // indetermination else tab[pos-1] = TMath::ACosH(tab[pos-1]); continue; case kasinh: tab[pos-1] = TMath::ASinH(tab[pos-1]); continue; case katanh: if (TMath::Abs(tab[pos-1]) > 1) {tab[pos-1] = 0;} // indetermination else tab[pos-1] = TMath::ATanH(tab[pos-1]); continue; case katan2: pos--; tab[pos-1] = TMath::ATan2(tab[pos-1],tab[pos]); continue; case kfmod : pos--; tab[pos-1] = fmod(tab[pos-1],tab[pos]); continue; case kpow : pos--; tab[pos-1] = TMath::Power(tab[pos-1],tab[pos]); continue; case ksq : tab[pos-1] = tab[pos-1]*tab[pos-1]; continue; case ksqrt : tab[pos-1] = TMath::Sqrt(TMath::Abs(tab[pos-1])); continue; case kstrstr : pos2 -= 2; pos++;if (strstr(stringStack[pos2],stringStack[pos2+1])) tab[pos-1]=1; else tab[pos-1]=0; continue; case kmin : pos--; tab[pos-1] = TMath::Min(tab[pos-1],tab[pos]); continue; case kmax : pos--; tab[pos-1] = TMath::Max(tab[pos-1],tab[pos]); continue; case klog : if (tab[pos-1] > 0) tab[pos-1] = TMath::Log(tab[pos-1]); else {tab[pos-1] = 0;} //{indetermination } continue; case kexp : { Double_t dexp = tab[pos-1]; if (dexp < -700) {tab[pos-1] = 0; continue;} if (dexp > 700) {tab[pos-1] = TMath::Exp(700); continue;} tab[pos-1] = TMath::Exp(dexp); continue; } case klog10: if (tab[pos-1] > 0) tab[pos-1] = TMath::Log10(tab[pos-1]); else {tab[pos-1] = 0;} //{indetermination } continue; case kpi : pos++; tab[pos-1] = TMath::ACos(-1); continue; case kabs : tab[pos-1] = TMath::Abs(tab[pos-1]); continue; case ksign : if (tab[pos-1] < 0) tab[pos-1] = -1; else tab[pos-1] = 1; continue; case kint : tab[pos-1] = Double_t(Int_t(tab[pos-1])); continue; case kSignInv: tab[pos-1] = -1 * tab[pos-1]; continue; case krndm : pos++; tab[pos-1] = gRandom->Rndm(1); continue; case kAnd : pos--; if (tab[pos-1]!=0 && tab[pos]!=0) tab[pos-1]=1; else tab[pos-1]=0; continue; case kOr : pos--; if (tab[pos-1]!=0 || tab[pos]!=0) tab[pos-1]=1; else tab[pos-1]=0; continue; case kEqual : pos--; tab[pos-1] = (tab[pos-1] == tab[pos]) ? 1 : 0; continue; case kNotEqual : pos--; tab[pos-1] = (tab[pos-1] != tab[pos]) ? 1 : 0; continue; case kLess : pos--; tab[pos-1] = (tab[pos-1] < tab[pos]) ? 1 : 0; continue; case kGreater : pos--; tab[pos-1] = (tab[pos-1] > tab[pos]) ? 1 : 0; continue; case kLessThan : pos--; tab[pos-1] = (tab[pos-1] <= tab[pos]) ? 1 : 0; continue; case kGreaterThan: pos--; tab[pos-1] = (tab[pos-1] >= tab[pos]) ? 1 : 0; continue; case kNot : tab[pos-1] = (tab[pos-1] != 0) ? 0 : 1; continue; case kStringEqual : pos2 -= 2; pos++; if (!strcmp(stringStack[pos2+1],stringStack[pos2])) tab[pos-1]=1; else tab[pos-1]=0; continue; case kStringNotEqual: pos2 -= 2; pos++;if (strcmp(stringStack[pos2+1],stringStack[pos2])) tab[pos-1]=1; else tab[pos-1]=0; continue; case kBitAnd : pos--; tab[pos-1]= ((Long64_t) tab[pos-1]) & ((Long64_t) tab[pos]); continue; case kBitOr : pos--; tab[pos-1]= ((Long64_t) tab[pos-1]) | ((Long64_t) tab[pos]); continue; case kLeftShift : pos--; tab[pos-1]= ((Long64_t) tab[pos-1]) <<((Long64_t) tab[pos]); continue; case kRightShift: pos--; tab[pos-1]= ((Long64_t) tab[pos-1]) >>((Long64_t) tab[pos]); continue; case kJump : i = (oper & kTFOperMask); continue; case kJumpIf : { pos--; if (!tab[pos]) { i = (oper & kTFOperMask); // If we skip the left (true) side of the if statement we may, // skip some of the branch loading (since we remove duplicate branch // request (in TTreeFormula constructor) and so we need to force the // loading here. if (willLoad) fDidBooleanOptimization = kTRUE; } continue; } case kStringConst: { // String pos2++; stringStack[pos2-1] = (char*)fExpr[i].Data(); if (fAxis) { // See TT_EVAL_INIT Int_t bin = fAxis->FindBin(stringStack[pos2-1]); \ return bin; } continue; } case kBoolOptimize: { // boolean operation optimizer int param = (oper & kTFOperMask); Bool_t skip = kFALSE; int op = param % 10; // 1 is && , 2 is || if (op == 1 && (!tab[pos-1]) ) { // &&: skip the right part if the left part is already false skip = kTRUE; // Preserve the existing behavior (i.e. the result of a&&b is // either 0 or 1) tab[pos-1] = 0; } else if (op == 2 && tab[pos-1] ) { // ||: skip the right part if the left part is already true skip = kTRUE; // Preserve the existing behavior (i.e. the result of a||b is // either 0 or 1) tab[pos-1] = 1; } if (skip) { int toskip = param / 10; i += toskip; if (willLoad) fDidBooleanOptimization = kTRUE; } continue; } case kFunctionCall: { // an external function call int param = (oper & kTFOperMask); int fno = param / 1000; int nargs = param % 1000; // Retrieve the function TMethodCall *method = (TMethodCall*)fFunctions.At(fno); // Set the arguments method->ResetParam(); if (nargs) { UInt_t argloc = pos-nargs; for(Int_t j=0;j<nargs;j++,argloc++,pos--) { method->SetParam( tab[argloc] ); } } pos++; Double_t ret = 0; method->Execute(ret); tab[pos-1] = ret; // check for the correct conversion! continue; } // case kParameter: { pos++; tab[pos-1] = fParams[(oper & kTFOperMask)]; continue; } } } else { // TTreeFormula operands. // a tree variable (the most used case). if (newaction == kDefinedVariable) { const Int_t code = (oper & kTFOperMask); const Int_t lookupType = fLookupType[code]; switch (lookupType) { case kIndexOfEntry: tab[pos++] = (Double_t)fTree->GetReadEntry(); continue; case kIndexOfLocalEntry: tab[pos++] = (Double_t)fTree->GetTree()->GetReadEntry(); continue; case kEntries: tab[pos++] = (Double_t)fTree->GetEntries(); continue; case kLength: tab[pos++] = fManager->fNdata; continue; case kLengthFunc: tab[pos++] = ((TTreeFormula*)fAliases.UncheckedAt(i))->GetNdata(); continue; case kIteration: tab[pos++] = instance; continue; case kSum: tab[pos++] = Summing((TTreeFormula*)fAliases.UncheckedAt(i)); continue; case kMin: tab[pos++] = FindMin((TTreeFormula*)fAliases.UncheckedAt(i)); continue; case kMax: tab[pos++] = FindMax((TTreeFormula*)fAliases.UncheckedAt(i)); continue; case kDirect: { TT_EVAL_INIT_LOOP; tab[pos++] = leaf->GetValue(real_instance); continue; } case kMethod: { TT_EVAL_INIT_LOOP; tab[pos++] = GetValueFromMethod(code,leaf); continue; } case kDataMember: { TT_EVAL_INIT_LOOP; tab[pos++] = ((TFormLeafInfo*)fDataMembers.UncheckedAt(code))-> GetValue(leaf,real_instance); continue; } case kTreeMember: { TREE_EVAL_INIT_LOOP; tab[pos++] = ((TFormLeafInfo*)fDataMembers.UncheckedAt(code))-> GetValue((TLeaf*)0x0,real_instance); continue; } case kEntryList: { TEntryList *elist = (TEntryList*)fExternalCuts.At(code); tab[pos++] = elist->Contains(fTree->GetReadEntry()); continue;} case -1: break; default: tab[pos++] = 0; continue; } switch (fCodes[code]) { case -2: { TCutG *gcut = (TCutG*)fExternalCuts.At(code); TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); TTreeFormula *fy = (TTreeFormula *)gcut->GetObjectY(); Double_t xcut = fx->EvalInstance(instance); Double_t ycut = fy->EvalInstance(instance); tab[pos++] = gcut->IsInside(xcut,ycut); continue; } case -1: { TCutG *gcut = (TCutG*)fExternalCuts.At(code); TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); tab[pos++] = fx->EvalInstance(instance); continue; } default: { tab[pos++] = 0; continue; } } } switch(newaction) { // a TTree Variable Alias (i.e. a sub-TTreeFormula) case kAlias: { int aliasN = i; TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(aliasN)); R__ASSERT(subform); Double_t param = subform->EvalInstance(instance); tab[pos] = param; pos++; continue; } // a TTree Variable Alias String (i.e. a sub-TTreeFormula) case kAliasString: { int aliasN = i; TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(aliasN)); R__ASSERT(subform); pos2++; stringStack[pos2-1] = subform->EvalStringInstance(instance); continue; } case kMinIf: { int alternateN = i; TTreeFormula *primary = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN)); TTreeFormula *condition = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN+1)); Double_t param = FindMin(primary,condition); ++i; // skip the place holder for the condition tab[pos] = param; pos++; continue; } case kMaxIf: { int alternateN = i; TTreeFormula *primary = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN)); TTreeFormula *condition = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN+1)); Double_t param = FindMax(primary,condition); ++i; // skip the place holder for the condition tab[pos] = param; pos++; continue; } // a TTree Variable Alternate (i.e. a sub-TTreeFormula) case kAlternate: { int alternateN = i; TTreeFormula *primary = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN)); // First check whether we are in range for the primary formula if (instance < primary->GetNdata()) { Double_t param = primary->EvalInstance(instance); ++i; // skip the alternate value. tab[pos] = param; pos++; } else { // The primary is not in rancge, we will calculate the alternate value // via the next operation (which will be a intentional). // kAlias no operations } continue; } case kAlternateString: { int alternateN = i; TTreeFormula *primary = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN)); // First check whether we are in range for the primary formula if (instance < primary->GetNdata()) { pos2++; stringStack[pos2-1] = primary->EvalStringInstance(instance); ++i; // skip the alternate value. } else { // The primary is not in rancge, we will calculate the alternate value // via the next operation (which will be a kAlias). // intentional no operations } continue; } // a tree string case kDefinedString: { Int_t string_code = (oper & kTFOperMask); TLeaf *leafc = (TLeaf*)fLeaves.UncheckedAt(string_code); // Now let calculate what physical instance we really need. const Int_t real_instance = GetRealInstance(instance,string_code); if (instance==0 || fNeedLoading) { fNeedLoading = kFALSE; TBranch *branch = leafc->GetBranch(); Long64_t readentry = branch->GetTree()->GetReadEntry(); R__LoadBranch(branch,readentry,fQuickLoad); } else { // In the cases where we are behind (i.e. right of) a potential boolean optimization // this tree variable reading may have not been executed with instance==0 which would // result in the branch being potentially not read in. if (fDidBooleanOptimization) { TBranch *br = leafc->GetBranch(); Long64_t treeEntry = br->GetTree()->GetReadEntry(); R__LoadBranch(br,treeEntry,kTRUE); } if (real_instance>fNdata[string_code]) return 0; } pos2++; if (fLookupType[string_code]==kDirect) { stringStack[pos2-1] = (char*)leafc->GetValuePointer(); } else { stringStack[pos2-1] = (char*)GetLeafInfo(string_code)->GetValuePointer(leafc,real_instance); } continue; } } } R__ASSERT(i<fNoper); } Double_t result = tab[0]; return result; } //______________________________________________________________________________ TFormLeafInfo *TTreeFormula::GetLeafInfo(Int_t code) const { //*-*-*-*-*-*-*-*Return DataMember corresponding to code*-*-*-*-*-* //*-* ======================================= // // function called by TLeafObject::GetValue // with the value of fLookupType computed in TTreeFormula::DefinedVariable return (TFormLeafInfo *)fDataMembers.UncheckedAt(code); } //______________________________________________________________________________ TLeaf *TTreeFormula::GetLeaf(Int_t n) const { //*-*-*-*-*-*-*-*Return leaf corresponding to serial number n*-*-*-*-*-* //*-* ============================================ // return (TLeaf*)fLeaves.UncheckedAt(n); } //______________________________________________________________________________ TMethodCall *TTreeFormula::GetMethodCall(Int_t code) const { //*-*-*-*-*-*-*-*Return methodcall corresponding to code*-*-*-*-*-* //*-* ======================================= // // function called by TLeafObject::GetValue // with the value of fLookupType computed in TTreeFormula::DefinedVariable return (TMethodCall *)fMethods.UncheckedAt(code); } //______________________________________________________________________________ Int_t TTreeFormula::GetNdata() { //*-*-*-*-*-*-*-*Return number of available instances in the formula-*-*-*-*-*-* //*-* =================================================== // return fManager->GetNdata(); } //______________________________________________________________________________ Double_t TTreeFormula::GetValueFromMethod(Int_t i, TLeaf* leaf) const { // Return result of a leafobject method. TMethodCall* m = GetMethodCall(i); if (!m) { return 0.0; } void* thisobj = 0; if (leaf->InheritsFrom(TLeafObject::Class())) { thisobj = ((TLeafObject*) leaf)->GetObject(); } else { TBranchElement* branch = (TBranchElement*) ((TLeafElement*) leaf)->GetBranch(); Int_t id = branch->GetID(); // FIXME: This is wrong for a top-level branch. Int_t offset = 0; if (id > -1) { TStreamerInfo* info = branch->GetInfo(); if (info) { offset = info->GetOffsets()[id]; } else { Warning("GetValueFromMethod", "No streamer info for branch %s.", branch->GetName()); } } if (id < 0) { char* address = branch->GetObject(); thisobj = address; } else { //char* address = branch->GetAddress(); char* address = branch->GetObject(); if (address) { thisobj = *((char**) (address + offset)); } else { // FIXME: If the address is not set, the object won't be either! thisobj = branch->GetObject(); } } } TMethodCall::EReturnType r = m->ReturnType(); if (r == TMethodCall::kLong) { Long_t l = 0; m->Execute(thisobj, l); return (Double_t) l; } if (r == TMethodCall::kDouble) { Double_t d = 0.0; m->Execute(thisobj, d); return d; } m->Execute(thisobj); return 0; } //______________________________________________________________________________ void* TTreeFormula::GetValuePointerFromMethod(Int_t i, TLeaf* leaf) const { // Return result of a leafobject method. TMethodCall* m = GetMethodCall(i); if (!m) { return 0; } void* thisobj; if (leaf->InheritsFrom(TLeafObject::Class())) { thisobj = ((TLeafObject*) leaf)->GetObject(); } else { TBranchElement* branch = (TBranchElement*) ((TLeafElement*) leaf)->GetBranch(); Int_t id = branch->GetID(); Int_t offset = 0; if (id > -1) { TStreamerInfo* info = branch->GetInfo(); if (info) { offset = info->GetOffsets()[id]; } else { Warning("GetValuePointerFromMethod", "No streamer info for branch %s.", branch->GetName()); } } if (id < 0) { char* address = branch->GetObject(); thisobj = address; } else { //char* address = branch->GetAddress(); char* address = branch->GetObject(); if (address) { thisobj = *((char**) (address + offset)); } else { // FIXME: If the address is not set, the object won't be either! thisobj = branch->GetObject(); } } } TMethodCall::EReturnType r = m->ReturnType(); if (r == TMethodCall::kLong) { Long_t l = 0; m->Execute(thisobj, l); return 0; } if (r == TMethodCall::kDouble) { Double_t d = 0.0; m->Execute(thisobj, d); return 0; } if (r == TMethodCall::kOther) { char* c = 0; m->Execute(thisobj, &c); return c; } m->Execute(thisobj); return 0; } //______________________________________________________________________________ Bool_t TTreeFormula::IsInteger(Bool_t fast) const { // return TRUE if the formula corresponds to one single Tree leaf // and this leaf is short, int or unsigned short, int // When a leaf is of type integer or string, the generated histogram is forced // to have an integer bin width if (fast) { if (TestBit(kIsInteger)) return kTRUE; else return kFALSE; } if (fNoper==2 && GetAction(0)==kAlternate) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); return subform->IsInteger(kFALSE); } if (GetAction(0)==kMinIf || GetAction(0)==kMaxIf) { return kFALSE; } if (fNoper > 1) return kFALSE; if (GetAction(0)==kAlias) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); return subform->IsInteger(kFALSE); } if (fLeaves.GetEntries() != 1) { switch (fLookupType[0]) { case kIndexOfEntry: case kIndexOfLocalEntry: case kEntries: case kLength: case kLengthFunc: case kIteration: return kTRUE; case kSum: case kMin: case kMax: case kEntryList: default: return kFALSE; } } if (EvalClass()==TBits::Class()) return kTRUE; if (IsLeafInteger(0) || IsLeafString(0)) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TTreeFormula::IsLeafInteger(Int_t code) const { // return TRUE if the leaf corresponding to code is short, int or unsigned // short, int When a leaf is of type integer, the generated histogram is // forced to have an integer bin width TLeaf *leaf = (TLeaf*)fLeaves.At(code); if (!leaf) { switch (fLookupType[code]) { case kIndexOfEntry: case kIndexOfLocalEntry: case kEntries: case kLength: case kLengthFunc: case kIteration: return kTRUE; case kSum: case kMin: case kMax: case kEntryList: default: return kFALSE; } } if (fAxis) return kTRUE; TFormLeafInfo * info; switch (fLookupType[code]) { case kMethod: case kTreeMember: case kDataMember: info = GetLeafInfo(code); return info->IsInteger(); case kDirect: break; } if (!strcmp(leaf->GetTypeName(),"Int_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"Short_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"UInt_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"UShort_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"Bool_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"Char_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"UChar_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"string")) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TTreeFormula::IsString() const { // return TRUE if the formula is a string // See TTreeFormula::Init for the setting of kIsCharacter. return TestBit(kIsCharacter); } //______________________________________________________________________________ Bool_t TTreeFormula::IsString(Int_t oper) const { // (fOper[i]>=105000 && fOper[i]<110000) || fOper[i] == kStrings) // return true if the expression at the index 'oper' is to be treated as // as string if (TFormula::IsString(oper)) return kTRUE; if (GetAction(oper)==kDefinedString) return kTRUE; if (GetAction(oper)==kAliasString) return kTRUE; if (GetAction(oper)==kAlternateString) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TTreeFormula::IsLeafString(Int_t code) const { // return TRUE if the leaf or data member corresponding to code is a string TLeaf *leaf = (TLeaf*)fLeaves.At(code); TFormLeafInfo * info; if (fLookupType[code]==kTreeMember) { info = GetLeafInfo(code); return info->IsString(); } switch(fLookupType[code]) { case kDirect: if ( !leaf->IsUnsigned() && (leaf->InheritsFrom(TLeafC::Class()) || leaf->InheritsFrom(TLeafB::Class()) ) ) { // Need to find out if it is an 'array' or a pointer. if (leaf->GetLenStatic() > 1) return kTRUE; // Now we need to differantiate between a variable length array and // a TClonesArray. if (leaf->GetLeafCount()) { const char* indexname = leaf->GetLeafCount()->GetName(); if (indexname[strlen(indexname)-1] == '_' ) { // This in a clones array return kFALSE; } else { // this is a variable length char array return kTRUE; } } return kFALSE; } else if (leaf->InheritsFrom(TLeafElement::Class())) { TBranchElement * br = (TBranchElement*)leaf->GetBranch(); Int_t bid = br->GetID(); if (bid < 0) return kFALSE; if (br->GetInfo()==0 || br->GetInfo()->GetElems()==0) { // Case where the file is corrupted is some ways. // We can not get to the actual type of the data // let's assume it is NOT a string. return kFALSE; } TStreamerElement * elem = (TStreamerElement*) br->GetInfo()->GetElems()[bid]; if (!elem) { // Case where the file is corrupted is some ways. // We can not get to the actual type of the data // let's assume it is NOT a string. return kFALSE; } if (elem->GetNewType()== TStreamerInfo::kOffsetL +kChar_t) { // Check whether a specific element of the string is specified! if (fIndexes[code][fNdimensions[code]-1] != -1) return kFALSE; return kTRUE; } if ( elem->GetNewType()== TStreamerInfo::kCharStar) { // Check whether a specific element of the string is specified! if (fNdimensions[code] && fIndexes[code][fNdimensions[code]-1] != -1) return kFALSE; return kTRUE; } return kFALSE; } else { return kFALSE; } case kMethod: //TMethodCall *m = GetMethodCall(code); //TMethodCall::EReturnType r = m->ReturnType(); return kFALSE; case kDataMember: info = GetLeafInfo(code); return info->IsString(); default: return kFALSE; } } //______________________________________________________________________________ char *TTreeFormula::PrintValue(Int_t mode) const { // Return value of variable as a string // // mode = -2 : Print line with *** // mode = -1 : Print column names // mode = 0 : Print column values return PrintValue(mode,0); } //______________________________________________________________________________ char *TTreeFormula::PrintValue(Int_t mode, Int_t instance, const char *decform) const { // Return value of variable as a string // // mode = -2 : Print line with *** // mode = -1 : Print column names // mode = 0 : Print column values // decform contains the requested format (with the same convention as printf). // const int kMAXLENGTH = 1024; static char value[kMAXLENGTH]; if (mode == -2) { for (int i = 0; i < kMAXLENGTH-1; i++) value[i] = '*'; value[kMAXLENGTH-1] = 0; } else if (mode == -1) { snprintf(value, kMAXLENGTH-1, "%s", GetTitle()); } else if (mode == 0) { if ( (fNstring && fNval==0 && fNoper==1) || IsString() ) { const char * val = 0; if (GetAction(0)==kStringConst) { val = fExpr[0].Data(); } else if (instance<fNdata[0]) { if (fNoper == 1) { if (fLookupType[0]==kTreeMember) { val = (char*)GetLeafInfo(0)->GetValuePointer((TLeaf*)0x0,instance); } else { TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); TBranch *branch = leaf->GetBranch(); Long64_t readentry = branch->GetTree()->GetReadEntry(); R__LoadBranch(branch,readentry,fQuickLoad); if (fLookupType[0]==kDirect && fNoper==1) { val = (const char*)leaf->GetValuePointer(); } else { val = ((TTreeFormula*)this)->EvalStringInstance(instance); } } } else { val = ((TTreeFormula*)this)->EvalStringInstance(instance); } } if (val) { strlcpy(value, val, kMAXLENGTH); } else { value[0] = '\0'; } value[kMAXLENGTH-1] = 0; } else { //NOTE: This is terrible form ... but is forced upon us by the fact that we can not //use the mutable keyword AND we should keep PrintValue const. Int_t real_instance = ((TTreeFormula*)this)->GetRealInstance(instance,-1); if (real_instance<fNdata[0]) { Ssiz_t len = strlen(decform); Char_t outputSizeLevel = 1; char *expo = 0; if (len>2) { switch (decform[len-2]) { case 'l': case 'L': { outputSizeLevel = 2; if (len>3 && tolower(decform[len-3])=='l') { outputSizeLevel = 3; } break; } case 'h': outputSizeLevel = 0; break; } } switch(decform[len-1]) { case 'c': case 'd': case 'i': { switch (outputSizeLevel) { case 0: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(Short_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 2: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(Long_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 3: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(Long64_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 1: default: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(Int_t)((TTreeFormula*)this)->EvalInstance(instance)); break; } break; } case 'o': case 'x': case 'X': case 'u': { switch (outputSizeLevel) { case 0: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(UShort_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 2: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(ULong_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 3: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(ULong64_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 1: default: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(UInt_t)((TTreeFormula*)this)->EvalInstance(instance)); break; } break; } case 'f': case 'e': case 'E': case 'g': case 'G': { switch (outputSizeLevel) { case 2: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(long double)((TTreeFormula*)this)->EvalInstance(instance)); break; case 1: default: snprintf(value,kMAXLENGTH,Form("%%%s",decform),((TTreeFormula*)this)->EvalInstance(instance)); break; } expo = strchr(value,'e'); break; } default: snprintf(value,kMAXLENGTH,Form("%%%sg",decform),((TTreeFormula*)this)->EvalInstance(instance)); expo = strchr(value,'e'); } if (expo) { // If there is an exponent we may be longer than planned. // so let's trim off the excess precission! UInt_t declen = atoi(decform); if (strlen(value)>declen) { UInt_t off = strlen(value)-declen; char *start = expo - off; UInt_t vlen = strlen(expo); for(UInt_t z=0;z<=vlen;++z) { start[z] = expo[z]; } //strcpy(expo-off,expo); } } } else { if (isalpha(decform[strlen(decform)-1])) { TString short_decform(decform); short_decform.Remove(short_decform.Length()-1); snprintf(value,kMAXLENGTH,Form(" %%%sc",short_decform.Data()),' '); } else { snprintf(value,kMAXLENGTH,Form(" %%%sc",decform),' '); } } } } return &value[0]; } //______________________________________________________________________________ void TTreeFormula::ResetLoading() { // Tell the formula that we are going to request a new entry. fNeedLoading = kTRUE; fDidBooleanOptimization = kFALSE; for(Int_t i=0; i<fNcodes; ++i) { UInt_t max_dim = fNdimensions[i]; for(UInt_t dim=0; dim<max_dim ;++dim) { if (fVarIndexes[i][dim]) { fVarIndexes[i][dim]->ResetLoading(); } } } Int_t n = fAliases.GetLast(); if ( fNoper < n ) { n = fNoper; } for(Int_t k=0; k <= n; ++k) { TTreeFormula *f = static_cast<TTreeFormula*>(fAliases.UncheckedAt(k)); if (f) { f->ResetLoading(); } } } //______________________________________________________________________________ void TTreeFormula::SetAxis(TAxis *axis) { // Set the axis (in particular get the type). if (!axis) {fAxis = 0; return;} if (IsString()) { fAxis = axis; if (fNoper==1 && GetAction(0)==kAliasString){ TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); subform->SetAxis(axis); } else if (fNoper==2 && GetAction(0)==kAlternateString){ TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); subform->SetAxis(axis); } // Since the bin are corresponding to 'string', we currently must also set // the axis to align the bins exactly on integer boundaries. axis->SetBit(TAxis::kIsInteger); } else if (IsInteger()) { axis->SetBit(TAxis::kIsInteger); } } //______________________________________________________________________________ void TTreeFormula::Streamer(TBuffer &R__b) { // Stream an object of class TTreeFormula. if (R__b.IsReading()) { UInt_t R__s, R__c; Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v > 2) { R__b.ReadClassBuffer(TTreeFormula::Class(), this, R__v, R__s, R__c); return; } //====process old versions before automatic schema evolution TFormula::Streamer(R__b); R__b >> fTree; R__b >> fNcodes; R__b.ReadFastArray(fCodes, fNcodes); R__b >> fMultiplicity; Int_t instance; R__b >> instance; //data member removed R__b >> fNindex; if (fNindex) { fLookupType = new Int_t[fNindex]; R__b.ReadFastArray(fLookupType, fNindex); } fMethods.Streamer(R__b); //====end of old versions } else { R__b.WriteClassBuffer(TTreeFormula::Class(),this); } } //______________________________________________________________________________ Bool_t TTreeFormula::StringToNumber(Int_t oper) { // Try to 'demote' a string into an array bytes. If this is not possible, // return false. Int_t code = GetActionParam(oper); if (GetAction(oper)==kDefinedString && fLookupType[code]==kDirect) { if (oper>0 && GetAction(oper-1)==kJump) { // We are the second hand of a ternary operator, let's not do the fixing. return kFALSE; } TLeaf *leaf = (TLeaf*)fLeaves.At(code); if (leaf && (leaf->InheritsFrom(TLeafC::Class()) || leaf->InheritsFrom(TLeafB::Class()) ) ) { SetAction(oper, kDefinedVariable, code ); fNval++; fNstring--; return kTRUE; } } return kFALSE; } //______________________________________________________________________________ void TTreeFormula::UpdateFormulaLeaves() { // this function is called TTreePlayer::UpdateFormulaLeaves, itself // called by TChain::LoadTree when a new Tree is loaded. // Because Trees in a TChain may have a different list of leaves, one // must update the leaves numbers in the TTreeFormula used by the TreePlayer. // A safer alternative would be to recompile the whole thing .... However // currently compile HAS TO be called from the constructor! Int_t nleaves = fLeafNames.GetEntriesFast(); ResetBit( kMissingLeaf ); for (Int_t i=0;i<nleaves;i++) { if (!fTree) break; if (!fLeafNames[i]) continue; TLeaf *leaf = fTree->GetLeaf(fLeafNames[i]->GetTitle(),fLeafNames[i]->GetName()); fLeaves[i] = leaf; if (fBranches[i] && leaf) { fBranches[i] = leaf->GetBranch(); // Since sometimes we might no read all the branches for all the entries, we // might sometimes only read the branch count and thus reset the colleciton // but might not read the data branches, to insure that a subsequent read // from TTreeFormula will properly load the data branches even if fQuickLoad is true, // we reset the entry of all branches in the TTree. ((TBranch*)fBranches[i])->ResetReadEntry(); } if (leaf==0) SetBit( kMissingLeaf ); } for (Int_t j=0; j<kMAXCODES; j++) { for (Int_t k = 0; k<kMAXFORMDIM; k++) { if (fVarIndexes[j][k]) { fVarIndexes[j][k]->UpdateFormulaLeaves(); } } if (fLookupType[j]==kDataMember || fLookupType[j]==kTreeMember) GetLeafInfo(j)->Update(); if (j<fNval && fCodes[j]<0) { TCutG *gcut = (TCutG*)fExternalCuts.At(j); if (gcut) { TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); TTreeFormula *fy = (TTreeFormula *)gcut->GetObjectY(); if (fx) fx->UpdateFormulaLeaves(); if (fy) fy->UpdateFormulaLeaves(); } } } for(Int_t k=0;k<fNoper;k++) { const Int_t oper = GetOper()[k]; switch(oper >> kTFOperShift) { case kAlias: case kAliasString: case kAlternate: case kAlternateString: case kMinIf: case kMaxIf: { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(k)); R__ASSERT(subform); subform->UpdateFormulaLeaves(); break; } case kDefinedVariable: { Int_t code = GetActionParam(k); if (fCodes[code]==0) switch(fLookupType[code]) { case kLengthFunc: case kSum: case kMin: case kMax: { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(k)); R__ASSERT(subform); subform->UpdateFormulaLeaves(); break; } default: break; } } default: break; } } } //______________________________________________________________________________ void TTreeFormula::ResetDimensions() { // Populate the TTreeFormulaManager with the dimension information. Int_t i,k; // Now that we saw all the expressions and variables AND that // we know whether arrays of chars are treated as string or // not, we can properly setup the dimensions. TIter next(fDimensionSetup); Int_t last_code = -1; Int_t virt_dim = 0; for(TDimensionInfo * info; (info = (TDimensionInfo*)next()); ) { if (last_code!=info->fCode) { // We know that the list is ordered by code number then by // dimension. Thus a different code means that we need to // restart at the lowest dimensions. virt_dim = 0; last_code = info->fCode; fNdimensions[last_code] = 0; } if (GetAction(info->fOper)==kDefinedString) { // We have a string used as a string (and not an array of number) // We need to determine which is the last dimension and skip it. TDimensionInfo *nextinfo = (TDimensionInfo*)next(); while(nextinfo && nextinfo->fCode==info->fCode) { DefineDimensions(info->fCode,info->fSize, info->fMultiDim, virt_dim); nextinfo = (TDimensionInfo*)next(); } if (!nextinfo) break; info = nextinfo; virt_dim = 0; last_code = info->fCode; fNdimensions[last_code] = 0; info->fSize = 1; // Maybe this should actually do nothing! } DefineDimensions(info->fCode,info->fSize, info->fMultiDim, virt_dim); } fMultiplicity = 0; for(i=0;i<fNoper;i++) { Int_t action = GetAction(i); if (action==kMinIf || action==kMaxIf) { // Skip/Ignore the 2nd args ++i; continue; } if (action==kAlias || action==kAliasString) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(i)); R__ASSERT(subform); switch(subform->GetMultiplicity()) { case 0: break; case 1: fMultiplicity = 1; break; case 2: if (fMultiplicity!=1) fMultiplicity = 2; break; } fManager->Add(subform); // since we are addint to this manager 'subform->ResetDimensions();' // will be called a little latter continue; } if (action==kDefinedString) { //if (fOper[i] >= 105000 && fOper[i]<110000) { // We have a string used as a string // This dormant portion of code would be used if (when?) we allow the histogramming // of the integral content (as opposed to the string content) of strings // held in a variable size container delimited by a null (as opposed to // a fixed size container or variable size container whose size is controlled // by a variable). In GetNdata, we will then use strlen to grab the current length. //fCumulSizes[i][fNdimensions[i]-1] = 1; //fUsedSizes[fNdimensions[i]-1] = -TMath::Abs(fUsedSizes[fNdimensions[i]-1]); //fUsedSizes[0] = - TMath::Abs( fUsedSizes[0]); //continue; } } for (i=0;i<fNcodes;i++) { if (fCodes[i] < 0) { TCutG *gcut = (TCutG*)fExternalCuts.At(i); if (!gcut) continue; TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); TTreeFormula *fy = (TTreeFormula *)gcut->GetObjectY(); if (fx) { switch(fx->GetMultiplicity()) { case 0: break; case 1: fMultiplicity = 1; break; case 2: if (fMultiplicity!=1) fMultiplicity = 2; break; } fManager->Add(fx); } if (fy) { switch(fy->GetMultiplicity()) { case 0: break; case 1: fMultiplicity = 1; break; case 2: if (fMultiplicity!=1) fMultiplicity = 2; break; } fManager->Add(fy); } continue; } if (fLookupType[i]==kIteration) { fMultiplicity = 1; continue; } TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(i); if (!leaf) continue; // Reminder of the meaning of fMultiplicity: // -1: Only one or 0 element per entry but contains variable length // -array! (Only used for TTreeFormulaManager) // 0: Only one element per entry, no variable length array // 1: loop over the elements of a variable length array // 2: loop over elements of fixed length array (nData is the same for all entry) if (leaf->GetLeafCount()) { // We assume only one possible variable length dimension (the left most) fMultiplicity = 1; } else if (fLookupType[i]==kDataMember) { TFormLeafInfo * leafinfo = GetLeafInfo(i); TStreamerElement * elem = leafinfo->fElement; if (fMultiplicity!=1) { if (leafinfo->HasCounter() ) fMultiplicity = 1; else if (elem && elem->GetArrayDim()>0) fMultiplicity = 2; else if (leaf->GetLenStatic()>1) fMultiplicity = 2; } } else { if (leaf->GetLenStatic()>1 && fMultiplicity!=1) fMultiplicity = 2; } if (fMultiplicity!=1) { // If the leaf belongs to a friend tree which has an index, we might // be in the case where some entry do not exist. TTree *realtree = fTree ? fTree->GetTree() : 0; TTree *tleaf = leaf->GetBranch()->GetTree(); if (tleaf && tleaf != realtree && tleaf->GetTreeIndex()) { // Reset the multiplicity if we have a friend tree with an index. fMultiplicity = 1; } } Int_t virt_dim2 = 0; for (k = 0; k < fNdimensions[i]; k++) { // At this point fCumulSizes[i][k] actually contain the physical // dimension of the k-th dimensions. if ( (fCumulSizes[i][k]>=0) && (fIndexes[i][k] >= fCumulSizes[i][k]) ) { // unreacheable element requested: fManager->CancelDimension(virt_dim2); // fCumulUsedSizes[virt_dim2] = 0; } if ( fIndexes[i][k] < 0 ) virt_dim2++; fFixedSizes[i][k] = fCumulSizes[i][k]; } // Add up the cumulative size for (k = fNdimensions[i]; (k > 0); k--) { // NOTE: When support for inside variable dimension is added this // will become inacurate (since one of the value in the middle of the chain // is unknown until GetNdata is called. fCumulSizes[i][k-1] *= TMath::Abs(fCumulSizes[i][k]); } // NOTE: We assume that the inside variable dimensions are dictated by the // first index. if (fCumulSizes[i][0]>0) fNdata[i] = fCumulSizes[i][0]; //for (k = 0; k<kMAXFORMDIM; k++) { // if (fVarIndexes[i][k]) fManager->Add(fVarIndexes[i][k]); //} } } //______________________________________________________________________________ void TTreeFormula::LoadBranches() { // Make sure that all the branches have been loaded properly. Int_t i; for (i=0; i<fNoper ; ++i) { TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(i); if (leaf==0) continue; TBranch *br = leaf->GetBranch(); Long64_t treeEntry = br->GetTree()->GetReadEntry(); R__LoadBranch(br,treeEntry,kTRUE); TTreeFormula *alias = (TTreeFormula*)fAliases.UncheckedAt(i); if (alias) alias->LoadBranches(); Int_t max_dim = fNdimensions[i]; for (Int_t dim = 0; dim < max_dim; ++dim) { if (fVarIndexes[i][dim]) fVarIndexes[i][dim]->LoadBranches(); } } } //______________________________________________________________________________ Bool_t TTreeFormula::LoadCurrentDim() { // Calculate the actual dimension for the current entry. Int_t size; Bool_t outofbounds = kFALSE; for (Int_t i=0;i<fNcodes;i++) { if (fCodes[i] < 0) continue; // NOTE: Currently only the leafcount can indicates a dimension that // is physically variable. So only the left-most dimension is variable. // When an API is introduced to be able to determine a variable inside dimensions // one would need to add a way to recalculate the values of fCumulSizes for this // leaf. This would probably require the addition of a new data member // fSizes[kMAXCODES][kMAXFORMDIM]; // Also note that EvalInstance expect all the values (but the very first one) // of fCumulSizes to be positive. So indicating that a physical dimension is // variable (expected for the first one) can NOT be done via negative values of // fCumulSizes. TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(i); if (!leaf) { switch(fLookupType[i]) { case kDirect: case kMethod: case kTreeMember: case kDataMember: fNdata[i] = 0; outofbounds = kTRUE; } continue; } TTree *realtree = fTree->GetTree(); TTree *tleaf = leaf->GetBranch()->GetTree(); if (tleaf && tleaf != realtree && tleaf->GetTreeIndex()) { if (tleaf->GetReadEntry() < 0) { fNdata[i] = 0; outofbounds = kTRUE; continue; } else { fNdata[i] = fCumulSizes[i][0]; } } Bool_t hasBranchCount2 = kFALSE; if (leaf->GetLeafCount()) { TLeaf* leafcount = leaf->GetLeafCount(); TBranch *branchcount = leafcount->GetBranch(); TFormLeafInfo * info = 0; if (leaf->IsA() == TLeafElement::Class()) { //if branchcount address not yet set, GetEntry will set the address // read branchcount value Long64_t readentry = leaf->GetBranch()->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; if (!branchcount->GetAddress()) { R__LoadBranch(branchcount, readentry, fQuickLoad); } else { // Since we do not read the full branch let's reset the read entry number // so that a subsequent read from TTreeFormula will properly load the full // object even if fQuickLoad is true. branchcount->TBranch::GetEntry(readentry); branchcount->ResetReadEntry(); } size = ((TBranchElement*)branchcount)->GetNdata(); // Reading the size as above is correct only when the branchcount // is of streamer type kCounter which require the underlying data // member to be signed integral type. TBranchElement* branch = (TBranchElement*) leaf->GetBranch(); // NOTE: could be sped up if (fHasMultipleVarDim[i]) {// info && info->GetVarDim()>=0) { info = (TFormLeafInfo* )fDataMembers.At(i); if (branch->GetBranchCount2()) R__LoadBranch(branch->GetBranchCount2(),readentry,fQuickLoad); else R__LoadBranch(branch,readentry,fQuickLoad); // Here we need to add the code to take in consideration the // double variable length // We fill up the array of sizes in the TLeafInfo: info->LoadSizes(branch); hasBranchCount2 = kTRUE; if (info->GetVirtVarDim()>=0) info->UpdateSizes(fManager->fVarDims[info->GetVirtVarDim()]); // Refresh the fCumulSizes[i] to have '1' for the // double variable dimensions Int_t vdim = info->GetVarDim(); fCumulSizes[i][vdim] = fCumulSizes[i][vdim+1]; for(Int_t k=vdim -1; k>=0; k--) { fCumulSizes[i][k] = fCumulSizes[i][k+1]*fFixedSizes[i][k]; } // Update fCumulUsedSizes // UpdateMultiVarSizes(vdim,info,i) //Int_t fixed = fCumulSizes[i][vdim+1]; //for(Int_t k=vdim - 1; k>=0; k++) { // Int_t fixed *= fFixedSizes[i][k]; // for(Int_t l=0;l<size; l++) { // fCumulSizes[i][k] += info->GetSize(l) * fixed; //} } } else { Long64_t readentry = leaf->GetBranch()->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; R__LoadBranch(branchcount,readentry,fQuickLoad); size = leaf->GetLen() / leaf->GetLenStatic(); } if (hasBranchCount2) { // We assume that fCumulSizes[i][1] contains the product of the fixed sizes fNdata[i] = fCumulSizes[i][1] * ((TFormLeafInfo *)fDataMembers.At(i))->GetSumOfSizes(); } else { fNdata[i] = size * fCumulSizes[i][1]; } if (fIndexes[i][0]==-1) { // Case where the index is not specified AND the 1st dimension has a variable // size. if (fManager->fUsedSizes[0]==1 || (size<fManager->fUsedSizes[0]) ) fManager->fUsedSizes[0] = size; if (info && fIndexes[i][info->GetVarDim()]>=0) { for(Int_t j=0; j<size; j++) { if (fIndexes[i][info->GetVarDim()] >= info->GetSize(j)) { info->SetSize(j,0); if (size>fManager->fCumulUsedVarDims->GetSize()) fManager->fCumulUsedVarDims->Set(size); fManager->fCumulUsedVarDims->AddAt(-1,j); } else if (fIndexes[i][info->GetVarDim()]>=0) { // There is an index and it is not too large info->SetSize(j,1); if (size>fManager->fCumulUsedVarDims->GetSize()) fManager->fCumulUsedVarDims->Set(size); fManager->fCumulUsedVarDims->AddAt(1,j); } } } } else if (fIndexes[i][0] >= size) { // unreacheable element requested: fManager->fUsedSizes[0] = 0; fNdata[i] = 0; outofbounds = kTRUE; } else if (hasBranchCount2) { TFormLeafInfo *info2; info2 = (TFormLeafInfo *)fDataMembers.At(i); if (fIndexes[i][0]<0 || fIndexes[i][info2->GetVarDim()] >= info2->GetSize(fIndexes[i][0])) { // unreacheable element requested: fManager->fUsedSizes[0] = 0; fNdata[i] = 0; outofbounds = kTRUE; } } } else if (fLookupType[i]==kDataMember) { TFormLeafInfo *leafinfo = (TFormLeafInfo*)fDataMembers.UncheckedAt(i); if (leafinfo->HasCounter()) { TBranch *branch = leaf->GetBranch(); Long64_t readentry = branch->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; R__LoadBranch(branch,readentry,fQuickLoad); size = (Int_t) leafinfo->GetCounterValue(leaf); if (fIndexes[i][0]==-1) { // Case where the index is not specified AND the 1st dimension has a variable // size. if (fManager->fUsedSizes[0]==1 || (size<fManager->fUsedSizes[0]) ) { fManager->fUsedSizes[0] = size; } } else if (fIndexes[i][0] >= size) { // unreacheable element requested: fManager->fUsedSizes[0] = 0; fNdata[i] = 0; outofbounds = kTRUE; } else { fNdata[i] = size*fCumulSizes[i][1]; } Int_t vdim = leafinfo->GetVarDim(); if (vdim>=0) { // Here we need to add the code to take in consideration the // double variable length // We fill up the array of sizes in the TLeafInfo: // here we can assume that branch is a TBranch element because the other style does NOT support this type // of complexity. leafinfo->LoadSizes(branch); hasBranchCount2 = kTRUE; if (fIndexes[i][0]==-1&&fIndexes[i][vdim] >= 0) { for(int z=0; z<size; ++z) { if (fIndexes[i][vdim] >= leafinfo->GetSize(z)) { leafinfo->SetSize(z,0); // --fManager->fUsedSizes[0]; } else if (fIndexes[i][vdim] >= 0 ) { leafinfo->SetSize(z,1); } } } leafinfo->UpdateSizes(fManager->fVarDims[vdim]); // Refresh the fCumulSizes[i] to have '1' for the // double variable dimensions fCumulSizes[i][vdim] = fCumulSizes[i][vdim+1]; for(Int_t k=vdim -1; k>=0; k--) { fCumulSizes[i][k] = fCumulSizes[i][k+1]*fFixedSizes[i][k]; } fNdata[i] = fCumulSizes[i][1] * leafinfo->GetSumOfSizes(); } else { fNdata[i] = size * fCumulSizes[i][1]; } } else if (leafinfo->GetMultiplicity()==-1) { TBranch *branch = leaf->GetBranch(); Long64_t readentry = branch->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; R__LoadBranch(branch,readentry,fQuickLoad); if (leafinfo->GetNdata(leaf)==0) { outofbounds = kTRUE; } } } // However we allow several dimensions that virtually vary via the size of their // index variables. So we have code to recalculate fCumulUsedSizes. Int_t index; TFormLeafInfo * info = 0; if (fLookupType[i]!=kDirect) { info = (TFormLeafInfo *)fDataMembers.At(i); } for(Int_t k=0, virt_dim=0; k < fNdimensions[i]; k++) { if (fIndexes[i][k]<0) { if (fIndexes[i][k]==-2 && fManager->fVirtUsedSizes[virt_dim]<0) { // if fVirtUsedSize[virt_dim] is positive then VarIndexes[i][k]->GetNdata() // is always the same and has already been factored in fUsedSize[virt_dim] index = fVarIndexes[i][k]->GetNdata(); if (index==1) { // We could either have a variable size array which is currently of size one // or a single element that might or not might not be present (and is currently present!) if (fVarIndexes[i][k]->GetManager()->GetMultiplicity()==1) { if (index<fManager->fUsedSizes[virt_dim]) fManager->fUsedSizes[virt_dim] = index; } } else if (fManager->fUsedSizes[virt_dim]==-fManager->fVirtUsedSizes[virt_dim] || index<fManager->fUsedSizes[virt_dim]) { fManager->fUsedSizes[virt_dim] = index; } } else if (hasBranchCount2 && info && k==info->GetVarDim()) { // NOTE: We assume the indexing of variable sizes on the first index! if (fIndexes[i][0]>=0) { index = info->GetSize(fIndexes[i][0]); if (fManager->fUsedSizes[virt_dim]==1 || (index!=1 && index<fManager->fUsedSizes[virt_dim]) ) fManager->fUsedSizes[virt_dim] = index; } } virt_dim++; } else if (hasBranchCount2 && info && k==info->GetVarDim()) { // nothing to do, at some point I thought this might be useful: // if (fIndexes[i][k]>=0) { // index = info->GetSize(fIndexes[i][k]); // if (fManager->fUsedSizes[virt_dim]==1 || (index!=1 && index<fManager->fUsedSizes[virt_dim]) ) // fManager->fUsedSizes[virt_dim] = index; // virt_dim++; // } } } } return ! outofbounds; } void TTreeFormula::Convert(UInt_t oldversion) { // Convert the fOper of a TTTreeFormula version fromVersion to the current in memory version enum { kOldAlias = /*TFormula::kVariable*/ 100000+10000+1, kOldAliasString = kOldAlias+1, kOldAlternate = kOldAlias+2, kOldAlternateString = kOldAliasString+2 }; for (int k=0; k<fNoper; k++) { // First hide from TFormula convertion Int_t action = GetOper()[k]; switch (action) { case kOldAlias: GetOper()[k] = -kOldAlias; break; case kOldAliasString: GetOper()[k] = -kOldAliasString; break; case kOldAlternate: GetOper()[k] = -kOldAlternate; break; case kOldAlternateString: GetOper()[k] = -kOldAlternateString; break; } } TFormula::Convert(oldversion); for (int i=0,offset=0; i<fNoper; i++) { Int_t action = GetOper()[i+offset]; switch (action) { case -kOldAlias: SetAction(i, kAlias, 0); break; case -kOldAliasString: SetAction(i, kAliasString, 0); break; case -kOldAlternate: SetAction(i, kAlternate, 0); break; case -kOldAlternateString: SetAction(i, kAlternateString, 0); break; } } } //______________________________________________________________________________ Bool_t TTreeFormula::SwitchToFormLeafInfo(Int_t code) { // Convert the underlying lookup method from the direct technique // (dereferencing the address held by the branch) to the method using // TFormLeafInfo. This is in particular usefull in the case where we // need to append an additional TFormLeafInfo (for example to call a // method). // Return false if the switch was unsuccessfull (basically in the // case of an old style split tree). TFormLeafInfo *last = 0; TLeaf *leaf = (TLeaf*)fLeaves.At(code); if (!leaf) return kFALSE; if (fLookupType[code]==kDirect) { if (leaf->InheritsFrom(TLeafElement::Class())) { TBranchElement * br = (TBranchElement*)leaf->GetBranch(); if (br->GetType()==31) { // sub branch of a TClonesArray TStreamerInfo *info = br->GetInfo(); TClass* cl = info->GetClass(); TStreamerElement *element = (TStreamerElement *)info->GetElems()[br->GetID()]; TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(cl, 0, element, kTRUE); Int_t offset; info->GetStreamerElement(element->GetName(),offset); clonesinfo->fNext = new TFormLeafInfo(cl,offset+br->GetOffset(),element); last = clonesinfo->fNext; fDataMembers.AddAtAndExpand(clonesinfo,code); fLookupType[code]=kDataMember; } else if (br->GetType()==41) { // sub branch of a Collection TBranchElement *count = br->GetBranchCount(); TFormLeafInfo* collectioninfo; if ( count->GetID() >= 0 ) { TStreamerElement *collectionElement = (TStreamerElement *)count->GetInfo()->GetElems()[count->GetID()]; TClass *collectionCl = collectionElement->GetClassPointer(); collectioninfo = new TFormLeafInfoCollection(collectionCl, 0, collectionElement, kTRUE); } else { TClass *collectionCl = TClass::GetClass(count->GetClassName()); collectioninfo = new TFormLeafInfoCollection(collectionCl, 0, collectionCl, kTRUE); } TStreamerInfo *info = br->GetInfo(); TClass* cl = info->GetClass(); TStreamerElement *element = (TStreamerElement *)info->GetElems()[br->GetID()]; Int_t offset; info->GetStreamerElement(element->GetName(),offset); collectioninfo->fNext = new TFormLeafInfo(cl,offset+br->GetOffset(),element); last = collectioninfo->fNext; fDataMembers.AddAtAndExpand(collectioninfo,code); fLookupType[code]=kDataMember; } else if (br->GetID()<0) { return kFALSE; } else { last = new TFormLeafInfoDirect(br); fDataMembers.AddAtAndExpand(last,code); fLookupType[code]=kDataMember; } } else { //last = new TFormLeafInfoDirect(br); //fDataMembers.AddAtAndExpand(last,code); //fLookupType[code]=kDataMember; return kFALSE; } } return kTRUE; }
/*************************************************************************/ /* editor_settings.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "editor_settings.h" #include "core/io/certs_compressed.gen.h" #include "core/io/compression.h" #include "core/io/config_file.h" #include "core/io/file_access_memory.h" #include "core/io/resource_loader.h" #include "core/io/resource_saver.h" #include "core/io/translation_loader_po.h" #include "core/os/dir_access.h" #include "core/os/file_access.h" #include "core/os/keyboard.h" #include "core/os/os.h" #include "core/project_settings.h" #include "core/version.h" #include "editor/editor_node.h" #include "editor/translations.gen.h" #include "scene/main/node.h" #include "scene/main/scene_tree.h" #include "scene/main/viewport.h" // PRIVATE METHODS Ref<EditorSettings> EditorSettings::singleton = NULL; // Properties bool EditorSettings::_set(const StringName &p_name, const Variant &p_value) { _THREAD_SAFE_METHOD_ bool changed = _set_only(p_name, p_value); if (changed) { emit_signal("settings_changed"); } return true; } bool EditorSettings::_set_only(const StringName &p_name, const Variant &p_value) { _THREAD_SAFE_METHOD_ if (p_name.operator String() == "shortcuts") { Array arr = p_value; ERR_FAIL_COND_V(arr.size() && arr.size() & 1, true); for (int i = 0; i < arr.size(); i += 2) { String name = arr[i]; Ref<InputEvent> shortcut = arr[i + 1]; Ref<ShortCut> sc; sc.instance(); sc->set_shortcut(shortcut); add_shortcut(name, sc); } return false; } bool changed = false; if (p_value.get_type() == Variant::NIL) { if (props.has(p_name)) { props.erase(p_name); changed = true; } } else { if (props.has(p_name)) { if (p_value != props[p_name].variant) { props[p_name].variant = p_value; changed = true; } } else { props[p_name] = VariantContainer(p_value, last_order++); changed = true; } if (save_changed_setting) { if (!props[p_name].save) { props[p_name].save = true; changed = true; } } } return changed; } bool EditorSettings::_get(const StringName &p_name, Variant &r_ret) const { _THREAD_SAFE_METHOD_ if (p_name.operator String() == "shortcuts") { Array arr; for (const Map<String, Ref<ShortCut> >::Element *E = shortcuts.front(); E; E = E->next()) { Ref<ShortCut> sc = E->get(); if (optimize_save) { if (!sc->has_meta("original")) { continue; //this came from settings but is not any longer used } Ref<InputEvent> original = sc->get_meta("original"); if (sc->is_shortcut(original) || (original.is_null() && sc->get_shortcut().is_null())) continue; //not changed from default, don't save } arr.push_back(E->key()); arr.push_back(sc->get_shortcut()); } r_ret = arr; return true; } const VariantContainer *v = props.getptr(p_name); if (!v) { WARN_PRINTS("EditorSettings::_get - Property not found: " + String(p_name)); return false; } r_ret = v->variant; return true; } void EditorSettings::_initial_set(const StringName &p_name, const Variant &p_value) { set(p_name, p_value); props[p_name].initial = p_value; props[p_name].has_default_value = true; } struct _EVCSort { String name; Variant::Type type; int order; bool save; bool restart_if_changed; bool operator<(const _EVCSort &p_vcs) const { return order < p_vcs.order; } }; void EditorSettings::_get_property_list(List<PropertyInfo> *p_list) const { _THREAD_SAFE_METHOD_ const String *k = NULL; Set<_EVCSort> vclist; while ((k = props.next(k))) { const VariantContainer *v = props.getptr(*k); if (v->hide_from_editor) continue; _EVCSort vc; vc.name = *k; vc.order = v->order; vc.type = v->variant.get_type(); vc.save = v->save; /*if (vc.save) { this should be implemented, but lets do after 3.1 is out. if (v->initial.get_type() != Variant::NIL && v->initial == v->variant) { vc.save = false; } }*/ vc.restart_if_changed = v->restart_if_changed; vclist.insert(vc); } for (Set<_EVCSort>::Element *E = vclist.front(); E; E = E->next()) { int pinfo = 0; if (E->get().save || !optimize_save) { pinfo |= PROPERTY_USAGE_STORAGE; } if (!E->get().name.begins_with("_") && !E->get().name.begins_with("projects/")) { pinfo |= PROPERTY_USAGE_EDITOR; } else { pinfo |= PROPERTY_USAGE_STORAGE; //hiddens must always be saved } PropertyInfo pi(E->get().type, E->get().name); pi.usage = pinfo; if (hints.has(E->get().name)) pi = hints[E->get().name]; if (E->get().restart_if_changed) { pi.usage |= PROPERTY_USAGE_RESTART_IF_CHANGED; } p_list->push_back(pi); } p_list->push_back(PropertyInfo(Variant::ARRAY, "shortcuts", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL)); //do not edit } void EditorSettings::_add_property_info_bind(const Dictionary &p_info) { ERR_FAIL_COND(!p_info.has("name")); ERR_FAIL_COND(!p_info.has("type")); PropertyInfo pinfo; pinfo.name = p_info["name"]; ERR_FAIL_COND(!props.has(pinfo.name)); pinfo.type = Variant::Type(p_info["type"].operator int()); ERR_FAIL_INDEX(pinfo.type, Variant::VARIANT_MAX); if (p_info.has("hint")) pinfo.hint = PropertyHint(p_info["hint"].operator int()); if (p_info.has("hint_string")) pinfo.hint_string = p_info["hint_string"]; add_property_hint(pinfo); } // Default configs bool EditorSettings::has_default_value(const String &p_setting) const { _THREAD_SAFE_METHOD_ if (!props.has(p_setting)) return false; return props[p_setting].has_default_value; } void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) { _THREAD_SAFE_METHOD_ /* Languages */ { String lang_hint = "en"; String host_lang = OS::get_singleton()->get_locale(); host_lang = TranslationServer::standardize_locale(host_lang); // Some locales are not properly supported currently in Godot due to lack of font shaping // (e.g. Arabic or Hindi), so even though we have work in progress translations for them, // we skip them as they don't render properly. (GH-28577) const Vector<String> locales_to_skip = String("ar,bn,fa,he,hi,ml,si,ta,te,ur").split(","); String best; EditorTranslationList *etl = _editor_translations; while (etl->data) { const String &locale = etl->lang; // Skip locales which we can't render properly (see above comment). // Test against language code without regional variants (e.g. ur_PK). String lang_code = locale.get_slice("_", 0); if (locales_to_skip.find(lang_code) != -1) { etl++; continue; } lang_hint += ","; lang_hint += locale; if (host_lang == locale) { best = locale; } if (best == String() && host_lang.begins_with(locale)) { best = locale; } etl++; } if (best == String()) { best = "en"; } _initial_set("interface/editor/editor_language", best); set_restart_if_changed("interface/editor/editor_language", true); hints["interface/editor/editor_language"] = PropertyInfo(Variant::STRING, "interface/editor/editor_language", PROPERTY_HINT_ENUM, lang_hint, PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); } /* Interface */ // Editor _initial_set("interface/editor/display_scale", 0); hints["interface/editor/display_scale"] = PropertyInfo(Variant::INT, "interface/editor/display_scale", PROPERTY_HINT_ENUM, "Auto,75%,100%,125%,150%,175%,200%,Custom", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/custom_display_scale", 1.0f); hints["interface/editor/custom_display_scale"] = PropertyInfo(Variant::REAL, "interface/editor/custom_display_scale", PROPERTY_HINT_RANGE, "0.5,3,0.01", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/main_font_size", 14); hints["interface/editor/main_font_size"] = PropertyInfo(Variant::INT, "interface/editor/main_font_size", PROPERTY_HINT_RANGE, "8,48,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/code_font_size", 14); hints["interface/editor/code_font_size"] = PropertyInfo(Variant::INT, "interface/editor/code_font_size", PROPERTY_HINT_RANGE, "8,48,1", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/font_antialiased", true); _initial_set("interface/editor/font_hinting", 0); hints["interface/editor/font_hinting"] = PropertyInfo(Variant::INT, "interface/editor/font_hinting", PROPERTY_HINT_ENUM, "Auto,None,Light,Normal", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/main_font", ""); hints["interface/editor/main_font"] = PropertyInfo(Variant::STRING, "interface/editor/main_font", PROPERTY_HINT_GLOBAL_FILE, "*.ttf,*.otf", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/main_font_bold", ""); hints["interface/editor/main_font_bold"] = PropertyInfo(Variant::STRING, "interface/editor/main_font_bold", PROPERTY_HINT_GLOBAL_FILE, "*.ttf,*.otf", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/code_font", ""); hints["interface/editor/code_font"] = PropertyInfo(Variant::STRING, "interface/editor/code_font", PROPERTY_HINT_GLOBAL_FILE, "*.ttf,*.otf", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/dim_editor_on_dialog_popup", true); _initial_set("interface/editor/low_processor_mode_sleep_usec", 6900); // ~144 FPS hints["interface/editor/low_processor_mode_sleep_usec"] = PropertyInfo(Variant::REAL, "interface/editor/low_processor_mode_sleep_usec", PROPERTY_HINT_RANGE, "1,100000,1", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/unfocused_low_processor_mode_sleep_usec", 50000); // 20 FPS hints["interface/editor/unfocused_low_processor_mode_sleep_usec"] = PropertyInfo(Variant::REAL, "interface/editor/unfocused_low_processor_mode_sleep_usec", PROPERTY_HINT_RANGE, "1,100000,1", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/separate_distraction_mode", false); _initial_set("interface/editor/automatically_open_screenshots", true); _initial_set("interface/editor/hide_console_window", false); _initial_set("interface/editor/save_each_scene_on_quit", true); // Regression _initial_set("interface/editor/quit_confirmation", true); // Theme _initial_set("interface/theme/preset", "Default"); hints["interface/theme/preset"] = PropertyInfo(Variant::STRING, "interface/theme/preset", PROPERTY_HINT_ENUM, "Default,Alien,Arc,Godot 2,Grey,Light,Solarized (Dark),Solarized (Light),Custom", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/icon_and_font_color", 0); hints["interface/theme/icon_and_font_color"] = PropertyInfo(Variant::INT, "interface/theme/icon_and_font_color", PROPERTY_HINT_ENUM, "Auto,Dark,Light", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/base_color", Color(0.2, 0.23, 0.31)); hints["interface/theme/base_color"] = PropertyInfo(Variant::COLOR, "interface/theme/base_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/accent_color", Color(0.41, 0.61, 0.91)); hints["interface/theme/accent_color"] = PropertyInfo(Variant::COLOR, "interface/theme/accent_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/contrast", 0.25); hints["interface/theme/contrast"] = PropertyInfo(Variant::REAL, "interface/theme/contrast", PROPERTY_HINT_RANGE, "0.01, 1, 0.01"); _initial_set("interface/theme/relationship_line_opacity", 0.1); hints["interface/theme/relationship_line_opacity"] = PropertyInfo(Variant::REAL, "interface/theme/relationship_line_opacity", PROPERTY_HINT_RANGE, "0.00, 1, 0.01"); _initial_set("interface/theme/highlight_tabs", false); _initial_set("interface/theme/border_size", 1); _initial_set("interface/theme/use_graph_node_headers", false); hints["interface/theme/border_size"] = PropertyInfo(Variant::INT, "interface/theme/border_size", PROPERTY_HINT_RANGE, "0,2,1", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/additional_spacing", 0); hints["interface/theme/additional_spacing"] = PropertyInfo(Variant::REAL, "interface/theme/additional_spacing", PROPERTY_HINT_RANGE, "0,5,0.1", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/custom_theme", ""); hints["interface/theme/custom_theme"] = PropertyInfo(Variant::STRING, "interface/theme/custom_theme", PROPERTY_HINT_GLOBAL_FILE, "*.res,*.tres,*.theme", PROPERTY_USAGE_DEFAULT); // Scene tabs _initial_set("interface/scene_tabs/show_extension", false); _initial_set("interface/scene_tabs/show_thumbnail_on_hover", true); _initial_set("interface/scene_tabs/resize_if_many_tabs", true); _initial_set("interface/scene_tabs/minimum_width", 50); hints["interface/scene_tabs/minimum_width"] = PropertyInfo(Variant::INT, "interface/scene_tabs/minimum_width", PROPERTY_HINT_RANGE, "50,500,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/scene_tabs/show_script_button", false); /* Filesystem */ // Directories _initial_set("filesystem/directories/autoscan_project_path", ""); hints["filesystem/directories/autoscan_project_path"] = PropertyInfo(Variant::STRING, "filesystem/directories/autoscan_project_path", PROPERTY_HINT_GLOBAL_DIR); _initial_set("filesystem/directories/default_project_path", OS::get_singleton()->has_environment("HOME") ? OS::get_singleton()->get_environment("HOME") : OS::get_singleton()->get_system_dir(OS::SYSTEM_DIR_DOCUMENTS)); hints["filesystem/directories/default_project_path"] = PropertyInfo(Variant::STRING, "filesystem/directories/default_project_path", PROPERTY_HINT_GLOBAL_DIR); // On save _initial_set("filesystem/on_save/compress_binary_resources", true); _initial_set("filesystem/on_save/safe_save_on_backup_then_rename", true); // File dialog _initial_set("filesystem/file_dialog/show_hidden_files", false); _initial_set("filesystem/file_dialog/display_mode", 0); hints["filesystem/file_dialog/display_mode"] = PropertyInfo(Variant::INT, "filesystem/file_dialog/display_mode", PROPERTY_HINT_ENUM, "Thumbnails,List"); _initial_set("filesystem/file_dialog/thumbnail_size", 64); hints["filesystem/file_dialog/thumbnail_size"] = PropertyInfo(Variant::INT, "filesystem/file_dialog/thumbnail_size", PROPERTY_HINT_RANGE, "32,128,16"); // Import _initial_set("filesystem/import/pvrtc_texture_tool", ""); #ifdef WINDOWS_ENABLED hints["filesystem/import/pvrtc_texture_tool"] = PropertyInfo(Variant::STRING, "filesystem/import/pvrtc_texture_tool", PROPERTY_HINT_GLOBAL_FILE, "*.exe"); #else hints["filesystem/import/pvrtc_texture_tool"] = PropertyInfo(Variant::STRING, "filesystem/import/pvrtc_texture_tool", PROPERTY_HINT_GLOBAL_FILE, ""); #endif _initial_set("filesystem/import/pvrtc_fast_conversion", false); /* Docks */ // SceneTree _initial_set("docks/scene_tree/start_create_dialog_fully_expanded", false); // FileSystem _initial_set("docks/filesystem/thumbnail_size", 64); hints["docks/filesystem/thumbnail_size"] = PropertyInfo(Variant::INT, "docks/filesystem/thumbnail_size", PROPERTY_HINT_RANGE, "32,128,16"); _initial_set("docks/filesystem/always_show_folders", true); // Property editor _initial_set("docks/property_editor/auto_refresh_interval", 0.3); /* Text editor */ // Theme _initial_set("text_editor/theme/color_theme", "Adaptive"); hints["text_editor/theme/color_theme"] = PropertyInfo(Variant::STRING, "text_editor/theme/color_theme", PROPERTY_HINT_ENUM, "Adaptive,Default,Custom"); _initial_set("text_editor/theme/line_spacing", 6); hints["text_editor/theme/line_spacing"] = PropertyInfo(Variant::INT, "text_editor/theme/line_spacing", PROPERTY_HINT_RANGE, "0,50,1"); _load_default_text_editor_theme(); // Highlighting _initial_set("text_editor/highlighting/syntax_highlighting", true); _initial_set("text_editor/highlighting/highlight_all_occurrences", true); _initial_set("text_editor/highlighting/highlight_current_line", true); _initial_set("text_editor/highlighting/highlight_type_safe_lines", true); // Indent _initial_set("text_editor/indent/type", 0); hints["text_editor/indent/type"] = PropertyInfo(Variant::INT, "text_editor/indent/type", PROPERTY_HINT_ENUM, "Tabs,Spaces"); _initial_set("text_editor/indent/size", 4); hints["text_editor/indent/size"] = PropertyInfo(Variant::INT, "text_editor/indent/size", PROPERTY_HINT_RANGE, "1, 64, 1"); // size of 0 crashes. _initial_set("text_editor/indent/auto_indent", true); _initial_set("text_editor/indent/convert_indent_on_save", false); _initial_set("text_editor/indent/draw_tabs", true); _initial_set("text_editor/indent/draw_spaces", false); // Line numbers _initial_set("text_editor/line_numbers/show_line_numbers", true); _initial_set("text_editor/line_numbers/line_numbers_zero_padded", false); _initial_set("text_editor/line_numbers/show_bookmark_gutter", true); _initial_set("text_editor/line_numbers/show_breakpoint_gutter", true); _initial_set("text_editor/line_numbers/show_info_gutter", true); _initial_set("text_editor/line_numbers/code_folding", true); _initial_set("text_editor/line_numbers/word_wrap", false); _initial_set("text_editor/line_numbers/show_line_length_guideline", false); _initial_set("text_editor/line_numbers/line_length_guideline_column", 80); hints["text_editor/line_numbers/line_length_guideline_column"] = PropertyInfo(Variant::INT, "text_editor/line_numbers/line_length_guideline_column", PROPERTY_HINT_RANGE, "20, 160, 1"); // Open scripts _initial_set("text_editor/open_scripts/smooth_scrolling", true); _initial_set("text_editor/open_scripts/v_scroll_speed", 80); _initial_set("text_editor/open_scripts/show_members_overview", true); // Files _initial_set("text_editor/files/trim_trailing_whitespace_on_save", false); _initial_set("text_editor/files/autosave_interval_secs", 0); _initial_set("text_editor/files/restore_scripts_on_load", true); // Tools _initial_set("text_editor/tools/create_signal_callbacks", true); _initial_set("text_editor/tools/sort_members_outline_alphabetically", false); // Cursor _initial_set("text_editor/cursor/scroll_past_end_of_file", false); _initial_set("text_editor/cursor/block_caret", false); _initial_set("text_editor/cursor/caret_blink", true); _initial_set("text_editor/cursor/caret_blink_speed", 0.5); hints["text_editor/cursor/caret_blink_speed"] = PropertyInfo(Variant::REAL, "text_editor/cursor/caret_blink_speed", PROPERTY_HINT_RANGE, "0.1, 10, 0.01"); _initial_set("text_editor/cursor/right_click_moves_caret", true); // Completion _initial_set("text_editor/completion/idle_parse_delay", 2.0); hints["text_editor/completion/idle_parse_delay"] = PropertyInfo(Variant::REAL, "text_editor/completion/idle_parse_delay", PROPERTY_HINT_RANGE, "0.1, 10, 0.01"); _initial_set("text_editor/completion/auto_brace_complete", true); _initial_set("text_editor/completion/code_complete_delay", 0.3); hints["text_editor/completion/code_complete_delay"] = PropertyInfo(Variant::REAL, "text_editor/completion/code_complete_delay", PROPERTY_HINT_RANGE, "0.01, 5, 0.01"); _initial_set("text_editor/completion/put_callhint_tooltip_below_current_line", true); _initial_set("text_editor/completion/callhint_tooltip_offset", Vector2()); _initial_set("text_editor/completion/complete_file_paths", true); _initial_set("text_editor/completion/add_type_hints", false); _initial_set("text_editor/completion/use_single_quotes", false); // Help _initial_set("text_editor/help/show_help_index", true); _initial_set("text_editor/help/help_font_size", 15); hints["text_editor/help/help_font_size"] = PropertyInfo(Variant::INT, "text_editor/help/help_font_size", PROPERTY_HINT_RANGE, "8,48,1"); _initial_set("text_editor/help/help_source_font_size", 14); hints["text_editor/help/help_source_font_size"] = PropertyInfo(Variant::INT, "text_editor/help/help_source_font_size", PROPERTY_HINT_RANGE, "8,48,1"); _initial_set("text_editor/help/help_title_font_size", 23); hints["text_editor/help/help_title_font_size"] = PropertyInfo(Variant::INT, "text_editor/help/help_title_font_size", PROPERTY_HINT_RANGE, "8,48,1"); /* Editors */ // GridMap _initial_set("editors/grid_map/pick_distance", 5000.0); // 3D _initial_set("editors/3d/primary_grid_color", Color(0.56, 0.56, 0.56)); hints["editors/3d/primary_grid_color"] = PropertyInfo(Variant::COLOR, "editors/3d/primary_grid_color", PROPERTY_HINT_COLOR_NO_ALPHA, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("editors/3d/secondary_grid_color", Color(0.38, 0.38, 0.38)); hints["editors/3d/secondary_grid_color"] = PropertyInfo(Variant::COLOR, "editors/3d/secondary_grid_color", PROPERTY_HINT_COLOR_NO_ALPHA, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("editors/3d/grid_size", 50); hints["editors/3d/grid_size"] = PropertyInfo(Variant::INT, "editors/3d/grid_size", PROPERTY_HINT_RANGE, "1,500,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("editors/3d/primary_grid_steps", 10); hints["editors/3d/primary_grid_steps"] = PropertyInfo(Variant::INT, "editors/3d/primary_grid_steps", PROPERTY_HINT_RANGE, "1,100,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("editors/3d/default_fov", 70.0); _initial_set("editors/3d/default_z_near", 0.05); _initial_set("editors/3d/default_z_far", 500.0); // 3D: Navigation _initial_set("editors/3d/navigation/navigation_scheme", 0); _initial_set("editors/3d/navigation/invert_y_axis", false); hints["editors/3d/navigation/navigation_scheme"] = PropertyInfo(Variant::INT, "editors/3d/navigation/navigation_scheme", PROPERTY_HINT_ENUM, "Godot,Maya,Modo"); _initial_set("editors/3d/navigation/zoom_style", 0); hints["editors/3d/navigation/zoom_style"] = PropertyInfo(Variant::INT, "editors/3d/navigation/zoom_style", PROPERTY_HINT_ENUM, "Vertical, Horizontal"); _initial_set("editors/3d/navigation/emulate_3_button_mouse", false); _initial_set("editors/3d/navigation/orbit_modifier", 0); hints["editors/3d/navigation/orbit_modifier"] = PropertyInfo(Variant::INT, "editors/3d/navigation/orbit_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl"); _initial_set("editors/3d/navigation/pan_modifier", 1); hints["editors/3d/navigation/pan_modifier"] = PropertyInfo(Variant::INT, "editors/3d/navigation/pan_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl"); _initial_set("editors/3d/navigation/zoom_modifier", 4); hints["editors/3d/navigation/zoom_modifier"] = PropertyInfo(Variant::INT, "editors/3d/navigation/zoom_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl"); _initial_set("editors/3d/navigation/warped_mouse_panning", true); // 3D: Navigation feel _initial_set("editors/3d/navigation_feel/orbit_sensitivity", 0.4); hints["editors/3d/navigation_feel/orbit_sensitivity"] = PropertyInfo(Variant::REAL, "editors/3d/navigation_feel/orbit_sensitivity", PROPERTY_HINT_RANGE, "0.0, 2, 0.01"); _initial_set("editors/3d/navigation_feel/orbit_inertia", 0.05); hints["editors/3d/navigation_feel/orbit_inertia"] = PropertyInfo(Variant::REAL, "editors/3d/navigation_feel/orbit_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/navigation_feel/translation_inertia", 0.15); hints["editors/3d/navigation_feel/translation_inertia"] = PropertyInfo(Variant::REAL, "editors/3d/navigation_feel/translation_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/navigation_feel/zoom_inertia", 0.075); hints["editors/3d/navigation_feel/zoom_inertia"] = PropertyInfo(Variant::REAL, "editors/3d/navigation_feel/zoom_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/navigation_feel/manipulation_orbit_inertia", 0.075); hints["editors/3d/navigation_feel/manipulation_orbit_inertia"] = PropertyInfo(Variant::REAL, "editors/3d/navigation_feel/manipulation_orbit_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/navigation_feel/manipulation_translation_inertia", 0.075); hints["editors/3d/navigation_feel/manipulation_translation_inertia"] = PropertyInfo(Variant::REAL, "editors/3d/navigation_feel/manipulation_translation_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); // 3D: Freelook _initial_set("editors/3d/freelook/freelook_inertia", 0.1); hints["editors/3d/freelook/freelook_inertia"] = PropertyInfo(Variant::REAL, "editors/3d/freelook/freelook_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/freelook/freelook_base_speed", 5.0); hints["editors/3d/freelook/freelook_base_speed"] = PropertyInfo(Variant::REAL, "editors/3d/freelook/freelook_base_speed", PROPERTY_HINT_RANGE, "0.0, 10, 0.01"); _initial_set("editors/3d/freelook/freelook_activation_modifier", 0); hints["editors/3d/freelook/freelook_activation_modifier"] = PropertyInfo(Variant::INT, "editors/3d/freelook/freelook_activation_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl"); _initial_set("editors/3d/freelook/freelook_modifier_speed_factor", 3.0); hints["editors/3d/freelook/freelook_modifier_speed_factor"] = PropertyInfo(Variant::REAL, "editors/3d/freelook/freelook_modifier_speed_factor", PROPERTY_HINT_RANGE, "0.0, 10.0, 0.1"); _initial_set("editors/3d/freelook/freelook_speed_zoom_link", false); // 2D _initial_set("editors/2d/grid_color", Color(1.0, 1.0, 1.0, 0.07)); _initial_set("editors/2d/guides_color", Color(0.6, 0.0, 0.8)); _initial_set("editors/2d/bone_width", 5); _initial_set("editors/2d/bone_color1", Color(1.0, 1.0, 1.0, 0.9)); _initial_set("editors/2d/bone_color2", Color(0.6, 0.6, 0.6, 0.9)); _initial_set("editors/2d/bone_selected_color", Color(0.9, 0.45, 0.45, 0.9)); _initial_set("editors/2d/bone_ik_color", Color(0.9, 0.9, 0.45, 0.9)); _initial_set("editors/2d/bone_outline_color", Color(0.35, 0.35, 0.35)); _initial_set("editors/2d/bone_outline_size", 2); _initial_set("editors/2d/viewport_border_color", Color(0.4, 0.4, 1.0, 0.4)); _initial_set("editors/2d/constrain_editor_view", true); _initial_set("editors/2d/warped_mouse_panning", true); _initial_set("editors/2d/simple_panning", false); _initial_set("editors/2d/scroll_to_pan", false); _initial_set("editors/2d/pan_speed", 20); // Polygon editor _initial_set("editors/poly_editor/point_grab_radius", 8); _initial_set("editors/poly_editor/show_previous_outline", true); // Animation _initial_set("editors/animation/autorename_animation_tracks", true); _initial_set("editors/animation/confirm_insert_track", true); _initial_set("editors/animation/onion_layers_past_color", Color(1, 0, 0)); _initial_set("editors/animation/onion_layers_future_color", Color(0, 1, 0)); /* Run */ // Window placement _initial_set("run/window_placement/rect", 1); hints["run/window_placement/rect"] = PropertyInfo(Variant::INT, "run/window_placement/rect", PROPERTY_HINT_ENUM, "Top Left,Centered,Custom Position,Force Maximized,Force Fullscreen"); String screen_hints = "Same as Editor,Previous Monitor,Next Monitor"; for (int i = 0; i < OS::get_singleton()->get_screen_count(); i++) { screen_hints += ",Monitor " + itos(i + 1); } _initial_set("run/window_placement/rect_custom_position", Vector2()); _initial_set("run/window_placement/screen", 0); hints["run/window_placement/screen"] = PropertyInfo(Variant::INT, "run/window_placement/screen", PROPERTY_HINT_ENUM, screen_hints); // Auto save _initial_set("run/auto_save/save_before_running", true); // Output _initial_set("run/output/font_size", 13); hints["run/output/font_size"] = PropertyInfo(Variant::INT, "run/output/font_size", PROPERTY_HINT_RANGE, "8,48,1"); _initial_set("run/output/always_clear_output_on_play", true); _initial_set("run/output/always_open_output_on_play", true); _initial_set("run/output/always_close_output_on_stop", false); /* Extra config */ _initial_set("project_manager/sorting_order", 0); hints["project_manager/sorting_order"] = PropertyInfo(Variant::INT, "project_manager/sorting_order", PROPERTY_HINT_ENUM, "Name,Path,Last Modified"); if (p_extra_config.is_valid()) { if (p_extra_config->has_section("init_projects") && p_extra_config->has_section_key("init_projects", "list")) { Vector<String> list = p_extra_config->get_value("init_projects", "list"); for (int i = 0; i < list.size(); i++) { String name = list[i].replace("/", "::"); set("projects/" + name, list[i]); }; }; if (p_extra_config->has_section("presets")) { List<String> keys; p_extra_config->get_section_keys("presets", &keys); for (List<String>::Element *E = keys.front(); E; E = E->next()) { String key = E->get(); Variant val = p_extra_config->get_value("presets", key); set(key, val); }; }; }; } void EditorSettings::_load_default_text_editor_theme() { bool dark_theme = is_dark_theme(); _initial_set("text_editor/highlighting/symbol_color", Color(0.73, 0.87, 1.0)); _initial_set("text_editor/highlighting/keyword_color", Color(1.0, 1.0, 0.7)); _initial_set("text_editor/highlighting/base_type_color", Color(0.64, 1.0, 0.83)); _initial_set("text_editor/highlighting/engine_type_color", Color(0.51, 0.83, 1.0)); _initial_set("text_editor/highlighting/comment_color", Color(0.4, 0.4, 0.4)); _initial_set("text_editor/highlighting/string_color", Color(0.94, 0.43, 0.75)); _initial_set("text_editor/highlighting/background_color", dark_theme ? Color(0.0, 0.0, 0.0, 0.23) : Color(0.2, 0.23, 0.31)); _initial_set("text_editor/highlighting/completion_background_color", Color(0.17, 0.16, 0.2)); _initial_set("text_editor/highlighting/completion_selected_color", Color(0.26, 0.26, 0.27)); _initial_set("text_editor/highlighting/completion_existing_color", Color(0.13, 0.87, 0.87, 0.87)); _initial_set("text_editor/highlighting/completion_scroll_color", Color(1, 1, 1)); _initial_set("text_editor/highlighting/completion_font_color", Color(0.67, 0.67, 0.67)); _initial_set("text_editor/highlighting/text_color", Color(0.67, 0.67, 0.67)); _initial_set("text_editor/highlighting/line_number_color", Color(0.67, 0.67, 0.67, 0.4)); _initial_set("text_editor/highlighting/safe_line_number_color", Color(0.67, 0.78, 0.67, 0.6)); _initial_set("text_editor/highlighting/caret_color", Color(0.67, 0.67, 0.67)); _initial_set("text_editor/highlighting/caret_background_color", Color(0, 0, 0)); _initial_set("text_editor/highlighting/text_selected_color", Color(0, 0, 0)); _initial_set("text_editor/highlighting/selection_color", Color(0.41, 0.61, 0.91, 0.35)); _initial_set("text_editor/highlighting/brace_mismatch_color", Color(1, 0.2, 0.2)); _initial_set("text_editor/highlighting/current_line_color", Color(0.3, 0.5, 0.8, 0.15)); _initial_set("text_editor/highlighting/line_length_guideline_color", Color(0.3, 0.5, 0.8, 0.1)); _initial_set("text_editor/highlighting/word_highlighted_color", Color(0.8, 0.9, 0.9, 0.15)); _initial_set("text_editor/highlighting/number_color", Color(0.92, 0.58, 0.2)); _initial_set("text_editor/highlighting/function_color", Color(0.4, 0.64, 0.81)); _initial_set("text_editor/highlighting/member_variable_color", Color(0.9, 0.31, 0.35)); _initial_set("text_editor/highlighting/mark_color", Color(1.0, 0.4, 0.4, 0.4)); _initial_set("text_editor/highlighting/bookmark_color", Color(0.08, 0.49, 0.98)); _initial_set("text_editor/highlighting/breakpoint_color", Color(0.8, 0.8, 0.4, 0.2)); _initial_set("text_editor/highlighting/executing_line_color", Color(0.2, 0.8, 0.2, 0.4)); _initial_set("text_editor/highlighting/code_folding_color", Color(0.8, 0.8, 0.8, 0.8)); _initial_set("text_editor/highlighting/search_result_color", Color(0.05, 0.25, 0.05, 1)); _initial_set("text_editor/highlighting/search_result_border_color", Color(0.41, 0.61, 0.91, 0.38)); } bool EditorSettings::_save_text_editor_theme(String p_file) { String theme_section = "color_theme"; Ref<ConfigFile> cf = memnew(ConfigFile); // hex is better? List<String> keys; props.get_key_list(&keys); keys.sort(); for (const List<String>::Element *E = keys.front(); E; E = E->next()) { const String &key = E->get(); if (key.begins_with("text_editor/highlighting/") && key.find("color") >= 0) { cf->set_value(theme_section, key.replace("text_editor/highlighting/", ""), ((Color)props[key].variant).to_html()); } } Error err = cf->save(p_file); return err == OK; } bool EditorSettings::_is_default_text_editor_theme(String p_theme_name) { return p_theme_name == "default" || p_theme_name == "adaptive" || p_theme_name == "custom"; } static Dictionary _get_builtin_script_templates() { Dictionary templates; // No Comments templates["no_comments.gd"] = "extends %BASE%\n" "\n" "func _ready()%VOID_RETURN%:\n" "%TS%pass\n"; // Empty templates["empty.gd"] = "extends %BASE%" "\n" "\n"; return templates; } static void _create_script_templates(const String &p_path) { Dictionary templates = _get_builtin_script_templates(); List<Variant> keys; templates.get_key_list(&keys); FileAccess *file = FileAccess::create(FileAccess::ACCESS_FILESYSTEM); DirAccess *dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); dir->change_dir(p_path); for (int i = 0; i < keys.size(); i++) { if (!dir->file_exists(keys[i])) { Error err = file->reopen(p_path.plus_file((String)keys[i]), FileAccess::WRITE); ERR_FAIL_COND(err != OK); file->store_string(templates[keys[i]]); file->close(); } } memdelete(dir); memdelete(file); } // PUBLIC METHODS EditorSettings *EditorSettings::get_singleton() { return singleton.ptr(); } void EditorSettings::create() { if (singleton.ptr()) return; //pointless DirAccess *dir = NULL; String data_path; String data_dir; String config_path; String config_dir; String cache_path; String cache_dir; Ref<ConfigFile> extra_config = memnew(ConfigFile); String exe_path = OS::get_singleton()->get_executable_path().get_base_dir(); DirAccess *d = DirAccess::create_for_path(exe_path); bool self_contained = false; if (d->file_exists(exe_path + "/._sc_")) { self_contained = true; Error err = extra_config->load(exe_path + "/._sc_"); if (err != OK) { ERR_PRINTS("Can't load config from path: " + exe_path + "/._sc_"); } } else if (d->file_exists(exe_path + "/_sc_")) { self_contained = true; Error err = extra_config->load(exe_path + "/_sc_"); if (err != OK) { ERR_PRINTS("Can't load config from path: " + exe_path + "/_sc_"); } } memdelete(d); if (self_contained) { // editor is self contained, all in same folder data_path = exe_path; data_dir = data_path.plus_file("editor_data"); config_path = exe_path; config_dir = data_dir; cache_path = exe_path; cache_dir = data_dir.plus_file("cache"); } else { // Typically XDG_DATA_HOME or %APPDATA% data_path = OS::get_singleton()->get_data_path(); data_dir = data_path.plus_file(OS::get_singleton()->get_godot_dir_name()); // Can be different from data_path e.g. on Linux or macOS config_path = OS::get_singleton()->get_config_path(); config_dir = config_path.plus_file(OS::get_singleton()->get_godot_dir_name()); // Can be different from above paths, otherwise a subfolder of data_dir cache_path = OS::get_singleton()->get_cache_path(); if (cache_path == data_path) { cache_dir = data_dir.plus_file("cache"); } else { cache_dir = cache_path.plus_file(OS::get_singleton()->get_godot_dir_name()); } } ClassDB::register_class<EditorSettings>(); //otherwise it can't be unserialized String config_file_path; if (data_path != "" && config_path != "" && cache_path != "") { // Validate/create data dir and subdirectories dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); if (dir->change_dir(data_dir) != OK) { dir->make_dir_recursive(data_dir); if (dir->change_dir(data_dir) != OK) { ERR_PRINT("Cannot create data directory!"); memdelete(dir); goto fail; } } if (dir->change_dir("templates") != OK) { dir->make_dir("templates"); } else { dir->change_dir(".."); } // Validate/create cache dir if (dir->change_dir(cache_dir) != OK) { dir->make_dir_recursive(cache_dir); if (dir->change_dir(cache_dir) != OK) { ERR_PRINT("Cannot create cache directory!"); memdelete(dir); goto fail; } } // Validate/create config dir and subdirectories if (dir->change_dir(config_dir) != OK) { dir->make_dir_recursive(config_dir); if (dir->change_dir(config_dir) != OK) { ERR_PRINT("Cannot create config directory!"); memdelete(dir); goto fail; } } if (dir->change_dir("text_editor_themes") != OK) { dir->make_dir("text_editor_themes"); } else { dir->change_dir(".."); } if (dir->change_dir("script_templates") != OK) { dir->make_dir("script_templates"); } else { dir->change_dir(".."); } if (dir->change_dir("feature_profiles") != OK) { dir->make_dir("feature_profiles"); } else { dir->change_dir(".."); } _create_script_templates(dir->get_current_dir().plus_file("script_templates")); if (dir->change_dir("projects") != OK) { dir->make_dir("projects"); } else { dir->change_dir(".."); } // Validate/create project-specific config dir dir->change_dir("projects"); String project_config_dir = ProjectSettings::get_singleton()->get_resource_path(); if (project_config_dir.ends_with("/")) project_config_dir = config_path.substr(0, project_config_dir.size() - 1); project_config_dir = project_config_dir.get_file() + "-" + project_config_dir.md5_text(); if (dir->change_dir(project_config_dir) != OK) { dir->make_dir(project_config_dir); } else { dir->change_dir(".."); } dir->change_dir(".."); // Validate editor config file String config_file_name = "editor_settings-" + itos(VERSION_MAJOR) + ".tres"; config_file_path = config_dir.plus_file(config_file_name); if (!dir->file_exists(config_file_name)) { goto fail; } memdelete(dir); singleton = ResourceLoader::load(config_file_path, "EditorSettings"); if (singleton.is_null()) { WARN_PRINT("Could not open config file."); goto fail; } singleton->save_changed_setting = true; singleton->config_file_path = config_file_path; singleton->project_config_dir = project_config_dir; singleton->settings_dir = config_dir; singleton->data_dir = data_dir; singleton->cache_dir = cache_dir; print_verbose("EditorSettings: Load OK!"); singleton->setup_language(); singleton->setup_network(); singleton->load_favorites(); singleton->list_text_editor_themes(); return; } fail: // patch init projects if (extra_config->has_section("init_projects")) { Vector<String> list = extra_config->get_value("init_projects", "list"); for (int i = 0; i < list.size(); i++) { list.write[i] = exe_path.plus_file(list[i]); }; extra_config->set_value("init_projects", "list", list); }; singleton = Ref<EditorSettings>(memnew(EditorSettings)); singleton->save_changed_setting = true; singleton->config_file_path = config_file_path; singleton->settings_dir = config_dir; singleton->data_dir = data_dir; singleton->cache_dir = cache_dir; singleton->_load_defaults(extra_config); singleton->setup_language(); singleton->setup_network(); singleton->list_text_editor_themes(); } void EditorSettings::setup_language() { String lang = get("interface/editor/editor_language"); if (lang == "en") return; //none to do EditorTranslationList *etl = _editor_translations; while (etl->data) { if (etl->lang == lang) { Vector<uint8_t> data; data.resize(etl->uncomp_size); Compression::decompress(data.ptrw(), etl->uncomp_size, etl->data, etl->comp_size, Compression::MODE_DEFLATE); FileAccessMemory *fa = memnew(FileAccessMemory); fa->open_custom(data.ptr(), data.size()); Ref<Translation> tr = TranslationLoaderPO::load_translation(fa, NULL, "translation_" + String(etl->lang)); if (tr.is_valid()) { tr->set_locale(etl->lang); TranslationServer::get_singleton()->set_tool_translation(tr); break; } } etl++; } } void EditorSettings::setup_network() { List<IP_Address> local_ip; IP::get_singleton()->get_local_addresses(&local_ip); String lip = "127.0.0.1"; String hint; String current = has_setting("network/debug/remote_host") ? get("network/debug/remote_host") : ""; int port = has_setting("network/debug/remote_port") ? (int)get("network/debug/remote_port") : 6007; for (List<IP_Address>::Element *E = local_ip.front(); E; E = E->next()) { String ip = E->get(); // link-local IPv6 addresses don't work, skipping them if (ip.begins_with("fe80:0:0:0:")) // fe80::/64 continue; // Same goes for IPv4 link-local (APIPA) addresses. if (ip.begins_with("169.254.")) // 169.254.0.0/16 continue; if (ip == current) lip = current; //so it saves if (hint != "") hint += ","; hint += ip; } _initial_set("network/debug/remote_host", lip); add_property_hint(PropertyInfo(Variant::STRING, "network/debug/remote_host", PROPERTY_HINT_ENUM, hint)); _initial_set("network/debug/remote_port", port); add_property_hint(PropertyInfo(Variant::INT, "network/debug/remote_port", PROPERTY_HINT_RANGE, "1,65535,1")); // Editor SSL certificates override _initial_set("network/ssl/editor_ssl_certificates", _SYSTEM_CERTS_PATH); add_property_hint(PropertyInfo(Variant::STRING, "network/ssl/editor_ssl_certificates", PROPERTY_HINT_GLOBAL_FILE, "*.crt,*.pem")); } void EditorSettings::save() { //_THREAD_SAFE_METHOD_ if (!singleton.ptr()) return; if (singleton->config_file_path == "") { ERR_PRINT("Cannot save EditorSettings config, no valid path"); return; } Error err = ResourceSaver::save(singleton->config_file_path, singleton); if (err != OK) { ERR_PRINTS("Error saving editor settings to " + singleton->config_file_path); } else { print_verbose("EditorSettings: Save OK!"); } } void EditorSettings::destroy() { if (!singleton.ptr()) return; save(); singleton = Ref<EditorSettings>(); } void EditorSettings::set_optimize_save(bool p_optimize) { optimize_save = p_optimize; } // Properties void EditorSettings::set_setting(const String &p_setting, const Variant &p_value) { _THREAD_SAFE_METHOD_ set(p_setting, p_value); } Variant EditorSettings::get_setting(const String &p_setting) const { _THREAD_SAFE_METHOD_ return get(p_setting); } bool EditorSettings::has_setting(const String &p_setting) const { _THREAD_SAFE_METHOD_ return props.has(p_setting); } void EditorSettings::erase(const String &p_setting) { _THREAD_SAFE_METHOD_ props.erase(p_setting); } void EditorSettings::raise_order(const String &p_setting) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND(!props.has(p_setting)); props[p_setting].order = ++last_order; } void EditorSettings::set_restart_if_changed(const StringName &p_setting, bool p_restart) { _THREAD_SAFE_METHOD_ if (!props.has(p_setting)) return; props[p_setting].restart_if_changed = p_restart; } void EditorSettings::set_initial_value(const StringName &p_setting, const Variant &p_value, bool p_update_current) { _THREAD_SAFE_METHOD_ if (!props.has(p_setting)) return; props[p_setting].initial = p_value; props[p_setting].has_default_value = true; if (p_update_current) { set(p_setting, p_value); } } Variant _EDITOR_DEF(const String &p_setting, const Variant &p_default, bool p_restart_if_changed) { Variant ret = p_default; if (EditorSettings::get_singleton()->has_setting(p_setting)) { ret = EditorSettings::get_singleton()->get(p_setting); } else { EditorSettings::get_singleton()->set_manually(p_setting, p_default); EditorSettings::get_singleton()->set_restart_if_changed(p_setting, p_restart_if_changed); } if (!EditorSettings::get_singleton()->has_default_value(p_setting)) { EditorSettings::get_singleton()->set_initial_value(p_setting, p_default); } return ret; } Variant _EDITOR_GET(const String &p_setting) { ERR_FAIL_COND_V(!EditorSettings::get_singleton()->has_setting(p_setting), Variant()); return EditorSettings::get_singleton()->get(p_setting); } bool EditorSettings::property_can_revert(const String &p_setting) { if (!props.has(p_setting)) return false; if (!props[p_setting].has_default_value) return false; return props[p_setting].initial != props[p_setting].variant; } Variant EditorSettings::property_get_revert(const String &p_setting) { if (!props.has(p_setting) || !props[p_setting].has_default_value) return Variant(); return props[p_setting].initial; } void EditorSettings::add_property_hint(const PropertyInfo &p_hint) { _THREAD_SAFE_METHOD_ hints[p_hint.name] = p_hint; } // Data directories String EditorSettings::get_data_dir() const { return data_dir; } String EditorSettings::get_templates_dir() const { return get_data_dir().plus_file("templates"); } // Config directories String EditorSettings::get_settings_dir() const { return settings_dir; } String EditorSettings::get_project_settings_dir() const { return get_settings_dir().plus_file("projects").plus_file(project_config_dir); } String EditorSettings::get_text_editor_themes_dir() const { return get_settings_dir().plus_file("text_editor_themes"); } String EditorSettings::get_script_templates_dir() const { return get_settings_dir().plus_file("script_templates"); } // Cache directory String EditorSettings::get_cache_dir() const { return cache_dir; } String EditorSettings::get_feature_profiles_dir() const { return get_settings_dir().plus_file("feature_profiles"); } // Metadata void EditorSettings::set_project_metadata(const String &p_section, const String &p_key, Variant p_data) { Ref<ConfigFile> cf = memnew(ConfigFile); String path = get_project_settings_dir().plus_file("project_metadata.cfg"); Error err; err = cf->load(path); ERR_FAIL_COND(err != OK); cf->set_value(p_section, p_key, p_data); err = cf->save(path); ERR_FAIL_COND(err != OK); } Variant EditorSettings::get_project_metadata(const String &p_section, const String &p_key, Variant p_default) const { Ref<ConfigFile> cf = memnew(ConfigFile); String path = get_project_settings_dir().plus_file("project_metadata.cfg"); Error err = cf->load(path); if (err != OK) { return p_default; } return cf->get_value(p_section, p_key, p_default); } void EditorSettings::set_favorites(const Vector<String> &p_favorites) { favorites = p_favorites; FileAccess *f = FileAccess::open(get_project_settings_dir().plus_file("favorites"), FileAccess::WRITE); if (f) { for (int i = 0; i < favorites.size(); i++) f->store_line(favorites[i]); memdelete(f); } } Vector<String> EditorSettings::get_favorites() const { return favorites; } void EditorSettings::set_recent_dirs(const Vector<String> &p_recent_dirs) { recent_dirs = p_recent_dirs; FileAccess *f = FileAccess::open(get_project_settings_dir().plus_file("recent_dirs"), FileAccess::WRITE); if (f) { for (int i = 0; i < recent_dirs.size(); i++) f->store_line(recent_dirs[i]); memdelete(f); } } Vector<String> EditorSettings::get_recent_dirs() const { return recent_dirs; } void EditorSettings::load_favorites() { FileAccess *f = FileAccess::open(get_project_settings_dir().plus_file("favorites"), FileAccess::READ); if (f) { String line = f->get_line().strip_edges(); while (line != "") { favorites.push_back(line); line = f->get_line().strip_edges(); } memdelete(f); } f = FileAccess::open(get_project_settings_dir().plus_file("recent_dirs"), FileAccess::READ); if (f) { String line = f->get_line().strip_edges(); while (line != "") { recent_dirs.push_back(line); line = f->get_line().strip_edges(); } memdelete(f); } } bool EditorSettings::is_dark_theme() { int AUTO_COLOR = 0; int LIGHT_COLOR = 2; Color base_color = get("interface/theme/base_color"); int icon_font_color_setting = get("interface/theme/icon_and_font_color"); return (icon_font_color_setting == AUTO_COLOR && ((base_color.r + base_color.g + base_color.b) / 3.0) < 0.5) || icon_font_color_setting == LIGHT_COLOR; } void EditorSettings::list_text_editor_themes() { String themes = "Adaptive,Default,Custom"; DirAccess *d = DirAccess::open(get_text_editor_themes_dir()); if (d) { List<String> custom_themes; d->list_dir_begin(); String file = d->get_next(); while (file != String()) { if (file.get_extension() == "tet" && !_is_default_text_editor_theme(file.get_basename().to_lower())) { custom_themes.push_back(file.get_basename()); } file = d->get_next(); } d->list_dir_end(); memdelete(d); custom_themes.sort(); for (List<String>::Element *E = custom_themes.front(); E; E = E->next()) { themes += "," + E->get(); } } add_property_hint(PropertyInfo(Variant::STRING, "text_editor/theme/color_theme", PROPERTY_HINT_ENUM, themes)); } void EditorSettings::load_text_editor_theme() { String p_file = get("text_editor/theme/color_theme"); if (_is_default_text_editor_theme(p_file.get_file().to_lower())) { if (p_file == "Default") { _load_default_text_editor_theme(); } return; // sorry for "Settings changed" console spam } String theme_path = get_text_editor_themes_dir().plus_file(p_file + ".tet"); Ref<ConfigFile> cf = memnew(ConfigFile); Error err = cf->load(theme_path); if (err != OK) { return; } List<String> keys; cf->get_section_keys("color_theme", &keys); for (List<String>::Element *E = keys.front(); E; E = E->next()) { String key = E->get(); String val = cf->get_value("color_theme", key); // don't load if it's not already there! if (has_setting("text_editor/highlighting/" + key)) { // make sure it is actually a color if (val.is_valid_html_color() && key.find("color") >= 0) { props["text_editor/highlighting/" + key].variant = Color::html(val); // change manually to prevent "Settings changed" console spam } } } emit_signal("settings_changed"); // if it doesn't load just use what is currently loaded } bool EditorSettings::import_text_editor_theme(String p_file) { if (!p_file.ends_with(".tet")) { return false; } else { if (p_file.get_file().to_lower() == "default.tet") { return false; } DirAccess *d = DirAccess::open(get_text_editor_themes_dir()); if (d) { d->copy(p_file, get_text_editor_themes_dir().plus_file(p_file.get_file())); memdelete(d); return true; } } return false; } bool EditorSettings::save_text_editor_theme() { String p_file = get("text_editor/theme/color_theme"); if (_is_default_text_editor_theme(p_file.get_file().to_lower())) { return false; } String theme_path = get_text_editor_themes_dir().plus_file(p_file + ".tet"); return _save_text_editor_theme(theme_path); } bool EditorSettings::save_text_editor_theme_as(String p_file) { if (!p_file.ends_with(".tet")) { p_file += ".tet"; } if (_is_default_text_editor_theme(p_file.get_file().to_lower().trim_suffix(".tet"))) { return false; } if (_save_text_editor_theme(p_file)) { // switch to theme is saved in the theme directory list_text_editor_themes(); String theme_name = p_file.substr(0, p_file.length() - 4).get_file(); if (p_file.get_base_dir() == get_text_editor_themes_dir()) { _initial_set("text_editor/theme/color_theme", theme_name); load_text_editor_theme(); } return true; } return false; } bool EditorSettings::is_default_text_editor_theme() { String p_file = get("text_editor/theme/color_theme"); return _is_default_text_editor_theme(p_file.get_file().to_lower()); } Vector<String> EditorSettings::get_script_templates(const String &p_extension) { Vector<String> templates; DirAccess *d = DirAccess::open(get_script_templates_dir()); if (d) { d->list_dir_begin(); String file = d->get_next(); while (file != String()) { if (file.get_extension() == p_extension) { templates.push_back(file.get_basename()); } file = d->get_next(); } d->list_dir_end(); memdelete(d); } return templates; } String EditorSettings::get_editor_layouts_config() const { return get_settings_dir().plus_file("editor_layouts.cfg"); } // Shortcuts void EditorSettings::add_shortcut(const String &p_name, Ref<ShortCut> &p_shortcut) { shortcuts[p_name] = p_shortcut; } bool EditorSettings::is_shortcut(const String &p_name, const Ref<InputEvent> &p_event) const { const Map<String, Ref<ShortCut> >::Element *E = shortcuts.find(p_name); if (!E) { ERR_EXPLAIN("Unknown Shortcut: " + p_name); ERR_FAIL_V(false); } return E->get()->is_shortcut(p_event); } Ref<ShortCut> EditorSettings::get_shortcut(const String &p_name) const { const Map<String, Ref<ShortCut> >::Element *E = shortcuts.find(p_name); if (!E) return Ref<ShortCut>(); return E->get(); } void EditorSettings::get_shortcut_list(List<String> *r_shortcuts) { for (const Map<String, Ref<ShortCut> >::Element *E = shortcuts.front(); E; E = E->next()) { r_shortcuts->push_back(E->key()); } } Ref<ShortCut> ED_GET_SHORTCUT(const String &p_path) { if (!EditorSettings::get_singleton()) { return NULL; } Ref<ShortCut> sc = EditorSettings::get_singleton()->get_shortcut(p_path); if (!sc.is_valid()) { ERR_EXPLAIN("Used ED_GET_SHORTCUT with invalid shortcut: " + p_path); ERR_FAIL_COND_V(!sc.is_valid(), sc); } return sc; } struct ShortCutMapping { const char *path; uint32_t keycode; }; Ref<ShortCut> ED_SHORTCUT(const String &p_path, const String &p_name, uint32_t p_keycode) { #ifdef OSX_ENABLED // Use Cmd+Backspace as a general replacement for Delete shortcuts on macOS if (p_keycode == KEY_DELETE) { p_keycode = KEY_MASK_CMD | KEY_BACKSPACE; } #endif Ref<InputEventKey> ie; if (p_keycode) { ie.instance(); ie->set_unicode(p_keycode & KEY_CODE_MASK); ie->set_scancode(p_keycode & KEY_CODE_MASK); ie->set_shift(bool(p_keycode & KEY_MASK_SHIFT)); ie->set_alt(bool(p_keycode & KEY_MASK_ALT)); ie->set_control(bool(p_keycode & KEY_MASK_CTRL)); ie->set_metakey(bool(p_keycode & KEY_MASK_META)); } if (!EditorSettings::get_singleton()) { Ref<ShortCut> sc; sc.instance(); sc->set_name(p_name); sc->set_shortcut(ie); sc->set_meta("original", ie); return sc; } Ref<ShortCut> sc = EditorSettings::get_singleton()->get_shortcut(p_path); if (sc.is_valid()) { sc->set_name(p_name); //keep name (the ones that come from disk have no name) sc->set_meta("original", ie); //to compare against changes return sc; } sc.instance(); sc->set_name(p_name); sc->set_shortcut(ie); sc->set_meta("original", ie); //to compare against changes EditorSettings::get_singleton()->add_shortcut(p_path, sc); return sc; } void EditorSettings::notify_changes() { _THREAD_SAFE_METHOD_ SceneTree *sml = Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop()); if (!sml) { return; } Node *root = sml->get_root()->get_child(0); if (!root) { return; } root->propagate_notification(NOTIFICATION_EDITOR_SETTINGS_CHANGED); } void EditorSettings::_bind_methods() { ClassDB::bind_method(D_METHOD("has_setting", "name"), &EditorSettings::has_setting); ClassDB::bind_method(D_METHOD("set_setting", "name", "value"), &EditorSettings::set_setting); ClassDB::bind_method(D_METHOD("get_setting", "name"), &EditorSettings::get_setting); ClassDB::bind_method(D_METHOD("erase", "property"), &EditorSettings::erase); ClassDB::bind_method(D_METHOD("set_initial_value", "name", "value", "update_current"), &EditorSettings::set_initial_value); ClassDB::bind_method(D_METHOD("property_can_revert", "name"), &EditorSettings::property_can_revert); ClassDB::bind_method(D_METHOD("property_get_revert", "name"), &EditorSettings::property_get_revert); ClassDB::bind_method(D_METHOD("add_property_info", "info"), &EditorSettings::_add_property_info_bind); ClassDB::bind_method(D_METHOD("get_settings_dir"), &EditorSettings::get_settings_dir); ClassDB::bind_method(D_METHOD("get_project_settings_dir"), &EditorSettings::get_project_settings_dir); ClassDB::bind_method(D_METHOD("set_project_metadata", "section", "key", "data"), &EditorSettings::set_project_metadata); ClassDB::bind_method(D_METHOD("get_project_metadata", "section", "key", "default"), &EditorSettings::get_project_metadata, DEFVAL(Variant())); ClassDB::bind_method(D_METHOD("set_favorites", "dirs"), &EditorSettings::set_favorites); ClassDB::bind_method(D_METHOD("get_favorites"), &EditorSettings::get_favorites); ClassDB::bind_method(D_METHOD("set_recent_dirs", "dirs"), &EditorSettings::set_recent_dirs); ClassDB::bind_method(D_METHOD("get_recent_dirs"), &EditorSettings::get_recent_dirs); ADD_SIGNAL(MethodInfo("settings_changed")); BIND_CONSTANT(NOTIFICATION_EDITOR_SETTINGS_CHANGED); } EditorSettings::EditorSettings() { last_order = 0; optimize_save = true; save_changed_setting = true; _load_defaults(); } EditorSettings::~EditorSettings() { } Set the low processor mode sleep editor settings to require a restart These settings are only read when the editor starts. /*************************************************************************/ /* editor_settings.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "editor_settings.h" #include "core/io/certs_compressed.gen.h" #include "core/io/compression.h" #include "core/io/config_file.h" #include "core/io/file_access_memory.h" #include "core/io/resource_loader.h" #include "core/io/resource_saver.h" #include "core/io/translation_loader_po.h" #include "core/os/dir_access.h" #include "core/os/file_access.h" #include "core/os/keyboard.h" #include "core/os/os.h" #include "core/project_settings.h" #include "core/version.h" #include "editor/editor_node.h" #include "editor/translations.gen.h" #include "scene/main/node.h" #include "scene/main/scene_tree.h" #include "scene/main/viewport.h" // PRIVATE METHODS Ref<EditorSettings> EditorSettings::singleton = NULL; // Properties bool EditorSettings::_set(const StringName &p_name, const Variant &p_value) { _THREAD_SAFE_METHOD_ bool changed = _set_only(p_name, p_value); if (changed) { emit_signal("settings_changed"); } return true; } bool EditorSettings::_set_only(const StringName &p_name, const Variant &p_value) { _THREAD_SAFE_METHOD_ if (p_name.operator String() == "shortcuts") { Array arr = p_value; ERR_FAIL_COND_V(arr.size() && arr.size() & 1, true); for (int i = 0; i < arr.size(); i += 2) { String name = arr[i]; Ref<InputEvent> shortcut = arr[i + 1]; Ref<ShortCut> sc; sc.instance(); sc->set_shortcut(shortcut); add_shortcut(name, sc); } return false; } bool changed = false; if (p_value.get_type() == Variant::NIL) { if (props.has(p_name)) { props.erase(p_name); changed = true; } } else { if (props.has(p_name)) { if (p_value != props[p_name].variant) { props[p_name].variant = p_value; changed = true; } } else { props[p_name] = VariantContainer(p_value, last_order++); changed = true; } if (save_changed_setting) { if (!props[p_name].save) { props[p_name].save = true; changed = true; } } } return changed; } bool EditorSettings::_get(const StringName &p_name, Variant &r_ret) const { _THREAD_SAFE_METHOD_ if (p_name.operator String() == "shortcuts") { Array arr; for (const Map<String, Ref<ShortCut> >::Element *E = shortcuts.front(); E; E = E->next()) { Ref<ShortCut> sc = E->get(); if (optimize_save) { if (!sc->has_meta("original")) { continue; //this came from settings but is not any longer used } Ref<InputEvent> original = sc->get_meta("original"); if (sc->is_shortcut(original) || (original.is_null() && sc->get_shortcut().is_null())) continue; //not changed from default, don't save } arr.push_back(E->key()); arr.push_back(sc->get_shortcut()); } r_ret = arr; return true; } const VariantContainer *v = props.getptr(p_name); if (!v) { WARN_PRINTS("EditorSettings::_get - Property not found: " + String(p_name)); return false; } r_ret = v->variant; return true; } void EditorSettings::_initial_set(const StringName &p_name, const Variant &p_value) { set(p_name, p_value); props[p_name].initial = p_value; props[p_name].has_default_value = true; } struct _EVCSort { String name; Variant::Type type; int order; bool save; bool restart_if_changed; bool operator<(const _EVCSort &p_vcs) const { return order < p_vcs.order; } }; void EditorSettings::_get_property_list(List<PropertyInfo> *p_list) const { _THREAD_SAFE_METHOD_ const String *k = NULL; Set<_EVCSort> vclist; while ((k = props.next(k))) { const VariantContainer *v = props.getptr(*k); if (v->hide_from_editor) continue; _EVCSort vc; vc.name = *k; vc.order = v->order; vc.type = v->variant.get_type(); vc.save = v->save; /*if (vc.save) { this should be implemented, but lets do after 3.1 is out. if (v->initial.get_type() != Variant::NIL && v->initial == v->variant) { vc.save = false; } }*/ vc.restart_if_changed = v->restart_if_changed; vclist.insert(vc); } for (Set<_EVCSort>::Element *E = vclist.front(); E; E = E->next()) { int pinfo = 0; if (E->get().save || !optimize_save) { pinfo |= PROPERTY_USAGE_STORAGE; } if (!E->get().name.begins_with("_") && !E->get().name.begins_with("projects/")) { pinfo |= PROPERTY_USAGE_EDITOR; } else { pinfo |= PROPERTY_USAGE_STORAGE; //hiddens must always be saved } PropertyInfo pi(E->get().type, E->get().name); pi.usage = pinfo; if (hints.has(E->get().name)) pi = hints[E->get().name]; if (E->get().restart_if_changed) { pi.usage |= PROPERTY_USAGE_RESTART_IF_CHANGED; } p_list->push_back(pi); } p_list->push_back(PropertyInfo(Variant::ARRAY, "shortcuts", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL)); //do not edit } void EditorSettings::_add_property_info_bind(const Dictionary &p_info) { ERR_FAIL_COND(!p_info.has("name")); ERR_FAIL_COND(!p_info.has("type")); PropertyInfo pinfo; pinfo.name = p_info["name"]; ERR_FAIL_COND(!props.has(pinfo.name)); pinfo.type = Variant::Type(p_info["type"].operator int()); ERR_FAIL_INDEX(pinfo.type, Variant::VARIANT_MAX); if (p_info.has("hint")) pinfo.hint = PropertyHint(p_info["hint"].operator int()); if (p_info.has("hint_string")) pinfo.hint_string = p_info["hint_string"]; add_property_hint(pinfo); } // Default configs bool EditorSettings::has_default_value(const String &p_setting) const { _THREAD_SAFE_METHOD_ if (!props.has(p_setting)) return false; return props[p_setting].has_default_value; } void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) { _THREAD_SAFE_METHOD_ /* Languages */ { String lang_hint = "en"; String host_lang = OS::get_singleton()->get_locale(); host_lang = TranslationServer::standardize_locale(host_lang); // Some locales are not properly supported currently in Godot due to lack of font shaping // (e.g. Arabic or Hindi), so even though we have work in progress translations for them, // we skip them as they don't render properly. (GH-28577) const Vector<String> locales_to_skip = String("ar,bn,fa,he,hi,ml,si,ta,te,ur").split(","); String best; EditorTranslationList *etl = _editor_translations; while (etl->data) { const String &locale = etl->lang; // Skip locales which we can't render properly (see above comment). // Test against language code without regional variants (e.g. ur_PK). String lang_code = locale.get_slice("_", 0); if (locales_to_skip.find(lang_code) != -1) { etl++; continue; } lang_hint += ","; lang_hint += locale; if (host_lang == locale) { best = locale; } if (best == String() && host_lang.begins_with(locale)) { best = locale; } etl++; } if (best == String()) { best = "en"; } _initial_set("interface/editor/editor_language", best); set_restart_if_changed("interface/editor/editor_language", true); hints["interface/editor/editor_language"] = PropertyInfo(Variant::STRING, "interface/editor/editor_language", PROPERTY_HINT_ENUM, lang_hint, PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); } /* Interface */ // Editor _initial_set("interface/editor/display_scale", 0); hints["interface/editor/display_scale"] = PropertyInfo(Variant::INT, "interface/editor/display_scale", PROPERTY_HINT_ENUM, "Auto,75%,100%,125%,150%,175%,200%,Custom", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/custom_display_scale", 1.0f); hints["interface/editor/custom_display_scale"] = PropertyInfo(Variant::REAL, "interface/editor/custom_display_scale", PROPERTY_HINT_RANGE, "0.5,3,0.01", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/main_font_size", 14); hints["interface/editor/main_font_size"] = PropertyInfo(Variant::INT, "interface/editor/main_font_size", PROPERTY_HINT_RANGE, "8,48,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/code_font_size", 14); hints["interface/editor/code_font_size"] = PropertyInfo(Variant::INT, "interface/editor/code_font_size", PROPERTY_HINT_RANGE, "8,48,1", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/font_antialiased", true); _initial_set("interface/editor/font_hinting", 0); hints["interface/editor/font_hinting"] = PropertyInfo(Variant::INT, "interface/editor/font_hinting", PROPERTY_HINT_ENUM, "Auto,None,Light,Normal", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/main_font", ""); hints["interface/editor/main_font"] = PropertyInfo(Variant::STRING, "interface/editor/main_font", PROPERTY_HINT_GLOBAL_FILE, "*.ttf,*.otf", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/main_font_bold", ""); hints["interface/editor/main_font_bold"] = PropertyInfo(Variant::STRING, "interface/editor/main_font_bold", PROPERTY_HINT_GLOBAL_FILE, "*.ttf,*.otf", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/code_font", ""); hints["interface/editor/code_font"] = PropertyInfo(Variant::STRING, "interface/editor/code_font", PROPERTY_HINT_GLOBAL_FILE, "*.ttf,*.otf", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/dim_editor_on_dialog_popup", true); _initial_set("interface/editor/low_processor_mode_sleep_usec", 6900); // ~144 FPS hints["interface/editor/low_processor_mode_sleep_usec"] = PropertyInfo(Variant::REAL, "interface/editor/low_processor_mode_sleep_usec", PROPERTY_HINT_RANGE, "1,100000,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/unfocused_low_processor_mode_sleep_usec", 50000); // 20 FPS hints["interface/editor/unfocused_low_processor_mode_sleep_usec"] = PropertyInfo(Variant::REAL, "interface/editor/unfocused_low_processor_mode_sleep_usec", PROPERTY_HINT_RANGE, "1,100000,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/separate_distraction_mode", false); _initial_set("interface/editor/automatically_open_screenshots", true); _initial_set("interface/editor/hide_console_window", false); _initial_set("interface/editor/save_each_scene_on_quit", true); // Regression _initial_set("interface/editor/quit_confirmation", true); // Theme _initial_set("interface/theme/preset", "Default"); hints["interface/theme/preset"] = PropertyInfo(Variant::STRING, "interface/theme/preset", PROPERTY_HINT_ENUM, "Default,Alien,Arc,Godot 2,Grey,Light,Solarized (Dark),Solarized (Light),Custom", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/icon_and_font_color", 0); hints["interface/theme/icon_and_font_color"] = PropertyInfo(Variant::INT, "interface/theme/icon_and_font_color", PROPERTY_HINT_ENUM, "Auto,Dark,Light", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/base_color", Color(0.2, 0.23, 0.31)); hints["interface/theme/base_color"] = PropertyInfo(Variant::COLOR, "interface/theme/base_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/accent_color", Color(0.41, 0.61, 0.91)); hints["interface/theme/accent_color"] = PropertyInfo(Variant::COLOR, "interface/theme/accent_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/contrast", 0.25); hints["interface/theme/contrast"] = PropertyInfo(Variant::REAL, "interface/theme/contrast", PROPERTY_HINT_RANGE, "0.01, 1, 0.01"); _initial_set("interface/theme/relationship_line_opacity", 0.1); hints["interface/theme/relationship_line_opacity"] = PropertyInfo(Variant::REAL, "interface/theme/relationship_line_opacity", PROPERTY_HINT_RANGE, "0.00, 1, 0.01"); _initial_set("interface/theme/highlight_tabs", false); _initial_set("interface/theme/border_size", 1); _initial_set("interface/theme/use_graph_node_headers", false); hints["interface/theme/border_size"] = PropertyInfo(Variant::INT, "interface/theme/border_size", PROPERTY_HINT_RANGE, "0,2,1", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/additional_spacing", 0); hints["interface/theme/additional_spacing"] = PropertyInfo(Variant::REAL, "interface/theme/additional_spacing", PROPERTY_HINT_RANGE, "0,5,0.1", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/custom_theme", ""); hints["interface/theme/custom_theme"] = PropertyInfo(Variant::STRING, "interface/theme/custom_theme", PROPERTY_HINT_GLOBAL_FILE, "*.res,*.tres,*.theme", PROPERTY_USAGE_DEFAULT); // Scene tabs _initial_set("interface/scene_tabs/show_extension", false); _initial_set("interface/scene_tabs/show_thumbnail_on_hover", true); _initial_set("interface/scene_tabs/resize_if_many_tabs", true); _initial_set("interface/scene_tabs/minimum_width", 50); hints["interface/scene_tabs/minimum_width"] = PropertyInfo(Variant::INT, "interface/scene_tabs/minimum_width", PROPERTY_HINT_RANGE, "50,500,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/scene_tabs/show_script_button", false); /* Filesystem */ // Directories _initial_set("filesystem/directories/autoscan_project_path", ""); hints["filesystem/directories/autoscan_project_path"] = PropertyInfo(Variant::STRING, "filesystem/directories/autoscan_project_path", PROPERTY_HINT_GLOBAL_DIR); _initial_set("filesystem/directories/default_project_path", OS::get_singleton()->has_environment("HOME") ? OS::get_singleton()->get_environment("HOME") : OS::get_singleton()->get_system_dir(OS::SYSTEM_DIR_DOCUMENTS)); hints["filesystem/directories/default_project_path"] = PropertyInfo(Variant::STRING, "filesystem/directories/default_project_path", PROPERTY_HINT_GLOBAL_DIR); // On save _initial_set("filesystem/on_save/compress_binary_resources", true); _initial_set("filesystem/on_save/safe_save_on_backup_then_rename", true); // File dialog _initial_set("filesystem/file_dialog/show_hidden_files", false); _initial_set("filesystem/file_dialog/display_mode", 0); hints["filesystem/file_dialog/display_mode"] = PropertyInfo(Variant::INT, "filesystem/file_dialog/display_mode", PROPERTY_HINT_ENUM, "Thumbnails,List"); _initial_set("filesystem/file_dialog/thumbnail_size", 64); hints["filesystem/file_dialog/thumbnail_size"] = PropertyInfo(Variant::INT, "filesystem/file_dialog/thumbnail_size", PROPERTY_HINT_RANGE, "32,128,16"); // Import _initial_set("filesystem/import/pvrtc_texture_tool", ""); #ifdef WINDOWS_ENABLED hints["filesystem/import/pvrtc_texture_tool"] = PropertyInfo(Variant::STRING, "filesystem/import/pvrtc_texture_tool", PROPERTY_HINT_GLOBAL_FILE, "*.exe"); #else hints["filesystem/import/pvrtc_texture_tool"] = PropertyInfo(Variant::STRING, "filesystem/import/pvrtc_texture_tool", PROPERTY_HINT_GLOBAL_FILE, ""); #endif _initial_set("filesystem/import/pvrtc_fast_conversion", false); /* Docks */ // SceneTree _initial_set("docks/scene_tree/start_create_dialog_fully_expanded", false); // FileSystem _initial_set("docks/filesystem/thumbnail_size", 64); hints["docks/filesystem/thumbnail_size"] = PropertyInfo(Variant::INT, "docks/filesystem/thumbnail_size", PROPERTY_HINT_RANGE, "32,128,16"); _initial_set("docks/filesystem/always_show_folders", true); // Property editor _initial_set("docks/property_editor/auto_refresh_interval", 0.3); /* Text editor */ // Theme _initial_set("text_editor/theme/color_theme", "Adaptive"); hints["text_editor/theme/color_theme"] = PropertyInfo(Variant::STRING, "text_editor/theme/color_theme", PROPERTY_HINT_ENUM, "Adaptive,Default,Custom"); _initial_set("text_editor/theme/line_spacing", 6); hints["text_editor/theme/line_spacing"] = PropertyInfo(Variant::INT, "text_editor/theme/line_spacing", PROPERTY_HINT_RANGE, "0,50,1"); _load_default_text_editor_theme(); // Highlighting _initial_set("text_editor/highlighting/syntax_highlighting", true); _initial_set("text_editor/highlighting/highlight_all_occurrences", true); _initial_set("text_editor/highlighting/highlight_current_line", true); _initial_set("text_editor/highlighting/highlight_type_safe_lines", true); // Indent _initial_set("text_editor/indent/type", 0); hints["text_editor/indent/type"] = PropertyInfo(Variant::INT, "text_editor/indent/type", PROPERTY_HINT_ENUM, "Tabs,Spaces"); _initial_set("text_editor/indent/size", 4); hints["text_editor/indent/size"] = PropertyInfo(Variant::INT, "text_editor/indent/size", PROPERTY_HINT_RANGE, "1, 64, 1"); // size of 0 crashes. _initial_set("text_editor/indent/auto_indent", true); _initial_set("text_editor/indent/convert_indent_on_save", false); _initial_set("text_editor/indent/draw_tabs", true); _initial_set("text_editor/indent/draw_spaces", false); // Line numbers _initial_set("text_editor/line_numbers/show_line_numbers", true); _initial_set("text_editor/line_numbers/line_numbers_zero_padded", false); _initial_set("text_editor/line_numbers/show_bookmark_gutter", true); _initial_set("text_editor/line_numbers/show_breakpoint_gutter", true); _initial_set("text_editor/line_numbers/show_info_gutter", true); _initial_set("text_editor/line_numbers/code_folding", true); _initial_set("text_editor/line_numbers/word_wrap", false); _initial_set("text_editor/line_numbers/show_line_length_guideline", false); _initial_set("text_editor/line_numbers/line_length_guideline_column", 80); hints["text_editor/line_numbers/line_length_guideline_column"] = PropertyInfo(Variant::INT, "text_editor/line_numbers/line_length_guideline_column", PROPERTY_HINT_RANGE, "20, 160, 1"); // Open scripts _initial_set("text_editor/open_scripts/smooth_scrolling", true); _initial_set("text_editor/open_scripts/v_scroll_speed", 80); _initial_set("text_editor/open_scripts/show_members_overview", true); // Files _initial_set("text_editor/files/trim_trailing_whitespace_on_save", false); _initial_set("text_editor/files/autosave_interval_secs", 0); _initial_set("text_editor/files/restore_scripts_on_load", true); // Tools _initial_set("text_editor/tools/create_signal_callbacks", true); _initial_set("text_editor/tools/sort_members_outline_alphabetically", false); // Cursor _initial_set("text_editor/cursor/scroll_past_end_of_file", false); _initial_set("text_editor/cursor/block_caret", false); _initial_set("text_editor/cursor/caret_blink", true); _initial_set("text_editor/cursor/caret_blink_speed", 0.5); hints["text_editor/cursor/caret_blink_speed"] = PropertyInfo(Variant::REAL, "text_editor/cursor/caret_blink_speed", PROPERTY_HINT_RANGE, "0.1, 10, 0.01"); _initial_set("text_editor/cursor/right_click_moves_caret", true); // Completion _initial_set("text_editor/completion/idle_parse_delay", 2.0); hints["text_editor/completion/idle_parse_delay"] = PropertyInfo(Variant::REAL, "text_editor/completion/idle_parse_delay", PROPERTY_HINT_RANGE, "0.1, 10, 0.01"); _initial_set("text_editor/completion/auto_brace_complete", true); _initial_set("text_editor/completion/code_complete_delay", 0.3); hints["text_editor/completion/code_complete_delay"] = PropertyInfo(Variant::REAL, "text_editor/completion/code_complete_delay", PROPERTY_HINT_RANGE, "0.01, 5, 0.01"); _initial_set("text_editor/completion/put_callhint_tooltip_below_current_line", true); _initial_set("text_editor/completion/callhint_tooltip_offset", Vector2()); _initial_set("text_editor/completion/complete_file_paths", true); _initial_set("text_editor/completion/add_type_hints", false); _initial_set("text_editor/completion/use_single_quotes", false); // Help _initial_set("text_editor/help/show_help_index", true); _initial_set("text_editor/help/help_font_size", 15); hints["text_editor/help/help_font_size"] = PropertyInfo(Variant::INT, "text_editor/help/help_font_size", PROPERTY_HINT_RANGE, "8,48,1"); _initial_set("text_editor/help/help_source_font_size", 14); hints["text_editor/help/help_source_font_size"] = PropertyInfo(Variant::INT, "text_editor/help/help_source_font_size", PROPERTY_HINT_RANGE, "8,48,1"); _initial_set("text_editor/help/help_title_font_size", 23); hints["text_editor/help/help_title_font_size"] = PropertyInfo(Variant::INT, "text_editor/help/help_title_font_size", PROPERTY_HINT_RANGE, "8,48,1"); /* Editors */ // GridMap _initial_set("editors/grid_map/pick_distance", 5000.0); // 3D _initial_set("editors/3d/primary_grid_color", Color(0.56, 0.56, 0.56)); hints["editors/3d/primary_grid_color"] = PropertyInfo(Variant::COLOR, "editors/3d/primary_grid_color", PROPERTY_HINT_COLOR_NO_ALPHA, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("editors/3d/secondary_grid_color", Color(0.38, 0.38, 0.38)); hints["editors/3d/secondary_grid_color"] = PropertyInfo(Variant::COLOR, "editors/3d/secondary_grid_color", PROPERTY_HINT_COLOR_NO_ALPHA, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("editors/3d/grid_size", 50); hints["editors/3d/grid_size"] = PropertyInfo(Variant::INT, "editors/3d/grid_size", PROPERTY_HINT_RANGE, "1,500,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("editors/3d/primary_grid_steps", 10); hints["editors/3d/primary_grid_steps"] = PropertyInfo(Variant::INT, "editors/3d/primary_grid_steps", PROPERTY_HINT_RANGE, "1,100,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("editors/3d/default_fov", 70.0); _initial_set("editors/3d/default_z_near", 0.05); _initial_set("editors/3d/default_z_far", 500.0); // 3D: Navigation _initial_set("editors/3d/navigation/navigation_scheme", 0); _initial_set("editors/3d/navigation/invert_y_axis", false); hints["editors/3d/navigation/navigation_scheme"] = PropertyInfo(Variant::INT, "editors/3d/navigation/navigation_scheme", PROPERTY_HINT_ENUM, "Godot,Maya,Modo"); _initial_set("editors/3d/navigation/zoom_style", 0); hints["editors/3d/navigation/zoom_style"] = PropertyInfo(Variant::INT, "editors/3d/navigation/zoom_style", PROPERTY_HINT_ENUM, "Vertical, Horizontal"); _initial_set("editors/3d/navigation/emulate_3_button_mouse", false); _initial_set("editors/3d/navigation/orbit_modifier", 0); hints["editors/3d/navigation/orbit_modifier"] = PropertyInfo(Variant::INT, "editors/3d/navigation/orbit_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl"); _initial_set("editors/3d/navigation/pan_modifier", 1); hints["editors/3d/navigation/pan_modifier"] = PropertyInfo(Variant::INT, "editors/3d/navigation/pan_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl"); _initial_set("editors/3d/navigation/zoom_modifier", 4); hints["editors/3d/navigation/zoom_modifier"] = PropertyInfo(Variant::INT, "editors/3d/navigation/zoom_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl"); _initial_set("editors/3d/navigation/warped_mouse_panning", true); // 3D: Navigation feel _initial_set("editors/3d/navigation_feel/orbit_sensitivity", 0.4); hints["editors/3d/navigation_feel/orbit_sensitivity"] = PropertyInfo(Variant::REAL, "editors/3d/navigation_feel/orbit_sensitivity", PROPERTY_HINT_RANGE, "0.0, 2, 0.01"); _initial_set("editors/3d/navigation_feel/orbit_inertia", 0.05); hints["editors/3d/navigation_feel/orbit_inertia"] = PropertyInfo(Variant::REAL, "editors/3d/navigation_feel/orbit_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/navigation_feel/translation_inertia", 0.15); hints["editors/3d/navigation_feel/translation_inertia"] = PropertyInfo(Variant::REAL, "editors/3d/navigation_feel/translation_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/navigation_feel/zoom_inertia", 0.075); hints["editors/3d/navigation_feel/zoom_inertia"] = PropertyInfo(Variant::REAL, "editors/3d/navigation_feel/zoom_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/navigation_feel/manipulation_orbit_inertia", 0.075); hints["editors/3d/navigation_feel/manipulation_orbit_inertia"] = PropertyInfo(Variant::REAL, "editors/3d/navigation_feel/manipulation_orbit_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/navigation_feel/manipulation_translation_inertia", 0.075); hints["editors/3d/navigation_feel/manipulation_translation_inertia"] = PropertyInfo(Variant::REAL, "editors/3d/navigation_feel/manipulation_translation_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); // 3D: Freelook _initial_set("editors/3d/freelook/freelook_inertia", 0.1); hints["editors/3d/freelook/freelook_inertia"] = PropertyInfo(Variant::REAL, "editors/3d/freelook/freelook_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/freelook/freelook_base_speed", 5.0); hints["editors/3d/freelook/freelook_base_speed"] = PropertyInfo(Variant::REAL, "editors/3d/freelook/freelook_base_speed", PROPERTY_HINT_RANGE, "0.0, 10, 0.01"); _initial_set("editors/3d/freelook/freelook_activation_modifier", 0); hints["editors/3d/freelook/freelook_activation_modifier"] = PropertyInfo(Variant::INT, "editors/3d/freelook/freelook_activation_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl"); _initial_set("editors/3d/freelook/freelook_modifier_speed_factor", 3.0); hints["editors/3d/freelook/freelook_modifier_speed_factor"] = PropertyInfo(Variant::REAL, "editors/3d/freelook/freelook_modifier_speed_factor", PROPERTY_HINT_RANGE, "0.0, 10.0, 0.1"); _initial_set("editors/3d/freelook/freelook_speed_zoom_link", false); // 2D _initial_set("editors/2d/grid_color", Color(1.0, 1.0, 1.0, 0.07)); _initial_set("editors/2d/guides_color", Color(0.6, 0.0, 0.8)); _initial_set("editors/2d/bone_width", 5); _initial_set("editors/2d/bone_color1", Color(1.0, 1.0, 1.0, 0.9)); _initial_set("editors/2d/bone_color2", Color(0.6, 0.6, 0.6, 0.9)); _initial_set("editors/2d/bone_selected_color", Color(0.9, 0.45, 0.45, 0.9)); _initial_set("editors/2d/bone_ik_color", Color(0.9, 0.9, 0.45, 0.9)); _initial_set("editors/2d/bone_outline_color", Color(0.35, 0.35, 0.35)); _initial_set("editors/2d/bone_outline_size", 2); _initial_set("editors/2d/viewport_border_color", Color(0.4, 0.4, 1.0, 0.4)); _initial_set("editors/2d/constrain_editor_view", true); _initial_set("editors/2d/warped_mouse_panning", true); _initial_set("editors/2d/simple_panning", false); _initial_set("editors/2d/scroll_to_pan", false); _initial_set("editors/2d/pan_speed", 20); // Polygon editor _initial_set("editors/poly_editor/point_grab_radius", 8); _initial_set("editors/poly_editor/show_previous_outline", true); // Animation _initial_set("editors/animation/autorename_animation_tracks", true); _initial_set("editors/animation/confirm_insert_track", true); _initial_set("editors/animation/onion_layers_past_color", Color(1, 0, 0)); _initial_set("editors/animation/onion_layers_future_color", Color(0, 1, 0)); /* Run */ // Window placement _initial_set("run/window_placement/rect", 1); hints["run/window_placement/rect"] = PropertyInfo(Variant::INT, "run/window_placement/rect", PROPERTY_HINT_ENUM, "Top Left,Centered,Custom Position,Force Maximized,Force Fullscreen"); String screen_hints = "Same as Editor,Previous Monitor,Next Monitor"; for (int i = 0; i < OS::get_singleton()->get_screen_count(); i++) { screen_hints += ",Monitor " + itos(i + 1); } _initial_set("run/window_placement/rect_custom_position", Vector2()); _initial_set("run/window_placement/screen", 0); hints["run/window_placement/screen"] = PropertyInfo(Variant::INT, "run/window_placement/screen", PROPERTY_HINT_ENUM, screen_hints); // Auto save _initial_set("run/auto_save/save_before_running", true); // Output _initial_set("run/output/font_size", 13); hints["run/output/font_size"] = PropertyInfo(Variant::INT, "run/output/font_size", PROPERTY_HINT_RANGE, "8,48,1"); _initial_set("run/output/always_clear_output_on_play", true); _initial_set("run/output/always_open_output_on_play", true); _initial_set("run/output/always_close_output_on_stop", false); /* Extra config */ _initial_set("project_manager/sorting_order", 0); hints["project_manager/sorting_order"] = PropertyInfo(Variant::INT, "project_manager/sorting_order", PROPERTY_HINT_ENUM, "Name,Path,Last Modified"); if (p_extra_config.is_valid()) { if (p_extra_config->has_section("init_projects") && p_extra_config->has_section_key("init_projects", "list")) { Vector<String> list = p_extra_config->get_value("init_projects", "list"); for (int i = 0; i < list.size(); i++) { String name = list[i].replace("/", "::"); set("projects/" + name, list[i]); }; }; if (p_extra_config->has_section("presets")) { List<String> keys; p_extra_config->get_section_keys("presets", &keys); for (List<String>::Element *E = keys.front(); E; E = E->next()) { String key = E->get(); Variant val = p_extra_config->get_value("presets", key); set(key, val); }; }; }; } void EditorSettings::_load_default_text_editor_theme() { bool dark_theme = is_dark_theme(); _initial_set("text_editor/highlighting/symbol_color", Color(0.73, 0.87, 1.0)); _initial_set("text_editor/highlighting/keyword_color", Color(1.0, 1.0, 0.7)); _initial_set("text_editor/highlighting/base_type_color", Color(0.64, 1.0, 0.83)); _initial_set("text_editor/highlighting/engine_type_color", Color(0.51, 0.83, 1.0)); _initial_set("text_editor/highlighting/comment_color", Color(0.4, 0.4, 0.4)); _initial_set("text_editor/highlighting/string_color", Color(0.94, 0.43, 0.75)); _initial_set("text_editor/highlighting/background_color", dark_theme ? Color(0.0, 0.0, 0.0, 0.23) : Color(0.2, 0.23, 0.31)); _initial_set("text_editor/highlighting/completion_background_color", Color(0.17, 0.16, 0.2)); _initial_set("text_editor/highlighting/completion_selected_color", Color(0.26, 0.26, 0.27)); _initial_set("text_editor/highlighting/completion_existing_color", Color(0.13, 0.87, 0.87, 0.87)); _initial_set("text_editor/highlighting/completion_scroll_color", Color(1, 1, 1)); _initial_set("text_editor/highlighting/completion_font_color", Color(0.67, 0.67, 0.67)); _initial_set("text_editor/highlighting/text_color", Color(0.67, 0.67, 0.67)); _initial_set("text_editor/highlighting/line_number_color", Color(0.67, 0.67, 0.67, 0.4)); _initial_set("text_editor/highlighting/safe_line_number_color", Color(0.67, 0.78, 0.67, 0.6)); _initial_set("text_editor/highlighting/caret_color", Color(0.67, 0.67, 0.67)); _initial_set("text_editor/highlighting/caret_background_color", Color(0, 0, 0)); _initial_set("text_editor/highlighting/text_selected_color", Color(0, 0, 0)); _initial_set("text_editor/highlighting/selection_color", Color(0.41, 0.61, 0.91, 0.35)); _initial_set("text_editor/highlighting/brace_mismatch_color", Color(1, 0.2, 0.2)); _initial_set("text_editor/highlighting/current_line_color", Color(0.3, 0.5, 0.8, 0.15)); _initial_set("text_editor/highlighting/line_length_guideline_color", Color(0.3, 0.5, 0.8, 0.1)); _initial_set("text_editor/highlighting/word_highlighted_color", Color(0.8, 0.9, 0.9, 0.15)); _initial_set("text_editor/highlighting/number_color", Color(0.92, 0.58, 0.2)); _initial_set("text_editor/highlighting/function_color", Color(0.4, 0.64, 0.81)); _initial_set("text_editor/highlighting/member_variable_color", Color(0.9, 0.31, 0.35)); _initial_set("text_editor/highlighting/mark_color", Color(1.0, 0.4, 0.4, 0.4)); _initial_set("text_editor/highlighting/bookmark_color", Color(0.08, 0.49, 0.98)); _initial_set("text_editor/highlighting/breakpoint_color", Color(0.8, 0.8, 0.4, 0.2)); _initial_set("text_editor/highlighting/executing_line_color", Color(0.2, 0.8, 0.2, 0.4)); _initial_set("text_editor/highlighting/code_folding_color", Color(0.8, 0.8, 0.8, 0.8)); _initial_set("text_editor/highlighting/search_result_color", Color(0.05, 0.25, 0.05, 1)); _initial_set("text_editor/highlighting/search_result_border_color", Color(0.41, 0.61, 0.91, 0.38)); } bool EditorSettings::_save_text_editor_theme(String p_file) { String theme_section = "color_theme"; Ref<ConfigFile> cf = memnew(ConfigFile); // hex is better? List<String> keys; props.get_key_list(&keys); keys.sort(); for (const List<String>::Element *E = keys.front(); E; E = E->next()) { const String &key = E->get(); if (key.begins_with("text_editor/highlighting/") && key.find("color") >= 0) { cf->set_value(theme_section, key.replace("text_editor/highlighting/", ""), ((Color)props[key].variant).to_html()); } } Error err = cf->save(p_file); return err == OK; } bool EditorSettings::_is_default_text_editor_theme(String p_theme_name) { return p_theme_name == "default" || p_theme_name == "adaptive" || p_theme_name == "custom"; } static Dictionary _get_builtin_script_templates() { Dictionary templates; // No Comments templates["no_comments.gd"] = "extends %BASE%\n" "\n" "func _ready()%VOID_RETURN%:\n" "%TS%pass\n"; // Empty templates["empty.gd"] = "extends %BASE%" "\n" "\n"; return templates; } static void _create_script_templates(const String &p_path) { Dictionary templates = _get_builtin_script_templates(); List<Variant> keys; templates.get_key_list(&keys); FileAccess *file = FileAccess::create(FileAccess::ACCESS_FILESYSTEM); DirAccess *dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); dir->change_dir(p_path); for (int i = 0; i < keys.size(); i++) { if (!dir->file_exists(keys[i])) { Error err = file->reopen(p_path.plus_file((String)keys[i]), FileAccess::WRITE); ERR_FAIL_COND(err != OK); file->store_string(templates[keys[i]]); file->close(); } } memdelete(dir); memdelete(file); } // PUBLIC METHODS EditorSettings *EditorSettings::get_singleton() { return singleton.ptr(); } void EditorSettings::create() { if (singleton.ptr()) return; //pointless DirAccess *dir = NULL; String data_path; String data_dir; String config_path; String config_dir; String cache_path; String cache_dir; Ref<ConfigFile> extra_config = memnew(ConfigFile); String exe_path = OS::get_singleton()->get_executable_path().get_base_dir(); DirAccess *d = DirAccess::create_for_path(exe_path); bool self_contained = false; if (d->file_exists(exe_path + "/._sc_")) { self_contained = true; Error err = extra_config->load(exe_path + "/._sc_"); if (err != OK) { ERR_PRINTS("Can't load config from path: " + exe_path + "/._sc_"); } } else if (d->file_exists(exe_path + "/_sc_")) { self_contained = true; Error err = extra_config->load(exe_path + "/_sc_"); if (err != OK) { ERR_PRINTS("Can't load config from path: " + exe_path + "/_sc_"); } } memdelete(d); if (self_contained) { // editor is self contained, all in same folder data_path = exe_path; data_dir = data_path.plus_file("editor_data"); config_path = exe_path; config_dir = data_dir; cache_path = exe_path; cache_dir = data_dir.plus_file("cache"); } else { // Typically XDG_DATA_HOME or %APPDATA% data_path = OS::get_singleton()->get_data_path(); data_dir = data_path.plus_file(OS::get_singleton()->get_godot_dir_name()); // Can be different from data_path e.g. on Linux or macOS config_path = OS::get_singleton()->get_config_path(); config_dir = config_path.plus_file(OS::get_singleton()->get_godot_dir_name()); // Can be different from above paths, otherwise a subfolder of data_dir cache_path = OS::get_singleton()->get_cache_path(); if (cache_path == data_path) { cache_dir = data_dir.plus_file("cache"); } else { cache_dir = cache_path.plus_file(OS::get_singleton()->get_godot_dir_name()); } } ClassDB::register_class<EditorSettings>(); //otherwise it can't be unserialized String config_file_path; if (data_path != "" && config_path != "" && cache_path != "") { // Validate/create data dir and subdirectories dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); if (dir->change_dir(data_dir) != OK) { dir->make_dir_recursive(data_dir); if (dir->change_dir(data_dir) != OK) { ERR_PRINT("Cannot create data directory!"); memdelete(dir); goto fail; } } if (dir->change_dir("templates") != OK) { dir->make_dir("templates"); } else { dir->change_dir(".."); } // Validate/create cache dir if (dir->change_dir(cache_dir) != OK) { dir->make_dir_recursive(cache_dir); if (dir->change_dir(cache_dir) != OK) { ERR_PRINT("Cannot create cache directory!"); memdelete(dir); goto fail; } } // Validate/create config dir and subdirectories if (dir->change_dir(config_dir) != OK) { dir->make_dir_recursive(config_dir); if (dir->change_dir(config_dir) != OK) { ERR_PRINT("Cannot create config directory!"); memdelete(dir); goto fail; } } if (dir->change_dir("text_editor_themes") != OK) { dir->make_dir("text_editor_themes"); } else { dir->change_dir(".."); } if (dir->change_dir("script_templates") != OK) { dir->make_dir("script_templates"); } else { dir->change_dir(".."); } if (dir->change_dir("feature_profiles") != OK) { dir->make_dir("feature_profiles"); } else { dir->change_dir(".."); } _create_script_templates(dir->get_current_dir().plus_file("script_templates")); if (dir->change_dir("projects") != OK) { dir->make_dir("projects"); } else { dir->change_dir(".."); } // Validate/create project-specific config dir dir->change_dir("projects"); String project_config_dir = ProjectSettings::get_singleton()->get_resource_path(); if (project_config_dir.ends_with("/")) project_config_dir = config_path.substr(0, project_config_dir.size() - 1); project_config_dir = project_config_dir.get_file() + "-" + project_config_dir.md5_text(); if (dir->change_dir(project_config_dir) != OK) { dir->make_dir(project_config_dir); } else { dir->change_dir(".."); } dir->change_dir(".."); // Validate editor config file String config_file_name = "editor_settings-" + itos(VERSION_MAJOR) + ".tres"; config_file_path = config_dir.plus_file(config_file_name); if (!dir->file_exists(config_file_name)) { goto fail; } memdelete(dir); singleton = ResourceLoader::load(config_file_path, "EditorSettings"); if (singleton.is_null()) { WARN_PRINT("Could not open config file."); goto fail; } singleton->save_changed_setting = true; singleton->config_file_path = config_file_path; singleton->project_config_dir = project_config_dir; singleton->settings_dir = config_dir; singleton->data_dir = data_dir; singleton->cache_dir = cache_dir; print_verbose("EditorSettings: Load OK!"); singleton->setup_language(); singleton->setup_network(); singleton->load_favorites(); singleton->list_text_editor_themes(); return; } fail: // patch init projects if (extra_config->has_section("init_projects")) { Vector<String> list = extra_config->get_value("init_projects", "list"); for (int i = 0; i < list.size(); i++) { list.write[i] = exe_path.plus_file(list[i]); }; extra_config->set_value("init_projects", "list", list); }; singleton = Ref<EditorSettings>(memnew(EditorSettings)); singleton->save_changed_setting = true; singleton->config_file_path = config_file_path; singleton->settings_dir = config_dir; singleton->data_dir = data_dir; singleton->cache_dir = cache_dir; singleton->_load_defaults(extra_config); singleton->setup_language(); singleton->setup_network(); singleton->list_text_editor_themes(); } void EditorSettings::setup_language() { String lang = get("interface/editor/editor_language"); if (lang == "en") return; //none to do EditorTranslationList *etl = _editor_translations; while (etl->data) { if (etl->lang == lang) { Vector<uint8_t> data; data.resize(etl->uncomp_size); Compression::decompress(data.ptrw(), etl->uncomp_size, etl->data, etl->comp_size, Compression::MODE_DEFLATE); FileAccessMemory *fa = memnew(FileAccessMemory); fa->open_custom(data.ptr(), data.size()); Ref<Translation> tr = TranslationLoaderPO::load_translation(fa, NULL, "translation_" + String(etl->lang)); if (tr.is_valid()) { tr->set_locale(etl->lang); TranslationServer::get_singleton()->set_tool_translation(tr); break; } } etl++; } } void EditorSettings::setup_network() { List<IP_Address> local_ip; IP::get_singleton()->get_local_addresses(&local_ip); String lip = "127.0.0.1"; String hint; String current = has_setting("network/debug/remote_host") ? get("network/debug/remote_host") : ""; int port = has_setting("network/debug/remote_port") ? (int)get("network/debug/remote_port") : 6007; for (List<IP_Address>::Element *E = local_ip.front(); E; E = E->next()) { String ip = E->get(); // link-local IPv6 addresses don't work, skipping them if (ip.begins_with("fe80:0:0:0:")) // fe80::/64 continue; // Same goes for IPv4 link-local (APIPA) addresses. if (ip.begins_with("169.254.")) // 169.254.0.0/16 continue; if (ip == current) lip = current; //so it saves if (hint != "") hint += ","; hint += ip; } _initial_set("network/debug/remote_host", lip); add_property_hint(PropertyInfo(Variant::STRING, "network/debug/remote_host", PROPERTY_HINT_ENUM, hint)); _initial_set("network/debug/remote_port", port); add_property_hint(PropertyInfo(Variant::INT, "network/debug/remote_port", PROPERTY_HINT_RANGE, "1,65535,1")); // Editor SSL certificates override _initial_set("network/ssl/editor_ssl_certificates", _SYSTEM_CERTS_PATH); add_property_hint(PropertyInfo(Variant::STRING, "network/ssl/editor_ssl_certificates", PROPERTY_HINT_GLOBAL_FILE, "*.crt,*.pem")); } void EditorSettings::save() { //_THREAD_SAFE_METHOD_ if (!singleton.ptr()) return; if (singleton->config_file_path == "") { ERR_PRINT("Cannot save EditorSettings config, no valid path"); return; } Error err = ResourceSaver::save(singleton->config_file_path, singleton); if (err != OK) { ERR_PRINTS("Error saving editor settings to " + singleton->config_file_path); } else { print_verbose("EditorSettings: Save OK!"); } } void EditorSettings::destroy() { if (!singleton.ptr()) return; save(); singleton = Ref<EditorSettings>(); } void EditorSettings::set_optimize_save(bool p_optimize) { optimize_save = p_optimize; } // Properties void EditorSettings::set_setting(const String &p_setting, const Variant &p_value) { _THREAD_SAFE_METHOD_ set(p_setting, p_value); } Variant EditorSettings::get_setting(const String &p_setting) const { _THREAD_SAFE_METHOD_ return get(p_setting); } bool EditorSettings::has_setting(const String &p_setting) const { _THREAD_SAFE_METHOD_ return props.has(p_setting); } void EditorSettings::erase(const String &p_setting) { _THREAD_SAFE_METHOD_ props.erase(p_setting); } void EditorSettings::raise_order(const String &p_setting) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND(!props.has(p_setting)); props[p_setting].order = ++last_order; } void EditorSettings::set_restart_if_changed(const StringName &p_setting, bool p_restart) { _THREAD_SAFE_METHOD_ if (!props.has(p_setting)) return; props[p_setting].restart_if_changed = p_restart; } void EditorSettings::set_initial_value(const StringName &p_setting, const Variant &p_value, bool p_update_current) { _THREAD_SAFE_METHOD_ if (!props.has(p_setting)) return; props[p_setting].initial = p_value; props[p_setting].has_default_value = true; if (p_update_current) { set(p_setting, p_value); } } Variant _EDITOR_DEF(const String &p_setting, const Variant &p_default, bool p_restart_if_changed) { Variant ret = p_default; if (EditorSettings::get_singleton()->has_setting(p_setting)) { ret = EditorSettings::get_singleton()->get(p_setting); } else { EditorSettings::get_singleton()->set_manually(p_setting, p_default); EditorSettings::get_singleton()->set_restart_if_changed(p_setting, p_restart_if_changed); } if (!EditorSettings::get_singleton()->has_default_value(p_setting)) { EditorSettings::get_singleton()->set_initial_value(p_setting, p_default); } return ret; } Variant _EDITOR_GET(const String &p_setting) { ERR_FAIL_COND_V(!EditorSettings::get_singleton()->has_setting(p_setting), Variant()); return EditorSettings::get_singleton()->get(p_setting); } bool EditorSettings::property_can_revert(const String &p_setting) { if (!props.has(p_setting)) return false; if (!props[p_setting].has_default_value) return false; return props[p_setting].initial != props[p_setting].variant; } Variant EditorSettings::property_get_revert(const String &p_setting) { if (!props.has(p_setting) || !props[p_setting].has_default_value) return Variant(); return props[p_setting].initial; } void EditorSettings::add_property_hint(const PropertyInfo &p_hint) { _THREAD_SAFE_METHOD_ hints[p_hint.name] = p_hint; } // Data directories String EditorSettings::get_data_dir() const { return data_dir; } String EditorSettings::get_templates_dir() const { return get_data_dir().plus_file("templates"); } // Config directories String EditorSettings::get_settings_dir() const { return settings_dir; } String EditorSettings::get_project_settings_dir() const { return get_settings_dir().plus_file("projects").plus_file(project_config_dir); } String EditorSettings::get_text_editor_themes_dir() const { return get_settings_dir().plus_file("text_editor_themes"); } String EditorSettings::get_script_templates_dir() const { return get_settings_dir().plus_file("script_templates"); } // Cache directory String EditorSettings::get_cache_dir() const { return cache_dir; } String EditorSettings::get_feature_profiles_dir() const { return get_settings_dir().plus_file("feature_profiles"); } // Metadata void EditorSettings::set_project_metadata(const String &p_section, const String &p_key, Variant p_data) { Ref<ConfigFile> cf = memnew(ConfigFile); String path = get_project_settings_dir().plus_file("project_metadata.cfg"); Error err; err = cf->load(path); ERR_FAIL_COND(err != OK); cf->set_value(p_section, p_key, p_data); err = cf->save(path); ERR_FAIL_COND(err != OK); } Variant EditorSettings::get_project_metadata(const String &p_section, const String &p_key, Variant p_default) const { Ref<ConfigFile> cf = memnew(ConfigFile); String path = get_project_settings_dir().plus_file("project_metadata.cfg"); Error err = cf->load(path); if (err != OK) { return p_default; } return cf->get_value(p_section, p_key, p_default); } void EditorSettings::set_favorites(const Vector<String> &p_favorites) { favorites = p_favorites; FileAccess *f = FileAccess::open(get_project_settings_dir().plus_file("favorites"), FileAccess::WRITE); if (f) { for (int i = 0; i < favorites.size(); i++) f->store_line(favorites[i]); memdelete(f); } } Vector<String> EditorSettings::get_favorites() const { return favorites; } void EditorSettings::set_recent_dirs(const Vector<String> &p_recent_dirs) { recent_dirs = p_recent_dirs; FileAccess *f = FileAccess::open(get_project_settings_dir().plus_file("recent_dirs"), FileAccess::WRITE); if (f) { for (int i = 0; i < recent_dirs.size(); i++) f->store_line(recent_dirs[i]); memdelete(f); } } Vector<String> EditorSettings::get_recent_dirs() const { return recent_dirs; } void EditorSettings::load_favorites() { FileAccess *f = FileAccess::open(get_project_settings_dir().plus_file("favorites"), FileAccess::READ); if (f) { String line = f->get_line().strip_edges(); while (line != "") { favorites.push_back(line); line = f->get_line().strip_edges(); } memdelete(f); } f = FileAccess::open(get_project_settings_dir().plus_file("recent_dirs"), FileAccess::READ); if (f) { String line = f->get_line().strip_edges(); while (line != "") { recent_dirs.push_back(line); line = f->get_line().strip_edges(); } memdelete(f); } } bool EditorSettings::is_dark_theme() { int AUTO_COLOR = 0; int LIGHT_COLOR = 2; Color base_color = get("interface/theme/base_color"); int icon_font_color_setting = get("interface/theme/icon_and_font_color"); return (icon_font_color_setting == AUTO_COLOR && ((base_color.r + base_color.g + base_color.b) / 3.0) < 0.5) || icon_font_color_setting == LIGHT_COLOR; } void EditorSettings::list_text_editor_themes() { String themes = "Adaptive,Default,Custom"; DirAccess *d = DirAccess::open(get_text_editor_themes_dir()); if (d) { List<String> custom_themes; d->list_dir_begin(); String file = d->get_next(); while (file != String()) { if (file.get_extension() == "tet" && !_is_default_text_editor_theme(file.get_basename().to_lower())) { custom_themes.push_back(file.get_basename()); } file = d->get_next(); } d->list_dir_end(); memdelete(d); custom_themes.sort(); for (List<String>::Element *E = custom_themes.front(); E; E = E->next()) { themes += "," + E->get(); } } add_property_hint(PropertyInfo(Variant::STRING, "text_editor/theme/color_theme", PROPERTY_HINT_ENUM, themes)); } void EditorSettings::load_text_editor_theme() { String p_file = get("text_editor/theme/color_theme"); if (_is_default_text_editor_theme(p_file.get_file().to_lower())) { if (p_file == "Default") { _load_default_text_editor_theme(); } return; // sorry for "Settings changed" console spam } String theme_path = get_text_editor_themes_dir().plus_file(p_file + ".tet"); Ref<ConfigFile> cf = memnew(ConfigFile); Error err = cf->load(theme_path); if (err != OK) { return; } List<String> keys; cf->get_section_keys("color_theme", &keys); for (List<String>::Element *E = keys.front(); E; E = E->next()) { String key = E->get(); String val = cf->get_value("color_theme", key); // don't load if it's not already there! if (has_setting("text_editor/highlighting/" + key)) { // make sure it is actually a color if (val.is_valid_html_color() && key.find("color") >= 0) { props["text_editor/highlighting/" + key].variant = Color::html(val); // change manually to prevent "Settings changed" console spam } } } emit_signal("settings_changed"); // if it doesn't load just use what is currently loaded } bool EditorSettings::import_text_editor_theme(String p_file) { if (!p_file.ends_with(".tet")) { return false; } else { if (p_file.get_file().to_lower() == "default.tet") { return false; } DirAccess *d = DirAccess::open(get_text_editor_themes_dir()); if (d) { d->copy(p_file, get_text_editor_themes_dir().plus_file(p_file.get_file())); memdelete(d); return true; } } return false; } bool EditorSettings::save_text_editor_theme() { String p_file = get("text_editor/theme/color_theme"); if (_is_default_text_editor_theme(p_file.get_file().to_lower())) { return false; } String theme_path = get_text_editor_themes_dir().plus_file(p_file + ".tet"); return _save_text_editor_theme(theme_path); } bool EditorSettings::save_text_editor_theme_as(String p_file) { if (!p_file.ends_with(".tet")) { p_file += ".tet"; } if (_is_default_text_editor_theme(p_file.get_file().to_lower().trim_suffix(".tet"))) { return false; } if (_save_text_editor_theme(p_file)) { // switch to theme is saved in the theme directory list_text_editor_themes(); String theme_name = p_file.substr(0, p_file.length() - 4).get_file(); if (p_file.get_base_dir() == get_text_editor_themes_dir()) { _initial_set("text_editor/theme/color_theme", theme_name); load_text_editor_theme(); } return true; } return false; } bool EditorSettings::is_default_text_editor_theme() { String p_file = get("text_editor/theme/color_theme"); return _is_default_text_editor_theme(p_file.get_file().to_lower()); } Vector<String> EditorSettings::get_script_templates(const String &p_extension) { Vector<String> templates; DirAccess *d = DirAccess::open(get_script_templates_dir()); if (d) { d->list_dir_begin(); String file = d->get_next(); while (file != String()) { if (file.get_extension() == p_extension) { templates.push_back(file.get_basename()); } file = d->get_next(); } d->list_dir_end(); memdelete(d); } return templates; } String EditorSettings::get_editor_layouts_config() const { return get_settings_dir().plus_file("editor_layouts.cfg"); } // Shortcuts void EditorSettings::add_shortcut(const String &p_name, Ref<ShortCut> &p_shortcut) { shortcuts[p_name] = p_shortcut; } bool EditorSettings::is_shortcut(const String &p_name, const Ref<InputEvent> &p_event) const { const Map<String, Ref<ShortCut> >::Element *E = shortcuts.find(p_name); if (!E) { ERR_EXPLAIN("Unknown Shortcut: " + p_name); ERR_FAIL_V(false); } return E->get()->is_shortcut(p_event); } Ref<ShortCut> EditorSettings::get_shortcut(const String &p_name) const { const Map<String, Ref<ShortCut> >::Element *E = shortcuts.find(p_name); if (!E) return Ref<ShortCut>(); return E->get(); } void EditorSettings::get_shortcut_list(List<String> *r_shortcuts) { for (const Map<String, Ref<ShortCut> >::Element *E = shortcuts.front(); E; E = E->next()) { r_shortcuts->push_back(E->key()); } } Ref<ShortCut> ED_GET_SHORTCUT(const String &p_path) { if (!EditorSettings::get_singleton()) { return NULL; } Ref<ShortCut> sc = EditorSettings::get_singleton()->get_shortcut(p_path); if (!sc.is_valid()) { ERR_EXPLAIN("Used ED_GET_SHORTCUT with invalid shortcut: " + p_path); ERR_FAIL_COND_V(!sc.is_valid(), sc); } return sc; } struct ShortCutMapping { const char *path; uint32_t keycode; }; Ref<ShortCut> ED_SHORTCUT(const String &p_path, const String &p_name, uint32_t p_keycode) { #ifdef OSX_ENABLED // Use Cmd+Backspace as a general replacement for Delete shortcuts on macOS if (p_keycode == KEY_DELETE) { p_keycode = KEY_MASK_CMD | KEY_BACKSPACE; } #endif Ref<InputEventKey> ie; if (p_keycode) { ie.instance(); ie->set_unicode(p_keycode & KEY_CODE_MASK); ie->set_scancode(p_keycode & KEY_CODE_MASK); ie->set_shift(bool(p_keycode & KEY_MASK_SHIFT)); ie->set_alt(bool(p_keycode & KEY_MASK_ALT)); ie->set_control(bool(p_keycode & KEY_MASK_CTRL)); ie->set_metakey(bool(p_keycode & KEY_MASK_META)); } if (!EditorSettings::get_singleton()) { Ref<ShortCut> sc; sc.instance(); sc->set_name(p_name); sc->set_shortcut(ie); sc->set_meta("original", ie); return sc; } Ref<ShortCut> sc = EditorSettings::get_singleton()->get_shortcut(p_path); if (sc.is_valid()) { sc->set_name(p_name); //keep name (the ones that come from disk have no name) sc->set_meta("original", ie); //to compare against changes return sc; } sc.instance(); sc->set_name(p_name); sc->set_shortcut(ie); sc->set_meta("original", ie); //to compare against changes EditorSettings::get_singleton()->add_shortcut(p_path, sc); return sc; } void EditorSettings::notify_changes() { _THREAD_SAFE_METHOD_ SceneTree *sml = Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop()); if (!sml) { return; } Node *root = sml->get_root()->get_child(0); if (!root) { return; } root->propagate_notification(NOTIFICATION_EDITOR_SETTINGS_CHANGED); } void EditorSettings::_bind_methods() { ClassDB::bind_method(D_METHOD("has_setting", "name"), &EditorSettings::has_setting); ClassDB::bind_method(D_METHOD("set_setting", "name", "value"), &EditorSettings::set_setting); ClassDB::bind_method(D_METHOD("get_setting", "name"), &EditorSettings::get_setting); ClassDB::bind_method(D_METHOD("erase", "property"), &EditorSettings::erase); ClassDB::bind_method(D_METHOD("set_initial_value", "name", "value", "update_current"), &EditorSettings::set_initial_value); ClassDB::bind_method(D_METHOD("property_can_revert", "name"), &EditorSettings::property_can_revert); ClassDB::bind_method(D_METHOD("property_get_revert", "name"), &EditorSettings::property_get_revert); ClassDB::bind_method(D_METHOD("add_property_info", "info"), &EditorSettings::_add_property_info_bind); ClassDB::bind_method(D_METHOD("get_settings_dir"), &EditorSettings::get_settings_dir); ClassDB::bind_method(D_METHOD("get_project_settings_dir"), &EditorSettings::get_project_settings_dir); ClassDB::bind_method(D_METHOD("set_project_metadata", "section", "key", "data"), &EditorSettings::set_project_metadata); ClassDB::bind_method(D_METHOD("get_project_metadata", "section", "key", "default"), &EditorSettings::get_project_metadata, DEFVAL(Variant())); ClassDB::bind_method(D_METHOD("set_favorites", "dirs"), &EditorSettings::set_favorites); ClassDB::bind_method(D_METHOD("get_favorites"), &EditorSettings::get_favorites); ClassDB::bind_method(D_METHOD("set_recent_dirs", "dirs"), &EditorSettings::set_recent_dirs); ClassDB::bind_method(D_METHOD("get_recent_dirs"), &EditorSettings::get_recent_dirs); ADD_SIGNAL(MethodInfo("settings_changed")); BIND_CONSTANT(NOTIFICATION_EDITOR_SETTINGS_CHANGED); } EditorSettings::EditorSettings() { last_order = 0; optimize_save = true; save_changed_setting = true; _load_defaults(); } EditorSettings::~EditorSettings() { }
// @(#)root/treeplayer:$Id$ // Author: Rene Brun 19/01/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TROOT.h" #include "TTreeFormula.h" #include "TTree.h" #include "TBranch.h" #include "TBranchObject.h" #include "TFunction.h" #include "TClonesArray.h" #include "TLeafB.h" #include "TLeafC.h" #include "TLeafObject.h" #include "TDataMember.h" #include "TMethodCall.h" #include "TCutG.h" #include "TRandom.h" #include "TInterpreter.h" #include "TDataType.h" #include "TStreamerInfo.h" #include "TStreamerElement.h" #include "TBranchElement.h" #include "TLeafElement.h" #include "TArrayI.h" #include "TAxis.h" #include "TError.h" #include "TVirtualCollectionProxy.h" #include "TString.h" #include "TTimeStamp.h" #include "TMath.h" #include "TVirtualRefProxy.h" #include "TTreeFormulaManager.h" #include "TFormLeafInfo.h" #include "TMethod.h" #include "TBaseClass.h" #include "TFormLeafInfoReference.h" #include "TEntryList.h" #include <ctype.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <typeinfo> #include <algorithm> const Int_t kMaxLen = 1024; R__EXTERN TTree *gTree; ClassImp(TTreeFormula) //______________________________________________________________________________ // // TTreeFormula now relies on a variety of TFormLeafInfo classes to handle the // reading of the information. Here is the list of theses classes: // TFormLeafInfo // TFormLeafInfoDirect // TFormLeafInfoNumerical // TFormLeafInfoClones // TFormLeafInfoCollection // TFormLeafInfoPointer // TFormLeafInfoMethod // TFormLeafInfoMultiVarDim // TFormLeafInfoMultiVarDimDirect // TFormLeafInfoCast // // The following method are available from the TFormLeafInfo interface: // // AddOffset(Int_t offset, TStreamerElement* element) // GetCounterValue(TLeaf* leaf) : return the size of the array pointed to. // GetObjectAddress(TLeafElement* leaf) : Returns the the location of the object pointed to. // GetMultiplicity() : Returns info on the variability of the number of elements // GetNdata(TLeaf* leaf) : Returns the number of elements // GetNdata() : Used by GetNdata(TLeaf* leaf) // GetValue(TLeaf *leaf, Int_t instance = 0) : Return the value // GetValuePointer(TLeaf *leaf, Int_t instance = 0) : Returns the address of the value // GetLocalValuePointer(TLeaf *leaf, Int_t instance = 0) : Returns the address of the value of 'this' LeafInfo // IsString() // ReadValue(char *where, Int_t instance = 0) : Internal function to interpret the location 'where' // Update() : react to the possible loading of a shared library. // // //______________________________________________________________________________ inline static void R__LoadBranch(TBranch* br, Long64_t entry, Bool_t quickLoad) { if (!quickLoad || (br->GetReadEntry() != entry)) { br->GetEntry(entry); } } //______________________________________________________________________________ // // This class is a small helper class to help in keeping track of the array // dimensions encountered in the analysis of the expression. class TDimensionInfo : public TObject { public: Int_t fCode; // Location of the leaf in TTreeFormula::fCode Int_t fOper; // Location of the Operation using the leaf in TTreeFormula::fOper Int_t fSize; TFormLeafInfoMultiVarDim* fMultiDim; TDimensionInfo(Int_t code, Int_t oper, Int_t size, TFormLeafInfoMultiVarDim* multiDim) : fCode(code), fOper(oper), fSize(size), fMultiDim(multiDim) {}; ~TDimensionInfo() {}; }; //______________________________________________________________________________ // // A TreeFormula is used to pass a selection expression // to the Tree drawing routine. See TTree::Draw // // A TreeFormula can contain any arithmetic expression including // standard operators and mathematical functions separated by operators. // Examples of valid expression: // "x<y && sqrt(z)>3.2" // //______________________________________________________________________________ TTreeFormula::TTreeFormula(): TFormula(), fQuickLoad(kFALSE), fNeedLoading(kTRUE), fDidBooleanOptimization(kFALSE), fDimensionSetup(0) { // Tree Formula default constructor fTree = 0; fLookupType = 0; fNindex = 0; fNcodes = 0; fAxis = 0; fHasCast = 0; fManager = 0; fMultiplicity = 0; Int_t j,k; for (j=0; j<kMAXCODES; j++) { fNdimensions[j] = 0; fCodes[j] = 0; fNdata[j] = 1; fHasMultipleVarDim[j] = kFALSE; for (k = 0; k<kMAXFORMDIM; k++) { fIndexes[j][k] = -1; fCumulSizes[j][k] = 1; fVarIndexes[j][k] = 0; } } } //______________________________________________________________________________ TTreeFormula::TTreeFormula(const char *name,const char *expression, TTree *tree) :TFormula(), fTree(tree), fQuickLoad(kFALSE), fNeedLoading(kTRUE), fDidBooleanOptimization(kFALSE), fDimensionSetup(0) { // Normal TTree Formula Constuctor Init(name,expression); } //______________________________________________________________________________ TTreeFormula::TTreeFormula(const char *name,const char *expression, TTree *tree, const std::vector<std::string>& aliases) :TFormula(), fTree(tree), fQuickLoad(kFALSE), fNeedLoading(kTRUE), fDidBooleanOptimization(kFALSE), fDimensionSetup(0), fAliasesUsed(aliases) { // Constructor used during the expansion of an alias Init(name,expression); } //______________________________________________________________________________ void TTreeFormula::Init(const char*name, const char* expression) { // Initialiation called from the constructors. TDirectory *const savedir=gDirectory; fNindex = kMAXFOUND; fLookupType = new Int_t[fNindex]; fNcodes = 0; fMultiplicity = 0; fAxis = 0; fHasCast = 0; Int_t i,j,k; fManager = new TTreeFormulaManager; fManager->Add(this); for (j=0; j<kMAXCODES; j++) { fNdimensions[j] = 0; fLookupType[j] = kDirect; fCodes[j] = 0; fNdata[j] = 1; fHasMultipleVarDim[j] = kFALSE; for (k = 0; k<kMAXFORMDIM; k++) { fIndexes[j][k] = -1; fCumulSizes[j][k] = 1; fVarIndexes[j][k] = 0; } } fDimensionSetup = new TList; if (Compile(expression)) { fTree = 0; fNdim = 0; if(savedir) savedir->cd(); return; } if (fNcodes >= kMAXFOUND) { Warning("TTreeFormula","Too many items in expression:%s",expression); fNcodes = kMAXFOUND; } SetName(name); for (i=0;i<fNoper;i++) { if (GetAction(i)==kDefinedString) { Int_t string_code = GetActionParam(i); TLeaf *leafc = (TLeaf*)fLeaves.UncheckedAt(string_code); if (!leafc) continue; // We have a string used as a string // This dormant portion of code would be used if (when?) we allow the histogramming // of the integral content (as opposed to the string content) of strings // held in a variable size container delimited by a null (as opposed to // a fixed size container or variable size container whose size is controlled // by a variable). In GetNdata, we will then use strlen to grab the current length. //fCumulSizes[i][fNdimensions[i]-1] = 1; //fUsedSizes[fNdimensions[i]-1] = -TMath::Abs(fUsedSizes[fNdimensions[i]-1]); //fUsedSizes[0] = - TMath::Abs( fUsedSizes[0]); if (fNcodes == 1) { // If the string is by itself, then it can safely be histogrammed as // in a string based axis. To histogram the number inside the string // just make it part of a useless expression (for example: mystring+0) SetBit(kIsCharacter); } continue; } if (GetAction(i)==kJump && GetActionParam(i)==(fNoper-1)) { // We have cond ? string1 : string2 if (IsString(fNoper-1)) SetBit(kIsCharacter); } } if (fNoper==1 && GetAction(0)==kAliasString) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); if (subform->TestBit(kIsCharacter)) SetBit(kIsCharacter); } else if (fNoper==2 && GetAction(0)==kAlternateString) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); if (subform->TestBit(kIsCharacter)) SetBit(kIsCharacter); } fManager->Sync(); // Let's verify the indexes and dies if we need to. Int_t k0,k1; for(k0 = 0; k0 < fNcodes; k0++) { for(k1 = 0; k1 < fNdimensions[k0]; k1++ ) { // fprintf(stderr,"Saw %d dim %d and index %d\n",k1, fFixedSizes[k0][k1], fIndexes[k0][k1]); if ( fIndexes[k0][k1]>=0 && fFixedSizes[k0][k1]>=0 && fIndexes[k0][k1]>=fFixedSizes[k0][k1]) { Error("TTreeFormula", "Index %d for dimension #%d in %s is too high (max is %d)", fIndexes[k0][k1],k1+1, expression,fFixedSizes[k0][k1]-1); fTree = 0; fNdim = 0; if(savedir) savedir->cd(); return; } } } // Create a list of uniques branches to load. for(k=0; k<fNcodes; k++) { TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(k); TBranch *branch = 0; if (leaf) { branch = leaf->GetBranch(); if (fBranches.FindObject(branch)) branch = 0; } fBranches.AddAtAndExpand(branch,k); } if (IsInteger(kFALSE)) SetBit(kIsInteger); if (TestBit(TTreeFormula::kNeedEntries)) { // Call TTree::GetEntries() to insure that it is already calculated. // This will need to be done anyway at the first iteration and insure // that it will not mess up the branch reading (because TTree::GetEntries // opens all the file in the chain and 'stays' on the last file. Long64_t readentry = fTree->GetReadEntry(); Int_t treenumber = fTree->GetTreeNumber(); fTree->GetEntries(); if (treenumber != fTree->GetTreeNumber()) { if (readentry != -1) { fTree->LoadTree(readentry); } UpdateFormulaLeaves(); } else { if (readentry != -1) { fTree->LoadTree(readentry); } } } if(savedir) savedir->cd(); } //______________________________________________________________________________ TTreeFormula::~TTreeFormula() { //*-*-*-*-*-*-*-*-*-*-*Tree Formula default destructor*-*-*-*-*-*-*-*-*-*-* //*-* ================================= if (fManager) { fManager->Remove(this); if (fManager->fFormulas.GetLast()<0) { delete fManager; fManager = 0; } } // Objects in fExternalCuts are not owned and should not be deleted // fExternalCuts.Clear(); fLeafNames.Delete(); fDataMembers.Delete(); fMethods.Delete(); fAliases.Delete(); if (fLookupType) delete [] fLookupType; for (int j=0; j<fNcodes; j++) { for (int k = 0; k<fNdimensions[j]; k++) { if (fVarIndexes[j][k]) delete fVarIndexes[j][k]; fVarIndexes[j][k] = 0; } } if (fDimensionSetup) { fDimensionSetup->Delete(); delete fDimensionSetup; } } //______________________________________________________________________________ void TTreeFormula::DefineDimensions(Int_t code, Int_t size, TFormLeafInfoMultiVarDim * info, Int_t& virt_dim) { // This method is used internally to decode the dimensions of the variables if (info) { fManager->EnableMultiVarDims(); //if (fIndexes[code][info->fDim]<0) { // removed because the index might be out of bounds! info->fVirtDim = virt_dim; fManager->AddVarDims(virt_dim); // if (!fVarDims[virt_dim]) fVarDims[virt_dim] = new TArrayI; //} } Int_t vsize = 0; if (fIndexes[code][fNdimensions[code]]==-2) { TTreeFormula *indexvar = fVarIndexes[code][fNdimensions[code]]; // ASSERT(indexvar!=0); Int_t index_multiplicity = indexvar->GetMultiplicity(); switch (index_multiplicity) { case -1: case 0: case 2: vsize = indexvar->GetNdata(); break; case 1: vsize = -1; break; }; } else vsize = size; fCumulSizes[code][fNdimensions[code]] = size; if ( fIndexes[code][fNdimensions[code]] < 0 ) { fManager->UpdateUsedSize(virt_dim, vsize); } fNdimensions[code] ++; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(const char *info, Int_t code) { // This method is used internally to decode the dimensions of the variables // We assume that there are NO white spaces in the info string const char * current; Int_t size, scanindex, vardim; current = info; vardim = 0; // the next value could be before the string but // that's okay because the next operation is ++ // (this is to avoid (?) a if statement at the end of the // loop) if (current[0] != '[') current--; while (current) { current++; scanindex = sscanf(current,"%d",&size); // if scanindex is 0 then we have a name index thus a variable // array (or TClonesArray!). if (scanindex==0) size = -1; vardim += RegisterDimensions(code, size); if (fNdimensions[code] >= kMAXFORMDIM) { // NOTE: test that fNdimensions[code] is NOT too big!! break; } current = (char*)strstr( current, "[" ); } return vardim; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(Int_t code, Int_t size, TFormLeafInfoMultiVarDim * multidim) { // This method stores the dimension information for later usage. TDimensionInfo * info = new TDimensionInfo(code,fNoper,size,multidim); fDimensionSetup->Add(info); fCumulSizes[code][fNdimensions[code]] = size; fNdimensions[code] ++; return (size==-1) ? 1 : 0; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(Int_t code, TFormLeafInfo *leafinfo, TFormLeafInfo * /* maininfo */, Bool_t useCollectionObject) { // This method is used internally to decode the dimensions of the variables Int_t ndim, size, current, vardim; vardim = 0; const TStreamerElement * elem = leafinfo->fElement; TClass* c = elem ? elem->GetClassPointer() : 0; TFormLeafInfoMultiVarDim * multi = dynamic_cast<TFormLeafInfoMultiVarDim * >(leafinfo); if (multi) { // We have a second variable dimensions fManager->EnableMultiVarDims(); multi->fDim = fNdimensions[code]; return RegisterDimensions(code, -1, multi); } if (elem->IsA() == TStreamerBasicPointer::Class()) { if (elem->GetArrayDim()>0) { ndim = elem->GetArrayDim(); size = elem->GetMaxIndex(0); vardim += RegisterDimensions(code, -1); } else { ndim = 1; size = -1; } TStreamerBasicPointer *array = (TStreamerBasicPointer*)elem; TClass *cl = leafinfo->fClass; Int_t offset; TStreamerElement* counter = ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(array->GetCountName(),offset); #if 1 leafinfo->fCounter = new TFormLeafInfo(cl,offset,counter); #else /* Code is not ready yet see revision 14078 */ if (maininfo==0 || maininfo==leafinfo || 1) { leafinfo->fCounter = new TFormLeafInfo(cl,offset,counter); } else { leafinfo->fCounter = maininfo->DeepCopy(); TFormLeafInfo *currentinfo = leafinfo->fCounter; while(currentinfo->fNext && currentinfo->fNext->fNext) currentinfo=currentinfo->fNext; delete currentinfo->fNext; currentinfo->fNext = new TFormLeafInfo(cl,offset,counter); } #endif } else if (!useCollectionObject && elem->GetClassPointer() == TClonesArray::Class() ) { ndim = 1; size = -1; TClass * clonesClass = TClonesArray::Class(); Int_t c_offset; TStreamerElement *counter = ((TStreamerInfo*)clonesClass->GetStreamerInfo())->GetStreamerElement("fLast",c_offset); leafinfo->fCounter = new TFormLeafInfo(clonesClass,c_offset,counter); } else if (!useCollectionObject && elem->GetClassPointer() && elem->GetClassPointer()->GetCollectionProxy() ) { if ( typeid(*leafinfo) == typeid(TFormLeafInfoCollection) ) { ndim = 1; size = -1; } else { R__ASSERT( fHasMultipleVarDim[code] ); ndim = 1; size = 1; } } else if ( c && c->GetReferenceProxy() && c->GetReferenceProxy()->HasCounter() ) { ndim = 1; size = -1; } else if (elem->GetArrayDim()>0) { ndim = elem->GetArrayDim(); size = elem->GetMaxIndex(0); } else if ( elem->GetNewType()== TStreamerInfo::kCharStar) { // When we implement being able to read the length from // strlen, we will have: // ndim = 1; // size = -1; // until then we more or so die: ndim = 1; size = 1; //NOTE: changed from 0 } else return 0; current = 0; do { vardim += RegisterDimensions(code, size); if (fNdimensions[code] >= kMAXFORMDIM) { // NOTE: test that fNdimensions[code] is NOT too big!! break; } current++; size = elem->GetMaxIndex(current); } while (current<ndim); return vardim; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(Int_t code, TBranchElement *branch) { // This method is used internally to decode the dimensions of the variables TBranchElement * leafcount2 = branch->GetBranchCount2(); if (leafcount2) { // With have a second variable dimensions TBranchElement *leafcount = dynamic_cast<TBranchElement*>(branch->GetBranchCount()); R__ASSERT(leafcount); // The function should only be called on a functional TBranchElement object fManager->EnableMultiVarDims(); TFormLeafInfoMultiVarDim * info = new TFormLeafInfoMultiVarDimDirect(); fDataMembers.AddAtAndExpand(info, code); fHasMultipleVarDim[code] = kTRUE; info->fCounter = new TFormLeafInfoDirect(leafcount); info->fCounter2 = new TFormLeafInfoDirect(leafcount2); info->fDim = fNdimensions[code]; //if (fIndexes[code][info->fDim]<0) { // info->fVirtDim = virt_dim; // if (!fVarDims[virt_dim]) fVarDims[virt_dim] = new TArrayI; //} return RegisterDimensions(code, -1, info); } return 0; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(Int_t code, TLeaf *leaf) { // This method is used internally to decode the dimensions of the variables Int_t numberOfVarDim = 0; // Let see if we can understand the structure of this branch. // Usually we have: leafname[fixed_array] leaftitle[var_array]\type // (with fixed_array that can be a multi-dimension array. const char *tname = leaf->GetTitle(); char *leaf_dim = (char*)strstr( tname, "[" ); const char *bname = leaf->GetBranch()->GetName(); char *branch_dim = (char*)strstr(bname,"["); if (branch_dim) branch_dim++; // skip the '[' Bool_t isString = kFALSE; if (leaf->IsA() == TLeafElement::Class()) { Int_t type =((TBranchElement*)leaf->GetBranch())->GetStreamerType(); isString = (type == TStreamerInfo::kOffsetL+TStreamerInfo::kChar) || (type == TStreamerInfo::kCharStar); } else { isString = (leaf->IsA() == TLeafC::Class()); } if (leaf_dim) { leaf_dim++; // skip the '[' if (!branch_dim || strncmp(branch_dim,leaf_dim,strlen(branch_dim))) { // then both are NOT the same so do the leaf title first: numberOfVarDim += RegisterDimensions( leaf_dim, code); } else if (branch_dim && strncmp(branch_dim,leaf_dim,strlen(branch_dim))==0 && strlen(leaf_dim)>strlen(branch_dim) && (leaf_dim+strlen(branch_dim))[0]=='[') { // we have extra info in the leaf title numberOfVarDim += RegisterDimensions( leaf_dim+strlen(branch_dim)+1, code); } } if (branch_dim) { // then both are NOT same so do the branch name next: if (isString) { numberOfVarDim += RegisterDimensions( code, 1); } else { numberOfVarDim += RegisterDimensions( branch_dim, code); } } if (leaf->IsA() == TLeafElement::Class()) { TBranchElement* branch = (TBranchElement*) leaf->GetBranch(); if (branch->GetBranchCount2()) { if (!branch->GetBranchCount()) { Warning("DefinedVariable", "Noticed an incorrect in-memory TBranchElement object (%s).\nIt has a BranchCount2 but no BranchCount!\nThe result might be incorrect!", branch->GetName()); return numberOfVarDim; } // Switch from old direct style to using a TLeafInfo if (fLookupType[code] == kDataMember) Warning("DefinedVariable", "Already in kDataMember mode when handling multiple variable dimensions"); fLookupType[code] = kDataMember; // Feed the information into the Dimensions system numberOfVarDim += RegisterDimensions( code, branch); } } return numberOfVarDim; } //______________________________________________________________________________ Int_t TTreeFormula::DefineAlternate(const char *expression) { // This method check for treat the case where expression contains $Atl and load up // both fAliases and fExpr. // We return // -1 in case of failure // 0 in case we did not find $Alt // the action number in case of success. static const char *altfunc = "Alt$("; static const char *minfunc = "MinIf$("; static const char *maxfunc = "MaxIf$("; Int_t action = 0; Int_t start = 0; if ( strncmp(expression,altfunc,strlen(altfunc))==0 && expression[strlen(expression)-1]==')' ) { action = kAlternate; start = strlen(altfunc); } if ( strncmp(expression,maxfunc,strlen(maxfunc))==0 && expression[strlen(expression)-1]==')' ) { action = kMaxIf; start = strlen(maxfunc); } if ( strncmp(expression,minfunc,strlen(minfunc))==0 && expression[strlen(expression)-1]==')' ) { action = kMinIf; start = strlen(minfunc); } if (action) { TString full = expression; TString part1; TString part2; int paran = 0; int instr = 0; int brack = 0; for(unsigned int i=start;i<strlen(expression);++i) { switch (expression[i]) { case '(': paran++; break; case ')': paran--; break; case '"': instr = instr ? 0 : 1; break; case '[': brack++; break; case ']': brack--; break; }; if (expression[i]==',' && paran==0 && instr==0 && brack==0) { part1 = full( start, i-start ); part2 = full( i+1, full.Length() -1 - (i+1) ); break; // out of the for loop } } if (part1.Length() && part2.Length()) { TTreeFormula *primary = new TTreeFormula("primary",part1,fTree); TTreeFormula *alternate = new TTreeFormula("alternate",part2,fTree); short isstring = 0; if (action == kAlternate) { if (alternate->GetManager()->GetMultiplicity() != 0 ) { Error("DefinedVariable","The 2nd arguments in %s can not be an array (%s,%d)!", expression,alternate->GetTitle(), alternate->GetManager()->GetMultiplicity()); return -1; } // Should check whether we have strings. if (primary->IsString()) { if (!alternate->IsString()) { Error("DefinedVariable", "The 2nd arguments in %s has to return the same type as the 1st argument (string)!", expression); return -1; } isstring = 1; } else if (alternate->IsString()) { Error("DefinedVariable", "The 2nd arguments in %s has to return the same type as the 1st argument (numerical type)!", expression); return -1; } } else { primary->GetManager()->Add( alternate ); primary->GetManager()->Sync(); if (primary->IsString() || alternate->IsString()) { if (!alternate->IsString()) { Error("DefinedVariable", "The arguments of %s can not be strings!", expression); return -1; } } } fAliases.AddAtAndExpand(primary,fNoper); fExpr[fNoper] = ""; SetAction(fNoper, (Int_t)action + isstring, 0 ); ++fNoper; fAliases.AddAtAndExpand(alternate,fNoper); return (Int_t)kAlias + isstring; } } return 0; } //______________________________________________________________________________ Int_t TTreeFormula::ParseWithLeaf(TLeaf* leaf, const char* subExpression, Bool_t final, UInt_t paran_level, TObjArray& castqueue, Bool_t useLeafCollectionObject, const char* fullExpression) { // Decompose 'expression' as pointing to something inside the leaf // Returns: // -2 Error: some information is missing (message already printed) // -1 Error: Syntax is incorrect (message already printed) // 0 // >0 the value returns is the action code. Int_t action = 0; Int_t numberOfVarDim = 0; char *current; char scratch[kMaxLen]; scratch[0] = '\0'; char work[kMaxLen]; work[0] = '\0'; const char *right = subExpression; TString name = fullExpression; TBranch *branch = leaf ? leaf->GetBranch() : 0; Long64_t readentry = fTree->GetTree()->GetReadEntry(); if (readentry==-1) readentry=0; Bool_t useLeafReferenceObject = false; Int_t code = fNcodes-1; // Make a check to prevent problem with some corrupted files (missing TStreamerInfo). if (leaf && leaf->IsA()==TLeafElement::Class()) { TBranchElement *br = 0; if( branch->IsA() == TBranchElement::Class() ) { br = ((TBranchElement*)branch); if ( br->GetInfo() == 0 ) { Error("DefinedVariable","Missing StreamerInfo for %s. We will be unable to read!", name.Data()); return -2; } } TBranch *bmom = branch->GetMother(); if( bmom->IsA() == TBranchElement::Class() ) { TBranchElement *mom = (TBranchElement*)br->GetMother(); if (mom!=br) { if (mom->GetInfo()==0) { Error("DefinedVariable","Missing StreamerInfo for %s." " We will be unable to read!", mom->GetName()); return -2; } if ((mom->GetType()) < -1 && !mom->GetAddress()) { Error("DefinedVariable", "Address not set when the type of the branch is negative for for %s. We will be unable to read!", mom->GetName()); return -2; } } } } // We need to record the location in the list of leaves because // the tree might actually be a chain and in that case the leaf will // change from tree to tree!. // Let's reconstruct the name of the leaf, including the possible friend alias TTree *realtree = fTree->GetTree(); const char* alias = 0; if (leaf) { if (realtree) alias = realtree->GetFriendAlias(leaf->GetBranch()->GetTree()); if (!alias && realtree!=fTree) { // Let's try on the chain alias = fTree->GetFriendAlias(leaf->GetBranch()->GetTree()); } } if (alias) snprintf(scratch,kMaxLen-1,"%s.%s",alias,leaf->GetName()); else if (leaf) strlcpy(scratch,leaf->GetName(),kMaxLen); TTree *tleaf = realtree; if (leaf) { tleaf = leaf->GetBranch()->GetTree(); fCodes[code] = tleaf->GetListOfLeaves()->IndexOf(leaf); const char *mother_name = leaf->GetBranch()->GetMother()->GetName(); TString br_extended_name; // Could do ( strlen(mother_name)+strlen( leaf->GetBranch()->GetName() ) + 2 ) if (leaf->GetBranch()!=leaf->GetBranch()->GetMother()) { if (mother_name[strlen(mother_name)-1]!='.') { br_extended_name = mother_name; br_extended_name.Append('.'); } } br_extended_name.Append( leaf->GetBranch()->GetName() ); Ssiz_t dim = br_extended_name.First('['); if (dim >= 0) br_extended_name.Remove(dim); TNamed *named = new TNamed(scratch,br_extended_name.Data()); fLeafNames.AddAtAndExpand(named,code); fLeaves.AddAtAndExpand(leaf,code); } // If the leaf belongs to a friend tree which has an index, we might // be in the case where some entry do not exist. if (tleaf != realtree && tleaf->GetTreeIndex()) { // reset the multiplicity if (fMultiplicity >= 0) fMultiplicity = 1; } // Analyze the content of 'right' // Try to find out the class (if any) of the object in the leaf. TClass * cl = 0; TFormLeafInfo *maininfo = 0; TFormLeafInfo *previnfo = 0; Bool_t unwindCollection = kFALSE; static TClassRef stdStringClass = TClass::GetClass("string"); if (leaf==0) { TNamed *names = (TNamed*)fLeafNames.UncheckedAt(code); fLeafNames.AddAt(0,code); TTree *what = (TTree*)fLeaves.UncheckedAt(code); fLeaves.AddAt(0,code); cl = what ? what->IsA() : TTree::Class(); maininfo = new TFormLeafInfoTTree(fTree,names->GetName(),what); previnfo = maininfo; delete names; } else if (leaf->InheritsFrom(TLeafObject::Class()) ) { TBranchObject *bobj = (TBranchObject*)leaf->GetBranch(); cl = TClass::GetClass(bobj->GetClassName()); } else if (leaf->InheritsFrom(TLeafElement::Class())) { TBranchElement *branchEl = (TBranchElement *)leaf->GetBranch(); branchEl->SetupAddresses(); TStreamerInfo *info = branchEl->GetInfo(); TStreamerElement *element = 0; Int_t type = branchEl->GetStreamerType(); switch(type) { case TStreamerInfo::kBase: case TStreamerInfo::kObject: case TStreamerInfo::kTString: case TStreamerInfo::kTNamed: case TStreamerInfo::kTObject: case TStreamerInfo::kAny: case TStreamerInfo::kAnyP: case TStreamerInfo::kAnyp: case TStreamerInfo::kSTL: case TStreamerInfo::kSTLp: case TStreamerInfo::kObjectp: case TStreamerInfo::kObjectP: { element = (TStreamerElement *)info->GetElems()[branchEl->GetID()]; if (element) cl = element->GetClassPointer(); } break; case TStreamerInfo::kOffsetL + TStreamerInfo::kSTL: case TStreamerInfo::kOffsetL + TStreamerInfo::kSTLp: case TStreamerInfo::kOffsetL + TStreamerInfo::kAny: case TStreamerInfo::kOffsetL + TStreamerInfo::kAnyp: case TStreamerInfo::kOffsetL + TStreamerInfo::kAnyP: case TStreamerInfo::kOffsetL + TStreamerInfo::kObjectp: case TStreamerInfo::kOffsetL + TStreamerInfo::kObjectP: case TStreamerInfo::kOffsetL + TStreamerInfo::kObject: { element = (TStreamerElement *)info->GetElems()[branchEl->GetID()]; if (element){ cl = element->GetClassPointer(); } } break; case -1: { cl = info->GetClass(); } break; } // If we got a class object, we need to verify whether it is on a // split TClonesArray sub branch. if (cl && branchEl->GetBranchCount()) { if (branchEl->GetType()==31) { // This is inside a TClonesArray. if (!element) { Warning("DefineVariable", "Missing TStreamerElement in object in TClonesArray section"); return -2; } TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(cl, 0, element, kTRUE); // The following code was commmented out because in THIS case // the dimension are actually handled by parsing the title and name of the leaf // and branch (see a little further) // The dimension needs to be handled! // numberOfVarDim += RegisterDimensions(code,clonesinfo); maininfo = clonesinfo; // We skip some cases because we can assume we have an object. Int_t offset=0; info->GetStreamerElement(element->GetName(),offset); if (type == TStreamerInfo::kObjectp || type == TStreamerInfo::kObjectP || type == TStreamerInfo::kOffsetL + TStreamerInfo::kObjectp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kObjectP || type == TStreamerInfo::kSTLp || type == TStreamerInfo::kAnyp || type == TStreamerInfo::kAnyP || type == TStreamerInfo::kOffsetL + TStreamerInfo::kSTLp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kAnyp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kAnyP) { previnfo = new TFormLeafInfoPointer(cl,offset+branchEl->GetOffset(),element); } else { previnfo = new TFormLeafInfo(cl,offset+branchEl->GetOffset(),element); } maininfo->fNext = previnfo; unwindCollection = kTRUE; } else if (branchEl->GetType()==41) { // This is inside a Collection if (!element) { Warning("DefineVariable","Missing TStreamerElement in object in Collection section"); return -2; } // First we need to recover the collection. TBranchElement *count = branchEl->GetBranchCount(); TFormLeafInfo* collectioninfo; if ( count->GetID() >= 0 ) { TStreamerElement *collectionElement = (TStreamerElement *)count->GetInfo()->GetElems()[count->GetID()]; TClass *collectionCl = collectionElement->GetClassPointer(); collectioninfo = new TFormLeafInfoCollection(collectionCl, 0, collectionElement, kTRUE); } else { TClass *collectionCl = TClass::GetClass(count->GetClassName()); collectioninfo = new TFormLeafInfoCollection(collectionCl, 0, collectionCl, kTRUE); } // The following code was commmented out because in THIS case // the dimension are actually handled by parsing the title and name of the leaf // and branch (see a little further) // The dimension needs to be handled! // numberOfVarDim += RegisterDimensions(code,clonesinfo); maininfo = collectioninfo; // We skip some cases because we can assume we have an object. Int_t offset=0; info->GetStreamerElement(element->GetName(),offset); if (type == TStreamerInfo::kObjectp || type == TStreamerInfo::kObjectP || type == TStreamerInfo::kOffsetL + TStreamerInfo::kObjectp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kObjectP || type == TStreamerInfo::kSTLp || type == TStreamerInfo::kAnyp || type == TStreamerInfo::kAnyP || type == TStreamerInfo::kOffsetL + TStreamerInfo::kSTLp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kAnyp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kAnyP) { previnfo = new TFormLeafInfoPointer(cl,offset+branchEl->GetOffset(),element); } else { previnfo = new TFormLeafInfo(cl,offset+branchEl->GetOffset(),element); } maininfo->fNext = previnfo; unwindCollection = kTRUE; } } else if ( branchEl->GetType()==3) { TFormLeafInfo* clonesinfo; if (useLeafCollectionObject) { clonesinfo = new TFormLeafInfoCollectionObject(cl); } else { clonesinfo = new TFormLeafInfoClones(cl, 0, kTRUE); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,clonesinfo,maininfo,useLeafCollectionObject); } maininfo = clonesinfo; previnfo = maininfo; } else if (!useLeafCollectionObject && branchEl->GetType()==4) { TFormLeafInfo* collectioninfo; if (useLeafCollectionObject) { collectioninfo = new TFormLeafInfoCollectionObject(cl); } else { collectioninfo = new TFormLeafInfoCollection(cl, 0, cl, kTRUE); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,useLeafCollectionObject); } maininfo = collectioninfo; previnfo = maininfo; } else if (branchEl->GetStreamerType()==-1 && cl && cl->GetCollectionProxy()) { if (useLeafCollectionObject) { TFormLeafInfo *collectioninfo = new TFormLeafInfoCollectionObject(cl); maininfo = collectioninfo; previnfo = collectioninfo; } else { TFormLeafInfo *collectioninfo = new TFormLeafInfoCollection(cl, 0, cl, kTRUE); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); maininfo = collectioninfo; previnfo = collectioninfo; if (cl->GetCollectionProxy()->GetValueClass()!=0 && cl->GetCollectionProxy()->GetValueClass()->GetCollectionProxy()!=0) { TFormLeafInfo *multi = new TFormLeafInfoMultiVarDimCollection(cl,0, cl->GetCollectionProxy()->GetValueClass(),collectioninfo); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,multi,maininfo,kFALSE); previnfo->fNext = multi; cl = cl->GetCollectionProxy()->GetValueClass(); multi->fNext = new TFormLeafInfoCollection(cl, 0, cl, false); previnfo = multi->fNext; } if (cl->GetCollectionProxy()->GetValueClass()==0 && cl->GetCollectionProxy()->GetType()>0) { previnfo->fNext = new TFormLeafInfoNumerical(cl->GetCollectionProxy()); previnfo = previnfo->fNext; } else { // nothing to do } } } else if (strlen(right)==0 && cl && element && final) { TClass *elemCl = element->GetClassPointer(); if (!useLeafCollectionObject && elemCl && elemCl->GetCollectionProxy() && elemCl->GetCollectionProxy()->GetValueClass() && elemCl->GetCollectionProxy()->GetValueClass()->GetCollectionProxy()) { TFormLeafInfo *collectioninfo = new TFormLeafInfoCollection(cl, 0, elemCl); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); maininfo = collectioninfo; previnfo = collectioninfo; TFormLeafInfo *multi = new TFormLeafInfoMultiVarDimCollection(elemCl, 0, elemCl->GetCollectionProxy()->GetValueClass(), collectioninfo); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,multi,maininfo,kFALSE); previnfo->fNext = multi; cl = elemCl->GetCollectionProxy()->GetValueClass(); multi->fNext = new TFormLeafInfoCollection(cl, 0, cl, false); previnfo = multi->fNext; if (cl->GetCollectionProxy()->GetValueClass()==0 && cl->GetCollectionProxy()->GetType()>0) { previnfo->fNext = new TFormLeafInfoNumerical(cl->GetCollectionProxy()); previnfo = previnfo->fNext; } } else if (!useLeafCollectionObject && elemCl && elemCl->GetCollectionProxy() && elemCl->GetCollectionProxy()->GetValueClass()==0 && elemCl->GetCollectionProxy()->GetType()>0) { // At this point we have an element which is inside a class (which is not // a collection) and this element of a collection of numerical type. // (Note: it is not possible to have more than one variable dimension // unless we were supporting variable size C-style array of collection). TFormLeafInfo* collectioninfo = new TFormLeafInfoCollection(cl, 0, elemCl); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); collectioninfo->fNext = new TFormLeafInfoNumerical(elemCl->GetCollectionProxy()); maininfo = collectioninfo; previnfo = maininfo->fNext; } else if (!useLeafCollectionObject && elemCl && elemCl->GetCollectionProxy()) { if (elemCl->GetCollectionProxy()->GetValueClass()==TString::Class()) { right = "Data()"; } else if (elemCl->GetCollectionProxy()->GetValueClass()==stdStringClass) { right = "c_str()"; } } else if (!element->IsaPointer()) { maininfo = new TFormLeafInfoDirect(branchEl); previnfo = maininfo; } } else if ( cl && cl->GetReferenceProxy() ) { if ( useLeafCollectionObject || fullExpression[0] == '@' || fullExpression[strlen(scratch)] == '@' ) { useLeafReferenceObject = true; } else { if ( !maininfo ) { maininfo = previnfo = new TFormLeafInfoReference(cl, element, 0); numberOfVarDim += RegisterDimensions(code,maininfo,maininfo,kFALSE); } cl = 0; for(int i=0; i<leaf->GetBranch()->GetEntries()-readentry; ++i) { R__LoadBranch(leaf->GetBranch(), readentry+i, fQuickLoad); cl = ((TFormLeafInfoReference*)maininfo)->GetValueClass(leaf); if ( cl ) break; } if ( !cl ) { Error("DefinedVariable","Failed to access class type of reference target (%s)",element->GetName()); return -1; } } } } // Treat the dimension information in the leaf name, title and 2nd branch count if (leaf) numberOfVarDim += RegisterDimensions(code,leaf); if (cl) { if (unwindCollection) { // So far we should get here only if we encounter a split collection of a class that contains // directly a collection. R__ASSERT(numberOfVarDim==1 && maininfo); if (!useLeafCollectionObject && cl && cl->GetCollectionProxy()) { TFormLeafInfo *multi = new TFormLeafInfoMultiVarDimCollection(cl, 0, cl, maininfo); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,multi,maininfo,kFALSE); previnfo->fNext = multi; multi->fNext = new TFormLeafInfoCollection(cl, 0, cl, false); previnfo = multi->fNext; if (cl->GetCollectionProxy()->GetValueClass()==0 && cl->GetCollectionProxy()->GetType()>0) { previnfo->fNext = new TFormLeafInfoNumerical(cl->GetCollectionProxy()); previnfo = previnfo->fNext; } } else if (!useLeafCollectionObject && cl == TClonesArray::Class()) { TFormLeafInfo *multi = new TFormLeafInfoMultiVarDimClones(cl, 0, cl, maininfo); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,multi,maininfo,kFALSE); previnfo->fNext = multi; multi->fNext = new TFormLeafInfoClones(cl, 0, false); previnfo = multi->fNext; } } Int_t offset=0; Int_t nchname = strlen(right); TFormLeafInfo *leafinfo = 0; TStreamerElement* element = 0; // Let see if the leaf was attempted to be casted. // Since there would have been something like // ((cast_class*)leafname)->.... we need to use // paran_level+1 // Also we disable this functionality in case of TClonesArray // because it is not yet allowed to have 'inheritance' (or virtuality) // in play in a TClonesArray. { TClass * casted = (TClass*) castqueue.At(paran_level+1); if (casted && cl != TClonesArray::Class()) { if ( ! casted->InheritsFrom(cl) ) { Error("DefinedVariable","%s does not inherit from %s. Casting not possible!", casted->GetName(),cl->GetName()); return -2; } leafinfo = new TFormLeafInfoCast(cl,casted); fHasCast = kTRUE; if (maininfo==0) { maininfo = leafinfo; } if (previnfo==0) { previnfo = leafinfo; } else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = 0; cl = casted; castqueue.AddAt(0,paran_level); } } Int_t i; Bool_t prevUseCollectionObject = useLeafCollectionObject; Bool_t useCollectionObject = useLeafCollectionObject; Bool_t useReferenceObject = useLeafReferenceObject; Bool_t prevUseReferenceObject = useLeafReferenceObject; for (i=0, current = &(work[0]); i<=nchname;i++ ) { // We will treated the terminator as a token. if (right[i] == '(') { // Right now we do not allow nested paranthesis do { *current++ = right[i++]; } while(right[i]!=')' && right[i]); *current++ = right[i]; *current='\0'; char *params = strchr(work,'('); if (params) { *params = 0; params++; } else params = (char *) ")"; if (cl==0) { Error("DefinedVariable","Can not call '%s' with a class",work); return -1; } if (cl->GetClassInfo()==0 && !cl->GetCollectionProxy()) { Error("DefinedVariable","Class probably unavailable:%s",cl->GetName()); return -2; } if (!useCollectionObject && cl == TClonesArray::Class()) { // We are not interested in the ClonesArray object but only // in its contents. // We need to retrieve the class of its content. TBranch *clbranch = leaf->GetBranch(); R__LoadBranch(clbranch,readentry,fQuickLoad); TClonesArray * clones; if (previnfo) clones = (TClonesArray*)previnfo->GetLocalValuePointer(leaf,0); else { Bool_t top = (clbranch==((TBranchElement*)clbranch)->GetMother() || !leaf->IsOnTerminalBranch()); TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)clbranch)->GetInfo()->GetClass(); } TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(mother_cl, 0, top); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,clonesinfo,maininfo,kFALSE); previnfo = clonesinfo; maininfo = clonesinfo; clones = (TClonesArray*)clonesinfo->GetLocalValuePointer(leaf,0); } TClass * inside_cl = clones->GetClass(); cl = inside_cl; } else if (!useCollectionObject && cl && cl->GetCollectionProxy() ) { // We are NEVER (for now!) interested in the ClonesArray object but only // in its contents. // We need to retrieve the class of its content. if (previnfo==0) { Bool_t top = (branch==((TBranchElement*)branch)->GetMother() || !leaf->IsOnTerminalBranch()); TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)branch)->GetInfo()->GetClass(); } TFormLeafInfo* collectioninfo = new TFormLeafInfoCollection(mother_cl, 0,cl,top); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); previnfo = collectioninfo; maininfo = collectioninfo; } TClass * inside_cl = cl->GetCollectionProxy()->GetValueClass(); if (inside_cl) cl = inside_cl; else if (cl->GetCollectionProxy()->GetType()>0) { Warning("DefinedVariable","Can not call method on content of %s in %s\n", cl->GetName(),name.Data()); return -2; } } TMethodCall *method = 0; if (cl==0) { Error("DefinedVariable", "Could not discover the TClass corresponding to (%s)!", right); return -2; } else if (cl==TClonesArray::Class() && strcmp(work,"size")==0) { method = new TMethodCall(cl, "GetEntriesFast", ""); } else if (cl->GetCollectionProxy() && strcmp(work,"size")==0) { if (maininfo==0) { TFormLeafInfo* collectioninfo=0; if (useLeafCollectionObject) { Bool_t top = (branch==((TBranchElement*)branch)->GetMother() || !leaf->IsOnTerminalBranch()); collectioninfo = new TFormLeafInfoCollectionObject(cl,top); } maininfo=previnfo=collectioninfo; } leafinfo = new TFormLeafInfoCollectionSize(cl); cl = 0; } else { if (cl->GetClassInfo()==0) { Error("DefinedVariable", "Can not call method %s on class without dictionary (%s)!", right,cl->GetName()); return -2; } method = new TMethodCall(cl, work, params); } if (method) { if (!method->GetMethod()) { Error("DefinedVariable","Unknown method:%s in %s",right,cl->GetName()); return -1; } switch(method->ReturnType()) { case TMethodCall::kLong: leafinfo = new TFormLeafInfoMethod(cl,method); cl = 0; break; case TMethodCall::kDouble: leafinfo = new TFormLeafInfoMethod(cl,method); cl = 0; break; case TMethodCall::kString: leafinfo = new TFormLeafInfoMethod(cl,method); // 1 will be replaced by -1 when we know how to use strlen numberOfVarDim += RegisterDimensions(code,1); //NOTE: changed from 0 cl = 0; break; case TMethodCall::kOther: { TString return_type = gInterpreter->TypeName(method->GetMethod()->GetReturnTypeName()); leafinfo = new TFormLeafInfoMethod(cl,method); cl = (return_type == "void") ? 0 : TClass::GetClass(return_type.Data()); } break; default: Error("DefineVariable","Method %s from %s has an impossible return type %d", work,cl->GetName(),method->ReturnType()); return -2; } } if (maininfo==0) { maininfo = leafinfo; } if (previnfo==0) { previnfo = leafinfo; } else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = 0; current = &(work[0]); *current = 0; prevUseCollectionObject = kFALSE; prevUseReferenceObject = kFALSE; useCollectionObject = kFALSE; if (cl && cl->GetCollectionProxy()) { if (numberOfVarDim>1) { Warning("DefinedVariable","TTreeFormula support only 2 level of variables size collections. Assuming '@' notation for the collection %s.", cl->GetName()); leafinfo = new TFormLeafInfo(cl,0,0); useCollectionObject = kTRUE; } else if (numberOfVarDim==0) { R__ASSERT(maininfo); leafinfo = new TFormLeafInfoCollection(cl,0,cl); numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); } else if (numberOfVarDim==1) { R__ASSERT(maininfo); leafinfo = new TFormLeafInfoMultiVarDimCollection(cl,0, (TStreamerElement*)0,maininfo); previnfo->fNext = leafinfo; previnfo = leafinfo; leafinfo = new TFormLeafInfoCollection(cl,0,cl); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); } previnfo->fNext = leafinfo; previnfo = leafinfo; leafinfo = 0; } continue; } else if (right[i] == ')') { // We should have the end of a cast operator. Let's introduce a TFormLeafCast // in the chain. TClass * casted = (TClass*) ((int(--paran_level)>=0) ? castqueue.At(paran_level) : 0); if (casted) { leafinfo = new TFormLeafInfoCast(cl,casted); fHasCast = kTRUE; if (maininfo==0) { maininfo = leafinfo; } if (previnfo==0) { previnfo = leafinfo; } else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = 0; current = &(work[0]); *current = 0; cl = casted; continue; } } else if (i > 0 && (right[i] == '.' || right[i] == '[' || right[i] == '\0') ) { // A delimiter happened let's see if what we have seen // so far does point to a data member. Bool_t needClass = kTRUE; *current = '\0'; // skip it all if there is nothing to look at if (strlen(work)==0) continue; prevUseCollectionObject = useCollectionObject; prevUseReferenceObject = useReferenceObject; if (work[0]=='@') { useReferenceObject = kTRUE; useCollectionObject = kTRUE; Int_t l = 0; for(l=0;work[l+1]!=0;++l) work[l] = work[l+1]; work[l] = '\0'; } else if (work[strlen(work)-1]=='@') { useReferenceObject = kTRUE; useCollectionObject = kTRUE; work[strlen(work)-1] = '\0'; } else { useReferenceObject = kFALSE; useCollectionObject = kFALSE; } Bool_t mustderef = kFALSE; if ( !prevUseReferenceObject && cl && cl->GetReferenceProxy() ) { R__LoadBranch(leaf->GetBranch(), readentry, fQuickLoad); if ( !maininfo ) { maininfo = previnfo = new TFormLeafInfoReference(cl, element, offset); if ( cl->GetReferenceProxy()->HasCounter() ) { numberOfVarDim += RegisterDimensions(code,-1); } prevUseReferenceObject = kFALSE; } needClass = kFALSE; mustderef = kTRUE; } else if (!prevUseCollectionObject && cl == TClonesArray::Class()) { // We are not interested in the ClonesArray object but only // in its contents. // We need to retrieve the class of its content. TBranch *clbranch = leaf->GetBranch(); R__LoadBranch(clbranch,readentry,fQuickLoad); TClonesArray * clones; if (maininfo) { clones = (TClonesArray*)maininfo->GetValuePointer(leaf,0); } else { // we have a unsplit TClonesArray leaves // or we did not yet match any of the sub-branches! TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)clbranch)->GetInfo()->GetClass(); } TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(mother_cl, 0); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,clonesinfo,maininfo,kFALSE); mustderef = kTRUE; previnfo = clonesinfo; maininfo = clonesinfo; if (clbranch->GetListOfBranches()->GetLast()>=0) { if (clbranch->IsA() != TBranchElement::Class()) { Error("DefinedVariable","Unimplemented usage of ClonesArray"); return -2; } //clbranch = ((TBranchElement*)clbranch)->GetMother(); clones = (TClonesArray*)((TBranchElement*)clbranch)->GetObject(); } else clones = (TClonesArray*)clonesinfo->GetLocalValuePointer(leaf,0); } // NOTE clones can be zero! if (clones==0) { Warning("DefinedVariable", "TClonesArray object was not retrievable for %s!", name.Data()); return -1; } TClass * inside_cl = clones->GetClass(); #if 1 cl = inside_cl; #else /* Maybe we should make those test lead to warning messages */ if (1 || inside_cl) cl = inside_cl; // if inside_cl is nul ... we have a problem of inconsistency :( if (0 && strlen(work)==0) { // However in this case we have NO content :( // so let get the number of objects //strcpy(work,"fLast"); } #endif } else if (!prevUseCollectionObject && cl && cl->GetCollectionProxy() ) { // We are NEVER interested in the Collection object but only // in its contents. // We need to retrieve the class of its content. TBranch *clbranch = leaf->GetBranch(); R__LoadBranch(clbranch,readentry,fQuickLoad); if (maininfo==0) { // we have a unsplit Collection leaf // or we did not yet match any of the sub-branches! TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)clbranch)->GetInfo()->GetClass(); } TFormLeafInfo* collectioninfo = new TFormLeafInfoCollection(mother_cl, 0, cl); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); mustderef = kTRUE; previnfo = collectioninfo; maininfo = collectioninfo; } //else if (clbranch->GetStreamerType()==0) { //} TClass * inside_cl = cl->GetCollectionProxy()->GetValueClass(); if (!inside_cl && cl->GetCollectionProxy()->GetType() > 0) { Warning("DefinedVariable","No data member in content of %s in %s\n", cl->GetName(),name.Data()); } cl = inside_cl; // if inside_cl is nul ... we have a problem of inconsistency. } if (!cl) { Warning("DefinedVariable","Missing class for %s!",name.Data()); } else { element = ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(work,offset); } if (!element && !prevUseCollectionObject) { // We allow for looking for a data member inside a class inside // a TClonesArray without mentioning the TClonesArrays variable name TIter next( cl->GetStreamerInfo()->GetElements() ); TStreamerElement * curelem; while ((curelem = (TStreamerElement*)next())) { if (curelem->GetClassPointer() == TClonesArray::Class()) { Int_t clones_offset; ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(curelem->GetName(),clones_offset); TFormLeafInfo* clonesinfo = new TFormLeafInfo(cl, clones_offset, curelem); TClonesArray * clones; R__LoadBranch(leaf->GetBranch(),readentry,fQuickLoad); if (previnfo) { previnfo->fNext = clonesinfo; clones = (TClonesArray*)maininfo->GetValuePointer(leaf,0); previnfo->fNext = 0; } else { clones = (TClonesArray*)clonesinfo->GetLocalValuePointer(leaf,0); } TClass *sub_cl = clones->GetClass(); if (sub_cl) element = ((TStreamerInfo*)sub_cl->GetStreamerInfo())->GetStreamerElement(work,offset); delete clonesinfo; if (element) { leafinfo = new TFormLeafInfoClones(cl,clones_offset,curelem); numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); if (maininfo==0) maininfo = leafinfo; if (previnfo==0) previnfo = leafinfo; else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = 0; cl = sub_cl; break; } } else if (curelem->GetClassPointer() && curelem->GetClassPointer()->GetCollectionProxy()) { Int_t coll_offset; ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(curelem->GetName(),coll_offset); TClass *sub_cl = curelem->GetClassPointer()->GetCollectionProxy()->GetValueClass(); if (sub_cl) { element = ((TStreamerInfo*)sub_cl->GetStreamerInfo())->GetStreamerElement(work,offset); } if (element) { if (numberOfVarDim>1) { Warning("DefinedVariable","TTreeFormula support only 2 level of variables size collections. Assuming '@' notation for the collection %s.", curelem->GetName()); leafinfo = new TFormLeafInfo(cl,coll_offset,curelem); useCollectionObject = kTRUE; } else if (numberOfVarDim==1) { R__ASSERT(maininfo); leafinfo = new TFormLeafInfoMultiVarDimCollection(cl,coll_offset, curelem,maininfo); fHasMultipleVarDim[code] = kTRUE; leafinfo->fNext = new TFormLeafInfoCollection(cl,coll_offset,curelem); numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); } else { leafinfo = new TFormLeafInfoCollection(cl,coll_offset,curelem); numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); } if (maininfo==0) maininfo = leafinfo; if (previnfo==0) previnfo = leafinfo; else { previnfo->fNext = leafinfo; previnfo = leafinfo; } if (leafinfo->fNext) { previnfo = leafinfo->fNext; } leafinfo = 0; cl = sub_cl; break; } } } } if (element) { Int_t type = element->GetNewType(); if (type<60 && type!=0) { // This is a basic type ... if (numberOfVarDim>=1 && type>40) { // We have a variable array within a variable array! leafinfo = new TFormLeafInfoMultiVarDim(cl,offset,element,maininfo); fHasMultipleVarDim[code] = kTRUE; } else { if (leafinfo && type<=40 ) { leafinfo->AddOffset(offset,element); } else { leafinfo = new TFormLeafInfo(cl,offset,element); } } } else { Bool_t object = kFALSE; Bool_t pointer = kFALSE; Bool_t objarr = kFALSE; switch(type) { case TStreamerInfo::kObjectp: case TStreamerInfo::kObjectP: case TStreamerInfo::kSTLp: case TStreamerInfo::kAnyp: case TStreamerInfo::kAnyP: case TStreamerInfo::kOffsetL + TStreamerInfo::kObjectP: case TStreamerInfo::kOffsetL + TStreamerInfo::kSTLp: case TStreamerInfo::kOffsetL + TStreamerInfo::kAnyp: case TStreamerInfo::kOffsetL + TStreamerInfo::kObjectp: case TStreamerInfo::kOffsetL + TStreamerInfo::kAnyP: pointer = kTRUE; break; case TStreamerInfo::kBase: case TStreamerInfo::kAny : case TStreamerInfo::kSTL: case TStreamerInfo::kObject: case TStreamerInfo::kTString: case TStreamerInfo::kTNamed: case TStreamerInfo::kTObject: object = kTRUE; break; case TStreamerInfo::kOffsetL + TStreamerInfo::kAny: case TStreamerInfo::kOffsetL + TStreamerInfo::kSTL: case TStreamerInfo::kOffsetL + TStreamerInfo::kObject: objarr = kTRUE; break; case TStreamerInfo::kStreamer: case TStreamerInfo::kStreamLoop: // Unsupported case. Error("DefinedVariable", "%s is a datamember of %s BUT is not yet of a supported type (%d)", right,cl ? cl->GetName() : "unknown class",type); return -2; default: // Unknown and Unsupported case. Error("DefinedVariable", "%s is a datamember of %s BUT is not of a unknown type (%d)", right,cl ? cl->GetName() : "unknown class",type); return -2; } if (object && !useCollectionObject && ( element->GetClassPointer() == TClonesArray::Class() || element->GetClassPointer()->GetCollectionProxy() ) ) { object = kFALSE; } if (object && leafinfo) { leafinfo->AddOffset(offset,element); } else if (objarr) { // This is an embedded array of objects. We can not increase the offset. leafinfo = new TFormLeafInfo(cl,offset,element); mustderef = kTRUE; } else { if (!useCollectionObject && element->GetClassPointer() == TClonesArray::Class()) { leafinfo = new TFormLeafInfoClones(cl,offset,element); mustderef = kTRUE; } else if (!useCollectionObject && element->GetClassPointer() && element->GetClassPointer()->GetCollectionProxy()) { mustderef = kTRUE; if (numberOfVarDim>1) { Warning("DefinedVariable","TTreeFormula support only 2 level of variables size collections. Assuming '@' notation for the collection %s.", element->GetName()); leafinfo = new TFormLeafInfo(cl,offset,element); useCollectionObject = kTRUE; } else if (numberOfVarDim==1) { R__ASSERT(maininfo); leafinfo = new TFormLeafInfoMultiVarDimCollection(cl,offset,element,maininfo); fHasMultipleVarDim[code] = kTRUE; //numberOfVarDim += RegisterDimensions(code,leafinfo); //cl = cl->GetCollectionProxy()->GetValueClass(); //if (maininfo==0) maininfo = leafinfo; //if (previnfo==0) previnfo = leafinfo; //else { // previnfo->fNext = leafinfo; // previnfo = leafinfo; //} leafinfo->fNext = new TFormLeafInfoCollection(cl, offset, element); if (element->GetClassPointer()->GetCollectionProxy()->GetValueClass()==0) { TFormLeafInfo *info = new TFormLeafInfoNumerical( element->GetClassPointer()->GetCollectionProxy()); if (leafinfo->fNext) leafinfo->fNext->fNext = info; else leafinfo->fNext = info; } } else { leafinfo = new TFormLeafInfoCollection(cl, offset, element); TClass *elemCl = element->GetClassPointer(); TClass *valueCl = elemCl->GetCollectionProxy()->GetValueClass(); if (!maininfo) maininfo = leafinfo; if (valueCl!=0 && valueCl->GetCollectionProxy()!=0) { numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); if (previnfo==0) previnfo = leafinfo; else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = new TFormLeafInfoMultiVarDimCollection(elemCl,0, elemCl->GetCollectionProxy()->GetValueClass(),maininfo); //numberOfVarDim += RegisterDimensions(code,previnfo->fNext); fHasMultipleVarDim[code] = kTRUE; //previnfo = previnfo->fNext; leafinfo->fNext = new TFormLeafInfoCollection(elemCl,0, valueCl); elemCl = valueCl; } if (elemCl->GetCollectionProxy() && elemCl->GetCollectionProxy()->GetValueClass()==0) { TFormLeafInfo *info = new TFormLeafInfoNumerical(elemCl->GetCollectionProxy()); if (leafinfo->fNext) leafinfo->fNext->fNext = info; else leafinfo->fNext = info; } } } else if ( (object || pointer) && !useReferenceObject && element->GetClassPointer()->GetReferenceProxy() ) { TClass* c = element->GetClassPointer(); R__LoadBranch(leaf->GetBranch(),readentry,fQuickLoad); if ( object ) { leafinfo = new TFormLeafInfoReference(c, element, offset); } else { leafinfo = new TFormLeafInfoPointer(cl,offset,element); leafinfo->fNext = new TFormLeafInfoReference(c, element, 0); } //if ( c->GetReferenceProxy()->HasCounter() ) { // numberOfVarDim += RegisterDimensions(code,-1); //} prevUseReferenceObject = kFALSE; needClass = kFALSE; mustderef = kTRUE; } else if (pointer) { // this is a pointer to be followed. leafinfo = new TFormLeafInfoPointer(cl,offset,element); mustderef = kTRUE; } else { // this is an embedded object. R__ASSERT(object); leafinfo = new TFormLeafInfo(cl,offset,element); } } } } else { if (cl) Error("DefinedVariable","%s is not a datamember of %s",work,cl->GetName()); // no else, we warned earlier that the class was missing. return -1; } numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,useCollectionObject); // Note or useCollectionObject||prevUseColectionObject if (maininfo==0) { maininfo = leafinfo; } if (previnfo==0) { previnfo = leafinfo; } else if (previnfo!=leafinfo) { previnfo->fNext = leafinfo; previnfo = leafinfo; } while (previnfo->fNext) previnfo = previnfo->fNext; if ( right[i] != '\0' ) { if ( !needClass && mustderef ) { maininfo->SetBranch(leaf->GetBranch()); char *ptr = (char*)maininfo->GetValuePointer(leaf,0); TFormLeafInfoReference* refInfo = 0; if ( !maininfo->IsReference() ) { for( TFormLeafInfo* inf = maininfo->fNext; inf; inf = inf->fNext ) { if ( inf->IsReference() ) { refInfo = (TFormLeafInfoReference*)inf; } } } else { refInfo = (TFormLeafInfoReference*)maininfo; } if ( refInfo ) { cl = refInfo->GetValueClass(ptr); if ( !cl ) { Error("DefinedVariable","Failed to access class type of reference target (%s)",element->GetName()); return -1; } element = ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(work,offset); } else { Error("DefinedVariable","Failed to access class type of reference target (%s)",element->GetName()); return -1; } } else if ( needClass ) { cl = element->GetClassPointer(); } } if (mustderef) leafinfo = 0; current = &(work[0]); *current = 0; R__ASSERT(right[i] != '['); // We are supposed to have removed all dimensions already! } else *current++ = right[i]; } if (maininfo) { fDataMembers.AddAtAndExpand(maininfo,code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } } if (strlen(work)!=0) { // We have something left to analyze. Let's make this an error case! return -1; } TClass *objClass = EvalClass(code); if (objClass && !useLeafCollectionObject && objClass->GetCollectionProxy() && objClass->GetCollectionProxy()->GetValueClass()) { TFormLeafInfo *last = 0; if ( SwitchToFormLeafInfo(code) ) { last = (TFormLeafInfo*)fDataMembers.At(code); if (!last) return action; while (last->fNext) { last = last->fNext; } } if (last && last->GetClass() != objClass) { TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)branch)->GetInfo()->GetClass(); } TFormLeafInfo* collectioninfo = new TFormLeafInfoCollection(mother_cl, 0, objClass, kFALSE); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); last->fNext = collectioninfo; } numberOfVarDim += RegisterDimensions(code,1); //NOTE: changed from 0 objClass = objClass->GetCollectionProxy()->GetValueClass(); } if (IsLeafString(code) || objClass == TString::Class() || objClass == stdStringClass) { TFormLeafInfo *last = 0; if ( SwitchToFormLeafInfo(code) ) { last = (TFormLeafInfo*)fDataMembers.At(code); if (!last) return action; while (last->fNext) { last = last->fNext; } } const char *funcname = 0; if (objClass == TString::Class()) { funcname = "Data"; //tobetested: numberOfVarDim += RegisterDimensions(code,1,0); // Register the dim of the implied char* } else if (objClass == stdStringClass) { funcname = "c_str"; //tobetested: numberOfVarDim += RegisterDimensions(code,1,0); // Register the dim of the implied char* } if (funcname) { TMethodCall *method = new TMethodCall(objClass, funcname, ""); if (last) { last->fNext = new TFormLeafInfoMethod(objClass,method); } else { fDataMembers.AddAtAndExpand(new TFormLeafInfoMethod(objClass,method),code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } } return kDefinedString; } if (objClass) { TMethodCall *method = new TMethodCall(objClass, "AsDouble", ""); if (method->IsValid() && (method->ReturnType() == TMethodCall::kLong || method->ReturnType() == TMethodCall::kDouble)) { TFormLeafInfo *last = 0; if (SwitchToFormLeafInfo(code)) { last = (TFormLeafInfo*)fDataMembers.At(code); // Improbable case if (!last) { delete method; return action; } while (last->fNext) { last = last->fNext; } } if (last) { last->fNext = new TFormLeafInfoMethod(objClass,method); } else { fDataMembers.AddAtAndExpand(new TFormLeafInfoMethod(objClass,method),code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } return kDefinedVariable; } delete method; method = new TMethodCall(objClass, "AsString", ""); if (method->IsValid() && method->ReturnType() == TMethodCall::kString) { TFormLeafInfo *last = 0; if (SwitchToFormLeafInfo(code)) { last = (TFormLeafInfo*)fDataMembers.At(code); // Improbable case if (!last) { delete method; return action; } while (last->fNext) { last = last->fNext; } } if (last) { last->fNext = new TFormLeafInfoMethod(objClass,method); } else { fDataMembers.AddAtAndExpand(new TFormLeafInfoMethod(objClass,method),code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } //tobetested: numberOfVarDim += RegisterDimensions(code,1,0); // Register the dim of the implied char* return kDefinedString; } if (method->IsValid() && method->ReturnType() == TMethodCall::kOther) { TClass *rcl = 0; TFunction *f = method->GetMethod(); if (f) rcl = TClass::GetClass(gInterpreter->TypeName(f->GetReturnTypeName())); if ((rcl == TString::Class() || rcl == stdStringClass) ) { TFormLeafInfo *last = 0; if (SwitchToFormLeafInfo(code)) { last = (TFormLeafInfo*)fDataMembers.At(code); // Improbable case if (!last) { delete method; return action; } while (last->fNext) { last = last->fNext; } } if (last) { last->fNext = new TFormLeafInfoMethod(objClass,method); last = last->fNext; } else { last = new TFormLeafInfoMethod(objClass,method); fDataMembers.AddAtAndExpand(last,code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } objClass = rcl; const char *funcname = 0; if (objClass == TString::Class()) { funcname = "Data"; } else if (objClass == stdStringClass) { funcname = "c_str"; } if (funcname) { method = new TMethodCall(objClass, funcname, ""); last->fNext = new TFormLeafInfoMethod(objClass,method); } return kDefinedString; } } delete method; } return action; } //______________________________________________________________________________ Int_t TTreeFormula::FindLeafForExpression(const char* expression, TLeaf*& leaf, TString& leftover, Bool_t& final, UInt_t& paran_level, TObjArray& castqueue, std::vector<std::string>& aliasUsed, Bool_t& useLeafCollectionObject, const char* fullExpression) { // Look for the leaf corresponding to the start of expression. // It returns the corresponding leaf if any. // It also modify the following arguments: // leftover: contain from expression that was not used to determine the leaf // final: // paran_level: number of un-matched open parenthesis // cast_queue: list of cast to be done // aliases: list of aliases used // Return <0 in case of failure // Return 0 if a leaf has been found // Return 2 if info about the TTree itself has been requested. // Later on we will need to read one entry, let's make sure // it is a real entry. if (fTree->GetTree()==0) { fTree->LoadTree(0); if (fTree->GetTree()==0) return -1; } Long64_t readentry = fTree->GetTree()->GetReadEntry(); if (readentry==-1) readentry=0; const char *cname = expression; char first[kMaxLen]; first[0] = '\0'; char second[kMaxLen]; second[0] = '\0'; char right[kMaxLen]; right[0] = '\0'; char work[kMaxLen]; work[0] = '\0'; char left[kMaxLen]; left[0] = '\0'; char scratch[kMaxLen]; char scratch2[kMaxLen]; std::string currentname; Int_t previousdot = 0; char *current; TLeaf *tmp_leaf=0; TBranch *branch=0, *tmp_branch=0; Int_t nchname = strlen(cname); Int_t i; Bool_t foundAtSign = kFALSE; for (i=0, current = &(work[0]); i<=nchname && !final;i++ ) { // We will treated the terminator as a token. *current++ = cname[i]; if (cname[i] == '(') { ++paran_level; if (current==work+1) { // If the expression starts with a paranthesis, we are likely // to have a cast operator inside. current--; } continue; //i++; //while( cname[i]!=')' && cname[i] ) { // *current++ = cname[i++]; //} //*current++ = cname[i]; ////*current = 0; //continue; } if (cname[i] == ')') { if (paran_level==0) { Error("DefinedVariable","Unmatched paranthesis in %s",fullExpression); return -1; } // Let's see if work is a classname. *(--current) = 0; paran_level--; TString cast_name = gInterpreter->TypeName(work); TClass *cast_cl = TClass::GetClass(cast_name); if (cast_cl) { // We must have a cast castqueue.AddAtAndExpand(cast_cl,paran_level); current = &(work[0]); *current = 0; // Warning("DefinedVariable","Found cast to %s",cast_fullExpression); continue; } else if (gROOT->GetType(cast_name)) { // We reset work current = &(work[0]); *current = 0; Warning("DefinedVariable", "Casting to primary types like \"%s\" is not supported yet",cast_name.Data()); continue; } *(current++)=')'; *current='\0'; char *params = strchr(work,'('); if (params) { *params = 0; params++; if (branch && !leaf) { // We have a branch but not a leaf. We are likely to have found // the top of split branch. if (BranchHasMethod(0, branch, work, params, readentry)) { //fprintf(stderr, "Does have a method %s for %s.\n", work, branch->GetName()); } } // What we have so far might be a member function of one of the // leaves that are not splitted (for example "GetNtrack" for the Event class). TIter next(fTree->GetIteratorOnAllLeaves()); TLeaf* leafcur = 0; while (!leaf && (leafcur = (TLeaf*) next())) { TBranch* br = leafcur->GetBranch(); Bool_t yes = BranchHasMethod(leafcur, br, work, params, readentry); if (yes) { leaf = leafcur; //fprintf(stderr, "Does have a method %s for %s found in leafcur %s.\n", work, leafcur->GetBranch()->GetName(), leafcur->GetName()); } } if (!leaf) { // Check for an alias. if (strlen(left) && left[strlen(left)-1]=='.') left[strlen(left)-1]=0; const char *aliasValue = fTree->GetAlias(left); if (aliasValue && strcspn(aliasValue,"+*/-%&!=<>|")==strlen(aliasValue)) { // First check whether we are using this alias recursively (this would // lead to an infinite recursion. if (find(aliasUsed.begin(), aliasUsed.end(), left) != aliasUsed.end()) { Error("DefinedVariable", "The substitution of the branch alias \"%s\" by \"%s\" in \"%s\" failed\n"\ "\tbecause \"%s\" is used [recursively] in its own definition!", left,aliasValue,fullExpression,left); return -3; } aliasUsed.push_back(left); TString newExpression = aliasValue; newExpression += (cname+strlen(left)); Int_t res = FindLeafForExpression(newExpression, leaf, leftover, final, paran_level, castqueue, aliasUsed, useLeafCollectionObject, fullExpression); if (res<0) { Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed.",left,aliasValue); return -3; } return res; } // This is actually not really any error, we probably received something // like "abs(some_val)", let TFormula decompose it first. return -1; } // if (!leaf->InheritsFrom(TLeafObject::Class()) ) { // If the leaf that we found so far is not a TLeafObject then there is // nothing we would be able to do. // Error("DefinedVariable","Need a TLeafObject to call a function!"); // return -1; //} // We need to recover the info not used. strlcpy(right,work,kMaxLen); strncat(right,"(",kMaxLen-1-strlen(right)); strncat(right,params,kMaxLen-1-strlen(right)); final = kTRUE; // we reset work current = &(work[0]); *current = 0; break; } } if (cname[i] == '.' || cname[i] == '\0' || cname[i] == ')') { // A delimiter happened let's see if what we have seen // so far does point to a leaf. *current = '\0'; Int_t len = strlen(work); if (work[0]=='@') { foundAtSign = kTRUE; Int_t l = 0; for(l=0;work[l+1]!=0;++l) work[l] = work[l+1]; work[l] = '\0'; --current; } else if (len>=2 && work[len-2]=='@') { foundAtSign = kTRUE; work[len-2] = cname[i]; work[len-1] = '\0'; --current; } else { foundAtSign = kFALSE; } if (left[0]==0) strlcpy(left,work,kMaxLen); if (!leaf && !branch) { // So far, we have not found a matching leaf or branch. strlcpy(first,work,kMaxLen); std::string treename(first); if (treename.size() && treename[treename.size()-1]=='.') { treename.erase(treename.size()-1); } if (treename== "This" /* || treename == fTree->GetName() */ ) { // Request info about the TTree object itself, TNamed *named = new TNamed(fTree->GetName(),fTree->GetName()); fLeafNames.AddAtAndExpand(named,fNcodes); fLeaves.AddAtAndExpand(fTree,fNcodes); if (cname[i]) leftover = &(cname[i+1]); return 2; } // The following would allow to access the friend by name // however, it would also prevent the access of the leaves // within the friend. We could use the '@' notation here // however this would not be aesthetically pleasing :( // What we need to do, is add the ability to look ahead to // the next 'token' to decide whether we to access the tree // or its leaf. //} else { // TTree *tfriend = fTree->GetFriend(treename.c_str()); // TTree *realtree = fTree->GetTree(); // if (!tfriend && realtree != fTree){ // // If it is a chain and we did not find a friend, // // let's try with the internal tree. // tfriend = realtree->GetFriend(treename.c_str()); // } // if (tfriend) { // TNamed *named = new TNamed(treename.c_str(),tfriend->GetName()); // fLeafNames.AddAtAndExpand(named,fNcodes); // fLeaves.AddAtAndExpand(tfriend,fNcodes); // if (cname[i]) leftover = &(cname[i+1]); // return 2; // } //} branch = fTree->FindBranch(first); leaf = fTree->FindLeaf(first); // Now look with the delimiter removed (we looked with it first // because a dot is allowed at the end of some branches). if (cname[i]) first[strlen(first)-1]='\0'; if (!branch) branch = fTree->FindBranch(first); if (!leaf) leaf = fTree->FindLeaf(first); TClass* cl = 0; if ( branch && branch->InheritsFrom(TBranchElement::Class()) ) { int offset=0; TBranchElement* bElt = (TBranchElement*)branch; TStreamerInfo* info = bElt->GetInfo(); TStreamerElement* element = info ? info->GetStreamerElement(first,offset) : 0; if (element) cl = element->GetClassPointer(); if ( cl && !cl->GetReferenceProxy() ) cl = 0; } if ( cl ) { // We have a reference class here.... final = kTRUE; useLeafCollectionObject = foundAtSign; // we reset work current = &(work[0]); *current = 0; } else if (branch && (foundAtSign || cname[i] != 0) ) { // Since we found a branch and there is more information in the name, // we do NOT look at the 'IsOnTerminalBranch' status of the leaf // we found ... yet! if (leaf==0) { // Note we do not know (yet?) what (if anything) to do // for a TBranchObject branch. if (branch->InheritsFrom(TBranchElement::Class()) ) { Int_t type = ((TBranchElement*)branch)->GetType(); if ( type == 3 || type ==4) { // We have a Collection branch. leaf = (TLeaf*)branch->GetListOfLeaves()->At(0); if (foundAtSign) { useLeafCollectionObject = foundAtSign; foundAtSign = kFALSE; current = &(work[0]); *current = 0; ++i; break; } } } } // we reset work useLeafCollectionObject = foundAtSign; foundAtSign = kFALSE; current = &(work[0]); *current = 0; } else if (leaf || branch) { if (leaf && branch) { // We found both a leaf and branch matching the request name // let's see which one is the proper one to use! (On annoying case // is that where the same name is repeated ( varname.varname ) // We always give priority to the branch // leaf = 0; } if (leaf && leaf->IsOnTerminalBranch()) { // This is a non-object leaf, it should NOT be specified more except for // dimensions. final = kTRUE; } // we reset work current = &(work[0]); *current = 0; } else { // What we have so far might be a data member of one of the // leaves that are not splitted (for example "fNtrack" for the Event class. TLeaf *leafcur = GetLeafWithDatamember(first,work,readentry); if (leafcur) { leaf = leafcur; branch = leaf->GetBranch(); if (leaf->IsOnTerminalBranch()) { final = kTRUE; strlcpy(right,first,kMaxLen); //We need to put the delimiter back! if (foundAtSign) strncat(right,"@",kMaxLen-1-strlen(right)); if (cname[i]=='.') strncat(right,".",kMaxLen-1-strlen(right)); // We reset work current = &(work[0]); *current = 0; }; } else if (cname[i] == '.') { // If we have a branch that match a name preceded by a dot // then we assume we are trying to drill down the branch // Let look if one of the top level branch has a branch with the name // we are looking for. TBranch *branchcur; TIter next( fTree->GetListOfBranches() ); while(!branch && (branchcur=(TBranch*)next()) ) { branch = branchcur->FindBranch(first); } if (branch) { // We reset work current = &(work[0]); *current = 0; } } } } else { // correspond to if (leaf || branch) if (final) { Error("DefinedVariable", "Unexpected control flow!"); return -1; } // No dot is allowed in subbranches and leaves, so // we always remove it in the present case. if (cname[i]) work[strlen(work)-1] = '\0'; snprintf(scratch,sizeof(scratch),"%s.%s",first,work); snprintf(scratch2,sizeof(scratch2),"%s.%s.%s",first,second,work); if (previousdot) { currentname = &(work[previousdot+1]); } // First look for the current 'word' in the list of // leaf of the if (branch) { tmp_leaf = branch->FindLeaf(work); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(scratch); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(scratch2); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(currentname.c_str()); } if (tmp_leaf && tmp_leaf->IsOnTerminalBranch() ) { // This is a non-object leaf, it should NOT be specified more except for // dimensions. final = kTRUE; } if (branch) { tmp_branch = branch->FindBranch(work); if (!tmp_branch) tmp_branch = branch->FindBranch(scratch); if (!tmp_branch) tmp_branch = branch->FindBranch(scratch2); if (!tmp_branch) tmp_branch = branch->FindBranch(currentname.c_str()); } if (tmp_branch) { branch=tmp_branch; // NOTE: Should we look for a leaf within here? if (!final) { tmp_leaf = branch->FindLeaf(work); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(scratch); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(scratch2); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(currentname.c_str()); if (tmp_leaf && tmp_leaf->IsOnTerminalBranch() ) { // This is a non-object leaf, it should NOT be specified // more except for dimensions. final = kTRUE; leaf = tmp_leaf; } } } if (tmp_leaf) { // Something was found. if (second[0]) strncat(second,".",kMaxLen-1-strlen(second)); strncat(second,work,kMaxLen-1-strlen(second)); leaf = tmp_leaf; useLeafCollectionObject = foundAtSign; foundAtSign = kFALSE; // we reset work current = &(work[0]); *current = 0; } else { //We need to put the delimiter back! if (strlen(work)) { if (foundAtSign) { Int_t where = strlen(work); work[where] = '@'; work[where+1] = cname[i]; ++current; previousdot = where+1; } else { previousdot = strlen(work); work[strlen(work)] = cname[i]; } } else --current; } } } } // Copy the left over for later use. if (strlen(work)) { strncat(right,work,kMaxLen-1-strlen(right)); } if (i<nchname) { if (strlen(right) && right[strlen(right)-1]!='.' && cname[i]!='.') { // In some cases we remove a little to fast the period, we add // it back if we need. It is assumed that 'right' and the rest of // the name was cut by a delimiter, so this should be safe. strncat(right,".",kMaxLen-1-strlen(right)); } strncat(right,&cname[i],kMaxLen-1-strlen(right)); } if (!final && branch) { if (!leaf) { leaf = (TLeaf*)branch->GetListOfLeaves()->UncheckedAt(0); if (!leaf) return -1; } final = leaf->IsOnTerminalBranch(); } if (leaf && leaf->InheritsFrom(TLeafObject::Class()) ) { if (strlen(right)==0) strlcpy(right,work,kMaxLen); } if (leaf==0 && left[0]!=0) { if (left[strlen(left)-1]=='.') left[strlen(left)-1]=0; // Check for an alias. const char *aliasValue = fTree->GetAlias(left); if (aliasValue && strcspn(aliasValue,"[]+*/-%&!=<>|")==strlen(aliasValue)) { // First check whether we are using this alias recursively (this would // lead to an infinite recursion). if (find(aliasUsed.begin(), aliasUsed.end(), left) != aliasUsed.end()) { Error("DefinedVariable", "The substitution of the branch alias \"%s\" by \"%s\" in \"%s\" failed\n"\ "\tbecause \"%s\" is used [recursively] in its own definition!", left,aliasValue,fullExpression,left); return -3; } aliasUsed.push_back(left); TString newExpression = aliasValue; newExpression += (cname+strlen(left)); Int_t res = FindLeafForExpression(newExpression, leaf, leftover, final, paran_level, castqueue, aliasUsed, useLeafCollectionObject, fullExpression); if (res<0) { Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed.",left,aliasValue); return -3; } return res; } } leftover = right; return 0; } //______________________________________________________________________________ Int_t TTreeFormula::DefinedVariable(TString &name, Int_t &action) { //*-*-*-*-*-*Check if name is in the list of Tree/Branch leaves*-*-*-*-* //*-* ================================================== // // This member function redefines the function in TFormula // If a leaf has a name corresponding to the argument name, then // returns a new code. // A TTreeFormula may contain more than one variable. // For each variable referenced, the pointers to the corresponding // branch and leaf is stored in the object arrays fBranches and fLeaves. // // name can be : // - Leaf_Name (simple variable or data member of a ClonesArray) // - Branch_Name.Leaf_Name // - Branch_Name.Method_Name // - Leaf_Name[index] // - Branch_Name.Leaf_Name[index] // - Branch_Name.Leaf_Name[index1] // - Branch_Name.Leaf_Name[][index2] // - Branch_Name.Leaf_Name[index1][index2] // New additions: // - Branch_Name.Leaf_Name[OtherLeaf_Name] // - Branch_Name.Datamember_Name // - '.' can be replaced by '->' // and // - Branch_Name[index1].Leaf_Name[index2] // - Leaf_name[index].Action().OtherAction(param) // - Leaf_name[index].Action()[val].OtherAction(param) // // The expected returns values are // -2 : the name has been recognized but won't be usable // -1 : the name has not been recognized // >=0 : the name has been recognized, return the internal code for this name. // action = kDefinedVariable; if (!fTree) return -1; fNpar = 0; if (name.Length() > kMaxLen) return -1; Int_t i,k; if (name == "Entry$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kIndexOfEntry; return code; } if (name == "LocalEntry$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kIndexOfLocalEntry; return code; } if (name == "Entries$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kEntries; SetBit(kNeedEntries); fManager->SetBit(kNeedEntries); return code; } if (name == "Iteration$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kIteration; return code; } if (name == "Length$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kLength; return code; } static const char *lenfunc = "Length$("; if (strncmp(name.Data(),"Length$(",strlen(lenfunc))==0 && name[name.Length()-1]==')') { TString subform = name.Data()+strlen(lenfunc); subform.Remove( subform.Length() - 1 ); TTreeFormula *lengthForm = new TTreeFormula("lengthForm",subform,fTree); fAliases.AddAtAndExpand(lengthForm,fNoper); Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kLengthFunc; return code; } static const char *minfunc = "Min$("; if (strncmp(name.Data(),"Min$(",strlen(minfunc))==0 && name[name.Length()-1]==')') { TString subform = name.Data()+strlen(minfunc); subform.Remove( subform.Length() - 1 ); TTreeFormula *minForm = new TTreeFormula("minForm",subform,fTree); fAliases.AddAtAndExpand(minForm,fNoper); Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kMin; return code; } static const char *maxfunc = "Max$("; if (strncmp(name.Data(),"Max$(",strlen(maxfunc))==0 && name[name.Length()-1]==')') { TString subform = name.Data()+strlen(maxfunc); subform.Remove( subform.Length() - 1 ); TTreeFormula *maxForm = new TTreeFormula("maxForm",subform,fTree); fAliases.AddAtAndExpand(maxForm,fNoper); Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kMax; return code; } static const char *sumfunc = "Sum$("; if (strncmp(name.Data(),"Sum$(",strlen(sumfunc))==0 && name[name.Length()-1]==')') { TString subform = name.Data()+strlen(sumfunc); subform.Remove( subform.Length() - 1 ); TTreeFormula *sumForm = new TTreeFormula("sumForm",subform,fTree); fAliases.AddAtAndExpand(sumForm,fNoper); Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kSum; return code; } // Check for $Alt(expression1,expression2) Int_t res = DefineAlternate(name.Data()); if (res!=0) { // There was either a syntax error or we found $Alt if (res<0) return res; action = res; return 0; } // Find the top level leaf and deal with dimensions char cname[kMaxLen]; strlcpy(cname,name.Data(),kMaxLen); char dims[kMaxLen]; dims[0] = '\0'; Bool_t final = kFALSE; UInt_t paran_level = 0; TObjArray castqueue; // First, it is easier to remove all dimensions information from 'cname' Int_t cnamelen = strlen(cname); for(i=0,k=0; i<cnamelen; ++i, ++k) { if (cname[i] == '[') { int bracket = i; int bracket_level = 1; int j; for (j=++i; j<cnamelen && (bracket_level>0 || cname[j]=='['); j++, i++) { if (cname[j]=='[') bracket_level++; else if (cname[j]==']') bracket_level--; } if (bracket_level != 0) { //Error("DefinedVariable","Bracket unbalanced"); return -1; } strncat(dims,&cname[bracket],j-bracket); //k += j-bracket; } if (i!=k) cname[k] = cname[i]; } cname[k]='\0'; Bool_t useLeafCollectionObject = kFALSE; TString leftover; TLeaf *leaf = 0; { std::vector<std::string> aliasSofar = fAliasesUsed; res = FindLeafForExpression(cname, leaf, leftover, final, paran_level, castqueue, aliasSofar, useLeafCollectionObject, name); } if (res<0) return res; if (!leaf && res!=2) { // Check for an alias. const char *aliasValue = fTree->GetAlias(cname); if (aliasValue) { // First check whether we are using this alias recursively (this would // lead to an infinite recursion. if (find(fAliasesUsed.begin(), fAliasesUsed.end(), cname) != fAliasesUsed.end()) { Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed\n"\ "\tbecause \"%s\" is recursively used in its own definition!", cname,aliasValue,cname); return -3; } if (strcspn(aliasValue,"+*/-%&!=<>|")!=strlen(aliasValue)) { // If the alias contains an operator, we need to use a nested formula // (since DefinedVariable must only add one entry to the operation's list). // Need to check the aliases used so far std::vector<std::string> aliasSofar = fAliasesUsed; aliasSofar.push_back( cname ); TString subValue( aliasValue ); if (dims[0]) { subValue += dims; } TTreeFormula *subform = new TTreeFormula(cname,subValue,fTree,aliasSofar); // Need to pass the aliases used so far. if (subform->GetNdim()==0) { delete subform; Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed.",cname,aliasValue); return -3; } fManager->Add(subform); fAliases.AddAtAndExpand(subform,fNoper); if (subform->IsString()) { action = kAliasString; return 0; } else { action = kAlias; return 0; } } else { /* assumes strcspn(aliasValue,"[]")!=strlen(aliasValue) */ TString thisAlias( aliasValue ); thisAlias += dims; Int_t aliasRes = DefinedVariable(thisAlias,action); if (aliasRes<0) { // We failed but DefinedVariable has not printed why yet. // and because we want thoses to be printed _before_ the notice // of the failure of the substitution, we need to print them here. if (aliasRes==-1) { Error("Compile", " Bad numerical expression : \"%s\"",thisAlias.Data()); } else if (aliasRes==-2) { Error("Compile", " Part of the Variable \"%s\" exists but some of it is not accessible or useable",thisAlias.Data()); } Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed.",cname,aliasValue); return -3; } return aliasRes; } } } if (leaf || res==2) { if (leaf && leaf->GetBranch() && leaf->GetBranch()->TestBit(kDoNotProcess)) { Error("DefinedVariable","the branch \"%s\" has to be enabled to be used",leaf->GetBranch()->GetName()); return -2; } Int_t code = fNcodes++; // If needed will now parse the indexes specified for // arrays. if (dims[0]) { char *current = &( dims[0] ); Int_t dim = 0; TString varindex; Int_t index; Int_t scanindex ; while (current) { current++; if (current[0] == ']') { fIndexes[code][dim] = -1; // Loop over all elements; } else { scanindex = sscanf(current,"%d",&index); if (scanindex) { fIndexes[code][dim] = index; } else { fIndexes[code][dim] = -2; // Index is calculated via a variable. varindex = current; char *end = (char*)(varindex.Data()); for(char bracket_level = 0;*end!=0;end++) { if (*end=='[') bracket_level++; if (bracket_level==0 && *end==']') break; if (*end==']') bracket_level--; } *end = '\0'; fVarIndexes[code][dim] = new TTreeFormula("index_var", varindex, fTree); current += strlen(varindex)+1; // move to the end of the index array } } dim ++; if (dim >= kMAXFORMDIM) { // NOTE: test that dim this is NOT too big!! break; } current = (char*)strstr( current, "[" ); } } // Now that we have cleaned-up the expression, let's compare it to the content // of the leaf! res = ParseWithLeaf(leaf,leftover,final,paran_level,castqueue,useLeafCollectionObject,name); if (res<0) return res; if (res>0) action = res; return code; } //*-*- May be a graphical cut ? TCutG *gcut = (TCutG*)gROOT->GetListOfSpecials()->FindObject(name.Data()); if (gcut) { if (gcut->GetObjectX()) { if(!gcut->GetObjectX()->InheritsFrom(TTreeFormula::Class())) { delete gcut->GetObjectX(); gcut->SetObjectX(0); } } if (gcut->GetObjectY()) { if(!gcut->GetObjectY()->InheritsFrom(TTreeFormula::Class())) { delete gcut->GetObjectY(); gcut->SetObjectY(0); } } Int_t code = fNcodes; if (strlen(gcut->GetVarX()) && strlen(gcut->GetVarY()) ) { TTreeFormula *fx = new TTreeFormula("f_x",gcut->GetVarX(),fTree); gcut->SetObjectX(fx); TTreeFormula *fy = new TTreeFormula("f_y",gcut->GetVarY(),fTree); gcut->SetObjectY(fy); fCodes[code] = -2; } else if (strlen(gcut->GetVarX())) { // Let's build the equivalent formula: // min(gcut->X) <= VarX <= max(gcut->Y) Double_t min = 0; Double_t max = 0; Int_t n = gcut->GetN(); Double_t *x = gcut->GetX(); min = max = x[0]; for(Int_t i2 = 1; i2<n; i2++) { if (x[i2] < min) min = x[i2]; if (x[i2] > max) max = x[i2]; } TString formula = "("; formula += min; formula += "<="; formula += gcut->GetVarX(); formula += " && "; formula += gcut->GetVarX(); formula += "<="; formula += max; formula += ")"; TTreeFormula *fx = new TTreeFormula("f_x",formula.Data(),fTree); gcut->SetObjectX(fx); fCodes[code] = -1; } else { Error("DefinedVariable","Found a TCutG without leaf information (%s)", gcut->GetName()); return -1; } fExternalCuts.AddAtAndExpand(gcut,code); fNcodes++; fLookupType[code] = -1; return code; } //may be an entrylist TEntryList *elist = dynamic_cast<TEntryList*> (gDirectory->Get(name.Data())); if (elist) { Int_t code = fNcodes; fCodes[code] = 0; fExternalCuts.AddAtAndExpand(elist, code); fNcodes++; fLookupType[code] = kEntryList; return code; } return -1; } //______________________________________________________________________________ TLeaf* TTreeFormula::GetLeafWithDatamember(const char* topchoice, const char* nextchoice, Long64_t readentry) const { // Return the leaf (if any) which contains an object containing // a data member which has the name provided in the arguments. TClass * cl = 0; TIter nextleaf (fTree->GetIteratorOnAllLeaves()); TFormLeafInfo* clonesinfo = 0; TLeaf *leafcur; while ((leafcur = (TLeaf*)nextleaf())) { // The following code is used somewhere else, we need to factor it out. // Here since we are interested in data member, we want to consider only // 'terminal' branch and leaf. cl = 0; if (leafcur->InheritsFrom(TLeafObject::Class()) && leafcur->GetBranch()->GetListOfBranches()->Last()==0) { TLeafObject *lobj = (TLeafObject*)leafcur; cl = lobj->GetClass(); } else if (leafcur->InheritsFrom(TLeafElement::Class()) && leafcur->IsOnTerminalBranch()) { TLeafElement * lElem = (TLeafElement*) leafcur; if (lElem->IsOnTerminalBranch()) { TBranchElement *branchEl = (TBranchElement *)leafcur->GetBranch(); Int_t type = branchEl->GetStreamerType(); if (type==-1) { cl = branchEl->GetInfo()->GetClass(); } else if (type>60 || type==0) { // Case of an object data member. Here we allow for the // variable name to be ommitted. Eg, for Event.root with split // level 1 or above Draw("GetXaxis") is the same as Draw("fH.GetXaxis()") TStreamerElement* element = (TStreamerElement*) branchEl->GetInfo()->GetElems()[branchEl->GetID()]; if (element) cl = element->GetClassPointer(); else cl = 0; } } } if (clonesinfo) { delete clonesinfo; clonesinfo = 0; } if (cl == TClonesArray::Class()) { // We have a unsplit TClonesArray leaves // In this case we assume that cl is the class in which the TClonesArray // belongs. R__LoadBranch(leafcur->GetBranch(),readentry,fQuickLoad); TClonesArray * clones; TBranch *branch = leafcur->GetBranch(); if ( branch->IsA()==TBranchElement::Class() && ((TBranchElement*)branch)->GetType()==31) { // We have an unsplit TClonesArray as part of a split TClonesArray! // Let's not dig any further. If the user really wants a data member // inside the nested TClonesArray, it has to specify it explicitly. continue; } else { Bool_t toplevel = (branch == branch->GetMother()); clonesinfo = new TFormLeafInfoClones(cl, 0, toplevel); clones = (TClonesArray*)clonesinfo->GetLocalValuePointer(leafcur,0); } if (clones) cl = clones->GetClass(); } else if (cl && cl->GetCollectionProxy()) { // We have a unsplit Collection leaves // In this case we assume that cl is the class in which the TClonesArray // belongs. TBranch *branch = leafcur->GetBranch(); if ( branch->IsA()==TBranchElement::Class() && ((TBranchElement*)branch)->GetType()==41) { // We have an unsplit Collection as part of a split Collection! // Let's not dig any further. If the user really wants a data member // inside the nested Collection, it has to specify it explicitly. continue; } else { clonesinfo = new TFormLeafInfoCollection(cl, 0); } cl = cl->GetCollectionProxy()->GetValueClass(); } if (cl) { // Now that we have the class, let's check if the topchoice is of its datamember // or if the nextchoice is a datamember of one of its datamember. Int_t offset; TStreamerInfo* info = (TStreamerInfo*)cl->GetStreamerInfo(); TStreamerElement* element = info?info->GetStreamerElement(topchoice,offset):0; if (!element) { TIter nextel( cl->GetStreamerInfo()->GetElements() ); TStreamerElement * curelem; while ((curelem = (TStreamerElement*)nextel())) { if (curelem->GetClassPointer() == TClonesArray::Class()) { // In case of a TClonesArray we need to load the data and read the // clonesArray object before being able to look into the class inside. // We need to do that because we are never interested in the TClonesArray // itself but only in the object inside. TBranch *branch = leafcur->GetBranch(); TFormLeafInfo *leafinfo = 0; if (clonesinfo) { leafinfo = clonesinfo; } else if (branch->IsA()==TBranchElement::Class() && ((TBranchElement*)branch)->GetType()==31) { // Case of a sub branch of a TClonesArray TBranchElement *branchEl = (TBranchElement*)branch; TStreamerInfo *bel_info = branchEl->GetInfo(); TClass * mother_cl = ((TBranchElement*)branch)->GetInfo()->GetClass(); TStreamerElement *bel_element = (TStreamerElement *)bel_info->GetElems()[branchEl->GetID()]; leafinfo = new TFormLeafInfoClones(mother_cl, 0, bel_element, kTRUE); } Int_t clones_offset; ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(curelem->GetName(),clones_offset); TFormLeafInfo* sub_clonesinfo = new TFormLeafInfo(cl, clones_offset, curelem); if (leafinfo) if (leafinfo->fNext) leafinfo->fNext->fNext = sub_clonesinfo; else leafinfo->fNext = sub_clonesinfo; else leafinfo = sub_clonesinfo; R__LoadBranch(branch,readentry,fQuickLoad); TClonesArray * clones = (TClonesArray*)leafinfo->GetValuePointer(leafcur,0); delete leafinfo; clonesinfo = 0; // If TClonesArray object does not exist we have no information, so let go // on. This is a weakish test since the TClonesArray object might exist in // the next entry ... In other word, we ONLY rely on the information available // in entry #0. if (!clones) continue; TClass *sub_cl = clones->GetClass(); // Now that we finally have the inside class, let's query it. element = ((TStreamerInfo*)sub_cl->GetStreamerInfo())->GetStreamerElement(nextchoice,offset); if (element) break; } // if clones array else if (curelem->GetClassPointer() && curelem->GetClassPointer()->GetCollectionProxy()) { TClass *sub_cl = curelem->GetClassPointer()->GetCollectionProxy()->GetValueClass(); while(sub_cl && sub_cl->GetCollectionProxy()) sub_cl = sub_cl->GetCollectionProxy()->GetValueClass(); // Now that we finally have the inside class, let's query it. if (sub_cl) element = ((TStreamerInfo*)sub_cl->GetStreamerInfo())->GetStreamerElement(nextchoice,offset); if (element) break; } } // loop on elements } if (element) break; else cl = 0; } } delete clonesinfo; if (cl) { return leafcur; } else { return 0; } } //______________________________________________________________________________ Bool_t TTreeFormula::BranchHasMethod(TLeaf* leafcur, TBranch* branch, const char* method, const char* params, Long64_t readentry) const { // Return the leaf (if any) of the tree with contains an object of a class // having a method which has the name provided in the argument. TClass *cl = 0; TLeafObject* lobj = 0; // Since the user does not want this branch to be loaded anyway, we just // skip it. This prevents us from warning the user that the method might // be on a disabled branch. However, and more usefully, this allows the // user to avoid error messages from branches that cannot be currently // read without warnings/errors. if (branch->TestBit(kDoNotProcess)) { return kFALSE; } // FIXME: The following code is used somewhere else, we need to factor it out. if (branch->InheritsFrom(TBranchObject::Class())) { lobj = (TLeafObject*) branch->GetListOfLeaves()->At(0); cl = lobj->GetClass(); } else if (branch->InheritsFrom(TBranchElement::Class())) { TBranchElement* branchEl = (TBranchElement*) branch; Int_t type = branchEl->GetStreamerType(); if (type == -1) { cl = branchEl->GetInfo()->GetClass(); } else if (type > 60) { // Case of an object data member. Here we allow for the // variable name to be ommitted. Eg, for Event.root with split // level 1 or above Draw("GetXaxis") is the same as Draw("fH.GetXaxis()") TStreamerElement* element = (TStreamerElement*) branchEl->GetInfo()->GetElems()[branchEl->GetID()]; if (element) { cl = element->GetClassPointer(); } else { cl = 0; } if ((cl == TClonesArray::Class()) && (branchEl->GetType() == 31)) { // we have a TClonesArray inside a split TClonesArray, // Let's not dig any further. If the user really wants a data member // inside the nested TClonesArray, it has to specify it explicitly. cl = 0; } // NOTE do we need code for Collection here? } } if (cl == TClonesArray::Class()) { // We might be try to call a method of the top class inside a // TClonesArray. // Since the leaf was not terminal, we might have a split or // unsplit and/or top leaf/branch. TClonesArray* clones = 0; R__LoadBranch(branch, readentry, fQuickLoad); if (branch->InheritsFrom(TBranchObject::Class())) { clones = (TClonesArray*) lobj->GetObject(); } else if (branch->InheritsFrom(TBranchElement::Class())) { // We do not know exactly where the leaf of the TClonesArray is // in the hierachy but we still need to get the correct class // holder. TBranchElement* bc = (TBranchElement*) branch; if (bc == bc->GetMother()) { // Top level branch //clones = *((TClonesArray**) bc->GetAddress()); clones = (TClonesArray*) bc->GetObject(); } else if (!leafcur || !leafcur->IsOnTerminalBranch()) { TStreamerElement* element = (TStreamerElement*) bc->GetInfo()->GetElems()[bc->GetID()]; if (element->IsaPointer()) { clones = *((TClonesArray**) bc->GetAddress()); //clones = *((TClonesArray**) bc->GetObject()); } else { //clones = (TClonesArray*) bc->GetAddress(); clones = (TClonesArray*) bc->GetObject(); } } if (!clones) { R__LoadBranch(bc, readentry, fQuickLoad); TClass* mother_cl; mother_cl = bc->GetInfo()->GetClass(); TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(mother_cl, 0); // if (!leafcur) { leafcur = (TLeaf*) branch->GetListOfLeaves()->At(0); } clones = (TClonesArray*) clonesinfo->GetLocalValuePointer(leafcur, 0); // cl = clones->GetClass(); delete clonesinfo; } } else { Error("BranchHasMethod","A TClonesArray was stored in a branch type no yet support (i.e. neither TBranchObject nor TBranchElement): %s",branch->IsA()->GetName()); return kFALSE; } cl = clones->GetClass(); } else if (cl && cl->GetCollectionProxy()) { cl = cl->GetCollectionProxy()->GetValueClass(); } if (cl) { if (cl->GetClassInfo()) { if (cl->GetMethodAllAny(method)) { // Let's try to see if the function we found belongs to the current // class. Note that this implementation currently can not work if // one the argument is another leaf or data member of the object. // (Anyway we do NOT support this case). TMethodCall* methodcall = new TMethodCall(cl, method, params); if (methodcall->GetMethod()) { // We have a method that works. // We will use it. return kTRUE; } delete methodcall; } } } return kFALSE; } //______________________________________________________________________________ Int_t TTreeFormula::GetRealInstance(Int_t instance, Int_t codeindex) { // Now let calculate what physical instance we really need. // Some redundant code is used to speed up the cases where // they are no dimensions. // We know that instance is less that fCumulUsedSize[0] so // we can skip the modulo when virt_dim is 0. Int_t real_instance = 0; Int_t virt_dim; Bool_t check = kFALSE; if (codeindex<0) { codeindex = 0; check = kTRUE; } TFormLeafInfo * info = 0; Int_t max_dim = fNdimensions[codeindex]; if ( max_dim ) { virt_dim = 0; max_dim--; if (!fManager->fMultiVarDim) { if (fIndexes[codeindex][0]>=0) { real_instance = fIndexes[codeindex][0] * fCumulSizes[codeindex][1]; } else { Int_t local_index; local_index = ( instance / fManager->fCumulUsedSizes[virt_dim+1]); if (fIndexes[codeindex][0]==-2) { // NOTE: Should we check that this is a valid index? if (check) { Int_t index_real_instance = fVarIndexes[codeindex][0]->GetRealInstance(local_index,-1); if (index_real_instance > fVarIndexes[codeindex][0]->fNdata[0]) { // out of bounds return fNdata[0]+1; } } if (fDidBooleanOptimization && local_index!=0) { // Force the loading of the index. fVarIndexes[codeindex][0]->LoadBranches(); } local_index = (Int_t)fVarIndexes[codeindex][0]->EvalInstance(local_index); if (local_index<0) { Error("EvalInstance","Index %s is out of bound (%d) in formula %s", fVarIndexes[codeindex][0]->GetTitle(), local_index, GetTitle()); return fNdata[0]+1; } } real_instance = local_index * fCumulSizes[codeindex][1]; virt_dim ++; } } else { // NOTE: We assume that ONLY the first dimension of a leaf can have a variable // size AND contain the index for the size of yet another sub-dimension. // I.e. a variable size array inside a variable size array can only have its // size vary with the VERY FIRST physical dimension of the leaf. // Thus once the index of the first dimension is found, all other dimensions // are fixed! // NOTE: We could unroll some of this loops to avoid a few tests. if (fHasMultipleVarDim[codeindex]) { info = (TFormLeafInfo *)(fDataMembers.At(codeindex)); // if (info && info->GetVarDim()==-1) info = 0; } Int_t local_index; switch (fIndexes[codeindex][0]) { case -2: if (fDidBooleanOptimization && instance!=0) { // Force the loading of the index. fVarIndexes[codeindex][0]->LoadBranches(); } local_index = (Int_t)fVarIndexes[codeindex][0]->EvalInstance(instance); if (local_index<0) { Error("EvalInstance","Index %s is out of bound (%d) in formula %s", fVarIndexes[codeindex][0]->GetTitle(), local_index, GetTitle()); local_index = 0; } break; case -1: { local_index = 0; Int_t virt_accum = 0; Int_t maxloop = fManager->fCumulUsedVarDims->GetSize(); if (maxloop == 0) { local_index--; instance = fNdata[0]+1; // out of bounds. if (check) return fNdata[0]+1; } else { do { virt_accum += fManager->fCumulUsedVarDims->GetArray()[local_index]; local_index++; } while( instance >= virt_accum && local_index<maxloop); if (local_index==maxloop && (instance >= virt_accum)) { local_index--; instance = fNdata[0]+1; // out of bounds. if (check) return fNdata[0]+1; } else { local_index--; if (fManager->fCumulUsedVarDims->At(local_index)) { instance -= (virt_accum - fManager->fCumulUsedVarDims->At(local_index)); } else { instance = fNdata[0]+1; // out of bounds. if (check) return fNdata[0]+1; } } } virt_dim ++; } break; default: local_index = fIndexes[codeindex][0]; } // Inform the (appropriate) MultiVarLeafInfo that the clones array index is // local_index. if (fManager->fVarDims[kMAXFORMDIM]) { fManager->fCumulUsedSizes[kMAXFORMDIM] = fManager->fVarDims[kMAXFORMDIM]->At(local_index); } else { fManager->fCumulUsedSizes[kMAXFORMDIM] = fManager->fUsedSizes[kMAXFORMDIM]; } for(Int_t d = kMAXFORMDIM-1; d>0; d--) { if (fManager->fVarDims[d]) { fManager->fCumulUsedSizes[d] = fManager->fCumulUsedSizes[d+1] * fManager->fVarDims[d]->At(local_index); } else { fManager->fCumulUsedSizes[d] = fManager->fCumulUsedSizes[d+1] * fManager->fUsedSizes[d]; } } if (info) { // When we have multiple variable dimensions, the LeafInfo only expect // the instance after the primary index has been set. info->SetPrimaryIndex(local_index); real_instance = 0; // Let's update fCumulSizes for the rest of the code. Int_t vdim = info->GetVarDim(); Int_t isize = info->GetSize(local_index); if (fIndexes[codeindex][vdim]>=0) { info->SetSecondaryIndex(fIndexes[codeindex][vdim]); } if (isize!=1 && fIndexes[codeindex][vdim]>isize) { // We are out of bounds! return fNdata[0]+1; } fCumulSizes[codeindex][vdim] = isize*fCumulSizes[codeindex][vdim+1]; for(Int_t k=vdim -1; k>0; --k) { fCumulSizes[codeindex][k] = fCumulSizes[codeindex][k+1]*fFixedSizes[codeindex][k]; } } else { real_instance = local_index * fCumulSizes[codeindex][1]; } } if (max_dim>0) { for (Int_t dim = 1; dim < max_dim; dim++) { if (fIndexes[codeindex][dim]>=0) { real_instance += fIndexes[codeindex][dim] * fCumulSizes[codeindex][dim+1]; } else { Int_t local_index; if (virt_dim && fManager->fCumulUsedSizes[virt_dim]>1) { local_index = ( ( instance % fManager->fCumulUsedSizes[virt_dim] ) / fManager->fCumulUsedSizes[virt_dim+1]); } else { local_index = ( instance / fManager->fCumulUsedSizes[virt_dim+1]); } if (fIndexes[codeindex][dim]==-2) { // NOTE: Should we check that this is a valid index? if (fDidBooleanOptimization && local_index!=0) { // Force the loading of the index. fVarIndexes[codeindex][dim]->LoadBranches(); } local_index = (Int_t)fVarIndexes[codeindex][dim]->EvalInstance(local_index); if (local_index<0 || local_index>=(fCumulSizes[codeindex][dim]/fCumulSizes[codeindex][dim+1])) { Error("EvalInstance","Index %s is out of bound (%d/%d) in formula %s", fVarIndexes[codeindex][dim]->GetTitle(), local_index, (fCumulSizes[codeindex][dim]/fCumulSizes[codeindex][dim+1]), GetTitle()); local_index = (fCumulSizes[codeindex][dim]/fCumulSizes[codeindex][dim+1])-1; } } real_instance += local_index * fCumulSizes[codeindex][dim+1]; virt_dim ++; } } if (fIndexes[codeindex][max_dim]>=0) { if (!info) real_instance += fIndexes[codeindex][max_dim]; } else { Int_t local_index; if (virt_dim && fManager->fCumulUsedSizes[virt_dim]>1) { local_index = instance % fManager->fCumulUsedSizes[virt_dim]; } else { local_index = instance; } if (info && local_index>=fCumulSizes[codeindex][max_dim]) { // We are out of bounds! [Multiple var dims, See same message a few line above] return fNdata[0]+1; } if (fIndexes[codeindex][max_dim]==-2) { if (fDidBooleanOptimization && local_index!=0) { // Force the loading of the index. fVarIndexes[codeindex][max_dim]->LoadBranches(); } local_index = (Int_t)fVarIndexes[codeindex][max_dim]->EvalInstance(local_index); if (local_index<0 || local_index>=fCumulSizes[codeindex][max_dim]) { Error("EvalInstance","Index %s is of out bound (%d/%d) in formula %s", fVarIndexes[codeindex][max_dim]->GetTitle(), local_index, fCumulSizes[codeindex][max_dim], GetTitle()); local_index = fCumulSizes[codeindex][max_dim]-1; } } real_instance += local_index; } } // if (max_dim-1>0) } // if (max_dim) return real_instance; } //______________________________________________________________________________ TClass* TTreeFormula::EvalClass() const { // Evaluate the class of this treeformula // // If the 'value' of this formula is a simple pointer to an object, // this function returns the TClass corresponding to its type. if (fNoper != 1 || fNcodes <=0 ) return 0; return EvalClass(0); } //______________________________________________________________________________ TClass* TTreeFormula::EvalClass(Int_t oper) const { // Evaluate the class of the operation oper // // If the 'value' in the requested operation is a simple pointer to an object, // this function returns the TClass corresponding to its type. TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(oper); switch(fLookupType[oper]) { case kDirect: { if (leaf->IsA()==TLeafObject::Class()) { return ((TLeafObject*)leaf)->GetClass(); } else if ( leaf->IsA()==TLeafElement::Class()) { TBranchElement * branch = (TBranchElement*)((TLeafElement*)leaf)->GetBranch(); TStreamerInfo * info = branch->GetInfo(); Int_t id = branch->GetID(); if (id>=0) { if (info==0 || info->GetElems()==0) { // we probably do not have a way to know the class of the object. return 0; } TStreamerElement* elem = (TStreamerElement*)info->GetElems()[id]; if (elem==0) { // we probably do not have a way to know the class of the object. return 0; } else { return elem->GetClass(); } } else return TClass::GetClass( branch->GetClassName() ); } else { return 0; } } case kMethod: return 0; // kMethod is deprecated so let's no waste time implementing this. case kTreeMember: case kDataMember: { TObject *obj = fDataMembers.UncheckedAt(oper); if (!obj) return 0; return ((TFormLeafInfo*)obj)->GetClass(); } default: return 0; } } //______________________________________________________________________________ void* TTreeFormula::EvalObject(int instance) { //*-*-*-*-*-*-*-*-*-*-*Evaluate this treeformula*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================= // // Return the address of the object pointed to by the formula. // Return 0 if the formula is not a single object // The object type can be retrieved using by call EvalClass(); if (fNoper != 1 || fNcodes <=0 ) return 0; switch (fLookupType[0]) { case kIndexOfEntry: case kIndexOfLocalEntry: case kEntries: case kLength: case kLengthFunc: case kIteration: case kEntryList: return 0; } TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); Int_t real_instance = GetRealInstance(instance,0); if (instance==0 || fNeedLoading) { fNeedLoading = kFALSE; R__LoadBranch(leaf->GetBranch(), leaf->GetBranch()->GetTree()->GetReadEntry(), fQuickLoad); } else if (real_instance>fNdata[0]) return 0; if (fAxis) { return 0; } switch(fLookupType[0]) { case kDirect: { if (real_instance) { Warning("EvalObject","Not yet implement for kDirect and arrays (for %s).\nPlease contact the developers",GetName()); } return leaf->GetValuePointer(); } case kMethod: return GetValuePointerFromMethod(0,leaf); case kTreeMember: case kDataMember: return ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->GetValuePointer(leaf,real_instance); default: return 0; } } //______________________________________________________________________________ const char* TTreeFormula::EvalStringInstance(Int_t instance) { // Eval the instance as a string. const Int_t kMAXSTRINGFOUND = 10; const char *stringStack[kMAXSTRINGFOUND]; if (fNoper==1 && fNcodes>0 && IsString()) { TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); Int_t real_instance = GetRealInstance(instance,0); if (instance==0 || fNeedLoading) { fNeedLoading = kFALSE; TBranch *branch = leaf->GetBranch(); R__LoadBranch(branch,branch->GetTree()->GetReadEntry(),fQuickLoad); } else if (real_instance>=fNdata[0]) { return 0; } if (fLookupType[0]==kDirect) { return (char*)leaf->GetValuePointer(); } else { return (char*)GetLeafInfo(0)->GetValuePointer(leaf,real_instance); } } EvalInstance(instance,stringStack); return stringStack[0]; } #define TT_EVAL_INIT \ TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); \ \ const Int_t real_instance = GetRealInstance(instance,0); \ \ if (instance==0) fNeedLoading = kTRUE; \ if (real_instance>fNdata[0]) return 0; \ \ /* Since the only operation in this formula is reading this branch, \ we are guaranteed that this function is first called with instance==0 and \ hence we are guaranteed that the branch is always properly read */ \ \ if (fNeedLoading) { \ fNeedLoading = kFALSE; \ TBranch *br = leaf->GetBranch(); \ Long64_t tentry = br->GetTree()->GetReadEntry(); \ R__LoadBranch(br,tentry,fQuickLoad); \ } \ \ if (fAxis) { \ char * label; \ /* This portion is a duplicate (for speed reason) of the code \ located in the main for loop at "a tree string" (and in EvalStringInstance) */ \ if (fLookupType[0]==kDirect) { \ label = (char*)leaf->GetValuePointer(); \ } else { \ label = (char*)GetLeafInfo(0)->GetValuePointer(leaf,instance); \ } \ Int_t bin = fAxis->FindBin(label); \ return bin-0.5; \ } #define TREE_EVAL_INIT \ const Int_t real_instance = GetRealInstance(instance,0); \ \ if (real_instance>fNdata[0]) return 0; \ \ if (fAxis) { \ char * label; \ /* This portion is a duplicate (for speed reason) of the code \ located in the main for loop at "a tree string" (and in EvalStringInstance) */ \ label = (char*)GetLeafInfo(0)->GetValuePointer((TLeaf*)0x0,instance); \ Int_t bin = fAxis->FindBin(label); \ return bin-0.5; \ } #define TT_EVAL_INIT_LOOP \ TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(code); \ \ /* Now let calculate what physical instance we really need. */ \ const Int_t real_instance = GetRealInstance(instance,code); \ \ if (willLoad) { \ TBranch *branch = (TBranch*)fBranches.UncheckedAt(code); \ if (branch) { \ Long64_t treeEntry = branch->GetTree()->GetReadEntry(); \ R__LoadBranch(branch,treeEntry,fQuickLoad); \ } else if (fDidBooleanOptimization) { \ branch = leaf->GetBranch(); \ Long64_t treeEntry = branch->GetTree()->GetReadEntry(); \ if (branch->GetReadEntry() != treeEntry) branch->GetEntry( treeEntry ); \ } \ } else { \ /* In the cases where we are behind (i.e. right of) a potential boolean optimization \ this tree variable reading may have not been executed with instance==0 which would \ result in the branch being potentially not read in. */ \ if (fDidBooleanOptimization) { \ TBranch *br = leaf->GetBranch(); \ Long64_t treeEntry = br->GetTree()->GetReadEntry(); \ if (br->GetReadEntry() != treeEntry) br->GetEntry( treeEntry ); \ } \ } \ if (real_instance>fNdata[code]) return 0; #define TREE_EVAL_INIT_LOOP \ /* Now let calculate what physical instance we really need. */ \ const Int_t real_instance = GetRealInstance(instance,code); \ \ if (real_instance>fNdata[code]) return 0; namespace { Double_t Summing(TTreeFormula *sum) { Int_t len = sum->GetNdata(); Double_t res = 0; for (int i=0; i<len; ++i) res += sum->EvalInstance(i); return res; } Double_t FindMin(TTreeFormula *arr) { Int_t len = arr->GetNdata(); Double_t res = 0; if (len) { res = arr->EvalInstance(0); for (int i=1; i<len; ++i) { Double_t val = arr->EvalInstance(i); if (val < res) { res = val; } } } return res; } Double_t FindMax(TTreeFormula *arr) { Int_t len = arr->GetNdata(); Double_t res = 0; if (len) { res = arr->EvalInstance(0); for (int i=1; i<len; ++i) { Double_t val = arr->EvalInstance(i); if (val > res) { res = val; } } } return res; } Double_t FindMin(TTreeFormula *arr, TTreeFormula *condition) { Int_t len = arr->GetNdata(); Double_t res = 0; if (len) { int i = 0; Double_t condval; do { condval = condition->EvalInstance(i); ++i; } while (!condval && i<len); if (i==len) { return 0; } if (i!=1) { // Insure the loading of the branch. arr->EvalInstance(0); } // Now we know that i>0 && i<len and cond==true res = arr->EvalInstance(i-1); for (; i<len; ++i) { condval = condition->EvalInstance(i); if (condval) { Double_t val = arr->EvalInstance(i); if (val < res) { res = val; } } } } return res; } Double_t FindMax(TTreeFormula *arr, TTreeFormula *condition) { Int_t len = arr->GetNdata(); Double_t res = 0; if (len) { int i = 0; Double_t condval; do { condval = condition->EvalInstance(i); ++i; } while (!condval && i<len); if (i==len) { return 0; } if (i!=1) { // Insure the loading of the branch. arr->EvalInstance(0); } // Now we know that i>0 && i<len and cond==true res = arr->EvalInstance(i-1); for (; i<len; ++i) { condval = condition->EvalInstance(i); if (condval) { Double_t val = arr->EvalInstance(i); if (val > res) { res = val; } } } } return res; } } //______________________________________________________________________________ Double_t TTreeFormula::EvalInstance(Int_t instance, const char *stringStackArg[]) { //*-*-*-*-*-*-*-*-*-*-*Evaluate this treeformula*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================= // // Note that the redundance and structure in this code is tailored to improve // efficiencies. if (TestBit(kMissingLeaf)) return 0; if (fNoper == 1 && fNcodes > 0) { switch (fLookupType[0]) { case kDirect: { TT_EVAL_INIT; Double_t result = leaf->GetValue(real_instance); return result; } case kMethod: { TT_EVAL_INIT; ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->SetBranch(leaf->GetBranch()); return GetValueFromMethod(0,leaf); } case kDataMember: { TT_EVAL_INIT; ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->SetBranch(leaf->GetBranch()); return ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->GetValue(leaf,real_instance); } case kTreeMember: { TREE_EVAL_INIT; return ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->GetValue((TLeaf*)0x0,real_instance); } case kIndexOfEntry: return (Double_t)fTree->GetReadEntry(); case kIndexOfLocalEntry: return (Double_t)fTree->GetTree()->GetReadEntry(); case kEntries: return (Double_t)fTree->GetEntries(); case kLength: return fManager->fNdata; case kLengthFunc: return ((TTreeFormula*)fAliases.UncheckedAt(0))->GetNdata(); case kIteration: return instance; case kSum: return Summing((TTreeFormula*)fAliases.UncheckedAt(0)); case kMin: return FindMin((TTreeFormula*)fAliases.UncheckedAt(0)); case kMax: return FindMax((TTreeFormula*)fAliases.UncheckedAt(0)); case kEntryList: { TEntryList *elist = (TEntryList*)fExternalCuts.At(0); return elist->Contains(fTree->GetTree()->GetReadEntry()); } case -1: break; } switch (fCodes[0]) { case -2: { TCutG *gcut = (TCutG*)fExternalCuts.At(0); TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); TTreeFormula *fy = (TTreeFormula *)gcut->GetObjectY(); Double_t xcut = fx->EvalInstance(instance); Double_t ycut = fy->EvalInstance(instance); return gcut->IsInside(xcut,ycut); } case -1: { TCutG *gcut = (TCutG*)fExternalCuts.At(0); TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); return fx->EvalInstance(instance); } default: return 0; } } Double_t tab[kMAXFOUND]; const Int_t kMAXSTRINGFOUND = 10; const char *stringStackLocal[kMAXSTRINGFOUND]; const char **stringStack = stringStackArg?stringStackArg:stringStackLocal; const bool willLoad = (instance==0 || fNeedLoading); fNeedLoading = kFALSE; if (willLoad) fDidBooleanOptimization = kFALSE; Int_t pos = 0; Int_t pos2 = 0; for (Int_t i=0; i<fNoper ; ++i) { const Int_t oper = GetOper()[i]; const Int_t newaction = oper >> kTFOperShift; if (newaction<kDefinedVariable) { // TFormula operands. // one of the most used cases if (newaction==kConstant) { pos++; tab[pos-1] = fConst[(oper & kTFOperMask)]; continue; } switch(newaction) { case kEnd : return tab[0]; case kAdd : pos--; tab[pos-1] += tab[pos]; continue; case kSubstract : pos--; tab[pos-1] -= tab[pos]; continue; case kMultiply : pos--; tab[pos-1] *= tab[pos]; continue; case kDivide : pos--; if (tab[pos] == 0) tab[pos-1] = 0; // division by 0 else tab[pos-1] /= tab[pos]; continue; case kModulo : {pos--; Long64_t int1((Long64_t)tab[pos-1]); Long64_t int2((Long64_t)tab[pos]); tab[pos-1] = Double_t(int1%int2); continue;} case kcos : tab[pos-1] = TMath::Cos(tab[pos-1]); continue; case ksin : tab[pos-1] = TMath::Sin(tab[pos-1]); continue; case ktan : if (TMath::Cos(tab[pos-1]) == 0) {tab[pos-1] = 0;} // { tangente indeterminee } else tab[pos-1] = TMath::Tan(tab[pos-1]); continue; case kacos : if (TMath::Abs(tab[pos-1]) > 1) {tab[pos-1] = 0;} // indetermination else tab[pos-1] = TMath::ACos(tab[pos-1]); continue; case kasin : if (TMath::Abs(tab[pos-1]) > 1) {tab[pos-1] = 0;} // indetermination else tab[pos-1] = TMath::ASin(tab[pos-1]); continue; case katan : tab[pos-1] = TMath::ATan(tab[pos-1]); continue; case kcosh : tab[pos-1] = TMath::CosH(tab[pos-1]); continue; case ksinh : tab[pos-1] = TMath::SinH(tab[pos-1]); continue; case ktanh : if (TMath::CosH(tab[pos-1]) == 0) {tab[pos-1] = 0;} // { tangente indeterminee } else tab[pos-1] = TMath::TanH(tab[pos-1]); continue; case kacosh: if (tab[pos-1] < 1) {tab[pos-1] = 0;} // indetermination else tab[pos-1] = TMath::ACosH(tab[pos-1]); continue; case kasinh: tab[pos-1] = TMath::ASinH(tab[pos-1]); continue; case katanh: if (TMath::Abs(tab[pos-1]) > 1) {tab[pos-1] = 0;} // indetermination else tab[pos-1] = TMath::ATanH(tab[pos-1]); continue; case katan2: pos--; tab[pos-1] = TMath::ATan2(tab[pos-1],tab[pos]); continue; case kfmod : pos--; tab[pos-1] = fmod(tab[pos-1],tab[pos]); continue; case kpow : pos--; tab[pos-1] = TMath::Power(tab[pos-1],tab[pos]); continue; case ksq : tab[pos-1] = tab[pos-1]*tab[pos-1]; continue; case ksqrt : tab[pos-1] = TMath::Sqrt(TMath::Abs(tab[pos-1])); continue; case kstrstr : pos2 -= 2; pos++;if (strstr(stringStack[pos2],stringStack[pos2+1])) tab[pos-1]=1; else tab[pos-1]=0; continue; case kmin : pos--; tab[pos-1] = TMath::Min(tab[pos-1],tab[pos]); continue; case kmax : pos--; tab[pos-1] = TMath::Max(tab[pos-1],tab[pos]); continue; case klog : if (tab[pos-1] > 0) tab[pos-1] = TMath::Log(tab[pos-1]); else {tab[pos-1] = 0;} //{indetermination } continue; case kexp : { Double_t dexp = tab[pos-1]; if (dexp < -700) {tab[pos-1] = 0; continue;} if (dexp > 700) {tab[pos-1] = TMath::Exp(700); continue;} tab[pos-1] = TMath::Exp(dexp); continue; } case klog10: if (tab[pos-1] > 0) tab[pos-1] = TMath::Log10(tab[pos-1]); else {tab[pos-1] = 0;} //{indetermination } continue; case kpi : pos++; tab[pos-1] = TMath::ACos(-1); continue; case kabs : tab[pos-1] = TMath::Abs(tab[pos-1]); continue; case ksign : if (tab[pos-1] < 0) tab[pos-1] = -1; else tab[pos-1] = 1; continue; case kint : tab[pos-1] = Double_t(Int_t(tab[pos-1])); continue; case kSignInv: tab[pos-1] = -1 * tab[pos-1]; continue; case krndm : pos++; tab[pos-1] = gRandom->Rndm(1); continue; case kAnd : pos--; if (tab[pos-1]!=0 && tab[pos]!=0) tab[pos-1]=1; else tab[pos-1]=0; continue; case kOr : pos--; if (tab[pos-1]!=0 || tab[pos]!=0) tab[pos-1]=1; else tab[pos-1]=0; continue; case kEqual : pos--; tab[pos-1] = (tab[pos-1] == tab[pos]) ? 1 : 0; continue; case kNotEqual : pos--; tab[pos-1] = (tab[pos-1] != tab[pos]) ? 1 : 0; continue; case kLess : pos--; tab[pos-1] = (tab[pos-1] < tab[pos]) ? 1 : 0; continue; case kGreater : pos--; tab[pos-1] = (tab[pos-1] > tab[pos]) ? 1 : 0; continue; case kLessThan : pos--; tab[pos-1] = (tab[pos-1] <= tab[pos]) ? 1 : 0; continue; case kGreaterThan: pos--; tab[pos-1] = (tab[pos-1] >= tab[pos]) ? 1 : 0; continue; case kNot : tab[pos-1] = (tab[pos-1] != 0) ? 0 : 1; continue; case kStringEqual : pos2 -= 2; pos++; if (!strcmp(stringStack[pos2+1],stringStack[pos2])) tab[pos-1]=1; else tab[pos-1]=0; continue; case kStringNotEqual: pos2 -= 2; pos++;if (strcmp(stringStack[pos2+1],stringStack[pos2])) tab[pos-1]=1; else tab[pos-1]=0; continue; case kBitAnd : pos--; tab[pos-1]= ((Long64_t) tab[pos-1]) & ((Long64_t) tab[pos]); continue; case kBitOr : pos--; tab[pos-1]= ((Long64_t) tab[pos-1]) | ((Long64_t) tab[pos]); continue; case kLeftShift : pos--; tab[pos-1]= ((Long64_t) tab[pos-1]) <<((Long64_t) tab[pos]); continue; case kRightShift: pos--; tab[pos-1]= ((Long64_t) tab[pos-1]) >>((Long64_t) tab[pos]); continue; case kJump : i = (oper & kTFOperMask); continue; case kJumpIf : pos--; if (!tab[pos]) i = (oper & kTFOperMask); continue; case kStringConst: { // String pos2++; stringStack[pos2-1] = (char*)fExpr[i].Data(); continue; } case kBoolOptimize: { // boolean operation optimizer int param = (oper & kTFOperMask); Bool_t skip = kFALSE; int op = param % 10; // 1 is && , 2 is || if (op == 1 && (!tab[pos-1]) ) { // &&: skip the right part if the left part is already false skip = kTRUE; // Preserve the existing behavior (i.e. the result of a&&b is // either 0 or 1) tab[pos-1] = 0; } else if (op == 2 && tab[pos-1] ) { // ||: skip the right part if the left part is already true skip = kTRUE; // Preserve the existing behavior (i.e. the result of a||b is // either 0 or 1) tab[pos-1] = 1; } if (skip) { int toskip = param / 10; i += toskip; if (willLoad) fDidBooleanOptimization = kTRUE; } continue; } case kFunctionCall: { // an external function call int param = (oper & kTFOperMask); int fno = param / 1000; int nargs = param % 1000; // Retrieve the function TMethodCall *method = (TMethodCall*)fFunctions.At(fno); // Set the arguments method->ResetParam(); if (nargs) { UInt_t argloc = pos-nargs; for(Int_t j=0;j<nargs;j++,argloc++,pos--) { method->SetParam( tab[argloc] ); } } pos++; Double_t ret; method->Execute(ret); tab[pos-1] = ret; // check for the correct conversion! continue; } // case kParameter: { pos++; tab[pos-1] = fParams[(oper & kTFOperMask)]; continue; } } } else { // TTreeFormula operands. // a tree variable (the most used case). if (newaction == kDefinedVariable) { const Int_t code = (oper & kTFOperMask); const Int_t lookupType = fLookupType[code]; switch (lookupType) { case kIndexOfEntry: tab[pos++] = (Double_t)fTree->GetReadEntry(); continue; case kIndexOfLocalEntry: tab[pos++] = (Double_t)fTree->GetTree()->GetReadEntry(); continue; case kEntries: tab[pos++] = (Double_t)fTree->GetEntries(); continue; case kLength: tab[pos++] = fManager->fNdata; continue; case kLengthFunc: tab[pos++] = ((TTreeFormula*)fAliases.UncheckedAt(i))->GetNdata(); continue; case kIteration: tab[pos++] = instance; continue; case kSum: tab[pos++] = Summing((TTreeFormula*)fAliases.UncheckedAt(i)); continue; case kMin: tab[pos++] = FindMin((TTreeFormula*)fAliases.UncheckedAt(i)); continue; case kMax: tab[pos++] = FindMax((TTreeFormula*)fAliases.UncheckedAt(i)); continue; case kDirect: { TT_EVAL_INIT_LOOP; tab[pos++] = leaf->GetValue(real_instance); continue; } case kMethod: { TT_EVAL_INIT_LOOP; tab[pos++] = GetValueFromMethod(code,leaf); continue; } case kDataMember: { TT_EVAL_INIT_LOOP; tab[pos++] = ((TFormLeafInfo*)fDataMembers.UncheckedAt(code))-> GetValue(leaf,real_instance); continue; } case kTreeMember: { TREE_EVAL_INIT_LOOP; tab[pos++] = ((TFormLeafInfo*)fDataMembers.UncheckedAt(code))-> GetValue((TLeaf*)0x0,real_instance); continue; } case kEntryList: { TEntryList *elist = (TEntryList*)fExternalCuts.At(code); tab[pos++] = elist->Contains(fTree->GetReadEntry()); continue;} case -1: break; default: tab[pos++] = 0; continue; } switch (fCodes[code]) { case -2: { TCutG *gcut = (TCutG*)fExternalCuts.At(code); TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); TTreeFormula *fy = (TTreeFormula *)gcut->GetObjectY(); Double_t xcut = fx->EvalInstance(instance); Double_t ycut = fy->EvalInstance(instance); tab[pos++] = gcut->IsInside(xcut,ycut); continue; } case -1: { TCutG *gcut = (TCutG*)fExternalCuts.At(code); TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); tab[pos++] = fx->EvalInstance(instance); continue; } default: { tab[pos++] = 0; continue; } } } switch(newaction) { // a TTree Variable Alias (i.e. a sub-TTreeFormula) case kAlias: { int aliasN = i; TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(aliasN)); R__ASSERT(subform); Double_t param = subform->EvalInstance(instance); tab[pos] = param; pos++; continue; } // a TTree Variable Alias String (i.e. a sub-TTreeFormula) case kAliasString: { int aliasN = i; TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(aliasN)); R__ASSERT(subform); pos2++; stringStack[pos2-1] = subform->EvalStringInstance(instance); continue; } case kMinIf: { int alternateN = i; TTreeFormula *primary = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN)); TTreeFormula *condition = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN+1)); Double_t param = FindMin(primary,condition); ++i; // skip the place holder for the condition tab[pos] = param; pos++; continue; } case kMaxIf: { int alternateN = i; TTreeFormula *primary = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN)); TTreeFormula *condition = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN+1)); Double_t param = FindMax(primary,condition); ++i; // skip the place holder for the condition tab[pos] = param; pos++; continue; } // a TTree Variable Alternate (i.e. a sub-TTreeFormula) case kAlternate: { int alternateN = i; TTreeFormula *primary = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN)); // First check whether we are in range for the primary formula if (instance < primary->GetNdata()) { Double_t param = primary->EvalInstance(instance); ++i; // skip the alternate value. tab[pos] = param; pos++; } else { // The primary is not in rancge, we will calculate the alternate value // via the next operation (which will be a intentional). // kAlias no operations } continue; } case kAlternateString: { int alternateN = i; TTreeFormula *primary = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN)); // First check whether we are in range for the primary formula if (instance < primary->GetNdata()) { pos2++; stringStack[pos2-1] = primary->EvalStringInstance(instance); ++i; // skip the alternate value. } else { // The primary is not in rancge, we will calculate the alternate value // via the next operation (which will be a kAlias). // intentional no operations } continue; } // a tree string case kDefinedString: { Int_t string_code = (oper & kTFOperMask); TLeaf *leafc = (TLeaf*)fLeaves.UncheckedAt(string_code); // Now let calculate what physical instance we really need. const Int_t real_instance = GetRealInstance(instance,string_code); if (instance==0 || fNeedLoading) { fNeedLoading = kFALSE; TBranch *branch = leafc->GetBranch(); Long64_t readentry = branch->GetTree()->GetReadEntry(); R__LoadBranch(branch,readentry,fQuickLoad); } else { // In the cases where we are behind (i.e. right of) a potential boolean optimization // this tree variable reading may have not been executed with instance==0 which would // result in the branch being potentially not read in. if (fDidBooleanOptimization) { TBranch *br = leafc->GetBranch(); Long64_t treeEntry = br->GetTree()->GetReadEntry(); R__LoadBranch(br,treeEntry,kTRUE); } if (real_instance>fNdata[string_code]) return 0; } pos2++; if (fLookupType[string_code]==kDirect) { stringStack[pos2-1] = (char*)leafc->GetValuePointer(); } else { stringStack[pos2-1] = (char*)GetLeafInfo(string_code)->GetValuePointer(leafc,real_instance); } continue; } } } R__ASSERT(i<fNoper); } Double_t result = tab[0]; return result; } //______________________________________________________________________________ TFormLeafInfo *TTreeFormula::GetLeafInfo(Int_t code) const { //*-*-*-*-*-*-*-*Return DataMember corresponding to code*-*-*-*-*-* //*-* ======================================= // // function called by TLeafObject::GetValue // with the value of fLookupType computed in TTreeFormula::DefinedVariable return (TFormLeafInfo *)fDataMembers.UncheckedAt(code); } //______________________________________________________________________________ TLeaf *TTreeFormula::GetLeaf(Int_t n) const { //*-*-*-*-*-*-*-*Return leaf corresponding to serial number n*-*-*-*-*-* //*-* ============================================ // return (TLeaf*)fLeaves.UncheckedAt(n); } //______________________________________________________________________________ TMethodCall *TTreeFormula::GetMethodCall(Int_t code) const { //*-*-*-*-*-*-*-*Return methodcall corresponding to code*-*-*-*-*-* //*-* ======================================= // // function called by TLeafObject::GetValue // with the value of fLookupType computed in TTreeFormula::DefinedVariable return (TMethodCall *)fMethods.UncheckedAt(code); } //______________________________________________________________________________ Int_t TTreeFormula::GetNdata() { //*-*-*-*-*-*-*-*Return number of available instances in the formula-*-*-*-*-*-* //*-* =================================================== // return fManager->GetNdata(); } //______________________________________________________________________________ Double_t TTreeFormula::GetValueFromMethod(Int_t i, TLeaf* leaf) const { // Return result of a leafobject method. TMethodCall* m = GetMethodCall(i); if (!m) { return 0.0; } void* thisobj = 0; if (leaf->InheritsFrom(TLeafObject::Class())) { thisobj = ((TLeafObject*) leaf)->GetObject(); } else { TBranchElement* branch = (TBranchElement*) ((TLeafElement*) leaf)->GetBranch(); Int_t id = branch->GetID(); // FIXME: This is wrong for a top-level branch. Int_t offset = 0; if (id > -1) { TStreamerInfo* info = branch->GetInfo(); if (info) { offset = info->GetOffsets()[id]; } else { Warning("GetValueFromMethod", "No streamer info for branch %s.", branch->GetName()); } } if (id < 0) { char* address = branch->GetObject(); thisobj = address; } else { //char* address = branch->GetAddress(); char* address = branch->GetObject(); if (address) { thisobj = *((char**) (address + offset)); } else { // FIXME: If the address is not set, the object won't be either! thisobj = branch->GetObject(); } } } TMethodCall::EReturnType r = m->ReturnType(); if (r == TMethodCall::kLong) { Long_t l; m->Execute(thisobj, l); return (Double_t) l; } if (r == TMethodCall::kDouble) { Double_t d; m->Execute(thisobj, d); return d; } m->Execute(thisobj); return 0; } //______________________________________________________________________________ void* TTreeFormula::GetValuePointerFromMethod(Int_t i, TLeaf* leaf) const { // Return result of a leafobject method. TMethodCall* m = GetMethodCall(i); if (!m) { return 0; } void* thisobj; if (leaf->InheritsFrom(TLeafObject::Class())) { thisobj = ((TLeafObject*) leaf)->GetObject(); } else { TBranchElement* branch = (TBranchElement*) ((TLeafElement*) leaf)->GetBranch(); Int_t id = branch->GetID(); Int_t offset = 0; if (id > -1) { TStreamerInfo* info = branch->GetInfo(); if (info) { offset = info->GetOffsets()[id]; } else { Warning("GetValuePointerFromMethod", "No streamer info for branch %s.", branch->GetName()); } } if (id < 0) { char* address = branch->GetObject(); thisobj = address; } else { //char* address = branch->GetAddress(); char* address = branch->GetObject(); if (address) { thisobj = *((char**) (address + offset)); } else { // FIXME: If the address is not set, the object won't be either! thisobj = branch->GetObject(); } } } TMethodCall::EReturnType r = m->ReturnType(); if (r == TMethodCall::kLong) { Long_t l; m->Execute(thisobj, l); return 0; } if (r == TMethodCall::kDouble) { Double_t d; m->Execute(thisobj, d); return 0; } if (r == TMethodCall::kOther) { char* c; m->Execute(thisobj, &c); return c; } m->Execute(thisobj); return 0; } //______________________________________________________________________________ Bool_t TTreeFormula::IsInteger(Bool_t fast) const { // return TRUE if the formula corresponds to one single Tree leaf // and this leaf is short, int or unsigned short, int // When a leaf is of type integer or string, the generated histogram is forced // to have an integer bin width if (fast) { if (TestBit(kIsInteger)) return kTRUE; else return kFALSE; } if (fNoper==2 && GetAction(0)==kAlternate) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); return subform->IsInteger(kFALSE); } if (GetAction(0)==kMinIf || GetAction(0)==kMaxIf) { return kFALSE; } if (fNoper > 1) return kFALSE; if (GetAction(0)==kAlias) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); return subform->IsInteger(kFALSE); } if (fLeaves.GetEntries() != 1) { switch (fLookupType[0]) { case kIndexOfEntry: case kIndexOfLocalEntry: case kEntries: case kLength: case kLengthFunc: case kIteration: return kTRUE; case kSum: case kMin: case kMax: case kEntryList: default: return kFALSE; } } if (EvalClass()==TBits::Class()) return kTRUE; if (IsLeafInteger(0) || IsLeafString(0)) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TTreeFormula::IsLeafInteger(Int_t code) const { // return TRUE if the leaf corresponding to code is short, int or unsigned // short, int When a leaf is of type integer, the generated histogram is // forced to have an integer bin width TLeaf *leaf = (TLeaf*)fLeaves.At(code); if (!leaf) { switch (fLookupType[code]) { case kIndexOfEntry: case kIndexOfLocalEntry: case kEntries: case kLength: case kLengthFunc: case kIteration: return kTRUE; case kSum: case kMin: case kMax: case kEntryList: default: return kFALSE; } } if (fAxis) return kTRUE; TFormLeafInfo * info; switch (fLookupType[code]) { case kMethod: case kTreeMember: case kDataMember: info = GetLeafInfo(code); return info->IsInteger(); case kDirect: break; } if (!strcmp(leaf->GetTypeName(),"Int_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"Short_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"UInt_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"UShort_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"Bool_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"Char_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"UChar_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"string")) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TTreeFormula::IsString() const { // return TRUE if the formula is a string return TestBit(kIsCharacter) || (fNoper==1 && IsString(0)); } //______________________________________________________________________________ Bool_t TTreeFormula::IsString(Int_t oper) const { // (fOper[i]>=105000 && fOper[i]<110000) || fOper[i] == kStrings) // return true if the expression at the index 'oper' is to be treated as // as string if (TFormula::IsString(oper)) return kTRUE; if (GetAction(oper)==kDefinedString) return kTRUE; if (GetAction(oper)==kAliasString) return kTRUE; if (GetAction(oper)==kAlternateString) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TTreeFormula::IsLeafString(Int_t code) const { // return TRUE if the leaf or data member corresponding to code is a string TLeaf *leaf = (TLeaf*)fLeaves.At(code); TFormLeafInfo * info; if (fLookupType[code]==kTreeMember) { info = GetLeafInfo(code); return info->IsString(); } switch(fLookupType[code]) { case kDirect: if ( !leaf->IsUnsigned() && (leaf->InheritsFrom(TLeafC::Class()) || leaf->InheritsFrom(TLeafB::Class()) ) ) { // Need to find out if it is an 'array' or a pointer. if (leaf->GetLenStatic() > 1) return kTRUE; // Now we need to differantiate between a variable length array and // a TClonesArray. if (leaf->GetLeafCount()) { const char* indexname = leaf->GetLeafCount()->GetName(); if (indexname[strlen(indexname)-1] == '_' ) { // This in a clones array return kFALSE; } else { // this is a variable length char array return kTRUE; } } return kFALSE; } else if (leaf->InheritsFrom(TLeafElement::Class())) { TBranchElement * br = (TBranchElement*)leaf->GetBranch(); Int_t bid = br->GetID(); if (bid < 0) return kFALSE; if (br->GetInfo()==0 || br->GetInfo()->GetElems()==0) { // Case where the file is corrupted is some ways. // We can not get to the actual type of the data // let's assume it is NOT a string. return kFALSE; } TStreamerElement * elem = (TStreamerElement*) br->GetInfo()->GetElems()[bid]; if (!elem) { // Case where the file is corrupted is some ways. // We can not get to the actual type of the data // let's assume it is NOT a string. return kFALSE; } if (elem->GetNewType()== TStreamerInfo::kOffsetL +kChar_t) { // Check whether a specific element of the string is specified! if (fIndexes[code][fNdimensions[code]-1] != -1) return kFALSE; return kTRUE; } if ( elem->GetNewType()== TStreamerInfo::kCharStar) { // Check whether a specific element of the string is specified! if (fNdimensions[code] && fIndexes[code][fNdimensions[code]-1] != -1) return kFALSE; return kTRUE; } return kFALSE; } else { return kFALSE; } case kMethod: //TMethodCall *m = GetMethodCall(code); //TMethodCall::EReturnType r = m->ReturnType(); return kFALSE; case kDataMember: info = GetLeafInfo(code); return info->IsString(); default: return kFALSE; } } //______________________________________________________________________________ char *TTreeFormula::PrintValue(Int_t mode) const { // Return value of variable as a string // // mode = -2 : Print line with *** // mode = -1 : Print column names // mode = 0 : Print column values return PrintValue(mode,0); } //______________________________________________________________________________ char *TTreeFormula::PrintValue(Int_t mode, Int_t instance, const char *decform) const { // Return value of variable as a string // // mode = -2 : Print line with *** // mode = -1 : Print column names // mode = 0 : Print column values // decform contains the requested format (with the same convention as printf). // const int kMAXLENGTH = 1024; static char value[kMAXLENGTH]; if (mode == -2) { for (int i = 0; i < kMAXLENGTH-1; i++) value[i] = '*'; value[kMAXLENGTH-1] = 0; } else if (mode == -1) { snprintf(value, kMAXLENGTH-1, "%s", GetTitle()); } else if (mode == 0) { if ( (fNstring && fNval==0 && fNoper==1) || (TestBit(kIsCharacter)) ) { const char * val = 0; if (instance<fNdata[0]) { if (fLookupType[0]==kTreeMember) { val = (char*)GetLeafInfo(0)->GetValuePointer((TLeaf*)0x0,instance); } else { TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); TBranch *branch = leaf->GetBranch(); Long64_t readentry = branch->GetTree()->GetReadEntry(); R__LoadBranch(branch,readentry,fQuickLoad); if (fLookupType[0]==kDirect && fNoper==1) { val = (const char*)leaf->GetValuePointer(); } else { val = ((TTreeFormula*)this)->EvalStringInstance(instance); } } } if (val) { strlcpy(value, val, kMAXLENGTH); } else { value[0] = '\0'; } value[kMAXLENGTH-1] = 0; } else { //NOTE: This is terrible form ... but is forced upon us by the fact that we can not //use the mutable keyword AND we should keep PrintValue const. Int_t real_instance = ((TTreeFormula*)this)->GetRealInstance(instance,-1); if (real_instance<fNdata[0]) { Ssiz_t len = strlen(decform); Char_t outputSizeLevel = 1; char *expo = 0; if (len>2) { switch (decform[len-2]) { case 'l': case 'L': { outputSizeLevel = 2; if (len>3 && tolower(decform[len-3])=='l') { outputSizeLevel = 3; } break; } case 'h': outputSizeLevel = 0; break; } } switch(decform[len-1]) { case 'c': case 'd': case 'i': { switch (outputSizeLevel) { case 0: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(Short_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 2: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(Long_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 3: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(Long64_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 1: default: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(Int_t)((TTreeFormula*)this)->EvalInstance(instance)); break; } break; } case 'o': case 'x': case 'X': case 'u': { switch (outputSizeLevel) { case 0: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(UShort_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 2: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(ULong_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 3: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(ULong64_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 1: default: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(UInt_t)((TTreeFormula*)this)->EvalInstance(instance)); break; } break; } case 'f': case 'e': case 'E': case 'g': case 'G': { switch (outputSizeLevel) { case 2: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(long double)((TTreeFormula*)this)->EvalInstance(instance)); break; case 1: default: snprintf(value,kMAXLENGTH,Form("%%%s",decform),((TTreeFormula*)this)->EvalInstance(instance)); break; } expo = strchr(value,'e'); break; } default: snprintf(value,kMAXLENGTH,Form("%%%sg",decform),((TTreeFormula*)this)->EvalInstance(instance)); expo = strchr(value,'e'); } if (expo) { // If there is an exponent we may be longer than planned. // so let's trim off the excess precission! UInt_t declen = atoi(decform); if (strlen(value)>declen) { UInt_t off = strlen(value)-declen; char *start = expo - off; UInt_t vlen = strlen(expo); for(UInt_t z=0;z<=vlen;++z) { start[z] = expo[z]; } //strcpy(expo-off,expo); } } } else { if (isalpha(decform[strlen(decform)-1])) { TString short_decform(decform); short_decform.Remove(short_decform.Length()-1); snprintf(value,kMAXLENGTH,Form(" %%%sc",short_decform.Data()),' '); } else { snprintf(value,kMAXLENGTH,Form(" %%%sc",decform),' '); } } } } return &value[0]; } //______________________________________________________________________________ void TTreeFormula::ResetLoading() { // Tell the formula that we are going to request a new entry. fNeedLoading = kTRUE; fDidBooleanOptimization = kFALSE; for(Int_t i=0; i<fNcodes; ++i) { UInt_t max_dim = fNdimensions[i]; for(UInt_t dim=0; dim<max_dim ;++dim) { if (fVarIndexes[i][dim]) { fVarIndexes[i][dim]->ResetLoading(); } } } Int_t n = fAliases.GetLast(); if ( fNoper < n ) { n = fNoper; } for(Int_t k=0; k <= n; ++k) { TTreeFormula *f = static_cast<TTreeFormula*>(fAliases.UncheckedAt(k)); if (f) { f->ResetLoading(); } } } //______________________________________________________________________________ void TTreeFormula::SetAxis(TAxis *axis) { // Set the axis (in particular get the type). if (!axis) {fAxis = 0; return;} if (TestBit(kIsCharacter)) { fAxis = axis; if (fNoper==1 && GetAction(0)==kAliasString){ TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); subform->SetAxis(axis); } else if (fNoper==2 && GetAction(0)==kAlternateString){ TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); subform->SetAxis(axis); } } if (IsInteger()) axis->SetBit(TAxis::kIsInteger); } //______________________________________________________________________________ void TTreeFormula::Streamer(TBuffer &R__b) { // Stream an object of class TTreeFormula. if (R__b.IsReading()) { UInt_t R__s, R__c; Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v > 2) { R__b.ReadClassBuffer(TTreeFormula::Class(), this, R__v, R__s, R__c); return; } //====process old versions before automatic schema evolution TFormula::Streamer(R__b); R__b >> fTree; R__b >> fNcodes; R__b.ReadFastArray(fCodes, fNcodes); R__b >> fMultiplicity; Int_t instance; R__b >> instance; //data member removed R__b >> fNindex; if (fNindex) { fLookupType = new Int_t[fNindex]; R__b.ReadFastArray(fLookupType, fNindex); } fMethods.Streamer(R__b); //====end of old versions } else { R__b.WriteClassBuffer(TTreeFormula::Class(),this); } } //______________________________________________________________________________ Bool_t TTreeFormula::StringToNumber(Int_t oper) { // Try to 'demote' a string into an array bytes. If this is not possible, // return false. Int_t code = GetActionParam(oper); if (GetAction(oper)==kDefinedString && fLookupType[code]==kDirect) { if (oper>0 && GetAction(oper-1)==kJump) { // We are the second hand of a ternary operator, let's not do the fixing. return kFALSE; } TLeaf *leaf = (TLeaf*)fLeaves.At(code); if (leaf && (leaf->InheritsFrom(TLeafC::Class()) || leaf->InheritsFrom(TLeafB::Class()) ) ) { SetAction(oper, kDefinedVariable, code ); fNval++; fNstring--; return kTRUE; } } return kFALSE; } //______________________________________________________________________________ void TTreeFormula::UpdateFormulaLeaves() { // this function is called TTreePlayer::UpdateFormulaLeaves, itself // called by TChain::LoadTree when a new Tree is loaded. // Because Trees in a TChain may have a different list of leaves, one // must update the leaves numbers in the TTreeFormula used by the TreePlayer. // A safer alternative would be to recompile the whole thing .... However // currently compile HAS TO be called from the constructor! TString names(kMaxLen); Int_t nleaves = fLeafNames.GetEntriesFast(); ResetBit( kMissingLeaf ); for (Int_t i=0;i<nleaves;i++) { if (!fTree) break; if (!fLeafNames[i]) continue; names.Form("%s/%s",fLeafNames[i]->GetTitle(),fLeafNames[i]->GetName()); TLeaf *leaf = fTree->GetLeaf(names); fLeaves[i] = leaf; if (fBranches[i] && leaf) { fBranches[i]=leaf->GetBranch(); // Since sometimes we might no read all the branches for all the entries, we // might sometimes only read the branch count and thus reset the colleciton // but might not read the data branches, to insure that a subsequent read // from TTreeFormula will properly load the data branches even if fQuickLoad is true, // we reset the entry of all branches in the TTree. ((TBranch*)fBranches[i])->ResetReadEntry(); } if (leaf==0) SetBit( kMissingLeaf ); } for (Int_t j=0; j<kMAXCODES; j++) { for (Int_t k = 0; k<kMAXFORMDIM; k++) { if (fVarIndexes[j][k]) { fVarIndexes[j][k]->UpdateFormulaLeaves(); } } if (fLookupType[j]==kDataMember || fLookupType[j]==kTreeMember) GetLeafInfo(j)->Update(); if (j<fNval && fCodes[j]<0) { TCutG *gcut = (TCutG*)fExternalCuts.At(j); if (gcut) { TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); TTreeFormula *fy = (TTreeFormula *)gcut->GetObjectY(); if (fx) fx->UpdateFormulaLeaves(); if (fy) fy->UpdateFormulaLeaves(); } } } for(Int_t k=0;k<fNoper;k++) { const Int_t oper = GetOper()[k]; switch(oper >> kTFOperShift) { case kAlias: case kAliasString: case kAlternate: case kAlternateString: case kMinIf: case kMaxIf: { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(k)); R__ASSERT(subform); subform->UpdateFormulaLeaves(); break; } case kDefinedVariable: { Int_t code = GetActionParam(k); if (fCodes[code]==0) switch(fLookupType[code]) { case kLengthFunc: case kSum: case kMin: case kMax: { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(k)); R__ASSERT(subform); subform->UpdateFormulaLeaves(); break; } default: break; } } default: break; } } } //______________________________________________________________________________ void TTreeFormula::ResetDimensions() { // Populate the TTreeFormulaManager with the dimension information. Int_t i,k; // Now that we saw all the expressions and variables AND that // we know whether arrays of chars are treated as string or // not, we can properly setup the dimensions. TIter next(fDimensionSetup); Int_t last_code = -1; Int_t virt_dim = 0; for(TDimensionInfo * info; (info = (TDimensionInfo*)next()); ) { if (last_code!=info->fCode) { // We know that the list is ordered by code number then by // dimension. Thus a different code means that we need to // restart at the lowest dimensions. virt_dim = 0; last_code = info->fCode; fNdimensions[last_code] = 0; } if (GetAction(info->fOper)==kDefinedString) { // We have a string used as a string (and not an array of number) // We need to determine which is the last dimension and skip it. TDimensionInfo *nextinfo = (TDimensionInfo*)next(); while(nextinfo && nextinfo->fCode==info->fCode) { DefineDimensions(info->fCode,info->fSize, info->fMultiDim, virt_dim); nextinfo = (TDimensionInfo*)next(); } if (!nextinfo) break; info = nextinfo; virt_dim = 0; last_code = info->fCode; fNdimensions[last_code] = 0; info->fSize = 1; // Maybe this should actually do nothing! } DefineDimensions(info->fCode,info->fSize, info->fMultiDim, virt_dim); } fMultiplicity = 0; for(i=0;i<fNoper;i++) { Int_t action = GetAction(i); if (action==kMinIf || action==kMaxIf) { // Skip/Ignore the 2nd args ++i; continue; } if (action==kAlias || action==kAliasString) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(i)); R__ASSERT(subform); switch(subform->GetMultiplicity()) { case 0: break; case 1: fMultiplicity = 1; break; case 2: if (fMultiplicity!=1) fMultiplicity = 2; break; } fManager->Add(subform); // since we are addint to this manager 'subform->ResetDimensions();' // will be called a little latter continue; } if (action==kDefinedString) { //if (fOper[i] >= 105000 && fOper[i]<110000) { // We have a string used as a string // This dormant portion of code would be used if (when?) we allow the histogramming // of the integral content (as opposed to the string content) of strings // held in a variable size container delimited by a null (as opposed to // a fixed size container or variable size container whose size is controlled // by a variable). In GetNdata, we will then use strlen to grab the current length. //fCumulSizes[i][fNdimensions[i]-1] = 1; //fUsedSizes[fNdimensions[i]-1] = -TMath::Abs(fUsedSizes[fNdimensions[i]-1]); //fUsedSizes[0] = - TMath::Abs( fUsedSizes[0]); //continue; } } for (i=0;i<fNcodes;i++) { if (fCodes[i] < 0) { TCutG *gcut = (TCutG*)fExternalCuts.At(i); if (!gcut) continue; TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); TTreeFormula *fy = (TTreeFormula *)gcut->GetObjectY(); if (fx) { switch(fx->GetMultiplicity()) { case 0: break; case 1: fMultiplicity = 1; break; case 2: if (fMultiplicity!=1) fMultiplicity = 2; break; } fManager->Add(fx); } if (fy) { switch(fy->GetMultiplicity()) { case 0: break; case 1: fMultiplicity = 1; break; case 2: if (fMultiplicity!=1) fMultiplicity = 2; break; } fManager->Add(fy); } continue; } if (fLookupType[i]==kIteration) { fMultiplicity = 1; continue; } TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(i); if (!leaf) continue; // Reminder of the meaning of fMultiplicity: // -1: Only one or 0 element per entry but contains variable length // -array! (Only used for TTreeFormulaManager) // 0: Only one element per entry, no variable length array // 1: loop over the elements of a variable length array // 2: loop over elements of fixed length array (nData is the same for all entry) if (leaf->GetLeafCount()) { // We assume only one possible variable length dimension (the left most) fMultiplicity = 1; } else if (fLookupType[i]==kDataMember) { TFormLeafInfo * leafinfo = GetLeafInfo(i); TStreamerElement * elem = leafinfo->fElement; if (fMultiplicity!=1) { if (leafinfo->HasCounter() ) fMultiplicity = 1; else if (elem && elem->GetArrayDim()>0) fMultiplicity = 2; else if (leaf->GetLenStatic()>1) fMultiplicity = 2; } } else { if (leaf->GetLenStatic()>1 && fMultiplicity!=1) fMultiplicity = 2; } if (fMultiplicity!=1) { // If the leaf belongs to a friend tree which has an index, we might // be in the case where some entry do not exist. TTree *realtree = fTree ? fTree->GetTree() : 0; TTree *tleaf = leaf->GetBranch()->GetTree(); if (tleaf && tleaf != realtree && tleaf->GetTreeIndex()) { // Reset the multiplicity if we have a friend tree with an index. fMultiplicity = 1; } } Int_t virt_dim2 = 0; for (k = 0; k < fNdimensions[i]; k++) { // At this point fCumulSizes[i][k] actually contain the physical // dimension of the k-th dimensions. if ( (fCumulSizes[i][k]>=0) && (fIndexes[i][k] >= fCumulSizes[i][k]) ) { // unreacheable element requested: fManager->CancelDimension(virt_dim2); // fCumulUsedSizes[virt_dim2] = 0; } if ( fIndexes[i][k] < 0 ) virt_dim2++; fFixedSizes[i][k] = fCumulSizes[i][k]; } // Add up the cumulative size for (k = fNdimensions[i]; (k > 0); k--) { // NOTE: When support for inside variable dimension is added this // will become inacurate (since one of the value in the middle of the chain // is unknown until GetNdata is called. fCumulSizes[i][k-1] *= TMath::Abs(fCumulSizes[i][k]); } // NOTE: We assume that the inside variable dimensions are dictated by the // first index. if (fCumulSizes[i][0]>0) fNdata[i] = fCumulSizes[i][0]; //for (k = 0; k<kMAXFORMDIM; k++) { // if (fVarIndexes[i][k]) fManager->Add(fVarIndexes[i][k]); //} } } //______________________________________________________________________________ void TTreeFormula::LoadBranches() { // Make sure that all the branches have been loaded properly. Int_t i; for (i=0; i<fNoper ; ++i) { TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(i); if (leaf==0) continue; TBranch *br = leaf->GetBranch(); Long64_t treeEntry = br->GetTree()->GetReadEntry(); R__LoadBranch(br,treeEntry,kTRUE); TTreeFormula *alias = (TTreeFormula*)fAliases.UncheckedAt(i); if (alias) alias->LoadBranches(); Int_t max_dim = fNdimensions[i]; for (Int_t dim = 0; dim < max_dim; ++dim) { if (fVarIndexes[i][dim]) fVarIndexes[i][dim]->LoadBranches(); } } } //______________________________________________________________________________ Bool_t TTreeFormula::LoadCurrentDim() { // Calculate the actual dimension for the current entry. Int_t size; Bool_t outofbounds = kFALSE; for (Int_t i=0;i<fNcodes;i++) { if (fCodes[i] < 0) continue; // NOTE: Currently only the leafcount can indicates a dimension that // is physically variable. So only the left-most dimension is variable. // When an API is introduced to be able to determine a variable inside dimensions // one would need to add a way to recalculate the values of fCumulSizes for this // leaf. This would probably require the addition of a new data member // fSizes[kMAXCODES][kMAXFORMDIM]; // Also note that EvalInstance expect all the values (but the very first one) // of fCumulSizes to be positive. So indicating that a physical dimension is // variable (expected for the first one) can NOT be done via negative values of // fCumulSizes. TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(i); if (!leaf) { switch(fLookupType[i]) { case kDirect: case kMethod: case kTreeMember: case kDataMember: fNdata[i] = 0; outofbounds = kTRUE; } continue; } TTree *realtree = fTree->GetTree(); TTree *tleaf = leaf->GetBranch()->GetTree(); if (tleaf && tleaf != realtree && tleaf->GetTreeIndex()) { if (tleaf->GetReadEntry()==-1) { fNdata[i] = 0; outofbounds = kTRUE; continue; } else { fNdata[i] = fCumulSizes[i][0]; } } Bool_t hasBranchCount2 = kFALSE; if (leaf->GetLeafCount()) { TLeaf* leafcount = leaf->GetLeafCount(); TBranch *branchcount = leafcount->GetBranch(); TFormLeafInfo * info = 0; if (leaf->IsA() == TLeafElement::Class()) { //if branchcount address not yet set, GetEntry will set the address // read branchcount value Long64_t readentry = leaf->GetBranch()->GetTree()->GetReadEntry(); if (readentry==-1) readentry=0; if (!branchcount->GetAddress()) { R__LoadBranch(branchcount, readentry, fQuickLoad); } else { // Since we do not read the full branch let's reset the read entry number // so that a subsequent read from TTreeFormula will properly load the full // object even if fQuickLoad is true. branchcount->TBranch::GetEntry(readentry); branchcount->ResetReadEntry(); } size = ((TBranchElement*)branchcount)->GetNdata(); // Reading the size as above is correct only when the branchcount // is of streamer type kCounter which require the underlying data // member to be signed integral type. TBranchElement* branch = (TBranchElement*) leaf->GetBranch(); // NOTE: could be sped up if (fHasMultipleVarDim[i]) {// info && info->GetVarDim()>=0) { info = (TFormLeafInfo* )fDataMembers.At(i); if (branch->GetBranchCount2()) R__LoadBranch(branch->GetBranchCount2(),readentry,fQuickLoad); else R__LoadBranch(branch,readentry,fQuickLoad); // Here we need to add the code to take in consideration the // double variable length // We fill up the array of sizes in the TLeafInfo: info->LoadSizes(branch); hasBranchCount2 = kTRUE; if (info->GetVirtVarDim()>=0) info->UpdateSizes(fManager->fVarDims[info->GetVirtVarDim()]); // Refresh the fCumulSizes[i] to have '1' for the // double variable dimensions Int_t vdim = info->GetVarDim(); fCumulSizes[i][vdim] = fCumulSizes[i][vdim+1]; for(Int_t k=vdim -1; k>=0; k--) { fCumulSizes[i][k] = fCumulSizes[i][k+1]*fFixedSizes[i][k]; } // Update fCumulUsedSizes // UpdateMultiVarSizes(vdim,info,i) //Int_t fixed = fCumulSizes[i][vdim+1]; //for(Int_t k=vdim - 1; k>=0; k++) { // Int_t fixed *= fFixedSizes[i][k]; // for(Int_t l=0;l<size; l++) { // fCumulSizes[i][k] += info->GetSize(l) * fixed; //} } } else { Long64_t readentry = leaf->GetBranch()->GetTree()->GetReadEntry(); if (readentry==-1) readentry=0; R__LoadBranch(branchcount,readentry,fQuickLoad); size = leaf->GetLen() / leaf->GetLenStatic(); } if (hasBranchCount2) { // We assume that fCumulSizes[i][1] contains the product of the fixed sizes fNdata[i] = fCumulSizes[i][1] * ((TFormLeafInfo *)fDataMembers.At(i))->GetSumOfSizes(); } else { fNdata[i] = size * fCumulSizes[i][1]; } if (fIndexes[i][0]==-1) { // Case where the index is not specified AND the 1st dimension has a variable // size. if (fManager->fUsedSizes[0]==1 || (size<fManager->fUsedSizes[0]) ) fManager->fUsedSizes[0] = size; if (info && fIndexes[i][info->GetVarDim()]>=0) { for(Int_t j=0; j<size; j++) { if (fIndexes[i][info->GetVarDim()] >= info->GetSize(j)) { info->SetSize(j,0); if (size>fManager->fCumulUsedVarDims->GetSize()) fManager->fCumulUsedVarDims->Set(size); fManager->fCumulUsedVarDims->AddAt(-1,j); } else if (fIndexes[i][info->GetVarDim()]>=0) { // There is an index and it is not too large info->SetSize(j,1); if (size>fManager->fCumulUsedVarDims->GetSize()) fManager->fCumulUsedVarDims->Set(size); fManager->fCumulUsedVarDims->AddAt(1,j); } } } } else if (fIndexes[i][0] >= size) { // unreacheable element requested: fManager->fUsedSizes[0] = 0; fNdata[i] = 0; outofbounds = kTRUE; } else if (hasBranchCount2) { TFormLeafInfo *info2; info2 = (TFormLeafInfo *)fDataMembers.At(i); if (fIndexes[i][0]<0 || fIndexes[i][info2->GetVarDim()] >= info2->GetSize(fIndexes[i][0])) { // unreacheable element requested: fManager->fUsedSizes[0] = 0; fNdata[i] = 0; outofbounds = kTRUE; } } } else if (fLookupType[i]==kDataMember) { TFormLeafInfo *leafinfo = (TFormLeafInfo*)fDataMembers.UncheckedAt(i); if (leafinfo->HasCounter()) { TBranch *branch = leaf->GetBranch(); Long64_t readentry = branch->GetTree()->GetReadEntry(); if (readentry==-1) readentry=0; R__LoadBranch(branch,readentry,fQuickLoad); size = (Int_t) leafinfo->GetCounterValue(leaf); if (fIndexes[i][0]==-1) { // Case where the index is not specified AND the 1st dimension has a variable // size. if (fManager->fUsedSizes[0]==1 || (size<fManager->fUsedSizes[0]) ) { fManager->fUsedSizes[0] = size; } } else if (fIndexes[i][0] >= size) { // unreacheable element requested: fManager->fUsedSizes[0] = 0; fNdata[i] = 0; outofbounds = kTRUE; } else { fNdata[i] = size*fCumulSizes[i][1]; } Int_t vdim = leafinfo->GetVarDim(); if (vdim>=0) { // Here we need to add the code to take in consideration the // double variable length // We fill up the array of sizes in the TLeafInfo: // here we can assume that branch is a TBranch element because the other style does NOT support this type // of complexity. leafinfo->LoadSizes(branch); hasBranchCount2 = kTRUE; if (fIndexes[i][0]==-1&&fIndexes[i][vdim] >= 0) { for(int z=0; z<size; ++z) { if (fIndexes[i][vdim] >= leafinfo->GetSize(z)) { leafinfo->SetSize(z,0); // --fManager->fUsedSizes[0]; } else if (fIndexes[i][vdim] >= 0 ) { leafinfo->SetSize(z,1); } } } leafinfo->UpdateSizes(fManager->fVarDims[vdim]); // Refresh the fCumulSizes[i] to have '1' for the // double variable dimensions fCumulSizes[i][vdim] = fCumulSizes[i][vdim+1]; for(Int_t k=vdim -1; k>=0; k--) { fCumulSizes[i][k] = fCumulSizes[i][k+1]*fFixedSizes[i][k]; } fNdata[i] = fCumulSizes[i][1] * leafinfo->GetSumOfSizes(); } else { fNdata[i] = size * fCumulSizes[i][1]; } } else if (leafinfo->GetMultiplicity()==-1) { TBranch *branch = leaf->GetBranch(); Long64_t readentry = branch->GetTree()->GetReadEntry(); if (readentry==-1) readentry=0; R__LoadBranch(branch,readentry,fQuickLoad); if (leafinfo->GetNdata(leaf)==0) { outofbounds = kTRUE; } } } // However we allow several dimensions that virtually vary via the size of their // index variables. So we have code to recalculate fCumulUsedSizes. Int_t index; TFormLeafInfo * info = 0; if (fLookupType[i]!=kDirect) { info = (TFormLeafInfo *)fDataMembers.At(i); } for(Int_t k=0, virt_dim=0; k < fNdimensions[i]; k++) { if (fIndexes[i][k]<0) { if (fIndexes[i][k]==-2 && fManager->fVirtUsedSizes[virt_dim]<0) { // if fVirtUsedSize[virt_dim] is positive then VarIndexes[i][k]->GetNdata() // is always the same and has already been factored in fUsedSize[virt_dim] index = fVarIndexes[i][k]->GetNdata(); if (index==1) { // We could either have a variable size array which is currently of size one // or a single element that might or not might not be present (and is currently present!) if (fVarIndexes[i][k]->GetManager()->GetMultiplicity()==1) { if (index<fManager->fUsedSizes[virt_dim]) fManager->fUsedSizes[virt_dim] = index; } } else if (fManager->fUsedSizes[virt_dim]==-fManager->fVirtUsedSizes[virt_dim] || index<fManager->fUsedSizes[virt_dim]) { fManager->fUsedSizes[virt_dim] = index; } } else if (hasBranchCount2 && info && k==info->GetVarDim()) { // NOTE: We assume the indexing of variable sizes on the first index! if (fIndexes[i][0]>=0) { index = info->GetSize(fIndexes[i][0]); if (fManager->fUsedSizes[virt_dim]==1 || (index!=1 && index<fManager->fUsedSizes[virt_dim]) ) fManager->fUsedSizes[virt_dim] = index; } } virt_dim++; } else if (hasBranchCount2 && info && k==info->GetVarDim()) { // nothing to do, at some point I thought this might be useful: // if (fIndexes[i][k]>=0) { // index = info->GetSize(fIndexes[i][k]); // if (fManager->fUsedSizes[virt_dim]==1 || (index!=1 && index<fManager->fUsedSizes[virt_dim]) ) // fManager->fUsedSizes[virt_dim] = index; // virt_dim++; // } } } } return ! outofbounds; } void TTreeFormula::Convert(UInt_t oldversion) { // Convert the fOper of a TTTreeFormula version fromVersion to the current in memory version enum { kOldAlias = /*TFormula::kVariable*/ 100000+10000+1, kOldAliasString = kOldAlias+1, kOldAlternate = kOldAlias+2, kOldAlternateString = kOldAliasString+2 }; for (int k=0; k<fNoper; k++) { // First hide from TFormula convertion Int_t action = GetOper()[k]; switch (action) { case kOldAlias: GetOper()[k] = -kOldAlias; break; case kOldAliasString: GetOper()[k] = -kOldAliasString; break; case kOldAlternate: GetOper()[k] = -kOldAlternate; break; case kOldAlternateString: GetOper()[k] = -kOldAlternateString; break; } } TFormula::Convert(oldversion); for (int i=0,offset=0; i<fNoper; i++) { Int_t action = GetOper()[i+offset]; switch (action) { case -kOldAlias: SetAction(i, kAlias, 0); break; case -kOldAliasString: SetAction(i, kAliasString, 0); break; case -kOldAlternate: SetAction(i, kAlternate, 0); break; case -kOldAlternateString: SetAction(i, kAlternateString, 0); break; } } } //______________________________________________________________________________ Bool_t TTreeFormula::SwitchToFormLeafInfo(Int_t code) { // Convert the underlying lookup method from the direct technique // (dereferencing the address held by the branch) to the method using // TFormLeafInfo. This is in particular usefull in the case where we // need to append an additional TFormLeafInfo (for example to call a // method). // Return false if the switch was unsuccessfull (basically in the // case of an old style split tree). TFormLeafInfo *last = 0; TLeaf *leaf = (TLeaf*)fLeaves.At(code); if (!leaf) return kFALSE; if (fLookupType[code]==kDirect) { if (leaf->InheritsFrom(TLeafElement::Class())) { TBranchElement * br = (TBranchElement*)leaf->GetBranch(); if (br->GetType()==31) { // sub branch of a TClonesArray TStreamerInfo *info = br->GetInfo(); TClass* cl = info->GetClass(); TStreamerElement *element = (TStreamerElement *)info->GetElems()[br->GetID()]; TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(cl, 0, element, kTRUE); Int_t offset; info->GetStreamerElement(element->GetName(),offset); clonesinfo->fNext = new TFormLeafInfo(cl,offset+br->GetOffset(),element); last = clonesinfo->fNext; fDataMembers.AddAtAndExpand(clonesinfo,code); fLookupType[code]=kDataMember; } else if (br->GetType()==41) { // sub branch of a Collection TBranchElement *count = br->GetBranchCount(); TFormLeafInfo* collectioninfo; if ( count->GetID() >= 0 ) { TStreamerElement *collectionElement = (TStreamerElement *)count->GetInfo()->GetElems()[count->GetID()]; TClass *collectionCl = collectionElement->GetClassPointer(); collectioninfo = new TFormLeafInfoCollection(collectionCl, 0, collectionElement, kTRUE); } else { TClass *collectionCl = TClass::GetClass(count->GetClassName()); collectioninfo = new TFormLeafInfoCollection(collectionCl, 0, collectionCl, kTRUE); } TStreamerInfo *info = br->GetInfo(); TClass* cl = info->GetClass(); TStreamerElement *element = (TStreamerElement *)info->GetElems()[br->GetID()]; Int_t offset; info->GetStreamerElement(element->GetName(),offset); collectioninfo->fNext = new TFormLeafInfo(cl,offset+br->GetOffset(),element); last = collectioninfo->fNext; fDataMembers.AddAtAndExpand(collectioninfo,code); fLookupType[code]=kDataMember; } else if (br->GetID()<0) { return kFALSE; } else { last = new TFormLeafInfoDirect(br); fDataMembers.AddAtAndExpand(last,code); fLookupType[code]=kDataMember; } } else { //last = new TFormLeafInfoDirect(br); //fDataMembers.AddAtAndExpand(last,code); //fLookupType[code]=kDataMember; return kFALSE; } } return kTRUE; } Properly handle the fact that LoadTree call also return -2 as an error code git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@38500 27541ba8-7e3a-0410-8455-c3a389f83636 // @(#)root/treeplayer:$Id$ // Author: Rene Brun 19/01/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TROOT.h" #include "TTreeFormula.h" #include "TTree.h" #include "TBranch.h" #include "TBranchObject.h" #include "TFunction.h" #include "TClonesArray.h" #include "TLeafB.h" #include "TLeafC.h" #include "TLeafObject.h" #include "TDataMember.h" #include "TMethodCall.h" #include "TCutG.h" #include "TRandom.h" #include "TInterpreter.h" #include "TDataType.h" #include "TStreamerInfo.h" #include "TStreamerElement.h" #include "TBranchElement.h" #include "TLeafElement.h" #include "TArrayI.h" #include "TAxis.h" #include "TError.h" #include "TVirtualCollectionProxy.h" #include "TString.h" #include "TTimeStamp.h" #include "TMath.h" #include "TVirtualRefProxy.h" #include "TTreeFormulaManager.h" #include "TFormLeafInfo.h" #include "TMethod.h" #include "TBaseClass.h" #include "TFormLeafInfoReference.h" #include "TEntryList.h" #include <ctype.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <typeinfo> #include <algorithm> const Int_t kMaxLen = 1024; R__EXTERN TTree *gTree; ClassImp(TTreeFormula) //______________________________________________________________________________ // // TTreeFormula now relies on a variety of TFormLeafInfo classes to handle the // reading of the information. Here is the list of theses classes: // TFormLeafInfo // TFormLeafInfoDirect // TFormLeafInfoNumerical // TFormLeafInfoClones // TFormLeafInfoCollection // TFormLeafInfoPointer // TFormLeafInfoMethod // TFormLeafInfoMultiVarDim // TFormLeafInfoMultiVarDimDirect // TFormLeafInfoCast // // The following method are available from the TFormLeafInfo interface: // // AddOffset(Int_t offset, TStreamerElement* element) // GetCounterValue(TLeaf* leaf) : return the size of the array pointed to. // GetObjectAddress(TLeafElement* leaf) : Returns the the location of the object pointed to. // GetMultiplicity() : Returns info on the variability of the number of elements // GetNdata(TLeaf* leaf) : Returns the number of elements // GetNdata() : Used by GetNdata(TLeaf* leaf) // GetValue(TLeaf *leaf, Int_t instance = 0) : Return the value // GetValuePointer(TLeaf *leaf, Int_t instance = 0) : Returns the address of the value // GetLocalValuePointer(TLeaf *leaf, Int_t instance = 0) : Returns the address of the value of 'this' LeafInfo // IsString() // ReadValue(char *where, Int_t instance = 0) : Internal function to interpret the location 'where' // Update() : react to the possible loading of a shared library. // // //______________________________________________________________________________ inline static void R__LoadBranch(TBranch* br, Long64_t entry, Bool_t quickLoad) { if (!quickLoad || (br->GetReadEntry() != entry)) { br->GetEntry(entry); } } //______________________________________________________________________________ // // This class is a small helper class to help in keeping track of the array // dimensions encountered in the analysis of the expression. class TDimensionInfo : public TObject { public: Int_t fCode; // Location of the leaf in TTreeFormula::fCode Int_t fOper; // Location of the Operation using the leaf in TTreeFormula::fOper Int_t fSize; TFormLeafInfoMultiVarDim* fMultiDim; TDimensionInfo(Int_t code, Int_t oper, Int_t size, TFormLeafInfoMultiVarDim* multiDim) : fCode(code), fOper(oper), fSize(size), fMultiDim(multiDim) {}; ~TDimensionInfo() {}; }; //______________________________________________________________________________ // // A TreeFormula is used to pass a selection expression // to the Tree drawing routine. See TTree::Draw // // A TreeFormula can contain any arithmetic expression including // standard operators and mathematical functions separated by operators. // Examples of valid expression: // "x<y && sqrt(z)>3.2" // //______________________________________________________________________________ TTreeFormula::TTreeFormula(): TFormula(), fQuickLoad(kFALSE), fNeedLoading(kTRUE), fDidBooleanOptimization(kFALSE), fDimensionSetup(0) { // Tree Formula default constructor fTree = 0; fLookupType = 0; fNindex = 0; fNcodes = 0; fAxis = 0; fHasCast = 0; fManager = 0; fMultiplicity = 0; Int_t j,k; for (j=0; j<kMAXCODES; j++) { fNdimensions[j] = 0; fCodes[j] = 0; fNdata[j] = 1; fHasMultipleVarDim[j] = kFALSE; for (k = 0; k<kMAXFORMDIM; k++) { fIndexes[j][k] = -1; fCumulSizes[j][k] = 1; fVarIndexes[j][k] = 0; } } } //______________________________________________________________________________ TTreeFormula::TTreeFormula(const char *name,const char *expression, TTree *tree) :TFormula(), fTree(tree), fQuickLoad(kFALSE), fNeedLoading(kTRUE), fDidBooleanOptimization(kFALSE), fDimensionSetup(0) { // Normal TTree Formula Constuctor Init(name,expression); } //______________________________________________________________________________ TTreeFormula::TTreeFormula(const char *name,const char *expression, TTree *tree, const std::vector<std::string>& aliases) :TFormula(), fTree(tree), fQuickLoad(kFALSE), fNeedLoading(kTRUE), fDidBooleanOptimization(kFALSE), fDimensionSetup(0), fAliasesUsed(aliases) { // Constructor used during the expansion of an alias Init(name,expression); } //______________________________________________________________________________ void TTreeFormula::Init(const char*name, const char* expression) { // Initialiation called from the constructors. TDirectory *const savedir=gDirectory; fNindex = kMAXFOUND; fLookupType = new Int_t[fNindex]; fNcodes = 0; fMultiplicity = 0; fAxis = 0; fHasCast = 0; Int_t i,j,k; fManager = new TTreeFormulaManager; fManager->Add(this); for (j=0; j<kMAXCODES; j++) { fNdimensions[j] = 0; fLookupType[j] = kDirect; fCodes[j] = 0; fNdata[j] = 1; fHasMultipleVarDim[j] = kFALSE; for (k = 0; k<kMAXFORMDIM; k++) { fIndexes[j][k] = -1; fCumulSizes[j][k] = 1; fVarIndexes[j][k] = 0; } } fDimensionSetup = new TList; if (Compile(expression)) { fTree = 0; fNdim = 0; if(savedir) savedir->cd(); return; } if (fNcodes >= kMAXFOUND) { Warning("TTreeFormula","Too many items in expression:%s",expression); fNcodes = kMAXFOUND; } SetName(name); for (i=0;i<fNoper;i++) { if (GetAction(i)==kDefinedString) { Int_t string_code = GetActionParam(i); TLeaf *leafc = (TLeaf*)fLeaves.UncheckedAt(string_code); if (!leafc) continue; // We have a string used as a string // This dormant portion of code would be used if (when?) we allow the histogramming // of the integral content (as opposed to the string content) of strings // held in a variable size container delimited by a null (as opposed to // a fixed size container or variable size container whose size is controlled // by a variable). In GetNdata, we will then use strlen to grab the current length. //fCumulSizes[i][fNdimensions[i]-1] = 1; //fUsedSizes[fNdimensions[i]-1] = -TMath::Abs(fUsedSizes[fNdimensions[i]-1]); //fUsedSizes[0] = - TMath::Abs( fUsedSizes[0]); if (fNcodes == 1) { // If the string is by itself, then it can safely be histogrammed as // in a string based axis. To histogram the number inside the string // just make it part of a useless expression (for example: mystring+0) SetBit(kIsCharacter); } continue; } if (GetAction(i)==kJump && GetActionParam(i)==(fNoper-1)) { // We have cond ? string1 : string2 if (IsString(fNoper-1)) SetBit(kIsCharacter); } } if (fNoper==1 && GetAction(0)==kAliasString) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); if (subform->TestBit(kIsCharacter)) SetBit(kIsCharacter); } else if (fNoper==2 && GetAction(0)==kAlternateString) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); if (subform->TestBit(kIsCharacter)) SetBit(kIsCharacter); } fManager->Sync(); // Let's verify the indexes and dies if we need to. Int_t k0,k1; for(k0 = 0; k0 < fNcodes; k0++) { for(k1 = 0; k1 < fNdimensions[k0]; k1++ ) { // fprintf(stderr,"Saw %d dim %d and index %d\n",k1, fFixedSizes[k0][k1], fIndexes[k0][k1]); if ( fIndexes[k0][k1]>=0 && fFixedSizes[k0][k1]>=0 && fIndexes[k0][k1]>=fFixedSizes[k0][k1]) { Error("TTreeFormula", "Index %d for dimension #%d in %s is too high (max is %d)", fIndexes[k0][k1],k1+1, expression,fFixedSizes[k0][k1]-1); fTree = 0; fNdim = 0; if(savedir) savedir->cd(); return; } } } // Create a list of uniques branches to load. for(k=0; k<fNcodes; k++) { TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(k); TBranch *branch = 0; if (leaf) { branch = leaf->GetBranch(); if (fBranches.FindObject(branch)) branch = 0; } fBranches.AddAtAndExpand(branch,k); } if (IsInteger(kFALSE)) SetBit(kIsInteger); if (TestBit(TTreeFormula::kNeedEntries)) { // Call TTree::GetEntries() to insure that it is already calculated. // This will need to be done anyway at the first iteration and insure // that it will not mess up the branch reading (because TTree::GetEntries // opens all the file in the chain and 'stays' on the last file. Long64_t readentry = fTree->GetReadEntry(); Int_t treenumber = fTree->GetTreeNumber(); fTree->GetEntries(); if (treenumber != fTree->GetTreeNumber()) { if (readentry >= 0) { fTree->LoadTree(readentry); } UpdateFormulaLeaves(); } else { if (readentry >= 0) { fTree->LoadTree(readentry); } } } if(savedir) savedir->cd(); } //______________________________________________________________________________ TTreeFormula::~TTreeFormula() { //*-*-*-*-*-*-*-*-*-*-*Tree Formula default destructor*-*-*-*-*-*-*-*-*-*-* //*-* ================================= if (fManager) { fManager->Remove(this); if (fManager->fFormulas.GetLast()<0) { delete fManager; fManager = 0; } } // Objects in fExternalCuts are not owned and should not be deleted // fExternalCuts.Clear(); fLeafNames.Delete(); fDataMembers.Delete(); fMethods.Delete(); fAliases.Delete(); if (fLookupType) delete [] fLookupType; for (int j=0; j<fNcodes; j++) { for (int k = 0; k<fNdimensions[j]; k++) { if (fVarIndexes[j][k]) delete fVarIndexes[j][k]; fVarIndexes[j][k] = 0; } } if (fDimensionSetup) { fDimensionSetup->Delete(); delete fDimensionSetup; } } //______________________________________________________________________________ void TTreeFormula::DefineDimensions(Int_t code, Int_t size, TFormLeafInfoMultiVarDim * info, Int_t& virt_dim) { // This method is used internally to decode the dimensions of the variables if (info) { fManager->EnableMultiVarDims(); //if (fIndexes[code][info->fDim]<0) { // removed because the index might be out of bounds! info->fVirtDim = virt_dim; fManager->AddVarDims(virt_dim); // if (!fVarDims[virt_dim]) fVarDims[virt_dim] = new TArrayI; //} } Int_t vsize = 0; if (fIndexes[code][fNdimensions[code]]==-2) { TTreeFormula *indexvar = fVarIndexes[code][fNdimensions[code]]; // ASSERT(indexvar!=0); Int_t index_multiplicity = indexvar->GetMultiplicity(); switch (index_multiplicity) { case -1: case 0: case 2: vsize = indexvar->GetNdata(); break; case 1: vsize = -1; break; }; } else vsize = size; fCumulSizes[code][fNdimensions[code]] = size; if ( fIndexes[code][fNdimensions[code]] < 0 ) { fManager->UpdateUsedSize(virt_dim, vsize); } fNdimensions[code] ++; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(const char *info, Int_t code) { // This method is used internally to decode the dimensions of the variables // We assume that there are NO white spaces in the info string const char * current; Int_t size, scanindex, vardim; current = info; vardim = 0; // the next value could be before the string but // that's okay because the next operation is ++ // (this is to avoid (?) a if statement at the end of the // loop) if (current[0] != '[') current--; while (current) { current++; scanindex = sscanf(current,"%d",&size); // if scanindex is 0 then we have a name index thus a variable // array (or TClonesArray!). if (scanindex==0) size = -1; vardim += RegisterDimensions(code, size); if (fNdimensions[code] >= kMAXFORMDIM) { // NOTE: test that fNdimensions[code] is NOT too big!! break; } current = (char*)strstr( current, "[" ); } return vardim; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(Int_t code, Int_t size, TFormLeafInfoMultiVarDim * multidim) { // This method stores the dimension information for later usage. TDimensionInfo * info = new TDimensionInfo(code,fNoper,size,multidim); fDimensionSetup->Add(info); fCumulSizes[code][fNdimensions[code]] = size; fNdimensions[code] ++; return (size==-1) ? 1 : 0; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(Int_t code, TFormLeafInfo *leafinfo, TFormLeafInfo * /* maininfo */, Bool_t useCollectionObject) { // This method is used internally to decode the dimensions of the variables Int_t ndim, size, current, vardim; vardim = 0; const TStreamerElement * elem = leafinfo->fElement; TClass* c = elem ? elem->GetClassPointer() : 0; TFormLeafInfoMultiVarDim * multi = dynamic_cast<TFormLeafInfoMultiVarDim * >(leafinfo); if (multi) { // We have a second variable dimensions fManager->EnableMultiVarDims(); multi->fDim = fNdimensions[code]; return RegisterDimensions(code, -1, multi); } if (elem->IsA() == TStreamerBasicPointer::Class()) { if (elem->GetArrayDim()>0) { ndim = elem->GetArrayDim(); size = elem->GetMaxIndex(0); vardim += RegisterDimensions(code, -1); } else { ndim = 1; size = -1; } TStreamerBasicPointer *array = (TStreamerBasicPointer*)elem; TClass *cl = leafinfo->fClass; Int_t offset; TStreamerElement* counter = ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(array->GetCountName(),offset); #if 1 leafinfo->fCounter = new TFormLeafInfo(cl,offset,counter); #else /* Code is not ready yet see revision 14078 */ if (maininfo==0 || maininfo==leafinfo || 1) { leafinfo->fCounter = new TFormLeafInfo(cl,offset,counter); } else { leafinfo->fCounter = maininfo->DeepCopy(); TFormLeafInfo *currentinfo = leafinfo->fCounter; while(currentinfo->fNext && currentinfo->fNext->fNext) currentinfo=currentinfo->fNext; delete currentinfo->fNext; currentinfo->fNext = new TFormLeafInfo(cl,offset,counter); } #endif } else if (!useCollectionObject && elem->GetClassPointer() == TClonesArray::Class() ) { ndim = 1; size = -1; TClass * clonesClass = TClonesArray::Class(); Int_t c_offset; TStreamerElement *counter = ((TStreamerInfo*)clonesClass->GetStreamerInfo())->GetStreamerElement("fLast",c_offset); leafinfo->fCounter = new TFormLeafInfo(clonesClass,c_offset,counter); } else if (!useCollectionObject && elem->GetClassPointer() && elem->GetClassPointer()->GetCollectionProxy() ) { if ( typeid(*leafinfo) == typeid(TFormLeafInfoCollection) ) { ndim = 1; size = -1; } else { R__ASSERT( fHasMultipleVarDim[code] ); ndim = 1; size = 1; } } else if ( c && c->GetReferenceProxy() && c->GetReferenceProxy()->HasCounter() ) { ndim = 1; size = -1; } else if (elem->GetArrayDim()>0) { ndim = elem->GetArrayDim(); size = elem->GetMaxIndex(0); } else if ( elem->GetNewType()== TStreamerInfo::kCharStar) { // When we implement being able to read the length from // strlen, we will have: // ndim = 1; // size = -1; // until then we more or so die: ndim = 1; size = 1; //NOTE: changed from 0 } else return 0; current = 0; do { vardim += RegisterDimensions(code, size); if (fNdimensions[code] >= kMAXFORMDIM) { // NOTE: test that fNdimensions[code] is NOT too big!! break; } current++; size = elem->GetMaxIndex(current); } while (current<ndim); return vardim; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(Int_t code, TBranchElement *branch) { // This method is used internally to decode the dimensions of the variables TBranchElement * leafcount2 = branch->GetBranchCount2(); if (leafcount2) { // With have a second variable dimensions TBranchElement *leafcount = dynamic_cast<TBranchElement*>(branch->GetBranchCount()); R__ASSERT(leafcount); // The function should only be called on a functional TBranchElement object fManager->EnableMultiVarDims(); TFormLeafInfoMultiVarDim * info = new TFormLeafInfoMultiVarDimDirect(); fDataMembers.AddAtAndExpand(info, code); fHasMultipleVarDim[code] = kTRUE; info->fCounter = new TFormLeafInfoDirect(leafcount); info->fCounter2 = new TFormLeafInfoDirect(leafcount2); info->fDim = fNdimensions[code]; //if (fIndexes[code][info->fDim]<0) { // info->fVirtDim = virt_dim; // if (!fVarDims[virt_dim]) fVarDims[virt_dim] = new TArrayI; //} return RegisterDimensions(code, -1, info); } return 0; } //______________________________________________________________________________ Int_t TTreeFormula::RegisterDimensions(Int_t code, TLeaf *leaf) { // This method is used internally to decode the dimensions of the variables Int_t numberOfVarDim = 0; // Let see if we can understand the structure of this branch. // Usually we have: leafname[fixed_array] leaftitle[var_array]\type // (with fixed_array that can be a multi-dimension array. const char *tname = leaf->GetTitle(); char *leaf_dim = (char*)strstr( tname, "[" ); const char *bname = leaf->GetBranch()->GetName(); char *branch_dim = (char*)strstr(bname,"["); if (branch_dim) branch_dim++; // skip the '[' Bool_t isString = kFALSE; if (leaf->IsA() == TLeafElement::Class()) { Int_t type =((TBranchElement*)leaf->GetBranch())->GetStreamerType(); isString = (type == TStreamerInfo::kOffsetL+TStreamerInfo::kChar) || (type == TStreamerInfo::kCharStar); } else { isString = (leaf->IsA() == TLeafC::Class()); } if (leaf_dim) { leaf_dim++; // skip the '[' if (!branch_dim || strncmp(branch_dim,leaf_dim,strlen(branch_dim))) { // then both are NOT the same so do the leaf title first: numberOfVarDim += RegisterDimensions( leaf_dim, code); } else if (branch_dim && strncmp(branch_dim,leaf_dim,strlen(branch_dim))==0 && strlen(leaf_dim)>strlen(branch_dim) && (leaf_dim+strlen(branch_dim))[0]=='[') { // we have extra info in the leaf title numberOfVarDim += RegisterDimensions( leaf_dim+strlen(branch_dim)+1, code); } } if (branch_dim) { // then both are NOT same so do the branch name next: if (isString) { numberOfVarDim += RegisterDimensions( code, 1); } else { numberOfVarDim += RegisterDimensions( branch_dim, code); } } if (leaf->IsA() == TLeafElement::Class()) { TBranchElement* branch = (TBranchElement*) leaf->GetBranch(); if (branch->GetBranchCount2()) { if (!branch->GetBranchCount()) { Warning("DefinedVariable", "Noticed an incorrect in-memory TBranchElement object (%s).\nIt has a BranchCount2 but no BranchCount!\nThe result might be incorrect!", branch->GetName()); return numberOfVarDim; } // Switch from old direct style to using a TLeafInfo if (fLookupType[code] == kDataMember) Warning("DefinedVariable", "Already in kDataMember mode when handling multiple variable dimensions"); fLookupType[code] = kDataMember; // Feed the information into the Dimensions system numberOfVarDim += RegisterDimensions( code, branch); } } return numberOfVarDim; } //______________________________________________________________________________ Int_t TTreeFormula::DefineAlternate(const char *expression) { // This method check for treat the case where expression contains $Atl and load up // both fAliases and fExpr. // We return // -1 in case of failure // 0 in case we did not find $Alt // the action number in case of success. static const char *altfunc = "Alt$("; static const char *minfunc = "MinIf$("; static const char *maxfunc = "MaxIf$("; Int_t action = 0; Int_t start = 0; if ( strncmp(expression,altfunc,strlen(altfunc))==0 && expression[strlen(expression)-1]==')' ) { action = kAlternate; start = strlen(altfunc); } if ( strncmp(expression,maxfunc,strlen(maxfunc))==0 && expression[strlen(expression)-1]==')' ) { action = kMaxIf; start = strlen(maxfunc); } if ( strncmp(expression,minfunc,strlen(minfunc))==0 && expression[strlen(expression)-1]==')' ) { action = kMinIf; start = strlen(minfunc); } if (action) { TString full = expression; TString part1; TString part2; int paran = 0; int instr = 0; int brack = 0; for(unsigned int i=start;i<strlen(expression);++i) { switch (expression[i]) { case '(': paran++; break; case ')': paran--; break; case '"': instr = instr ? 0 : 1; break; case '[': brack++; break; case ']': brack--; break; }; if (expression[i]==',' && paran==0 && instr==0 && brack==0) { part1 = full( start, i-start ); part2 = full( i+1, full.Length() -1 - (i+1) ); break; // out of the for loop } } if (part1.Length() && part2.Length()) { TTreeFormula *primary = new TTreeFormula("primary",part1,fTree); TTreeFormula *alternate = new TTreeFormula("alternate",part2,fTree); short isstring = 0; if (action == kAlternate) { if (alternate->GetManager()->GetMultiplicity() != 0 ) { Error("DefinedVariable","The 2nd arguments in %s can not be an array (%s,%d)!", expression,alternate->GetTitle(), alternate->GetManager()->GetMultiplicity()); return -1; } // Should check whether we have strings. if (primary->IsString()) { if (!alternate->IsString()) { Error("DefinedVariable", "The 2nd arguments in %s has to return the same type as the 1st argument (string)!", expression); return -1; } isstring = 1; } else if (alternate->IsString()) { Error("DefinedVariable", "The 2nd arguments in %s has to return the same type as the 1st argument (numerical type)!", expression); return -1; } } else { primary->GetManager()->Add( alternate ); primary->GetManager()->Sync(); if (primary->IsString() || alternate->IsString()) { if (!alternate->IsString()) { Error("DefinedVariable", "The arguments of %s can not be strings!", expression); return -1; } } } fAliases.AddAtAndExpand(primary,fNoper); fExpr[fNoper] = ""; SetAction(fNoper, (Int_t)action + isstring, 0 ); ++fNoper; fAliases.AddAtAndExpand(alternate,fNoper); return (Int_t)kAlias + isstring; } } return 0; } //______________________________________________________________________________ Int_t TTreeFormula::ParseWithLeaf(TLeaf* leaf, const char* subExpression, Bool_t final, UInt_t paran_level, TObjArray& castqueue, Bool_t useLeafCollectionObject, const char* fullExpression) { // Decompose 'expression' as pointing to something inside the leaf // Returns: // -2 Error: some information is missing (message already printed) // -1 Error: Syntax is incorrect (message already printed) // 0 // >0 the value returns is the action code. Int_t action = 0; Int_t numberOfVarDim = 0; char *current; char scratch[kMaxLen]; scratch[0] = '\0'; char work[kMaxLen]; work[0] = '\0'; const char *right = subExpression; TString name = fullExpression; TBranch *branch = leaf ? leaf->GetBranch() : 0; Long64_t readentry = fTree->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; Bool_t useLeafReferenceObject = false; Int_t code = fNcodes-1; // Make a check to prevent problem with some corrupted files (missing TStreamerInfo). if (leaf && leaf->IsA()==TLeafElement::Class()) { TBranchElement *br = 0; if( branch->IsA() == TBranchElement::Class() ) { br = ((TBranchElement*)branch); if ( br->GetInfo() == 0 ) { Error("DefinedVariable","Missing StreamerInfo for %s. We will be unable to read!", name.Data()); return -2; } } TBranch *bmom = branch->GetMother(); if( bmom->IsA() == TBranchElement::Class() ) { TBranchElement *mom = (TBranchElement*)br->GetMother(); if (mom!=br) { if (mom->GetInfo()==0) { Error("DefinedVariable","Missing StreamerInfo for %s." " We will be unable to read!", mom->GetName()); return -2; } if ((mom->GetType()) < -1 && !mom->GetAddress()) { Error("DefinedVariable", "Address not set when the type of the branch is negative for for %s. We will be unable to read!", mom->GetName()); return -2; } } } } // We need to record the location in the list of leaves because // the tree might actually be a chain and in that case the leaf will // change from tree to tree!. // Let's reconstruct the name of the leaf, including the possible friend alias TTree *realtree = fTree->GetTree(); const char* alias = 0; if (leaf) { if (realtree) alias = realtree->GetFriendAlias(leaf->GetBranch()->GetTree()); if (!alias && realtree!=fTree) { // Let's try on the chain alias = fTree->GetFriendAlias(leaf->GetBranch()->GetTree()); } } if (alias) snprintf(scratch,kMaxLen-1,"%s.%s",alias,leaf->GetName()); else if (leaf) strlcpy(scratch,leaf->GetName(),kMaxLen); TTree *tleaf = realtree; if (leaf) { tleaf = leaf->GetBranch()->GetTree(); fCodes[code] = tleaf->GetListOfLeaves()->IndexOf(leaf); const char *mother_name = leaf->GetBranch()->GetMother()->GetName(); TString br_extended_name; // Could do ( strlen(mother_name)+strlen( leaf->GetBranch()->GetName() ) + 2 ) if (leaf->GetBranch()!=leaf->GetBranch()->GetMother()) { if (mother_name[strlen(mother_name)-1]!='.') { br_extended_name = mother_name; br_extended_name.Append('.'); } } br_extended_name.Append( leaf->GetBranch()->GetName() ); Ssiz_t dim = br_extended_name.First('['); if (dim >= 0) br_extended_name.Remove(dim); TNamed *named = new TNamed(scratch,br_extended_name.Data()); fLeafNames.AddAtAndExpand(named,code); fLeaves.AddAtAndExpand(leaf,code); } // If the leaf belongs to a friend tree which has an index, we might // be in the case where some entry do not exist. if (tleaf != realtree && tleaf->GetTreeIndex()) { // reset the multiplicity if (fMultiplicity >= 0) fMultiplicity = 1; } // Analyze the content of 'right' // Try to find out the class (if any) of the object in the leaf. TClass * cl = 0; TFormLeafInfo *maininfo = 0; TFormLeafInfo *previnfo = 0; Bool_t unwindCollection = kFALSE; static TClassRef stdStringClass = TClass::GetClass("string"); if (leaf==0) { TNamed *names = (TNamed*)fLeafNames.UncheckedAt(code); fLeafNames.AddAt(0,code); TTree *what = (TTree*)fLeaves.UncheckedAt(code); fLeaves.AddAt(0,code); cl = what ? what->IsA() : TTree::Class(); maininfo = new TFormLeafInfoTTree(fTree,names->GetName(),what); previnfo = maininfo; delete names; } else if (leaf->InheritsFrom(TLeafObject::Class()) ) { TBranchObject *bobj = (TBranchObject*)leaf->GetBranch(); cl = TClass::GetClass(bobj->GetClassName()); } else if (leaf->InheritsFrom(TLeafElement::Class())) { TBranchElement *branchEl = (TBranchElement *)leaf->GetBranch(); branchEl->SetupAddresses(); TStreamerInfo *info = branchEl->GetInfo(); TStreamerElement *element = 0; Int_t type = branchEl->GetStreamerType(); switch(type) { case TStreamerInfo::kBase: case TStreamerInfo::kObject: case TStreamerInfo::kTString: case TStreamerInfo::kTNamed: case TStreamerInfo::kTObject: case TStreamerInfo::kAny: case TStreamerInfo::kAnyP: case TStreamerInfo::kAnyp: case TStreamerInfo::kSTL: case TStreamerInfo::kSTLp: case TStreamerInfo::kObjectp: case TStreamerInfo::kObjectP: { element = (TStreamerElement *)info->GetElems()[branchEl->GetID()]; if (element) cl = element->GetClassPointer(); } break; case TStreamerInfo::kOffsetL + TStreamerInfo::kSTL: case TStreamerInfo::kOffsetL + TStreamerInfo::kSTLp: case TStreamerInfo::kOffsetL + TStreamerInfo::kAny: case TStreamerInfo::kOffsetL + TStreamerInfo::kAnyp: case TStreamerInfo::kOffsetL + TStreamerInfo::kAnyP: case TStreamerInfo::kOffsetL + TStreamerInfo::kObjectp: case TStreamerInfo::kOffsetL + TStreamerInfo::kObjectP: case TStreamerInfo::kOffsetL + TStreamerInfo::kObject: { element = (TStreamerElement *)info->GetElems()[branchEl->GetID()]; if (element){ cl = element->GetClassPointer(); } } break; case -1: { cl = info->GetClass(); } break; } // If we got a class object, we need to verify whether it is on a // split TClonesArray sub branch. if (cl && branchEl->GetBranchCount()) { if (branchEl->GetType()==31) { // This is inside a TClonesArray. if (!element) { Warning("DefineVariable", "Missing TStreamerElement in object in TClonesArray section"); return -2; } TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(cl, 0, element, kTRUE); // The following code was commmented out because in THIS case // the dimension are actually handled by parsing the title and name of the leaf // and branch (see a little further) // The dimension needs to be handled! // numberOfVarDim += RegisterDimensions(code,clonesinfo); maininfo = clonesinfo; // We skip some cases because we can assume we have an object. Int_t offset=0; info->GetStreamerElement(element->GetName(),offset); if (type == TStreamerInfo::kObjectp || type == TStreamerInfo::kObjectP || type == TStreamerInfo::kOffsetL + TStreamerInfo::kObjectp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kObjectP || type == TStreamerInfo::kSTLp || type == TStreamerInfo::kAnyp || type == TStreamerInfo::kAnyP || type == TStreamerInfo::kOffsetL + TStreamerInfo::kSTLp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kAnyp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kAnyP) { previnfo = new TFormLeafInfoPointer(cl,offset+branchEl->GetOffset(),element); } else { previnfo = new TFormLeafInfo(cl,offset+branchEl->GetOffset(),element); } maininfo->fNext = previnfo; unwindCollection = kTRUE; } else if (branchEl->GetType()==41) { // This is inside a Collection if (!element) { Warning("DefineVariable","Missing TStreamerElement in object in Collection section"); return -2; } // First we need to recover the collection. TBranchElement *count = branchEl->GetBranchCount(); TFormLeafInfo* collectioninfo; if ( count->GetID() >= 0 ) { TStreamerElement *collectionElement = (TStreamerElement *)count->GetInfo()->GetElems()[count->GetID()]; TClass *collectionCl = collectionElement->GetClassPointer(); collectioninfo = new TFormLeafInfoCollection(collectionCl, 0, collectionElement, kTRUE); } else { TClass *collectionCl = TClass::GetClass(count->GetClassName()); collectioninfo = new TFormLeafInfoCollection(collectionCl, 0, collectionCl, kTRUE); } // The following code was commmented out because in THIS case // the dimension are actually handled by parsing the title and name of the leaf // and branch (see a little further) // The dimension needs to be handled! // numberOfVarDim += RegisterDimensions(code,clonesinfo); maininfo = collectioninfo; // We skip some cases because we can assume we have an object. Int_t offset=0; info->GetStreamerElement(element->GetName(),offset); if (type == TStreamerInfo::kObjectp || type == TStreamerInfo::kObjectP || type == TStreamerInfo::kOffsetL + TStreamerInfo::kObjectp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kObjectP || type == TStreamerInfo::kSTLp || type == TStreamerInfo::kAnyp || type == TStreamerInfo::kAnyP || type == TStreamerInfo::kOffsetL + TStreamerInfo::kSTLp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kAnyp || type == TStreamerInfo::kOffsetL + TStreamerInfo::kAnyP) { previnfo = new TFormLeafInfoPointer(cl,offset+branchEl->GetOffset(),element); } else { previnfo = new TFormLeafInfo(cl,offset+branchEl->GetOffset(),element); } maininfo->fNext = previnfo; unwindCollection = kTRUE; } } else if ( branchEl->GetType()==3) { TFormLeafInfo* clonesinfo; if (useLeafCollectionObject) { clonesinfo = new TFormLeafInfoCollectionObject(cl); } else { clonesinfo = new TFormLeafInfoClones(cl, 0, kTRUE); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,clonesinfo,maininfo,useLeafCollectionObject); } maininfo = clonesinfo; previnfo = maininfo; } else if (!useLeafCollectionObject && branchEl->GetType()==4) { TFormLeafInfo* collectioninfo; if (useLeafCollectionObject) { collectioninfo = new TFormLeafInfoCollectionObject(cl); } else { collectioninfo = new TFormLeafInfoCollection(cl, 0, cl, kTRUE); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,useLeafCollectionObject); } maininfo = collectioninfo; previnfo = maininfo; } else if (branchEl->GetStreamerType()==-1 && cl && cl->GetCollectionProxy()) { if (useLeafCollectionObject) { TFormLeafInfo *collectioninfo = new TFormLeafInfoCollectionObject(cl); maininfo = collectioninfo; previnfo = collectioninfo; } else { TFormLeafInfo *collectioninfo = new TFormLeafInfoCollection(cl, 0, cl, kTRUE); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); maininfo = collectioninfo; previnfo = collectioninfo; if (cl->GetCollectionProxy()->GetValueClass()!=0 && cl->GetCollectionProxy()->GetValueClass()->GetCollectionProxy()!=0) { TFormLeafInfo *multi = new TFormLeafInfoMultiVarDimCollection(cl,0, cl->GetCollectionProxy()->GetValueClass(),collectioninfo); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,multi,maininfo,kFALSE); previnfo->fNext = multi; cl = cl->GetCollectionProxy()->GetValueClass(); multi->fNext = new TFormLeafInfoCollection(cl, 0, cl, false); previnfo = multi->fNext; } if (cl->GetCollectionProxy()->GetValueClass()==0 && cl->GetCollectionProxy()->GetType()>0) { previnfo->fNext = new TFormLeafInfoNumerical(cl->GetCollectionProxy()); previnfo = previnfo->fNext; } else { // nothing to do } } } else if (strlen(right)==0 && cl && element && final) { TClass *elemCl = element->GetClassPointer(); if (!useLeafCollectionObject && elemCl && elemCl->GetCollectionProxy() && elemCl->GetCollectionProxy()->GetValueClass() && elemCl->GetCollectionProxy()->GetValueClass()->GetCollectionProxy()) { TFormLeafInfo *collectioninfo = new TFormLeafInfoCollection(cl, 0, elemCl); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); maininfo = collectioninfo; previnfo = collectioninfo; TFormLeafInfo *multi = new TFormLeafInfoMultiVarDimCollection(elemCl, 0, elemCl->GetCollectionProxy()->GetValueClass(), collectioninfo); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,multi,maininfo,kFALSE); previnfo->fNext = multi; cl = elemCl->GetCollectionProxy()->GetValueClass(); multi->fNext = new TFormLeafInfoCollection(cl, 0, cl, false); previnfo = multi->fNext; if (cl->GetCollectionProxy()->GetValueClass()==0 && cl->GetCollectionProxy()->GetType()>0) { previnfo->fNext = new TFormLeafInfoNumerical(cl->GetCollectionProxy()); previnfo = previnfo->fNext; } } else if (!useLeafCollectionObject && elemCl && elemCl->GetCollectionProxy() && elemCl->GetCollectionProxy()->GetValueClass()==0 && elemCl->GetCollectionProxy()->GetType()>0) { // At this point we have an element which is inside a class (which is not // a collection) and this element of a collection of numerical type. // (Note: it is not possible to have more than one variable dimension // unless we were supporting variable size C-style array of collection). TFormLeafInfo* collectioninfo = new TFormLeafInfoCollection(cl, 0, elemCl); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); collectioninfo->fNext = new TFormLeafInfoNumerical(elemCl->GetCollectionProxy()); maininfo = collectioninfo; previnfo = maininfo->fNext; } else if (!useLeafCollectionObject && elemCl && elemCl->GetCollectionProxy()) { if (elemCl->GetCollectionProxy()->GetValueClass()==TString::Class()) { right = "Data()"; } else if (elemCl->GetCollectionProxy()->GetValueClass()==stdStringClass) { right = "c_str()"; } } else if (!element->IsaPointer()) { maininfo = new TFormLeafInfoDirect(branchEl); previnfo = maininfo; } } else if ( cl && cl->GetReferenceProxy() ) { if ( useLeafCollectionObject || fullExpression[0] == '@' || fullExpression[strlen(scratch)] == '@' ) { useLeafReferenceObject = true; } else { if ( !maininfo ) { maininfo = previnfo = new TFormLeafInfoReference(cl, element, 0); numberOfVarDim += RegisterDimensions(code,maininfo,maininfo,kFALSE); } cl = 0; for(int i=0; i<leaf->GetBranch()->GetEntries()-readentry; ++i) { R__LoadBranch(leaf->GetBranch(), readentry+i, fQuickLoad); cl = ((TFormLeafInfoReference*)maininfo)->GetValueClass(leaf); if ( cl ) break; } if ( !cl ) { Error("DefinedVariable","Failed to access class type of reference target (%s)",element->GetName()); return -1; } } } } // Treat the dimension information in the leaf name, title and 2nd branch count if (leaf) numberOfVarDim += RegisterDimensions(code,leaf); if (cl) { if (unwindCollection) { // So far we should get here only if we encounter a split collection of a class that contains // directly a collection. R__ASSERT(numberOfVarDim==1 && maininfo); if (!useLeafCollectionObject && cl && cl->GetCollectionProxy()) { TFormLeafInfo *multi = new TFormLeafInfoMultiVarDimCollection(cl, 0, cl, maininfo); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,multi,maininfo,kFALSE); previnfo->fNext = multi; multi->fNext = new TFormLeafInfoCollection(cl, 0, cl, false); previnfo = multi->fNext; if (cl->GetCollectionProxy()->GetValueClass()==0 && cl->GetCollectionProxy()->GetType()>0) { previnfo->fNext = new TFormLeafInfoNumerical(cl->GetCollectionProxy()); previnfo = previnfo->fNext; } } else if (!useLeafCollectionObject && cl == TClonesArray::Class()) { TFormLeafInfo *multi = new TFormLeafInfoMultiVarDimClones(cl, 0, cl, maininfo); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,multi,maininfo,kFALSE); previnfo->fNext = multi; multi->fNext = new TFormLeafInfoClones(cl, 0, false); previnfo = multi->fNext; } } Int_t offset=0; Int_t nchname = strlen(right); TFormLeafInfo *leafinfo = 0; TStreamerElement* element = 0; // Let see if the leaf was attempted to be casted. // Since there would have been something like // ((cast_class*)leafname)->.... we need to use // paran_level+1 // Also we disable this functionality in case of TClonesArray // because it is not yet allowed to have 'inheritance' (or virtuality) // in play in a TClonesArray. { TClass * casted = (TClass*) castqueue.At(paran_level+1); if (casted && cl != TClonesArray::Class()) { if ( ! casted->InheritsFrom(cl) ) { Error("DefinedVariable","%s does not inherit from %s. Casting not possible!", casted->GetName(),cl->GetName()); return -2; } leafinfo = new TFormLeafInfoCast(cl,casted); fHasCast = kTRUE; if (maininfo==0) { maininfo = leafinfo; } if (previnfo==0) { previnfo = leafinfo; } else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = 0; cl = casted; castqueue.AddAt(0,paran_level); } } Int_t i; Bool_t prevUseCollectionObject = useLeafCollectionObject; Bool_t useCollectionObject = useLeafCollectionObject; Bool_t useReferenceObject = useLeafReferenceObject; Bool_t prevUseReferenceObject = useLeafReferenceObject; for (i=0, current = &(work[0]); i<=nchname;i++ ) { // We will treated the terminator as a token. if (right[i] == '(') { // Right now we do not allow nested paranthesis do { *current++ = right[i++]; } while(right[i]!=')' && right[i]); *current++ = right[i]; *current='\0'; char *params = strchr(work,'('); if (params) { *params = 0; params++; } else params = (char *) ")"; if (cl==0) { Error("DefinedVariable","Can not call '%s' with a class",work); return -1; } if (cl->GetClassInfo()==0 && !cl->GetCollectionProxy()) { Error("DefinedVariable","Class probably unavailable:%s",cl->GetName()); return -2; } if (!useCollectionObject && cl == TClonesArray::Class()) { // We are not interested in the ClonesArray object but only // in its contents. // We need to retrieve the class of its content. TBranch *clbranch = leaf->GetBranch(); R__LoadBranch(clbranch,readentry,fQuickLoad); TClonesArray * clones; if (previnfo) clones = (TClonesArray*)previnfo->GetLocalValuePointer(leaf,0); else { Bool_t top = (clbranch==((TBranchElement*)clbranch)->GetMother() || !leaf->IsOnTerminalBranch()); TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)clbranch)->GetInfo()->GetClass(); } TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(mother_cl, 0, top); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,clonesinfo,maininfo,kFALSE); previnfo = clonesinfo; maininfo = clonesinfo; clones = (TClonesArray*)clonesinfo->GetLocalValuePointer(leaf,0); } TClass * inside_cl = clones->GetClass(); cl = inside_cl; } else if (!useCollectionObject && cl && cl->GetCollectionProxy() ) { // We are NEVER (for now!) interested in the ClonesArray object but only // in its contents. // We need to retrieve the class of its content. if (previnfo==0) { Bool_t top = (branch==((TBranchElement*)branch)->GetMother() || !leaf->IsOnTerminalBranch()); TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)branch)->GetInfo()->GetClass(); } TFormLeafInfo* collectioninfo = new TFormLeafInfoCollection(mother_cl, 0,cl,top); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); previnfo = collectioninfo; maininfo = collectioninfo; } TClass * inside_cl = cl->GetCollectionProxy()->GetValueClass(); if (inside_cl) cl = inside_cl; else if (cl->GetCollectionProxy()->GetType()>0) { Warning("DefinedVariable","Can not call method on content of %s in %s\n", cl->GetName(),name.Data()); return -2; } } TMethodCall *method = 0; if (cl==0) { Error("DefinedVariable", "Could not discover the TClass corresponding to (%s)!", right); return -2; } else if (cl==TClonesArray::Class() && strcmp(work,"size")==0) { method = new TMethodCall(cl, "GetEntriesFast", ""); } else if (cl->GetCollectionProxy() && strcmp(work,"size")==0) { if (maininfo==0) { TFormLeafInfo* collectioninfo=0; if (useLeafCollectionObject) { Bool_t top = (branch==((TBranchElement*)branch)->GetMother() || !leaf->IsOnTerminalBranch()); collectioninfo = new TFormLeafInfoCollectionObject(cl,top); } maininfo=previnfo=collectioninfo; } leafinfo = new TFormLeafInfoCollectionSize(cl); cl = 0; } else { if (cl->GetClassInfo()==0) { Error("DefinedVariable", "Can not call method %s on class without dictionary (%s)!", right,cl->GetName()); return -2; } method = new TMethodCall(cl, work, params); } if (method) { if (!method->GetMethod()) { Error("DefinedVariable","Unknown method:%s in %s",right,cl->GetName()); return -1; } switch(method->ReturnType()) { case TMethodCall::kLong: leafinfo = new TFormLeafInfoMethod(cl,method); cl = 0; break; case TMethodCall::kDouble: leafinfo = new TFormLeafInfoMethod(cl,method); cl = 0; break; case TMethodCall::kString: leafinfo = new TFormLeafInfoMethod(cl,method); // 1 will be replaced by -1 when we know how to use strlen numberOfVarDim += RegisterDimensions(code,1); //NOTE: changed from 0 cl = 0; break; case TMethodCall::kOther: { TString return_type = gInterpreter->TypeName(method->GetMethod()->GetReturnTypeName()); leafinfo = new TFormLeafInfoMethod(cl,method); cl = (return_type == "void") ? 0 : TClass::GetClass(return_type.Data()); } break; default: Error("DefineVariable","Method %s from %s has an impossible return type %d", work,cl->GetName(),method->ReturnType()); return -2; } } if (maininfo==0) { maininfo = leafinfo; } if (previnfo==0) { previnfo = leafinfo; } else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = 0; current = &(work[0]); *current = 0; prevUseCollectionObject = kFALSE; prevUseReferenceObject = kFALSE; useCollectionObject = kFALSE; if (cl && cl->GetCollectionProxy()) { if (numberOfVarDim>1) { Warning("DefinedVariable","TTreeFormula support only 2 level of variables size collections. Assuming '@' notation for the collection %s.", cl->GetName()); leafinfo = new TFormLeafInfo(cl,0,0); useCollectionObject = kTRUE; } else if (numberOfVarDim==0) { R__ASSERT(maininfo); leafinfo = new TFormLeafInfoCollection(cl,0,cl); numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); } else if (numberOfVarDim==1) { R__ASSERT(maininfo); leafinfo = new TFormLeafInfoMultiVarDimCollection(cl,0, (TStreamerElement*)0,maininfo); previnfo->fNext = leafinfo; previnfo = leafinfo; leafinfo = new TFormLeafInfoCollection(cl,0,cl); fHasMultipleVarDim[code] = kTRUE; numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); } previnfo->fNext = leafinfo; previnfo = leafinfo; leafinfo = 0; } continue; } else if (right[i] == ')') { // We should have the end of a cast operator. Let's introduce a TFormLeafCast // in the chain. TClass * casted = (TClass*) ((int(--paran_level)>=0) ? castqueue.At(paran_level) : 0); if (casted) { leafinfo = new TFormLeafInfoCast(cl,casted); fHasCast = kTRUE; if (maininfo==0) { maininfo = leafinfo; } if (previnfo==0) { previnfo = leafinfo; } else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = 0; current = &(work[0]); *current = 0; cl = casted; continue; } } else if (i > 0 && (right[i] == '.' || right[i] == '[' || right[i] == '\0') ) { // A delimiter happened let's see if what we have seen // so far does point to a data member. Bool_t needClass = kTRUE; *current = '\0'; // skip it all if there is nothing to look at if (strlen(work)==0) continue; prevUseCollectionObject = useCollectionObject; prevUseReferenceObject = useReferenceObject; if (work[0]=='@') { useReferenceObject = kTRUE; useCollectionObject = kTRUE; Int_t l = 0; for(l=0;work[l+1]!=0;++l) work[l] = work[l+1]; work[l] = '\0'; } else if (work[strlen(work)-1]=='@') { useReferenceObject = kTRUE; useCollectionObject = kTRUE; work[strlen(work)-1] = '\0'; } else { useReferenceObject = kFALSE; useCollectionObject = kFALSE; } Bool_t mustderef = kFALSE; if ( !prevUseReferenceObject && cl && cl->GetReferenceProxy() ) { R__LoadBranch(leaf->GetBranch(), readentry, fQuickLoad); if ( !maininfo ) { maininfo = previnfo = new TFormLeafInfoReference(cl, element, offset); if ( cl->GetReferenceProxy()->HasCounter() ) { numberOfVarDim += RegisterDimensions(code,-1); } prevUseReferenceObject = kFALSE; } needClass = kFALSE; mustderef = kTRUE; } else if (!prevUseCollectionObject && cl == TClonesArray::Class()) { // We are not interested in the ClonesArray object but only // in its contents. // We need to retrieve the class of its content. TBranch *clbranch = leaf->GetBranch(); R__LoadBranch(clbranch,readentry,fQuickLoad); TClonesArray * clones; if (maininfo) { clones = (TClonesArray*)maininfo->GetValuePointer(leaf,0); } else { // we have a unsplit TClonesArray leaves // or we did not yet match any of the sub-branches! TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)clbranch)->GetInfo()->GetClass(); } TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(mother_cl, 0); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,clonesinfo,maininfo,kFALSE); mustderef = kTRUE; previnfo = clonesinfo; maininfo = clonesinfo; if (clbranch->GetListOfBranches()->GetLast()>=0) { if (clbranch->IsA() != TBranchElement::Class()) { Error("DefinedVariable","Unimplemented usage of ClonesArray"); return -2; } //clbranch = ((TBranchElement*)clbranch)->GetMother(); clones = (TClonesArray*)((TBranchElement*)clbranch)->GetObject(); } else clones = (TClonesArray*)clonesinfo->GetLocalValuePointer(leaf,0); } // NOTE clones can be zero! if (clones==0) { Warning("DefinedVariable", "TClonesArray object was not retrievable for %s!", name.Data()); return -1; } TClass * inside_cl = clones->GetClass(); #if 1 cl = inside_cl; #else /* Maybe we should make those test lead to warning messages */ if (1 || inside_cl) cl = inside_cl; // if inside_cl is nul ... we have a problem of inconsistency :( if (0 && strlen(work)==0) { // However in this case we have NO content :( // so let get the number of objects //strcpy(work,"fLast"); } #endif } else if (!prevUseCollectionObject && cl && cl->GetCollectionProxy() ) { // We are NEVER interested in the Collection object but only // in its contents. // We need to retrieve the class of its content. TBranch *clbranch = leaf->GetBranch(); R__LoadBranch(clbranch,readentry,fQuickLoad); if (maininfo==0) { // we have a unsplit Collection leaf // or we did not yet match any of the sub-branches! TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)clbranch)->GetInfo()->GetClass(); } TFormLeafInfo* collectioninfo = new TFormLeafInfoCollection(mother_cl, 0, cl); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); mustderef = kTRUE; previnfo = collectioninfo; maininfo = collectioninfo; } //else if (clbranch->GetStreamerType()==0) { //} TClass * inside_cl = cl->GetCollectionProxy()->GetValueClass(); if (!inside_cl && cl->GetCollectionProxy()->GetType() > 0) { Warning("DefinedVariable","No data member in content of %s in %s\n", cl->GetName(),name.Data()); } cl = inside_cl; // if inside_cl is nul ... we have a problem of inconsistency. } if (!cl) { Warning("DefinedVariable","Missing class for %s!",name.Data()); } else { element = ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(work,offset); } if (!element && !prevUseCollectionObject) { // We allow for looking for a data member inside a class inside // a TClonesArray without mentioning the TClonesArrays variable name TIter next( cl->GetStreamerInfo()->GetElements() ); TStreamerElement * curelem; while ((curelem = (TStreamerElement*)next())) { if (curelem->GetClassPointer() == TClonesArray::Class()) { Int_t clones_offset; ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(curelem->GetName(),clones_offset); TFormLeafInfo* clonesinfo = new TFormLeafInfo(cl, clones_offset, curelem); TClonesArray * clones; R__LoadBranch(leaf->GetBranch(),readentry,fQuickLoad); if (previnfo) { previnfo->fNext = clonesinfo; clones = (TClonesArray*)maininfo->GetValuePointer(leaf,0); previnfo->fNext = 0; } else { clones = (TClonesArray*)clonesinfo->GetLocalValuePointer(leaf,0); } TClass *sub_cl = clones->GetClass(); if (sub_cl) element = ((TStreamerInfo*)sub_cl->GetStreamerInfo())->GetStreamerElement(work,offset); delete clonesinfo; if (element) { leafinfo = new TFormLeafInfoClones(cl,clones_offset,curelem); numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); if (maininfo==0) maininfo = leafinfo; if (previnfo==0) previnfo = leafinfo; else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = 0; cl = sub_cl; break; } } else if (curelem->GetClassPointer() && curelem->GetClassPointer()->GetCollectionProxy()) { Int_t coll_offset; ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(curelem->GetName(),coll_offset); TClass *sub_cl = curelem->GetClassPointer()->GetCollectionProxy()->GetValueClass(); if (sub_cl) { element = ((TStreamerInfo*)sub_cl->GetStreamerInfo())->GetStreamerElement(work,offset); } if (element) { if (numberOfVarDim>1) { Warning("DefinedVariable","TTreeFormula support only 2 level of variables size collections. Assuming '@' notation for the collection %s.", curelem->GetName()); leafinfo = new TFormLeafInfo(cl,coll_offset,curelem); useCollectionObject = kTRUE; } else if (numberOfVarDim==1) { R__ASSERT(maininfo); leafinfo = new TFormLeafInfoMultiVarDimCollection(cl,coll_offset, curelem,maininfo); fHasMultipleVarDim[code] = kTRUE; leafinfo->fNext = new TFormLeafInfoCollection(cl,coll_offset,curelem); numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); } else { leafinfo = new TFormLeafInfoCollection(cl,coll_offset,curelem); numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); } if (maininfo==0) maininfo = leafinfo; if (previnfo==0) previnfo = leafinfo; else { previnfo->fNext = leafinfo; previnfo = leafinfo; } if (leafinfo->fNext) { previnfo = leafinfo->fNext; } leafinfo = 0; cl = sub_cl; break; } } } } if (element) { Int_t type = element->GetNewType(); if (type<60 && type!=0) { // This is a basic type ... if (numberOfVarDim>=1 && type>40) { // We have a variable array within a variable array! leafinfo = new TFormLeafInfoMultiVarDim(cl,offset,element,maininfo); fHasMultipleVarDim[code] = kTRUE; } else { if (leafinfo && type<=40 ) { leafinfo->AddOffset(offset,element); } else { leafinfo = new TFormLeafInfo(cl,offset,element); } } } else { Bool_t object = kFALSE; Bool_t pointer = kFALSE; Bool_t objarr = kFALSE; switch(type) { case TStreamerInfo::kObjectp: case TStreamerInfo::kObjectP: case TStreamerInfo::kSTLp: case TStreamerInfo::kAnyp: case TStreamerInfo::kAnyP: case TStreamerInfo::kOffsetL + TStreamerInfo::kObjectP: case TStreamerInfo::kOffsetL + TStreamerInfo::kSTLp: case TStreamerInfo::kOffsetL + TStreamerInfo::kAnyp: case TStreamerInfo::kOffsetL + TStreamerInfo::kObjectp: case TStreamerInfo::kOffsetL + TStreamerInfo::kAnyP: pointer = kTRUE; break; case TStreamerInfo::kBase: case TStreamerInfo::kAny : case TStreamerInfo::kSTL: case TStreamerInfo::kObject: case TStreamerInfo::kTString: case TStreamerInfo::kTNamed: case TStreamerInfo::kTObject: object = kTRUE; break; case TStreamerInfo::kOffsetL + TStreamerInfo::kAny: case TStreamerInfo::kOffsetL + TStreamerInfo::kSTL: case TStreamerInfo::kOffsetL + TStreamerInfo::kObject: objarr = kTRUE; break; case TStreamerInfo::kStreamer: case TStreamerInfo::kStreamLoop: // Unsupported case. Error("DefinedVariable", "%s is a datamember of %s BUT is not yet of a supported type (%d)", right,cl ? cl->GetName() : "unknown class",type); return -2; default: // Unknown and Unsupported case. Error("DefinedVariable", "%s is a datamember of %s BUT is not of a unknown type (%d)", right,cl ? cl->GetName() : "unknown class",type); return -2; } if (object && !useCollectionObject && ( element->GetClassPointer() == TClonesArray::Class() || element->GetClassPointer()->GetCollectionProxy() ) ) { object = kFALSE; } if (object && leafinfo) { leafinfo->AddOffset(offset,element); } else if (objarr) { // This is an embedded array of objects. We can not increase the offset. leafinfo = new TFormLeafInfo(cl,offset,element); mustderef = kTRUE; } else { if (!useCollectionObject && element->GetClassPointer() == TClonesArray::Class()) { leafinfo = new TFormLeafInfoClones(cl,offset,element); mustderef = kTRUE; } else if (!useCollectionObject && element->GetClassPointer() && element->GetClassPointer()->GetCollectionProxy()) { mustderef = kTRUE; if (numberOfVarDim>1) { Warning("DefinedVariable","TTreeFormula support only 2 level of variables size collections. Assuming '@' notation for the collection %s.", element->GetName()); leafinfo = new TFormLeafInfo(cl,offset,element); useCollectionObject = kTRUE; } else if (numberOfVarDim==1) { R__ASSERT(maininfo); leafinfo = new TFormLeafInfoMultiVarDimCollection(cl,offset,element,maininfo); fHasMultipleVarDim[code] = kTRUE; //numberOfVarDim += RegisterDimensions(code,leafinfo); //cl = cl->GetCollectionProxy()->GetValueClass(); //if (maininfo==0) maininfo = leafinfo; //if (previnfo==0) previnfo = leafinfo; //else { // previnfo->fNext = leafinfo; // previnfo = leafinfo; //} leafinfo->fNext = new TFormLeafInfoCollection(cl, offset, element); if (element->GetClassPointer()->GetCollectionProxy()->GetValueClass()==0) { TFormLeafInfo *info = new TFormLeafInfoNumerical( element->GetClassPointer()->GetCollectionProxy()); if (leafinfo->fNext) leafinfo->fNext->fNext = info; else leafinfo->fNext = info; } } else { leafinfo = new TFormLeafInfoCollection(cl, offset, element); TClass *elemCl = element->GetClassPointer(); TClass *valueCl = elemCl->GetCollectionProxy()->GetValueClass(); if (!maininfo) maininfo = leafinfo; if (valueCl!=0 && valueCl->GetCollectionProxy()!=0) { numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,kFALSE); if (previnfo==0) previnfo = leafinfo; else { previnfo->fNext = leafinfo; previnfo = leafinfo; } leafinfo = new TFormLeafInfoMultiVarDimCollection(elemCl,0, elemCl->GetCollectionProxy()->GetValueClass(),maininfo); //numberOfVarDim += RegisterDimensions(code,previnfo->fNext); fHasMultipleVarDim[code] = kTRUE; //previnfo = previnfo->fNext; leafinfo->fNext = new TFormLeafInfoCollection(elemCl,0, valueCl); elemCl = valueCl; } if (elemCl->GetCollectionProxy() && elemCl->GetCollectionProxy()->GetValueClass()==0) { TFormLeafInfo *info = new TFormLeafInfoNumerical(elemCl->GetCollectionProxy()); if (leafinfo->fNext) leafinfo->fNext->fNext = info; else leafinfo->fNext = info; } } } else if ( (object || pointer) && !useReferenceObject && element->GetClassPointer()->GetReferenceProxy() ) { TClass* c = element->GetClassPointer(); R__LoadBranch(leaf->GetBranch(),readentry,fQuickLoad); if ( object ) { leafinfo = new TFormLeafInfoReference(c, element, offset); } else { leafinfo = new TFormLeafInfoPointer(cl,offset,element); leafinfo->fNext = new TFormLeafInfoReference(c, element, 0); } //if ( c->GetReferenceProxy()->HasCounter() ) { // numberOfVarDim += RegisterDimensions(code,-1); //} prevUseReferenceObject = kFALSE; needClass = kFALSE; mustderef = kTRUE; } else if (pointer) { // this is a pointer to be followed. leafinfo = new TFormLeafInfoPointer(cl,offset,element); mustderef = kTRUE; } else { // this is an embedded object. R__ASSERT(object); leafinfo = new TFormLeafInfo(cl,offset,element); } } } } else { if (cl) Error("DefinedVariable","%s is not a datamember of %s",work,cl->GetName()); // no else, we warned earlier that the class was missing. return -1; } numberOfVarDim += RegisterDimensions(code,leafinfo,maininfo,useCollectionObject); // Note or useCollectionObject||prevUseColectionObject if (maininfo==0) { maininfo = leafinfo; } if (previnfo==0) { previnfo = leafinfo; } else if (previnfo!=leafinfo) { previnfo->fNext = leafinfo; previnfo = leafinfo; } while (previnfo->fNext) previnfo = previnfo->fNext; if ( right[i] != '\0' ) { if ( !needClass && mustderef ) { maininfo->SetBranch(leaf->GetBranch()); char *ptr = (char*)maininfo->GetValuePointer(leaf,0); TFormLeafInfoReference* refInfo = 0; if ( !maininfo->IsReference() ) { for( TFormLeafInfo* inf = maininfo->fNext; inf; inf = inf->fNext ) { if ( inf->IsReference() ) { refInfo = (TFormLeafInfoReference*)inf; } } } else { refInfo = (TFormLeafInfoReference*)maininfo; } if ( refInfo ) { cl = refInfo->GetValueClass(ptr); if ( !cl ) { Error("DefinedVariable","Failed to access class type of reference target (%s)",element->GetName()); return -1; } element = ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(work,offset); } else { Error("DefinedVariable","Failed to access class type of reference target (%s)",element->GetName()); return -1; } } else if ( needClass ) { cl = element->GetClassPointer(); } } if (mustderef) leafinfo = 0; current = &(work[0]); *current = 0; R__ASSERT(right[i] != '['); // We are supposed to have removed all dimensions already! } else *current++ = right[i]; } if (maininfo) { fDataMembers.AddAtAndExpand(maininfo,code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } } if (strlen(work)!=0) { // We have something left to analyze. Let's make this an error case! return -1; } TClass *objClass = EvalClass(code); if (objClass && !useLeafCollectionObject && objClass->GetCollectionProxy() && objClass->GetCollectionProxy()->GetValueClass()) { TFormLeafInfo *last = 0; if ( SwitchToFormLeafInfo(code) ) { last = (TFormLeafInfo*)fDataMembers.At(code); if (!last) return action; while (last->fNext) { last = last->fNext; } } if (last && last->GetClass() != objClass) { TClass *mother_cl; if (leaf->IsA()==TLeafObject::Class()) { // in this case mother_cl is not really used mother_cl = cl; } else { mother_cl = ((TBranchElement*)branch)->GetInfo()->GetClass(); } TFormLeafInfo* collectioninfo = new TFormLeafInfoCollection(mother_cl, 0, objClass, kFALSE); // The dimension needs to be handled! numberOfVarDim += RegisterDimensions(code,collectioninfo,maininfo,kFALSE); last->fNext = collectioninfo; } numberOfVarDim += RegisterDimensions(code,1); //NOTE: changed from 0 objClass = objClass->GetCollectionProxy()->GetValueClass(); } if (IsLeafString(code) || objClass == TString::Class() || objClass == stdStringClass) { TFormLeafInfo *last = 0; if ( SwitchToFormLeafInfo(code) ) { last = (TFormLeafInfo*)fDataMembers.At(code); if (!last) return action; while (last->fNext) { last = last->fNext; } } const char *funcname = 0; if (objClass == TString::Class()) { funcname = "Data"; //tobetested: numberOfVarDim += RegisterDimensions(code,1,0); // Register the dim of the implied char* } else if (objClass == stdStringClass) { funcname = "c_str"; //tobetested: numberOfVarDim += RegisterDimensions(code,1,0); // Register the dim of the implied char* } if (funcname) { TMethodCall *method = new TMethodCall(objClass, funcname, ""); if (last) { last->fNext = new TFormLeafInfoMethod(objClass,method); } else { fDataMembers.AddAtAndExpand(new TFormLeafInfoMethod(objClass,method),code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } } return kDefinedString; } if (objClass) { TMethodCall *method = new TMethodCall(objClass, "AsDouble", ""); if (method->IsValid() && (method->ReturnType() == TMethodCall::kLong || method->ReturnType() == TMethodCall::kDouble)) { TFormLeafInfo *last = 0; if (SwitchToFormLeafInfo(code)) { last = (TFormLeafInfo*)fDataMembers.At(code); // Improbable case if (!last) { delete method; return action; } while (last->fNext) { last = last->fNext; } } if (last) { last->fNext = new TFormLeafInfoMethod(objClass,method); } else { fDataMembers.AddAtAndExpand(new TFormLeafInfoMethod(objClass,method),code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } return kDefinedVariable; } delete method; method = new TMethodCall(objClass, "AsString", ""); if (method->IsValid() && method->ReturnType() == TMethodCall::kString) { TFormLeafInfo *last = 0; if (SwitchToFormLeafInfo(code)) { last = (TFormLeafInfo*)fDataMembers.At(code); // Improbable case if (!last) { delete method; return action; } while (last->fNext) { last = last->fNext; } } if (last) { last->fNext = new TFormLeafInfoMethod(objClass,method); } else { fDataMembers.AddAtAndExpand(new TFormLeafInfoMethod(objClass,method),code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } //tobetested: numberOfVarDim += RegisterDimensions(code,1,0); // Register the dim of the implied char* return kDefinedString; } if (method->IsValid() && method->ReturnType() == TMethodCall::kOther) { TClass *rcl = 0; TFunction *f = method->GetMethod(); if (f) rcl = TClass::GetClass(gInterpreter->TypeName(f->GetReturnTypeName())); if ((rcl == TString::Class() || rcl == stdStringClass) ) { TFormLeafInfo *last = 0; if (SwitchToFormLeafInfo(code)) { last = (TFormLeafInfo*)fDataMembers.At(code); // Improbable case if (!last) { delete method; return action; } while (last->fNext) { last = last->fNext; } } if (last) { last->fNext = new TFormLeafInfoMethod(objClass,method); last = last->fNext; } else { last = new TFormLeafInfoMethod(objClass,method); fDataMembers.AddAtAndExpand(last,code); if (leaf) fLookupType[code] = kDataMember; else fLookupType[code] = kTreeMember; } objClass = rcl; const char *funcname = 0; if (objClass == TString::Class()) { funcname = "Data"; } else if (objClass == stdStringClass) { funcname = "c_str"; } if (funcname) { method = new TMethodCall(objClass, funcname, ""); last->fNext = new TFormLeafInfoMethod(objClass,method); } return kDefinedString; } } delete method; } return action; } //______________________________________________________________________________ Int_t TTreeFormula::FindLeafForExpression(const char* expression, TLeaf*& leaf, TString& leftover, Bool_t& final, UInt_t& paran_level, TObjArray& castqueue, std::vector<std::string>& aliasUsed, Bool_t& useLeafCollectionObject, const char* fullExpression) { // Look for the leaf corresponding to the start of expression. // It returns the corresponding leaf if any. // It also modify the following arguments: // leftover: contain from expression that was not used to determine the leaf // final: // paran_level: number of un-matched open parenthesis // cast_queue: list of cast to be done // aliases: list of aliases used // Return <0 in case of failure // Return 0 if a leaf has been found // Return 2 if info about the TTree itself has been requested. // Later on we will need to read one entry, let's make sure // it is a real entry. if (fTree->GetTree()==0) { fTree->LoadTree(0); if (fTree->GetTree()==0) return -1; } Long64_t readentry = fTree->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; const char *cname = expression; char first[kMaxLen]; first[0] = '\0'; char second[kMaxLen]; second[0] = '\0'; char right[kMaxLen]; right[0] = '\0'; char work[kMaxLen]; work[0] = '\0'; char left[kMaxLen]; left[0] = '\0'; char scratch[kMaxLen]; char scratch2[kMaxLen]; std::string currentname; Int_t previousdot = 0; char *current; TLeaf *tmp_leaf=0; TBranch *branch=0, *tmp_branch=0; Int_t nchname = strlen(cname); Int_t i; Bool_t foundAtSign = kFALSE; for (i=0, current = &(work[0]); i<=nchname && !final;i++ ) { // We will treated the terminator as a token. *current++ = cname[i]; if (cname[i] == '(') { ++paran_level; if (current==work+1) { // If the expression starts with a paranthesis, we are likely // to have a cast operator inside. current--; } continue; //i++; //while( cname[i]!=')' && cname[i] ) { // *current++ = cname[i++]; //} //*current++ = cname[i]; ////*current = 0; //continue; } if (cname[i] == ')') { if (paran_level==0) { Error("DefinedVariable","Unmatched paranthesis in %s",fullExpression); return -1; } // Let's see if work is a classname. *(--current) = 0; paran_level--; TString cast_name = gInterpreter->TypeName(work); TClass *cast_cl = TClass::GetClass(cast_name); if (cast_cl) { // We must have a cast castqueue.AddAtAndExpand(cast_cl,paran_level); current = &(work[0]); *current = 0; // Warning("DefinedVariable","Found cast to %s",cast_fullExpression); continue; } else if (gROOT->GetType(cast_name)) { // We reset work current = &(work[0]); *current = 0; Warning("DefinedVariable", "Casting to primary types like \"%s\" is not supported yet",cast_name.Data()); continue; } *(current++)=')'; *current='\0'; char *params = strchr(work,'('); if (params) { *params = 0; params++; if (branch && !leaf) { // We have a branch but not a leaf. We are likely to have found // the top of split branch. if (BranchHasMethod(0, branch, work, params, readentry)) { //fprintf(stderr, "Does have a method %s for %s.\n", work, branch->GetName()); } } // What we have so far might be a member function of one of the // leaves that are not splitted (for example "GetNtrack" for the Event class). TIter next(fTree->GetIteratorOnAllLeaves()); TLeaf* leafcur = 0; while (!leaf && (leafcur = (TLeaf*) next())) { TBranch* br = leafcur->GetBranch(); Bool_t yes = BranchHasMethod(leafcur, br, work, params, readentry); if (yes) { leaf = leafcur; //fprintf(stderr, "Does have a method %s for %s found in leafcur %s.\n", work, leafcur->GetBranch()->GetName(), leafcur->GetName()); } } if (!leaf) { // Check for an alias. if (strlen(left) && left[strlen(left)-1]=='.') left[strlen(left)-1]=0; const char *aliasValue = fTree->GetAlias(left); if (aliasValue && strcspn(aliasValue,"+*/-%&!=<>|")==strlen(aliasValue)) { // First check whether we are using this alias recursively (this would // lead to an infinite recursion. if (find(aliasUsed.begin(), aliasUsed.end(), left) != aliasUsed.end()) { Error("DefinedVariable", "The substitution of the branch alias \"%s\" by \"%s\" in \"%s\" failed\n"\ "\tbecause \"%s\" is used [recursively] in its own definition!", left,aliasValue,fullExpression,left); return -3; } aliasUsed.push_back(left); TString newExpression = aliasValue; newExpression += (cname+strlen(left)); Int_t res = FindLeafForExpression(newExpression, leaf, leftover, final, paran_level, castqueue, aliasUsed, useLeafCollectionObject, fullExpression); if (res<0) { Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed.",left,aliasValue); return -3; } return res; } // This is actually not really any error, we probably received something // like "abs(some_val)", let TFormula decompose it first. return -1; } // if (!leaf->InheritsFrom(TLeafObject::Class()) ) { // If the leaf that we found so far is not a TLeafObject then there is // nothing we would be able to do. // Error("DefinedVariable","Need a TLeafObject to call a function!"); // return -1; //} // We need to recover the info not used. strlcpy(right,work,kMaxLen); strncat(right,"(",kMaxLen-1-strlen(right)); strncat(right,params,kMaxLen-1-strlen(right)); final = kTRUE; // we reset work current = &(work[0]); *current = 0; break; } } if (cname[i] == '.' || cname[i] == '\0' || cname[i] == ')') { // A delimiter happened let's see if what we have seen // so far does point to a leaf. *current = '\0'; Int_t len = strlen(work); if (work[0]=='@') { foundAtSign = kTRUE; Int_t l = 0; for(l=0;work[l+1]!=0;++l) work[l] = work[l+1]; work[l] = '\0'; --current; } else if (len>=2 && work[len-2]=='@') { foundAtSign = kTRUE; work[len-2] = cname[i]; work[len-1] = '\0'; --current; } else { foundAtSign = kFALSE; } if (left[0]==0) strlcpy(left,work,kMaxLen); if (!leaf && !branch) { // So far, we have not found a matching leaf or branch. strlcpy(first,work,kMaxLen); std::string treename(first); if (treename.size() && treename[treename.size()-1]=='.') { treename.erase(treename.size()-1); } if (treename== "This" /* || treename == fTree->GetName() */ ) { // Request info about the TTree object itself, TNamed *named = new TNamed(fTree->GetName(),fTree->GetName()); fLeafNames.AddAtAndExpand(named,fNcodes); fLeaves.AddAtAndExpand(fTree,fNcodes); if (cname[i]) leftover = &(cname[i+1]); return 2; } // The following would allow to access the friend by name // however, it would also prevent the access of the leaves // within the friend. We could use the '@' notation here // however this would not be aesthetically pleasing :( // What we need to do, is add the ability to look ahead to // the next 'token' to decide whether we to access the tree // or its leaf. //} else { // TTree *tfriend = fTree->GetFriend(treename.c_str()); // TTree *realtree = fTree->GetTree(); // if (!tfriend && realtree != fTree){ // // If it is a chain and we did not find a friend, // // let's try with the internal tree. // tfriend = realtree->GetFriend(treename.c_str()); // } // if (tfriend) { // TNamed *named = new TNamed(treename.c_str(),tfriend->GetName()); // fLeafNames.AddAtAndExpand(named,fNcodes); // fLeaves.AddAtAndExpand(tfriend,fNcodes); // if (cname[i]) leftover = &(cname[i+1]); // return 2; // } //} branch = fTree->FindBranch(first); leaf = fTree->FindLeaf(first); // Now look with the delimiter removed (we looked with it first // because a dot is allowed at the end of some branches). if (cname[i]) first[strlen(first)-1]='\0'; if (!branch) branch = fTree->FindBranch(first); if (!leaf) leaf = fTree->FindLeaf(first); TClass* cl = 0; if ( branch && branch->InheritsFrom(TBranchElement::Class()) ) { int offset=0; TBranchElement* bElt = (TBranchElement*)branch; TStreamerInfo* info = bElt->GetInfo(); TStreamerElement* element = info ? info->GetStreamerElement(first,offset) : 0; if (element) cl = element->GetClassPointer(); if ( cl && !cl->GetReferenceProxy() ) cl = 0; } if ( cl ) { // We have a reference class here.... final = kTRUE; useLeafCollectionObject = foundAtSign; // we reset work current = &(work[0]); *current = 0; } else if (branch && (foundAtSign || cname[i] != 0) ) { // Since we found a branch and there is more information in the name, // we do NOT look at the 'IsOnTerminalBranch' status of the leaf // we found ... yet! if (leaf==0) { // Note we do not know (yet?) what (if anything) to do // for a TBranchObject branch. if (branch->InheritsFrom(TBranchElement::Class()) ) { Int_t type = ((TBranchElement*)branch)->GetType(); if ( type == 3 || type ==4) { // We have a Collection branch. leaf = (TLeaf*)branch->GetListOfLeaves()->At(0); if (foundAtSign) { useLeafCollectionObject = foundAtSign; foundAtSign = kFALSE; current = &(work[0]); *current = 0; ++i; break; } } } } // we reset work useLeafCollectionObject = foundAtSign; foundAtSign = kFALSE; current = &(work[0]); *current = 0; } else if (leaf || branch) { if (leaf && branch) { // We found both a leaf and branch matching the request name // let's see which one is the proper one to use! (On annoying case // is that where the same name is repeated ( varname.varname ) // We always give priority to the branch // leaf = 0; } if (leaf && leaf->IsOnTerminalBranch()) { // This is a non-object leaf, it should NOT be specified more except for // dimensions. final = kTRUE; } // we reset work current = &(work[0]); *current = 0; } else { // What we have so far might be a data member of one of the // leaves that are not splitted (for example "fNtrack" for the Event class. TLeaf *leafcur = GetLeafWithDatamember(first,work,readentry); if (leafcur) { leaf = leafcur; branch = leaf->GetBranch(); if (leaf->IsOnTerminalBranch()) { final = kTRUE; strlcpy(right,first,kMaxLen); //We need to put the delimiter back! if (foundAtSign) strncat(right,"@",kMaxLen-1-strlen(right)); if (cname[i]=='.') strncat(right,".",kMaxLen-1-strlen(right)); // We reset work current = &(work[0]); *current = 0; }; } else if (cname[i] == '.') { // If we have a branch that match a name preceded by a dot // then we assume we are trying to drill down the branch // Let look if one of the top level branch has a branch with the name // we are looking for. TBranch *branchcur; TIter next( fTree->GetListOfBranches() ); while(!branch && (branchcur=(TBranch*)next()) ) { branch = branchcur->FindBranch(first); } if (branch) { // We reset work current = &(work[0]); *current = 0; } } } } else { // correspond to if (leaf || branch) if (final) { Error("DefinedVariable", "Unexpected control flow!"); return -1; } // No dot is allowed in subbranches and leaves, so // we always remove it in the present case. if (cname[i]) work[strlen(work)-1] = '\0'; snprintf(scratch,sizeof(scratch),"%s.%s",first,work); snprintf(scratch2,sizeof(scratch2),"%s.%s.%s",first,second,work); if (previousdot) { currentname = &(work[previousdot+1]); } // First look for the current 'word' in the list of // leaf of the if (branch) { tmp_leaf = branch->FindLeaf(work); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(scratch); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(scratch2); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(currentname.c_str()); } if (tmp_leaf && tmp_leaf->IsOnTerminalBranch() ) { // This is a non-object leaf, it should NOT be specified more except for // dimensions. final = kTRUE; } if (branch) { tmp_branch = branch->FindBranch(work); if (!tmp_branch) tmp_branch = branch->FindBranch(scratch); if (!tmp_branch) tmp_branch = branch->FindBranch(scratch2); if (!tmp_branch) tmp_branch = branch->FindBranch(currentname.c_str()); } if (tmp_branch) { branch=tmp_branch; // NOTE: Should we look for a leaf within here? if (!final) { tmp_leaf = branch->FindLeaf(work); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(scratch); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(scratch2); if (!tmp_leaf) tmp_leaf = branch->FindLeaf(currentname.c_str()); if (tmp_leaf && tmp_leaf->IsOnTerminalBranch() ) { // This is a non-object leaf, it should NOT be specified // more except for dimensions. final = kTRUE; leaf = tmp_leaf; } } } if (tmp_leaf) { // Something was found. if (second[0]) strncat(second,".",kMaxLen-1-strlen(second)); strncat(second,work,kMaxLen-1-strlen(second)); leaf = tmp_leaf; useLeafCollectionObject = foundAtSign; foundAtSign = kFALSE; // we reset work current = &(work[0]); *current = 0; } else { //We need to put the delimiter back! if (strlen(work)) { if (foundAtSign) { Int_t where = strlen(work); work[where] = '@'; work[where+1] = cname[i]; ++current; previousdot = where+1; } else { previousdot = strlen(work); work[strlen(work)] = cname[i]; } } else --current; } } } } // Copy the left over for later use. if (strlen(work)) { strncat(right,work,kMaxLen-1-strlen(right)); } if (i<nchname) { if (strlen(right) && right[strlen(right)-1]!='.' && cname[i]!='.') { // In some cases we remove a little to fast the period, we add // it back if we need. It is assumed that 'right' and the rest of // the name was cut by a delimiter, so this should be safe. strncat(right,".",kMaxLen-1-strlen(right)); } strncat(right,&cname[i],kMaxLen-1-strlen(right)); } if (!final && branch) { if (!leaf) { leaf = (TLeaf*)branch->GetListOfLeaves()->UncheckedAt(0); if (!leaf) return -1; } final = leaf->IsOnTerminalBranch(); } if (leaf && leaf->InheritsFrom(TLeafObject::Class()) ) { if (strlen(right)==0) strlcpy(right,work,kMaxLen); } if (leaf==0 && left[0]!=0) { if (left[strlen(left)-1]=='.') left[strlen(left)-1]=0; // Check for an alias. const char *aliasValue = fTree->GetAlias(left); if (aliasValue && strcspn(aliasValue,"[]+*/-%&!=<>|")==strlen(aliasValue)) { // First check whether we are using this alias recursively (this would // lead to an infinite recursion). if (find(aliasUsed.begin(), aliasUsed.end(), left) != aliasUsed.end()) { Error("DefinedVariable", "The substitution of the branch alias \"%s\" by \"%s\" in \"%s\" failed\n"\ "\tbecause \"%s\" is used [recursively] in its own definition!", left,aliasValue,fullExpression,left); return -3; } aliasUsed.push_back(left); TString newExpression = aliasValue; newExpression += (cname+strlen(left)); Int_t res = FindLeafForExpression(newExpression, leaf, leftover, final, paran_level, castqueue, aliasUsed, useLeafCollectionObject, fullExpression); if (res<0) { Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed.",left,aliasValue); return -3; } return res; } } leftover = right; return 0; } //______________________________________________________________________________ Int_t TTreeFormula::DefinedVariable(TString &name, Int_t &action) { //*-*-*-*-*-*Check if name is in the list of Tree/Branch leaves*-*-*-*-* //*-* ================================================== // // This member function redefines the function in TFormula // If a leaf has a name corresponding to the argument name, then // returns a new code. // A TTreeFormula may contain more than one variable. // For each variable referenced, the pointers to the corresponding // branch and leaf is stored in the object arrays fBranches and fLeaves. // // name can be : // - Leaf_Name (simple variable or data member of a ClonesArray) // - Branch_Name.Leaf_Name // - Branch_Name.Method_Name // - Leaf_Name[index] // - Branch_Name.Leaf_Name[index] // - Branch_Name.Leaf_Name[index1] // - Branch_Name.Leaf_Name[][index2] // - Branch_Name.Leaf_Name[index1][index2] // New additions: // - Branch_Name.Leaf_Name[OtherLeaf_Name] // - Branch_Name.Datamember_Name // - '.' can be replaced by '->' // and // - Branch_Name[index1].Leaf_Name[index2] // - Leaf_name[index].Action().OtherAction(param) // - Leaf_name[index].Action()[val].OtherAction(param) // // The expected returns values are // -2 : the name has been recognized but won't be usable // -1 : the name has not been recognized // >=0 : the name has been recognized, return the internal code for this name. // action = kDefinedVariable; if (!fTree) return -1; fNpar = 0; if (name.Length() > kMaxLen) return -1; Int_t i,k; if (name == "Entry$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kIndexOfEntry; return code; } if (name == "LocalEntry$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kIndexOfLocalEntry; return code; } if (name == "Entries$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kEntries; SetBit(kNeedEntries); fManager->SetBit(kNeedEntries); return code; } if (name == "Iteration$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kIteration; return code; } if (name == "Length$") { Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kLength; return code; } static const char *lenfunc = "Length$("; if (strncmp(name.Data(),"Length$(",strlen(lenfunc))==0 && name[name.Length()-1]==')') { TString subform = name.Data()+strlen(lenfunc); subform.Remove( subform.Length() - 1 ); TTreeFormula *lengthForm = new TTreeFormula("lengthForm",subform,fTree); fAliases.AddAtAndExpand(lengthForm,fNoper); Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kLengthFunc; return code; } static const char *minfunc = "Min$("; if (strncmp(name.Data(),"Min$(",strlen(minfunc))==0 && name[name.Length()-1]==')') { TString subform = name.Data()+strlen(minfunc); subform.Remove( subform.Length() - 1 ); TTreeFormula *minForm = new TTreeFormula("minForm",subform,fTree); fAliases.AddAtAndExpand(minForm,fNoper); Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kMin; return code; } static const char *maxfunc = "Max$("; if (strncmp(name.Data(),"Max$(",strlen(maxfunc))==0 && name[name.Length()-1]==')') { TString subform = name.Data()+strlen(maxfunc); subform.Remove( subform.Length() - 1 ); TTreeFormula *maxForm = new TTreeFormula("maxForm",subform,fTree); fAliases.AddAtAndExpand(maxForm,fNoper); Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kMax; return code; } static const char *sumfunc = "Sum$("; if (strncmp(name.Data(),"Sum$(",strlen(sumfunc))==0 && name[name.Length()-1]==')') { TString subform = name.Data()+strlen(sumfunc); subform.Remove( subform.Length() - 1 ); TTreeFormula *sumForm = new TTreeFormula("sumForm",subform,fTree); fAliases.AddAtAndExpand(sumForm,fNoper); Int_t code = fNcodes++; fCodes[code] = 0; fLookupType[code] = kSum; return code; } // Check for $Alt(expression1,expression2) Int_t res = DefineAlternate(name.Data()); if (res!=0) { // There was either a syntax error or we found $Alt if (res<0) return res; action = res; return 0; } // Find the top level leaf and deal with dimensions char cname[kMaxLen]; strlcpy(cname,name.Data(),kMaxLen); char dims[kMaxLen]; dims[0] = '\0'; Bool_t final = kFALSE; UInt_t paran_level = 0; TObjArray castqueue; // First, it is easier to remove all dimensions information from 'cname' Int_t cnamelen = strlen(cname); for(i=0,k=0; i<cnamelen; ++i, ++k) { if (cname[i] == '[') { int bracket = i; int bracket_level = 1; int j; for (j=++i; j<cnamelen && (bracket_level>0 || cname[j]=='['); j++, i++) { if (cname[j]=='[') bracket_level++; else if (cname[j]==']') bracket_level--; } if (bracket_level != 0) { //Error("DefinedVariable","Bracket unbalanced"); return -1; } strncat(dims,&cname[bracket],j-bracket); //k += j-bracket; } if (i!=k) cname[k] = cname[i]; } cname[k]='\0'; Bool_t useLeafCollectionObject = kFALSE; TString leftover; TLeaf *leaf = 0; { std::vector<std::string> aliasSofar = fAliasesUsed; res = FindLeafForExpression(cname, leaf, leftover, final, paran_level, castqueue, aliasSofar, useLeafCollectionObject, name); } if (res<0) return res; if (!leaf && res!=2) { // Check for an alias. const char *aliasValue = fTree->GetAlias(cname); if (aliasValue) { // First check whether we are using this alias recursively (this would // lead to an infinite recursion. if (find(fAliasesUsed.begin(), fAliasesUsed.end(), cname) != fAliasesUsed.end()) { Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed\n"\ "\tbecause \"%s\" is recursively used in its own definition!", cname,aliasValue,cname); return -3; } if (strcspn(aliasValue,"+*/-%&!=<>|")!=strlen(aliasValue)) { // If the alias contains an operator, we need to use a nested formula // (since DefinedVariable must only add one entry to the operation's list). // Need to check the aliases used so far std::vector<std::string> aliasSofar = fAliasesUsed; aliasSofar.push_back( cname ); TString subValue( aliasValue ); if (dims[0]) { subValue += dims; } TTreeFormula *subform = new TTreeFormula(cname,subValue,fTree,aliasSofar); // Need to pass the aliases used so far. if (subform->GetNdim()==0) { delete subform; Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed.",cname,aliasValue); return -3; } fManager->Add(subform); fAliases.AddAtAndExpand(subform,fNoper); if (subform->IsString()) { action = kAliasString; return 0; } else { action = kAlias; return 0; } } else { /* assumes strcspn(aliasValue,"[]")!=strlen(aliasValue) */ TString thisAlias( aliasValue ); thisAlias += dims; Int_t aliasRes = DefinedVariable(thisAlias,action); if (aliasRes<0) { // We failed but DefinedVariable has not printed why yet. // and because we want thoses to be printed _before_ the notice // of the failure of the substitution, we need to print them here. if (aliasRes==-1) { Error("Compile", " Bad numerical expression : \"%s\"",thisAlias.Data()); } else if (aliasRes==-2) { Error("Compile", " Part of the Variable \"%s\" exists but some of it is not accessible or useable",thisAlias.Data()); } Error("DefinedVariable", "The substitution of the alias \"%s\" by \"%s\" failed.",cname,aliasValue); return -3; } return aliasRes; } } } if (leaf || res==2) { if (leaf && leaf->GetBranch() && leaf->GetBranch()->TestBit(kDoNotProcess)) { Error("DefinedVariable","the branch \"%s\" has to be enabled to be used",leaf->GetBranch()->GetName()); return -2; } Int_t code = fNcodes++; // If needed will now parse the indexes specified for // arrays. if (dims[0]) { char *current = &( dims[0] ); Int_t dim = 0; TString varindex; Int_t index; Int_t scanindex ; while (current) { current++; if (current[0] == ']') { fIndexes[code][dim] = -1; // Loop over all elements; } else { scanindex = sscanf(current,"%d",&index); if (scanindex) { fIndexes[code][dim] = index; } else { fIndexes[code][dim] = -2; // Index is calculated via a variable. varindex = current; char *end = (char*)(varindex.Data()); for(char bracket_level = 0;*end!=0;end++) { if (*end=='[') bracket_level++; if (bracket_level==0 && *end==']') break; if (*end==']') bracket_level--; } *end = '\0'; fVarIndexes[code][dim] = new TTreeFormula("index_var", varindex, fTree); current += strlen(varindex)+1; // move to the end of the index array } } dim ++; if (dim >= kMAXFORMDIM) { // NOTE: test that dim this is NOT too big!! break; } current = (char*)strstr( current, "[" ); } } // Now that we have cleaned-up the expression, let's compare it to the content // of the leaf! res = ParseWithLeaf(leaf,leftover,final,paran_level,castqueue,useLeafCollectionObject,name); if (res<0) return res; if (res>0) action = res; return code; } //*-*- May be a graphical cut ? TCutG *gcut = (TCutG*)gROOT->GetListOfSpecials()->FindObject(name.Data()); if (gcut) { if (gcut->GetObjectX()) { if(!gcut->GetObjectX()->InheritsFrom(TTreeFormula::Class())) { delete gcut->GetObjectX(); gcut->SetObjectX(0); } } if (gcut->GetObjectY()) { if(!gcut->GetObjectY()->InheritsFrom(TTreeFormula::Class())) { delete gcut->GetObjectY(); gcut->SetObjectY(0); } } Int_t code = fNcodes; if (strlen(gcut->GetVarX()) && strlen(gcut->GetVarY()) ) { TTreeFormula *fx = new TTreeFormula("f_x",gcut->GetVarX(),fTree); gcut->SetObjectX(fx); TTreeFormula *fy = new TTreeFormula("f_y",gcut->GetVarY(),fTree); gcut->SetObjectY(fy); fCodes[code] = -2; } else if (strlen(gcut->GetVarX())) { // Let's build the equivalent formula: // min(gcut->X) <= VarX <= max(gcut->Y) Double_t min = 0; Double_t max = 0; Int_t n = gcut->GetN(); Double_t *x = gcut->GetX(); min = max = x[0]; for(Int_t i2 = 1; i2<n; i2++) { if (x[i2] < min) min = x[i2]; if (x[i2] > max) max = x[i2]; } TString formula = "("; formula += min; formula += "<="; formula += gcut->GetVarX(); formula += " && "; formula += gcut->GetVarX(); formula += "<="; formula += max; formula += ")"; TTreeFormula *fx = new TTreeFormula("f_x",formula.Data(),fTree); gcut->SetObjectX(fx); fCodes[code] = -1; } else { Error("DefinedVariable","Found a TCutG without leaf information (%s)", gcut->GetName()); return -1; } fExternalCuts.AddAtAndExpand(gcut,code); fNcodes++; fLookupType[code] = -1; return code; } //may be an entrylist TEntryList *elist = dynamic_cast<TEntryList*> (gDirectory->Get(name.Data())); if (elist) { Int_t code = fNcodes; fCodes[code] = 0; fExternalCuts.AddAtAndExpand(elist, code); fNcodes++; fLookupType[code] = kEntryList; return code; } return -1; } //______________________________________________________________________________ TLeaf* TTreeFormula::GetLeafWithDatamember(const char* topchoice, const char* nextchoice, Long64_t readentry) const { // Return the leaf (if any) which contains an object containing // a data member which has the name provided in the arguments. TClass * cl = 0; TIter nextleaf (fTree->GetIteratorOnAllLeaves()); TFormLeafInfo* clonesinfo = 0; TLeaf *leafcur; while ((leafcur = (TLeaf*)nextleaf())) { // The following code is used somewhere else, we need to factor it out. // Here since we are interested in data member, we want to consider only // 'terminal' branch and leaf. cl = 0; if (leafcur->InheritsFrom(TLeafObject::Class()) && leafcur->GetBranch()->GetListOfBranches()->Last()==0) { TLeafObject *lobj = (TLeafObject*)leafcur; cl = lobj->GetClass(); } else if (leafcur->InheritsFrom(TLeafElement::Class()) && leafcur->IsOnTerminalBranch()) { TLeafElement * lElem = (TLeafElement*) leafcur; if (lElem->IsOnTerminalBranch()) { TBranchElement *branchEl = (TBranchElement *)leafcur->GetBranch(); Int_t type = branchEl->GetStreamerType(); if (type==-1) { cl = branchEl->GetInfo()->GetClass(); } else if (type>60 || type==0) { // Case of an object data member. Here we allow for the // variable name to be ommitted. Eg, for Event.root with split // level 1 or above Draw("GetXaxis") is the same as Draw("fH.GetXaxis()") TStreamerElement* element = (TStreamerElement*) branchEl->GetInfo()->GetElems()[branchEl->GetID()]; if (element) cl = element->GetClassPointer(); else cl = 0; } } } if (clonesinfo) { delete clonesinfo; clonesinfo = 0; } if (cl == TClonesArray::Class()) { // We have a unsplit TClonesArray leaves // In this case we assume that cl is the class in which the TClonesArray // belongs. R__LoadBranch(leafcur->GetBranch(),readentry,fQuickLoad); TClonesArray * clones; TBranch *branch = leafcur->GetBranch(); if ( branch->IsA()==TBranchElement::Class() && ((TBranchElement*)branch)->GetType()==31) { // We have an unsplit TClonesArray as part of a split TClonesArray! // Let's not dig any further. If the user really wants a data member // inside the nested TClonesArray, it has to specify it explicitly. continue; } else { Bool_t toplevel = (branch == branch->GetMother()); clonesinfo = new TFormLeafInfoClones(cl, 0, toplevel); clones = (TClonesArray*)clonesinfo->GetLocalValuePointer(leafcur,0); } if (clones) cl = clones->GetClass(); } else if (cl && cl->GetCollectionProxy()) { // We have a unsplit Collection leaves // In this case we assume that cl is the class in which the TClonesArray // belongs. TBranch *branch = leafcur->GetBranch(); if ( branch->IsA()==TBranchElement::Class() && ((TBranchElement*)branch)->GetType()==41) { // We have an unsplit Collection as part of a split Collection! // Let's not dig any further. If the user really wants a data member // inside the nested Collection, it has to specify it explicitly. continue; } else { clonesinfo = new TFormLeafInfoCollection(cl, 0); } cl = cl->GetCollectionProxy()->GetValueClass(); } if (cl) { // Now that we have the class, let's check if the topchoice is of its datamember // or if the nextchoice is a datamember of one of its datamember. Int_t offset; TStreamerInfo* info = (TStreamerInfo*)cl->GetStreamerInfo(); TStreamerElement* element = info?info->GetStreamerElement(topchoice,offset):0; if (!element) { TIter nextel( cl->GetStreamerInfo()->GetElements() ); TStreamerElement * curelem; while ((curelem = (TStreamerElement*)nextel())) { if (curelem->GetClassPointer() == TClonesArray::Class()) { // In case of a TClonesArray we need to load the data and read the // clonesArray object before being able to look into the class inside. // We need to do that because we are never interested in the TClonesArray // itself but only in the object inside. TBranch *branch = leafcur->GetBranch(); TFormLeafInfo *leafinfo = 0; if (clonesinfo) { leafinfo = clonesinfo; } else if (branch->IsA()==TBranchElement::Class() && ((TBranchElement*)branch)->GetType()==31) { // Case of a sub branch of a TClonesArray TBranchElement *branchEl = (TBranchElement*)branch; TStreamerInfo *bel_info = branchEl->GetInfo(); TClass * mother_cl = ((TBranchElement*)branch)->GetInfo()->GetClass(); TStreamerElement *bel_element = (TStreamerElement *)bel_info->GetElems()[branchEl->GetID()]; leafinfo = new TFormLeafInfoClones(mother_cl, 0, bel_element, kTRUE); } Int_t clones_offset; ((TStreamerInfo*)cl->GetStreamerInfo())->GetStreamerElement(curelem->GetName(),clones_offset); TFormLeafInfo* sub_clonesinfo = new TFormLeafInfo(cl, clones_offset, curelem); if (leafinfo) if (leafinfo->fNext) leafinfo->fNext->fNext = sub_clonesinfo; else leafinfo->fNext = sub_clonesinfo; else leafinfo = sub_clonesinfo; R__LoadBranch(branch,readentry,fQuickLoad); TClonesArray * clones = (TClonesArray*)leafinfo->GetValuePointer(leafcur,0); delete leafinfo; clonesinfo = 0; // If TClonesArray object does not exist we have no information, so let go // on. This is a weakish test since the TClonesArray object might exist in // the next entry ... In other word, we ONLY rely on the information available // in entry #0. if (!clones) continue; TClass *sub_cl = clones->GetClass(); // Now that we finally have the inside class, let's query it. element = ((TStreamerInfo*)sub_cl->GetStreamerInfo())->GetStreamerElement(nextchoice,offset); if (element) break; } // if clones array else if (curelem->GetClassPointer() && curelem->GetClassPointer()->GetCollectionProxy()) { TClass *sub_cl = curelem->GetClassPointer()->GetCollectionProxy()->GetValueClass(); while(sub_cl && sub_cl->GetCollectionProxy()) sub_cl = sub_cl->GetCollectionProxy()->GetValueClass(); // Now that we finally have the inside class, let's query it. if (sub_cl) element = ((TStreamerInfo*)sub_cl->GetStreamerInfo())->GetStreamerElement(nextchoice,offset); if (element) break; } } // loop on elements } if (element) break; else cl = 0; } } delete clonesinfo; if (cl) { return leafcur; } else { return 0; } } //______________________________________________________________________________ Bool_t TTreeFormula::BranchHasMethod(TLeaf* leafcur, TBranch* branch, const char* method, const char* params, Long64_t readentry) const { // Return the leaf (if any) of the tree with contains an object of a class // having a method which has the name provided in the argument. TClass *cl = 0; TLeafObject* lobj = 0; // Since the user does not want this branch to be loaded anyway, we just // skip it. This prevents us from warning the user that the method might // be on a disabled branch. However, and more usefully, this allows the // user to avoid error messages from branches that cannot be currently // read without warnings/errors. if (branch->TestBit(kDoNotProcess)) { return kFALSE; } // FIXME: The following code is used somewhere else, we need to factor it out. if (branch->InheritsFrom(TBranchObject::Class())) { lobj = (TLeafObject*) branch->GetListOfLeaves()->At(0); cl = lobj->GetClass(); } else if (branch->InheritsFrom(TBranchElement::Class())) { TBranchElement* branchEl = (TBranchElement*) branch; Int_t type = branchEl->GetStreamerType(); if (type == -1) { cl = branchEl->GetInfo()->GetClass(); } else if (type > 60) { // Case of an object data member. Here we allow for the // variable name to be ommitted. Eg, for Event.root with split // level 1 or above Draw("GetXaxis") is the same as Draw("fH.GetXaxis()") TStreamerElement* element = (TStreamerElement*) branchEl->GetInfo()->GetElems()[branchEl->GetID()]; if (element) { cl = element->GetClassPointer(); } else { cl = 0; } if ((cl == TClonesArray::Class()) && (branchEl->GetType() == 31)) { // we have a TClonesArray inside a split TClonesArray, // Let's not dig any further. If the user really wants a data member // inside the nested TClonesArray, it has to specify it explicitly. cl = 0; } // NOTE do we need code for Collection here? } } if (cl == TClonesArray::Class()) { // We might be try to call a method of the top class inside a // TClonesArray. // Since the leaf was not terminal, we might have a split or // unsplit and/or top leaf/branch. TClonesArray* clones = 0; R__LoadBranch(branch, readentry, fQuickLoad); if (branch->InheritsFrom(TBranchObject::Class())) { clones = (TClonesArray*) lobj->GetObject(); } else if (branch->InheritsFrom(TBranchElement::Class())) { // We do not know exactly where the leaf of the TClonesArray is // in the hierachy but we still need to get the correct class // holder. TBranchElement* bc = (TBranchElement*) branch; if (bc == bc->GetMother()) { // Top level branch //clones = *((TClonesArray**) bc->GetAddress()); clones = (TClonesArray*) bc->GetObject(); } else if (!leafcur || !leafcur->IsOnTerminalBranch()) { TStreamerElement* element = (TStreamerElement*) bc->GetInfo()->GetElems()[bc->GetID()]; if (element->IsaPointer()) { clones = *((TClonesArray**) bc->GetAddress()); //clones = *((TClonesArray**) bc->GetObject()); } else { //clones = (TClonesArray*) bc->GetAddress(); clones = (TClonesArray*) bc->GetObject(); } } if (!clones) { R__LoadBranch(bc, readentry, fQuickLoad); TClass* mother_cl; mother_cl = bc->GetInfo()->GetClass(); TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(mother_cl, 0); // if (!leafcur) { leafcur = (TLeaf*) branch->GetListOfLeaves()->At(0); } clones = (TClonesArray*) clonesinfo->GetLocalValuePointer(leafcur, 0); // cl = clones->GetClass(); delete clonesinfo; } } else { Error("BranchHasMethod","A TClonesArray was stored in a branch type no yet support (i.e. neither TBranchObject nor TBranchElement): %s",branch->IsA()->GetName()); return kFALSE; } cl = clones->GetClass(); } else if (cl && cl->GetCollectionProxy()) { cl = cl->GetCollectionProxy()->GetValueClass(); } if (cl) { if (cl->GetClassInfo()) { if (cl->GetMethodAllAny(method)) { // Let's try to see if the function we found belongs to the current // class. Note that this implementation currently can not work if // one the argument is another leaf or data member of the object. // (Anyway we do NOT support this case). TMethodCall* methodcall = new TMethodCall(cl, method, params); if (methodcall->GetMethod()) { // We have a method that works. // We will use it. return kTRUE; } delete methodcall; } } } return kFALSE; } //______________________________________________________________________________ Int_t TTreeFormula::GetRealInstance(Int_t instance, Int_t codeindex) { // Now let calculate what physical instance we really need. // Some redundant code is used to speed up the cases where // they are no dimensions. // We know that instance is less that fCumulUsedSize[0] so // we can skip the modulo when virt_dim is 0. Int_t real_instance = 0; Int_t virt_dim; Bool_t check = kFALSE; if (codeindex<0) { codeindex = 0; check = kTRUE; } TFormLeafInfo * info = 0; Int_t max_dim = fNdimensions[codeindex]; if ( max_dim ) { virt_dim = 0; max_dim--; if (!fManager->fMultiVarDim) { if (fIndexes[codeindex][0]>=0) { real_instance = fIndexes[codeindex][0] * fCumulSizes[codeindex][1]; } else { Int_t local_index; local_index = ( instance / fManager->fCumulUsedSizes[virt_dim+1]); if (fIndexes[codeindex][0]==-2) { // NOTE: Should we check that this is a valid index? if (check) { Int_t index_real_instance = fVarIndexes[codeindex][0]->GetRealInstance(local_index,-1); if (index_real_instance > fVarIndexes[codeindex][0]->fNdata[0]) { // out of bounds return fNdata[0]+1; } } if (fDidBooleanOptimization && local_index!=0) { // Force the loading of the index. fVarIndexes[codeindex][0]->LoadBranches(); } local_index = (Int_t)fVarIndexes[codeindex][0]->EvalInstance(local_index); if (local_index<0) { Error("EvalInstance","Index %s is out of bound (%d) in formula %s", fVarIndexes[codeindex][0]->GetTitle(), local_index, GetTitle()); return fNdata[0]+1; } } real_instance = local_index * fCumulSizes[codeindex][1]; virt_dim ++; } } else { // NOTE: We assume that ONLY the first dimension of a leaf can have a variable // size AND contain the index for the size of yet another sub-dimension. // I.e. a variable size array inside a variable size array can only have its // size vary with the VERY FIRST physical dimension of the leaf. // Thus once the index of the first dimension is found, all other dimensions // are fixed! // NOTE: We could unroll some of this loops to avoid a few tests. if (fHasMultipleVarDim[codeindex]) { info = (TFormLeafInfo *)(fDataMembers.At(codeindex)); // if (info && info->GetVarDim()==-1) info = 0; } Int_t local_index; switch (fIndexes[codeindex][0]) { case -2: if (fDidBooleanOptimization && instance!=0) { // Force the loading of the index. fVarIndexes[codeindex][0]->LoadBranches(); } local_index = (Int_t)fVarIndexes[codeindex][0]->EvalInstance(instance); if (local_index<0) { Error("EvalInstance","Index %s is out of bound (%d) in formula %s", fVarIndexes[codeindex][0]->GetTitle(), local_index, GetTitle()); local_index = 0; } break; case -1: { local_index = 0; Int_t virt_accum = 0; Int_t maxloop = fManager->fCumulUsedVarDims->GetSize(); if (maxloop == 0) { local_index--; instance = fNdata[0]+1; // out of bounds. if (check) return fNdata[0]+1; } else { do { virt_accum += fManager->fCumulUsedVarDims->GetArray()[local_index]; local_index++; } while( instance >= virt_accum && local_index<maxloop); if (local_index==maxloop && (instance >= virt_accum)) { local_index--; instance = fNdata[0]+1; // out of bounds. if (check) return fNdata[0]+1; } else { local_index--; if (fManager->fCumulUsedVarDims->At(local_index)) { instance -= (virt_accum - fManager->fCumulUsedVarDims->At(local_index)); } else { instance = fNdata[0]+1; // out of bounds. if (check) return fNdata[0]+1; } } } virt_dim ++; } break; default: local_index = fIndexes[codeindex][0]; } // Inform the (appropriate) MultiVarLeafInfo that the clones array index is // local_index. if (fManager->fVarDims[kMAXFORMDIM]) { fManager->fCumulUsedSizes[kMAXFORMDIM] = fManager->fVarDims[kMAXFORMDIM]->At(local_index); } else { fManager->fCumulUsedSizes[kMAXFORMDIM] = fManager->fUsedSizes[kMAXFORMDIM]; } for(Int_t d = kMAXFORMDIM-1; d>0; d--) { if (fManager->fVarDims[d]) { fManager->fCumulUsedSizes[d] = fManager->fCumulUsedSizes[d+1] * fManager->fVarDims[d]->At(local_index); } else { fManager->fCumulUsedSizes[d] = fManager->fCumulUsedSizes[d+1] * fManager->fUsedSizes[d]; } } if (info) { // When we have multiple variable dimensions, the LeafInfo only expect // the instance after the primary index has been set. info->SetPrimaryIndex(local_index); real_instance = 0; // Let's update fCumulSizes for the rest of the code. Int_t vdim = info->GetVarDim(); Int_t isize = info->GetSize(local_index); if (fIndexes[codeindex][vdim]>=0) { info->SetSecondaryIndex(fIndexes[codeindex][vdim]); } if (isize!=1 && fIndexes[codeindex][vdim]>isize) { // We are out of bounds! return fNdata[0]+1; } fCumulSizes[codeindex][vdim] = isize*fCumulSizes[codeindex][vdim+1]; for(Int_t k=vdim -1; k>0; --k) { fCumulSizes[codeindex][k] = fCumulSizes[codeindex][k+1]*fFixedSizes[codeindex][k]; } } else { real_instance = local_index * fCumulSizes[codeindex][1]; } } if (max_dim>0) { for (Int_t dim = 1; dim < max_dim; dim++) { if (fIndexes[codeindex][dim]>=0) { real_instance += fIndexes[codeindex][dim] * fCumulSizes[codeindex][dim+1]; } else { Int_t local_index; if (virt_dim && fManager->fCumulUsedSizes[virt_dim]>1) { local_index = ( ( instance % fManager->fCumulUsedSizes[virt_dim] ) / fManager->fCumulUsedSizes[virt_dim+1]); } else { local_index = ( instance / fManager->fCumulUsedSizes[virt_dim+1]); } if (fIndexes[codeindex][dim]==-2) { // NOTE: Should we check that this is a valid index? if (fDidBooleanOptimization && local_index!=0) { // Force the loading of the index. fVarIndexes[codeindex][dim]->LoadBranches(); } local_index = (Int_t)fVarIndexes[codeindex][dim]->EvalInstance(local_index); if (local_index<0 || local_index>=(fCumulSizes[codeindex][dim]/fCumulSizes[codeindex][dim+1])) { Error("EvalInstance","Index %s is out of bound (%d/%d) in formula %s", fVarIndexes[codeindex][dim]->GetTitle(), local_index, (fCumulSizes[codeindex][dim]/fCumulSizes[codeindex][dim+1]), GetTitle()); local_index = (fCumulSizes[codeindex][dim]/fCumulSizes[codeindex][dim+1])-1; } } real_instance += local_index * fCumulSizes[codeindex][dim+1]; virt_dim ++; } } if (fIndexes[codeindex][max_dim]>=0) { if (!info) real_instance += fIndexes[codeindex][max_dim]; } else { Int_t local_index; if (virt_dim && fManager->fCumulUsedSizes[virt_dim]>1) { local_index = instance % fManager->fCumulUsedSizes[virt_dim]; } else { local_index = instance; } if (info && local_index>=fCumulSizes[codeindex][max_dim]) { // We are out of bounds! [Multiple var dims, See same message a few line above] return fNdata[0]+1; } if (fIndexes[codeindex][max_dim]==-2) { if (fDidBooleanOptimization && local_index!=0) { // Force the loading of the index. fVarIndexes[codeindex][max_dim]->LoadBranches(); } local_index = (Int_t)fVarIndexes[codeindex][max_dim]->EvalInstance(local_index); if (local_index<0 || local_index>=fCumulSizes[codeindex][max_dim]) { Error("EvalInstance","Index %s is of out bound (%d/%d) in formula %s", fVarIndexes[codeindex][max_dim]->GetTitle(), local_index, fCumulSizes[codeindex][max_dim], GetTitle()); local_index = fCumulSizes[codeindex][max_dim]-1; } } real_instance += local_index; } } // if (max_dim-1>0) } // if (max_dim) return real_instance; } //______________________________________________________________________________ TClass* TTreeFormula::EvalClass() const { // Evaluate the class of this treeformula // // If the 'value' of this formula is a simple pointer to an object, // this function returns the TClass corresponding to its type. if (fNoper != 1 || fNcodes <=0 ) return 0; return EvalClass(0); } //______________________________________________________________________________ TClass* TTreeFormula::EvalClass(Int_t oper) const { // Evaluate the class of the operation oper // // If the 'value' in the requested operation is a simple pointer to an object, // this function returns the TClass corresponding to its type. TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(oper); switch(fLookupType[oper]) { case kDirect: { if (leaf->IsA()==TLeafObject::Class()) { return ((TLeafObject*)leaf)->GetClass(); } else if ( leaf->IsA()==TLeafElement::Class()) { TBranchElement * branch = (TBranchElement*)((TLeafElement*)leaf)->GetBranch(); TStreamerInfo * info = branch->GetInfo(); Int_t id = branch->GetID(); if (id>=0) { if (info==0 || info->GetElems()==0) { // we probably do not have a way to know the class of the object. return 0; } TStreamerElement* elem = (TStreamerElement*)info->GetElems()[id]; if (elem==0) { // we probably do not have a way to know the class of the object. return 0; } else { return elem->GetClass(); } } else return TClass::GetClass( branch->GetClassName() ); } else { return 0; } } case kMethod: return 0; // kMethod is deprecated so let's no waste time implementing this. case kTreeMember: case kDataMember: { TObject *obj = fDataMembers.UncheckedAt(oper); if (!obj) return 0; return ((TFormLeafInfo*)obj)->GetClass(); } default: return 0; } } //______________________________________________________________________________ void* TTreeFormula::EvalObject(int instance) { //*-*-*-*-*-*-*-*-*-*-*Evaluate this treeformula*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================= // // Return the address of the object pointed to by the formula. // Return 0 if the formula is not a single object // The object type can be retrieved using by call EvalClass(); if (fNoper != 1 || fNcodes <=0 ) return 0; switch (fLookupType[0]) { case kIndexOfEntry: case kIndexOfLocalEntry: case kEntries: case kLength: case kLengthFunc: case kIteration: case kEntryList: return 0; } TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); Int_t real_instance = GetRealInstance(instance,0); if (instance==0 || fNeedLoading) { fNeedLoading = kFALSE; R__LoadBranch(leaf->GetBranch(), leaf->GetBranch()->GetTree()->GetReadEntry(), fQuickLoad); } else if (real_instance>fNdata[0]) return 0; if (fAxis) { return 0; } switch(fLookupType[0]) { case kDirect: { if (real_instance) { Warning("EvalObject","Not yet implement for kDirect and arrays (for %s).\nPlease contact the developers",GetName()); } return leaf->GetValuePointer(); } case kMethod: return GetValuePointerFromMethod(0,leaf); case kTreeMember: case kDataMember: return ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->GetValuePointer(leaf,real_instance); default: return 0; } } //______________________________________________________________________________ const char* TTreeFormula::EvalStringInstance(Int_t instance) { // Eval the instance as a string. const Int_t kMAXSTRINGFOUND = 10; const char *stringStack[kMAXSTRINGFOUND]; if (fNoper==1 && fNcodes>0 && IsString()) { TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); Int_t real_instance = GetRealInstance(instance,0); if (instance==0 || fNeedLoading) { fNeedLoading = kFALSE; TBranch *branch = leaf->GetBranch(); R__LoadBranch(branch,branch->GetTree()->GetReadEntry(),fQuickLoad); } else if (real_instance>=fNdata[0]) { return 0; } if (fLookupType[0]==kDirect) { return (char*)leaf->GetValuePointer(); } else { return (char*)GetLeafInfo(0)->GetValuePointer(leaf,real_instance); } } EvalInstance(instance,stringStack); return stringStack[0]; } #define TT_EVAL_INIT \ TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); \ \ const Int_t real_instance = GetRealInstance(instance,0); \ \ if (instance==0) fNeedLoading = kTRUE; \ if (real_instance>fNdata[0]) return 0; \ \ /* Since the only operation in this formula is reading this branch, \ we are guaranteed that this function is first called with instance==0 and \ hence we are guaranteed that the branch is always properly read */ \ \ if (fNeedLoading) { \ fNeedLoading = kFALSE; \ TBranch *br = leaf->GetBranch(); \ Long64_t tentry = br->GetTree()->GetReadEntry(); \ R__LoadBranch(br,tentry,fQuickLoad); \ } \ \ if (fAxis) { \ char * label; \ /* This portion is a duplicate (for speed reason) of the code \ located in the main for loop at "a tree string" (and in EvalStringInstance) */ \ if (fLookupType[0]==kDirect) { \ label = (char*)leaf->GetValuePointer(); \ } else { \ label = (char*)GetLeafInfo(0)->GetValuePointer(leaf,instance); \ } \ Int_t bin = fAxis->FindBin(label); \ return bin-0.5; \ } #define TREE_EVAL_INIT \ const Int_t real_instance = GetRealInstance(instance,0); \ \ if (real_instance>fNdata[0]) return 0; \ \ if (fAxis) { \ char * label; \ /* This portion is a duplicate (for speed reason) of the code \ located in the main for loop at "a tree string" (and in EvalStringInstance) */ \ label = (char*)GetLeafInfo(0)->GetValuePointer((TLeaf*)0x0,instance); \ Int_t bin = fAxis->FindBin(label); \ return bin-0.5; \ } #define TT_EVAL_INIT_LOOP \ TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(code); \ \ /* Now let calculate what physical instance we really need. */ \ const Int_t real_instance = GetRealInstance(instance,code); \ \ if (willLoad) { \ TBranch *branch = (TBranch*)fBranches.UncheckedAt(code); \ if (branch) { \ Long64_t treeEntry = branch->GetTree()->GetReadEntry(); \ R__LoadBranch(branch,treeEntry,fQuickLoad); \ } else if (fDidBooleanOptimization) { \ branch = leaf->GetBranch(); \ Long64_t treeEntry = branch->GetTree()->GetReadEntry(); \ if (branch->GetReadEntry() != treeEntry) branch->GetEntry( treeEntry ); \ } \ } else { \ /* In the cases where we are behind (i.e. right of) a potential boolean optimization \ this tree variable reading may have not been executed with instance==0 which would \ result in the branch being potentially not read in. */ \ if (fDidBooleanOptimization) { \ TBranch *br = leaf->GetBranch(); \ Long64_t treeEntry = br->GetTree()->GetReadEntry(); \ if (br->GetReadEntry() != treeEntry) br->GetEntry( treeEntry ); \ } \ } \ if (real_instance>fNdata[code]) return 0; #define TREE_EVAL_INIT_LOOP \ /* Now let calculate what physical instance we really need. */ \ const Int_t real_instance = GetRealInstance(instance,code); \ \ if (real_instance>fNdata[code]) return 0; namespace { Double_t Summing(TTreeFormula *sum) { Int_t len = sum->GetNdata(); Double_t res = 0; for (int i=0; i<len; ++i) res += sum->EvalInstance(i); return res; } Double_t FindMin(TTreeFormula *arr) { Int_t len = arr->GetNdata(); Double_t res = 0; if (len) { res = arr->EvalInstance(0); for (int i=1; i<len; ++i) { Double_t val = arr->EvalInstance(i); if (val < res) { res = val; } } } return res; } Double_t FindMax(TTreeFormula *arr) { Int_t len = arr->GetNdata(); Double_t res = 0; if (len) { res = arr->EvalInstance(0); for (int i=1; i<len; ++i) { Double_t val = arr->EvalInstance(i); if (val > res) { res = val; } } } return res; } Double_t FindMin(TTreeFormula *arr, TTreeFormula *condition) { Int_t len = arr->GetNdata(); Double_t res = 0; if (len) { int i = 0; Double_t condval; do { condval = condition->EvalInstance(i); ++i; } while (!condval && i<len); if (i==len) { return 0; } if (i!=1) { // Insure the loading of the branch. arr->EvalInstance(0); } // Now we know that i>0 && i<len and cond==true res = arr->EvalInstance(i-1); for (; i<len; ++i) { condval = condition->EvalInstance(i); if (condval) { Double_t val = arr->EvalInstance(i); if (val < res) { res = val; } } } } return res; } Double_t FindMax(TTreeFormula *arr, TTreeFormula *condition) { Int_t len = arr->GetNdata(); Double_t res = 0; if (len) { int i = 0; Double_t condval; do { condval = condition->EvalInstance(i); ++i; } while (!condval && i<len); if (i==len) { return 0; } if (i!=1) { // Insure the loading of the branch. arr->EvalInstance(0); } // Now we know that i>0 && i<len and cond==true res = arr->EvalInstance(i-1); for (; i<len; ++i) { condval = condition->EvalInstance(i); if (condval) { Double_t val = arr->EvalInstance(i); if (val > res) { res = val; } } } } return res; } } //______________________________________________________________________________ Double_t TTreeFormula::EvalInstance(Int_t instance, const char *stringStackArg[]) { //*-*-*-*-*-*-*-*-*-*-*Evaluate this treeformula*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================= // // Note that the redundance and structure in this code is tailored to improve // efficiencies. if (TestBit(kMissingLeaf)) return 0; if (fNoper == 1 && fNcodes > 0) { switch (fLookupType[0]) { case kDirect: { TT_EVAL_INIT; Double_t result = leaf->GetValue(real_instance); return result; } case kMethod: { TT_EVAL_INIT; ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->SetBranch(leaf->GetBranch()); return GetValueFromMethod(0,leaf); } case kDataMember: { TT_EVAL_INIT; ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->SetBranch(leaf->GetBranch()); return ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->GetValue(leaf,real_instance); } case kTreeMember: { TREE_EVAL_INIT; return ((TFormLeafInfo*)fDataMembers.UncheckedAt(0))->GetValue((TLeaf*)0x0,real_instance); } case kIndexOfEntry: return (Double_t)fTree->GetReadEntry(); case kIndexOfLocalEntry: return (Double_t)fTree->GetTree()->GetReadEntry(); case kEntries: return (Double_t)fTree->GetEntries(); case kLength: return fManager->fNdata; case kLengthFunc: return ((TTreeFormula*)fAliases.UncheckedAt(0))->GetNdata(); case kIteration: return instance; case kSum: return Summing((TTreeFormula*)fAliases.UncheckedAt(0)); case kMin: return FindMin((TTreeFormula*)fAliases.UncheckedAt(0)); case kMax: return FindMax((TTreeFormula*)fAliases.UncheckedAt(0)); case kEntryList: { TEntryList *elist = (TEntryList*)fExternalCuts.At(0); return elist->Contains(fTree->GetTree()->GetReadEntry()); } case -1: break; } switch (fCodes[0]) { case -2: { TCutG *gcut = (TCutG*)fExternalCuts.At(0); TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); TTreeFormula *fy = (TTreeFormula *)gcut->GetObjectY(); Double_t xcut = fx->EvalInstance(instance); Double_t ycut = fy->EvalInstance(instance); return gcut->IsInside(xcut,ycut); } case -1: { TCutG *gcut = (TCutG*)fExternalCuts.At(0); TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); return fx->EvalInstance(instance); } default: return 0; } } Double_t tab[kMAXFOUND]; const Int_t kMAXSTRINGFOUND = 10; const char *stringStackLocal[kMAXSTRINGFOUND]; const char **stringStack = stringStackArg?stringStackArg:stringStackLocal; const bool willLoad = (instance==0 || fNeedLoading); fNeedLoading = kFALSE; if (willLoad) fDidBooleanOptimization = kFALSE; Int_t pos = 0; Int_t pos2 = 0; for (Int_t i=0; i<fNoper ; ++i) { const Int_t oper = GetOper()[i]; const Int_t newaction = oper >> kTFOperShift; if (newaction<kDefinedVariable) { // TFormula operands. // one of the most used cases if (newaction==kConstant) { pos++; tab[pos-1] = fConst[(oper & kTFOperMask)]; continue; } switch(newaction) { case kEnd : return tab[0]; case kAdd : pos--; tab[pos-1] += tab[pos]; continue; case kSubstract : pos--; tab[pos-1] -= tab[pos]; continue; case kMultiply : pos--; tab[pos-1] *= tab[pos]; continue; case kDivide : pos--; if (tab[pos] == 0) tab[pos-1] = 0; // division by 0 else tab[pos-1] /= tab[pos]; continue; case kModulo : {pos--; Long64_t int1((Long64_t)tab[pos-1]); Long64_t int2((Long64_t)tab[pos]); tab[pos-1] = Double_t(int1%int2); continue;} case kcos : tab[pos-1] = TMath::Cos(tab[pos-1]); continue; case ksin : tab[pos-1] = TMath::Sin(tab[pos-1]); continue; case ktan : if (TMath::Cos(tab[pos-1]) == 0) {tab[pos-1] = 0;} // { tangente indeterminee } else tab[pos-1] = TMath::Tan(tab[pos-1]); continue; case kacos : if (TMath::Abs(tab[pos-1]) > 1) {tab[pos-1] = 0;} // indetermination else tab[pos-1] = TMath::ACos(tab[pos-1]); continue; case kasin : if (TMath::Abs(tab[pos-1]) > 1) {tab[pos-1] = 0;} // indetermination else tab[pos-1] = TMath::ASin(tab[pos-1]); continue; case katan : tab[pos-1] = TMath::ATan(tab[pos-1]); continue; case kcosh : tab[pos-1] = TMath::CosH(tab[pos-1]); continue; case ksinh : tab[pos-1] = TMath::SinH(tab[pos-1]); continue; case ktanh : if (TMath::CosH(tab[pos-1]) == 0) {tab[pos-1] = 0;} // { tangente indeterminee } else tab[pos-1] = TMath::TanH(tab[pos-1]); continue; case kacosh: if (tab[pos-1] < 1) {tab[pos-1] = 0;} // indetermination else tab[pos-1] = TMath::ACosH(tab[pos-1]); continue; case kasinh: tab[pos-1] = TMath::ASinH(tab[pos-1]); continue; case katanh: if (TMath::Abs(tab[pos-1]) > 1) {tab[pos-1] = 0;} // indetermination else tab[pos-1] = TMath::ATanH(tab[pos-1]); continue; case katan2: pos--; tab[pos-1] = TMath::ATan2(tab[pos-1],tab[pos]); continue; case kfmod : pos--; tab[pos-1] = fmod(tab[pos-1],tab[pos]); continue; case kpow : pos--; tab[pos-1] = TMath::Power(tab[pos-1],tab[pos]); continue; case ksq : tab[pos-1] = tab[pos-1]*tab[pos-1]; continue; case ksqrt : tab[pos-1] = TMath::Sqrt(TMath::Abs(tab[pos-1])); continue; case kstrstr : pos2 -= 2; pos++;if (strstr(stringStack[pos2],stringStack[pos2+1])) tab[pos-1]=1; else tab[pos-1]=0; continue; case kmin : pos--; tab[pos-1] = TMath::Min(tab[pos-1],tab[pos]); continue; case kmax : pos--; tab[pos-1] = TMath::Max(tab[pos-1],tab[pos]); continue; case klog : if (tab[pos-1] > 0) tab[pos-1] = TMath::Log(tab[pos-1]); else {tab[pos-1] = 0;} //{indetermination } continue; case kexp : { Double_t dexp = tab[pos-1]; if (dexp < -700) {tab[pos-1] = 0; continue;} if (dexp > 700) {tab[pos-1] = TMath::Exp(700); continue;} tab[pos-1] = TMath::Exp(dexp); continue; } case klog10: if (tab[pos-1] > 0) tab[pos-1] = TMath::Log10(tab[pos-1]); else {tab[pos-1] = 0;} //{indetermination } continue; case kpi : pos++; tab[pos-1] = TMath::ACos(-1); continue; case kabs : tab[pos-1] = TMath::Abs(tab[pos-1]); continue; case ksign : if (tab[pos-1] < 0) tab[pos-1] = -1; else tab[pos-1] = 1; continue; case kint : tab[pos-1] = Double_t(Int_t(tab[pos-1])); continue; case kSignInv: tab[pos-1] = -1 * tab[pos-1]; continue; case krndm : pos++; tab[pos-1] = gRandom->Rndm(1); continue; case kAnd : pos--; if (tab[pos-1]!=0 && tab[pos]!=0) tab[pos-1]=1; else tab[pos-1]=0; continue; case kOr : pos--; if (tab[pos-1]!=0 || tab[pos]!=0) tab[pos-1]=1; else tab[pos-1]=0; continue; case kEqual : pos--; tab[pos-1] = (tab[pos-1] == tab[pos]) ? 1 : 0; continue; case kNotEqual : pos--; tab[pos-1] = (tab[pos-1] != tab[pos]) ? 1 : 0; continue; case kLess : pos--; tab[pos-1] = (tab[pos-1] < tab[pos]) ? 1 : 0; continue; case kGreater : pos--; tab[pos-1] = (tab[pos-1] > tab[pos]) ? 1 : 0; continue; case kLessThan : pos--; tab[pos-1] = (tab[pos-1] <= tab[pos]) ? 1 : 0; continue; case kGreaterThan: pos--; tab[pos-1] = (tab[pos-1] >= tab[pos]) ? 1 : 0; continue; case kNot : tab[pos-1] = (tab[pos-1] != 0) ? 0 : 1; continue; case kStringEqual : pos2 -= 2; pos++; if (!strcmp(stringStack[pos2+1],stringStack[pos2])) tab[pos-1]=1; else tab[pos-1]=0; continue; case kStringNotEqual: pos2 -= 2; pos++;if (strcmp(stringStack[pos2+1],stringStack[pos2])) tab[pos-1]=1; else tab[pos-1]=0; continue; case kBitAnd : pos--; tab[pos-1]= ((Long64_t) tab[pos-1]) & ((Long64_t) tab[pos]); continue; case kBitOr : pos--; tab[pos-1]= ((Long64_t) tab[pos-1]) | ((Long64_t) tab[pos]); continue; case kLeftShift : pos--; tab[pos-1]= ((Long64_t) tab[pos-1]) <<((Long64_t) tab[pos]); continue; case kRightShift: pos--; tab[pos-1]= ((Long64_t) tab[pos-1]) >>((Long64_t) tab[pos]); continue; case kJump : i = (oper & kTFOperMask); continue; case kJumpIf : pos--; if (!tab[pos]) i = (oper & kTFOperMask); continue; case kStringConst: { // String pos2++; stringStack[pos2-1] = (char*)fExpr[i].Data(); continue; } case kBoolOptimize: { // boolean operation optimizer int param = (oper & kTFOperMask); Bool_t skip = kFALSE; int op = param % 10; // 1 is && , 2 is || if (op == 1 && (!tab[pos-1]) ) { // &&: skip the right part if the left part is already false skip = kTRUE; // Preserve the existing behavior (i.e. the result of a&&b is // either 0 or 1) tab[pos-1] = 0; } else if (op == 2 && tab[pos-1] ) { // ||: skip the right part if the left part is already true skip = kTRUE; // Preserve the existing behavior (i.e. the result of a||b is // either 0 or 1) tab[pos-1] = 1; } if (skip) { int toskip = param / 10; i += toskip; if (willLoad) fDidBooleanOptimization = kTRUE; } continue; } case kFunctionCall: { // an external function call int param = (oper & kTFOperMask); int fno = param / 1000; int nargs = param % 1000; // Retrieve the function TMethodCall *method = (TMethodCall*)fFunctions.At(fno); // Set the arguments method->ResetParam(); if (nargs) { UInt_t argloc = pos-nargs; for(Int_t j=0;j<nargs;j++,argloc++,pos--) { method->SetParam( tab[argloc] ); } } pos++; Double_t ret; method->Execute(ret); tab[pos-1] = ret; // check for the correct conversion! continue; } // case kParameter: { pos++; tab[pos-1] = fParams[(oper & kTFOperMask)]; continue; } } } else { // TTreeFormula operands. // a tree variable (the most used case). if (newaction == kDefinedVariable) { const Int_t code = (oper & kTFOperMask); const Int_t lookupType = fLookupType[code]; switch (lookupType) { case kIndexOfEntry: tab[pos++] = (Double_t)fTree->GetReadEntry(); continue; case kIndexOfLocalEntry: tab[pos++] = (Double_t)fTree->GetTree()->GetReadEntry(); continue; case kEntries: tab[pos++] = (Double_t)fTree->GetEntries(); continue; case kLength: tab[pos++] = fManager->fNdata; continue; case kLengthFunc: tab[pos++] = ((TTreeFormula*)fAliases.UncheckedAt(i))->GetNdata(); continue; case kIteration: tab[pos++] = instance; continue; case kSum: tab[pos++] = Summing((TTreeFormula*)fAliases.UncheckedAt(i)); continue; case kMin: tab[pos++] = FindMin((TTreeFormula*)fAliases.UncheckedAt(i)); continue; case kMax: tab[pos++] = FindMax((TTreeFormula*)fAliases.UncheckedAt(i)); continue; case kDirect: { TT_EVAL_INIT_LOOP; tab[pos++] = leaf->GetValue(real_instance); continue; } case kMethod: { TT_EVAL_INIT_LOOP; tab[pos++] = GetValueFromMethod(code,leaf); continue; } case kDataMember: { TT_EVAL_INIT_LOOP; tab[pos++] = ((TFormLeafInfo*)fDataMembers.UncheckedAt(code))-> GetValue(leaf,real_instance); continue; } case kTreeMember: { TREE_EVAL_INIT_LOOP; tab[pos++] = ((TFormLeafInfo*)fDataMembers.UncheckedAt(code))-> GetValue((TLeaf*)0x0,real_instance); continue; } case kEntryList: { TEntryList *elist = (TEntryList*)fExternalCuts.At(code); tab[pos++] = elist->Contains(fTree->GetReadEntry()); continue;} case -1: break; default: tab[pos++] = 0; continue; } switch (fCodes[code]) { case -2: { TCutG *gcut = (TCutG*)fExternalCuts.At(code); TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); TTreeFormula *fy = (TTreeFormula *)gcut->GetObjectY(); Double_t xcut = fx->EvalInstance(instance); Double_t ycut = fy->EvalInstance(instance); tab[pos++] = gcut->IsInside(xcut,ycut); continue; } case -1: { TCutG *gcut = (TCutG*)fExternalCuts.At(code); TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); tab[pos++] = fx->EvalInstance(instance); continue; } default: { tab[pos++] = 0; continue; } } } switch(newaction) { // a TTree Variable Alias (i.e. a sub-TTreeFormula) case kAlias: { int aliasN = i; TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(aliasN)); R__ASSERT(subform); Double_t param = subform->EvalInstance(instance); tab[pos] = param; pos++; continue; } // a TTree Variable Alias String (i.e. a sub-TTreeFormula) case kAliasString: { int aliasN = i; TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(aliasN)); R__ASSERT(subform); pos2++; stringStack[pos2-1] = subform->EvalStringInstance(instance); continue; } case kMinIf: { int alternateN = i; TTreeFormula *primary = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN)); TTreeFormula *condition = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN+1)); Double_t param = FindMin(primary,condition); ++i; // skip the place holder for the condition tab[pos] = param; pos++; continue; } case kMaxIf: { int alternateN = i; TTreeFormula *primary = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN)); TTreeFormula *condition = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN+1)); Double_t param = FindMax(primary,condition); ++i; // skip the place holder for the condition tab[pos] = param; pos++; continue; } // a TTree Variable Alternate (i.e. a sub-TTreeFormula) case kAlternate: { int alternateN = i; TTreeFormula *primary = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN)); // First check whether we are in range for the primary formula if (instance < primary->GetNdata()) { Double_t param = primary->EvalInstance(instance); ++i; // skip the alternate value. tab[pos] = param; pos++; } else { // The primary is not in rancge, we will calculate the alternate value // via the next operation (which will be a intentional). // kAlias no operations } continue; } case kAlternateString: { int alternateN = i; TTreeFormula *primary = static_cast<TTreeFormula*>(fAliases.UncheckedAt(alternateN)); // First check whether we are in range for the primary formula if (instance < primary->GetNdata()) { pos2++; stringStack[pos2-1] = primary->EvalStringInstance(instance); ++i; // skip the alternate value. } else { // The primary is not in rancge, we will calculate the alternate value // via the next operation (which will be a kAlias). // intentional no operations } continue; } // a tree string case kDefinedString: { Int_t string_code = (oper & kTFOperMask); TLeaf *leafc = (TLeaf*)fLeaves.UncheckedAt(string_code); // Now let calculate what physical instance we really need. const Int_t real_instance = GetRealInstance(instance,string_code); if (instance==0 || fNeedLoading) { fNeedLoading = kFALSE; TBranch *branch = leafc->GetBranch(); Long64_t readentry = branch->GetTree()->GetReadEntry(); R__LoadBranch(branch,readentry,fQuickLoad); } else { // In the cases where we are behind (i.e. right of) a potential boolean optimization // this tree variable reading may have not been executed with instance==0 which would // result in the branch being potentially not read in. if (fDidBooleanOptimization) { TBranch *br = leafc->GetBranch(); Long64_t treeEntry = br->GetTree()->GetReadEntry(); R__LoadBranch(br,treeEntry,kTRUE); } if (real_instance>fNdata[string_code]) return 0; } pos2++; if (fLookupType[string_code]==kDirect) { stringStack[pos2-1] = (char*)leafc->GetValuePointer(); } else { stringStack[pos2-1] = (char*)GetLeafInfo(string_code)->GetValuePointer(leafc,real_instance); } continue; } } } R__ASSERT(i<fNoper); } Double_t result = tab[0]; return result; } //______________________________________________________________________________ TFormLeafInfo *TTreeFormula::GetLeafInfo(Int_t code) const { //*-*-*-*-*-*-*-*Return DataMember corresponding to code*-*-*-*-*-* //*-* ======================================= // // function called by TLeafObject::GetValue // with the value of fLookupType computed in TTreeFormula::DefinedVariable return (TFormLeafInfo *)fDataMembers.UncheckedAt(code); } //______________________________________________________________________________ TLeaf *TTreeFormula::GetLeaf(Int_t n) const { //*-*-*-*-*-*-*-*Return leaf corresponding to serial number n*-*-*-*-*-* //*-* ============================================ // return (TLeaf*)fLeaves.UncheckedAt(n); } //______________________________________________________________________________ TMethodCall *TTreeFormula::GetMethodCall(Int_t code) const { //*-*-*-*-*-*-*-*Return methodcall corresponding to code*-*-*-*-*-* //*-* ======================================= // // function called by TLeafObject::GetValue // with the value of fLookupType computed in TTreeFormula::DefinedVariable return (TMethodCall *)fMethods.UncheckedAt(code); } //______________________________________________________________________________ Int_t TTreeFormula::GetNdata() { //*-*-*-*-*-*-*-*Return number of available instances in the formula-*-*-*-*-*-* //*-* =================================================== // return fManager->GetNdata(); } //______________________________________________________________________________ Double_t TTreeFormula::GetValueFromMethod(Int_t i, TLeaf* leaf) const { // Return result of a leafobject method. TMethodCall* m = GetMethodCall(i); if (!m) { return 0.0; } void* thisobj = 0; if (leaf->InheritsFrom(TLeafObject::Class())) { thisobj = ((TLeafObject*) leaf)->GetObject(); } else { TBranchElement* branch = (TBranchElement*) ((TLeafElement*) leaf)->GetBranch(); Int_t id = branch->GetID(); // FIXME: This is wrong for a top-level branch. Int_t offset = 0; if (id > -1) { TStreamerInfo* info = branch->GetInfo(); if (info) { offset = info->GetOffsets()[id]; } else { Warning("GetValueFromMethod", "No streamer info for branch %s.", branch->GetName()); } } if (id < 0) { char* address = branch->GetObject(); thisobj = address; } else { //char* address = branch->GetAddress(); char* address = branch->GetObject(); if (address) { thisobj = *((char**) (address + offset)); } else { // FIXME: If the address is not set, the object won't be either! thisobj = branch->GetObject(); } } } TMethodCall::EReturnType r = m->ReturnType(); if (r == TMethodCall::kLong) { Long_t l; m->Execute(thisobj, l); return (Double_t) l; } if (r == TMethodCall::kDouble) { Double_t d; m->Execute(thisobj, d); return d; } m->Execute(thisobj); return 0; } //______________________________________________________________________________ void* TTreeFormula::GetValuePointerFromMethod(Int_t i, TLeaf* leaf) const { // Return result of a leafobject method. TMethodCall* m = GetMethodCall(i); if (!m) { return 0; } void* thisobj; if (leaf->InheritsFrom(TLeafObject::Class())) { thisobj = ((TLeafObject*) leaf)->GetObject(); } else { TBranchElement* branch = (TBranchElement*) ((TLeafElement*) leaf)->GetBranch(); Int_t id = branch->GetID(); Int_t offset = 0; if (id > -1) { TStreamerInfo* info = branch->GetInfo(); if (info) { offset = info->GetOffsets()[id]; } else { Warning("GetValuePointerFromMethod", "No streamer info for branch %s.", branch->GetName()); } } if (id < 0) { char* address = branch->GetObject(); thisobj = address; } else { //char* address = branch->GetAddress(); char* address = branch->GetObject(); if (address) { thisobj = *((char**) (address + offset)); } else { // FIXME: If the address is not set, the object won't be either! thisobj = branch->GetObject(); } } } TMethodCall::EReturnType r = m->ReturnType(); if (r == TMethodCall::kLong) { Long_t l; m->Execute(thisobj, l); return 0; } if (r == TMethodCall::kDouble) { Double_t d; m->Execute(thisobj, d); return 0; } if (r == TMethodCall::kOther) { char* c; m->Execute(thisobj, &c); return c; } m->Execute(thisobj); return 0; } //______________________________________________________________________________ Bool_t TTreeFormula::IsInteger(Bool_t fast) const { // return TRUE if the formula corresponds to one single Tree leaf // and this leaf is short, int or unsigned short, int // When a leaf is of type integer or string, the generated histogram is forced // to have an integer bin width if (fast) { if (TestBit(kIsInteger)) return kTRUE; else return kFALSE; } if (fNoper==2 && GetAction(0)==kAlternate) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); return subform->IsInteger(kFALSE); } if (GetAction(0)==kMinIf || GetAction(0)==kMaxIf) { return kFALSE; } if (fNoper > 1) return kFALSE; if (GetAction(0)==kAlias) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); return subform->IsInteger(kFALSE); } if (fLeaves.GetEntries() != 1) { switch (fLookupType[0]) { case kIndexOfEntry: case kIndexOfLocalEntry: case kEntries: case kLength: case kLengthFunc: case kIteration: return kTRUE; case kSum: case kMin: case kMax: case kEntryList: default: return kFALSE; } } if (EvalClass()==TBits::Class()) return kTRUE; if (IsLeafInteger(0) || IsLeafString(0)) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TTreeFormula::IsLeafInteger(Int_t code) const { // return TRUE if the leaf corresponding to code is short, int or unsigned // short, int When a leaf is of type integer, the generated histogram is // forced to have an integer bin width TLeaf *leaf = (TLeaf*)fLeaves.At(code); if (!leaf) { switch (fLookupType[code]) { case kIndexOfEntry: case kIndexOfLocalEntry: case kEntries: case kLength: case kLengthFunc: case kIteration: return kTRUE; case kSum: case kMin: case kMax: case kEntryList: default: return kFALSE; } } if (fAxis) return kTRUE; TFormLeafInfo * info; switch (fLookupType[code]) { case kMethod: case kTreeMember: case kDataMember: info = GetLeafInfo(code); return info->IsInteger(); case kDirect: break; } if (!strcmp(leaf->GetTypeName(),"Int_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"Short_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"UInt_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"UShort_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"Bool_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"Char_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"UChar_t")) return kTRUE; if (!strcmp(leaf->GetTypeName(),"string")) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TTreeFormula::IsString() const { // return TRUE if the formula is a string return TestBit(kIsCharacter) || (fNoper==1 && IsString(0)); } //______________________________________________________________________________ Bool_t TTreeFormula::IsString(Int_t oper) const { // (fOper[i]>=105000 && fOper[i]<110000) || fOper[i] == kStrings) // return true if the expression at the index 'oper' is to be treated as // as string if (TFormula::IsString(oper)) return kTRUE; if (GetAction(oper)==kDefinedString) return kTRUE; if (GetAction(oper)==kAliasString) return kTRUE; if (GetAction(oper)==kAlternateString) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TTreeFormula::IsLeafString(Int_t code) const { // return TRUE if the leaf or data member corresponding to code is a string TLeaf *leaf = (TLeaf*)fLeaves.At(code); TFormLeafInfo * info; if (fLookupType[code]==kTreeMember) { info = GetLeafInfo(code); return info->IsString(); } switch(fLookupType[code]) { case kDirect: if ( !leaf->IsUnsigned() && (leaf->InheritsFrom(TLeafC::Class()) || leaf->InheritsFrom(TLeafB::Class()) ) ) { // Need to find out if it is an 'array' or a pointer. if (leaf->GetLenStatic() > 1) return kTRUE; // Now we need to differantiate between a variable length array and // a TClonesArray. if (leaf->GetLeafCount()) { const char* indexname = leaf->GetLeafCount()->GetName(); if (indexname[strlen(indexname)-1] == '_' ) { // This in a clones array return kFALSE; } else { // this is a variable length char array return kTRUE; } } return kFALSE; } else if (leaf->InheritsFrom(TLeafElement::Class())) { TBranchElement * br = (TBranchElement*)leaf->GetBranch(); Int_t bid = br->GetID(); if (bid < 0) return kFALSE; if (br->GetInfo()==0 || br->GetInfo()->GetElems()==0) { // Case where the file is corrupted is some ways. // We can not get to the actual type of the data // let's assume it is NOT a string. return kFALSE; } TStreamerElement * elem = (TStreamerElement*) br->GetInfo()->GetElems()[bid]; if (!elem) { // Case where the file is corrupted is some ways. // We can not get to the actual type of the data // let's assume it is NOT a string. return kFALSE; } if (elem->GetNewType()== TStreamerInfo::kOffsetL +kChar_t) { // Check whether a specific element of the string is specified! if (fIndexes[code][fNdimensions[code]-1] != -1) return kFALSE; return kTRUE; } if ( elem->GetNewType()== TStreamerInfo::kCharStar) { // Check whether a specific element of the string is specified! if (fNdimensions[code] && fIndexes[code][fNdimensions[code]-1] != -1) return kFALSE; return kTRUE; } return kFALSE; } else { return kFALSE; } case kMethod: //TMethodCall *m = GetMethodCall(code); //TMethodCall::EReturnType r = m->ReturnType(); return kFALSE; case kDataMember: info = GetLeafInfo(code); return info->IsString(); default: return kFALSE; } } //______________________________________________________________________________ char *TTreeFormula::PrintValue(Int_t mode) const { // Return value of variable as a string // // mode = -2 : Print line with *** // mode = -1 : Print column names // mode = 0 : Print column values return PrintValue(mode,0); } //______________________________________________________________________________ char *TTreeFormula::PrintValue(Int_t mode, Int_t instance, const char *decform) const { // Return value of variable as a string // // mode = -2 : Print line with *** // mode = -1 : Print column names // mode = 0 : Print column values // decform contains the requested format (with the same convention as printf). // const int kMAXLENGTH = 1024; static char value[kMAXLENGTH]; if (mode == -2) { for (int i = 0; i < kMAXLENGTH-1; i++) value[i] = '*'; value[kMAXLENGTH-1] = 0; } else if (mode == -1) { snprintf(value, kMAXLENGTH-1, "%s", GetTitle()); } else if (mode == 0) { if ( (fNstring && fNval==0 && fNoper==1) || (TestBit(kIsCharacter)) ) { const char * val = 0; if (instance<fNdata[0]) { if (fLookupType[0]==kTreeMember) { val = (char*)GetLeafInfo(0)->GetValuePointer((TLeaf*)0x0,instance); } else { TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); TBranch *branch = leaf->GetBranch(); Long64_t readentry = branch->GetTree()->GetReadEntry(); R__LoadBranch(branch,readentry,fQuickLoad); if (fLookupType[0]==kDirect && fNoper==1) { val = (const char*)leaf->GetValuePointer(); } else { val = ((TTreeFormula*)this)->EvalStringInstance(instance); } } } if (val) { strlcpy(value, val, kMAXLENGTH); } else { value[0] = '\0'; } value[kMAXLENGTH-1] = 0; } else { //NOTE: This is terrible form ... but is forced upon us by the fact that we can not //use the mutable keyword AND we should keep PrintValue const. Int_t real_instance = ((TTreeFormula*)this)->GetRealInstance(instance,-1); if (real_instance<fNdata[0]) { Ssiz_t len = strlen(decform); Char_t outputSizeLevel = 1; char *expo = 0; if (len>2) { switch (decform[len-2]) { case 'l': case 'L': { outputSizeLevel = 2; if (len>3 && tolower(decform[len-3])=='l') { outputSizeLevel = 3; } break; } case 'h': outputSizeLevel = 0; break; } } switch(decform[len-1]) { case 'c': case 'd': case 'i': { switch (outputSizeLevel) { case 0: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(Short_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 2: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(Long_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 3: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(Long64_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 1: default: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(Int_t)((TTreeFormula*)this)->EvalInstance(instance)); break; } break; } case 'o': case 'x': case 'X': case 'u': { switch (outputSizeLevel) { case 0: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(UShort_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 2: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(ULong_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 3: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(ULong64_t)((TTreeFormula*)this)->EvalInstance(instance)); break; case 1: default: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(UInt_t)((TTreeFormula*)this)->EvalInstance(instance)); break; } break; } case 'f': case 'e': case 'E': case 'g': case 'G': { switch (outputSizeLevel) { case 2: snprintf(value,kMAXLENGTH,Form("%%%s",decform),(long double)((TTreeFormula*)this)->EvalInstance(instance)); break; case 1: default: snprintf(value,kMAXLENGTH,Form("%%%s",decform),((TTreeFormula*)this)->EvalInstance(instance)); break; } expo = strchr(value,'e'); break; } default: snprintf(value,kMAXLENGTH,Form("%%%sg",decform),((TTreeFormula*)this)->EvalInstance(instance)); expo = strchr(value,'e'); } if (expo) { // If there is an exponent we may be longer than planned. // so let's trim off the excess precission! UInt_t declen = atoi(decform); if (strlen(value)>declen) { UInt_t off = strlen(value)-declen; char *start = expo - off; UInt_t vlen = strlen(expo); for(UInt_t z=0;z<=vlen;++z) { start[z] = expo[z]; } //strcpy(expo-off,expo); } } } else { if (isalpha(decform[strlen(decform)-1])) { TString short_decform(decform); short_decform.Remove(short_decform.Length()-1); snprintf(value,kMAXLENGTH,Form(" %%%sc",short_decform.Data()),' '); } else { snprintf(value,kMAXLENGTH,Form(" %%%sc",decform),' '); } } } } return &value[0]; } //______________________________________________________________________________ void TTreeFormula::ResetLoading() { // Tell the formula that we are going to request a new entry. fNeedLoading = kTRUE; fDidBooleanOptimization = kFALSE; for(Int_t i=0; i<fNcodes; ++i) { UInt_t max_dim = fNdimensions[i]; for(UInt_t dim=0; dim<max_dim ;++dim) { if (fVarIndexes[i][dim]) { fVarIndexes[i][dim]->ResetLoading(); } } } Int_t n = fAliases.GetLast(); if ( fNoper < n ) { n = fNoper; } for(Int_t k=0; k <= n; ++k) { TTreeFormula *f = static_cast<TTreeFormula*>(fAliases.UncheckedAt(k)); if (f) { f->ResetLoading(); } } } //______________________________________________________________________________ void TTreeFormula::SetAxis(TAxis *axis) { // Set the axis (in particular get the type). if (!axis) {fAxis = 0; return;} if (TestBit(kIsCharacter)) { fAxis = axis; if (fNoper==1 && GetAction(0)==kAliasString){ TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); subform->SetAxis(axis); } else if (fNoper==2 && GetAction(0)==kAlternateString){ TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(0)); R__ASSERT(subform); subform->SetAxis(axis); } } if (IsInteger()) axis->SetBit(TAxis::kIsInteger); } //______________________________________________________________________________ void TTreeFormula::Streamer(TBuffer &R__b) { // Stream an object of class TTreeFormula. if (R__b.IsReading()) { UInt_t R__s, R__c; Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v > 2) { R__b.ReadClassBuffer(TTreeFormula::Class(), this, R__v, R__s, R__c); return; } //====process old versions before automatic schema evolution TFormula::Streamer(R__b); R__b >> fTree; R__b >> fNcodes; R__b.ReadFastArray(fCodes, fNcodes); R__b >> fMultiplicity; Int_t instance; R__b >> instance; //data member removed R__b >> fNindex; if (fNindex) { fLookupType = new Int_t[fNindex]; R__b.ReadFastArray(fLookupType, fNindex); } fMethods.Streamer(R__b); //====end of old versions } else { R__b.WriteClassBuffer(TTreeFormula::Class(),this); } } //______________________________________________________________________________ Bool_t TTreeFormula::StringToNumber(Int_t oper) { // Try to 'demote' a string into an array bytes. If this is not possible, // return false. Int_t code = GetActionParam(oper); if (GetAction(oper)==kDefinedString && fLookupType[code]==kDirect) { if (oper>0 && GetAction(oper-1)==kJump) { // We are the second hand of a ternary operator, let's not do the fixing. return kFALSE; } TLeaf *leaf = (TLeaf*)fLeaves.At(code); if (leaf && (leaf->InheritsFrom(TLeafC::Class()) || leaf->InheritsFrom(TLeafB::Class()) ) ) { SetAction(oper, kDefinedVariable, code ); fNval++; fNstring--; return kTRUE; } } return kFALSE; } //______________________________________________________________________________ void TTreeFormula::UpdateFormulaLeaves() { // this function is called TTreePlayer::UpdateFormulaLeaves, itself // called by TChain::LoadTree when a new Tree is loaded. // Because Trees in a TChain may have a different list of leaves, one // must update the leaves numbers in the TTreeFormula used by the TreePlayer. // A safer alternative would be to recompile the whole thing .... However // currently compile HAS TO be called from the constructor! TString names(kMaxLen); Int_t nleaves = fLeafNames.GetEntriesFast(); ResetBit( kMissingLeaf ); for (Int_t i=0;i<nleaves;i++) { if (!fTree) break; if (!fLeafNames[i]) continue; names.Form("%s/%s",fLeafNames[i]->GetTitle(),fLeafNames[i]->GetName()); TLeaf *leaf = fTree->GetLeaf(names); fLeaves[i] = leaf; if (fBranches[i] && leaf) { fBranches[i]=leaf->GetBranch(); // Since sometimes we might no read all the branches for all the entries, we // might sometimes only read the branch count and thus reset the colleciton // but might not read the data branches, to insure that a subsequent read // from TTreeFormula will properly load the data branches even if fQuickLoad is true, // we reset the entry of all branches in the TTree. ((TBranch*)fBranches[i])->ResetReadEntry(); } if (leaf==0) SetBit( kMissingLeaf ); } for (Int_t j=0; j<kMAXCODES; j++) { for (Int_t k = 0; k<kMAXFORMDIM; k++) { if (fVarIndexes[j][k]) { fVarIndexes[j][k]->UpdateFormulaLeaves(); } } if (fLookupType[j]==kDataMember || fLookupType[j]==kTreeMember) GetLeafInfo(j)->Update(); if (j<fNval && fCodes[j]<0) { TCutG *gcut = (TCutG*)fExternalCuts.At(j); if (gcut) { TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); TTreeFormula *fy = (TTreeFormula *)gcut->GetObjectY(); if (fx) fx->UpdateFormulaLeaves(); if (fy) fy->UpdateFormulaLeaves(); } } } for(Int_t k=0;k<fNoper;k++) { const Int_t oper = GetOper()[k]; switch(oper >> kTFOperShift) { case kAlias: case kAliasString: case kAlternate: case kAlternateString: case kMinIf: case kMaxIf: { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(k)); R__ASSERT(subform); subform->UpdateFormulaLeaves(); break; } case kDefinedVariable: { Int_t code = GetActionParam(k); if (fCodes[code]==0) switch(fLookupType[code]) { case kLengthFunc: case kSum: case kMin: case kMax: { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(k)); R__ASSERT(subform); subform->UpdateFormulaLeaves(); break; } default: break; } } default: break; } } } //______________________________________________________________________________ void TTreeFormula::ResetDimensions() { // Populate the TTreeFormulaManager with the dimension information. Int_t i,k; // Now that we saw all the expressions and variables AND that // we know whether arrays of chars are treated as string or // not, we can properly setup the dimensions. TIter next(fDimensionSetup); Int_t last_code = -1; Int_t virt_dim = 0; for(TDimensionInfo * info; (info = (TDimensionInfo*)next()); ) { if (last_code!=info->fCode) { // We know that the list is ordered by code number then by // dimension. Thus a different code means that we need to // restart at the lowest dimensions. virt_dim = 0; last_code = info->fCode; fNdimensions[last_code] = 0; } if (GetAction(info->fOper)==kDefinedString) { // We have a string used as a string (and not an array of number) // We need to determine which is the last dimension and skip it. TDimensionInfo *nextinfo = (TDimensionInfo*)next(); while(nextinfo && nextinfo->fCode==info->fCode) { DefineDimensions(info->fCode,info->fSize, info->fMultiDim, virt_dim); nextinfo = (TDimensionInfo*)next(); } if (!nextinfo) break; info = nextinfo; virt_dim = 0; last_code = info->fCode; fNdimensions[last_code] = 0; info->fSize = 1; // Maybe this should actually do nothing! } DefineDimensions(info->fCode,info->fSize, info->fMultiDim, virt_dim); } fMultiplicity = 0; for(i=0;i<fNoper;i++) { Int_t action = GetAction(i); if (action==kMinIf || action==kMaxIf) { // Skip/Ignore the 2nd args ++i; continue; } if (action==kAlias || action==kAliasString) { TTreeFormula *subform = static_cast<TTreeFormula*>(fAliases.UncheckedAt(i)); R__ASSERT(subform); switch(subform->GetMultiplicity()) { case 0: break; case 1: fMultiplicity = 1; break; case 2: if (fMultiplicity!=1) fMultiplicity = 2; break; } fManager->Add(subform); // since we are addint to this manager 'subform->ResetDimensions();' // will be called a little latter continue; } if (action==kDefinedString) { //if (fOper[i] >= 105000 && fOper[i]<110000) { // We have a string used as a string // This dormant portion of code would be used if (when?) we allow the histogramming // of the integral content (as opposed to the string content) of strings // held in a variable size container delimited by a null (as opposed to // a fixed size container or variable size container whose size is controlled // by a variable). In GetNdata, we will then use strlen to grab the current length. //fCumulSizes[i][fNdimensions[i]-1] = 1; //fUsedSizes[fNdimensions[i]-1] = -TMath::Abs(fUsedSizes[fNdimensions[i]-1]); //fUsedSizes[0] = - TMath::Abs( fUsedSizes[0]); //continue; } } for (i=0;i<fNcodes;i++) { if (fCodes[i] < 0) { TCutG *gcut = (TCutG*)fExternalCuts.At(i); if (!gcut) continue; TTreeFormula *fx = (TTreeFormula *)gcut->GetObjectX(); TTreeFormula *fy = (TTreeFormula *)gcut->GetObjectY(); if (fx) { switch(fx->GetMultiplicity()) { case 0: break; case 1: fMultiplicity = 1; break; case 2: if (fMultiplicity!=1) fMultiplicity = 2; break; } fManager->Add(fx); } if (fy) { switch(fy->GetMultiplicity()) { case 0: break; case 1: fMultiplicity = 1; break; case 2: if (fMultiplicity!=1) fMultiplicity = 2; break; } fManager->Add(fy); } continue; } if (fLookupType[i]==kIteration) { fMultiplicity = 1; continue; } TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(i); if (!leaf) continue; // Reminder of the meaning of fMultiplicity: // -1: Only one or 0 element per entry but contains variable length // -array! (Only used for TTreeFormulaManager) // 0: Only one element per entry, no variable length array // 1: loop over the elements of a variable length array // 2: loop over elements of fixed length array (nData is the same for all entry) if (leaf->GetLeafCount()) { // We assume only one possible variable length dimension (the left most) fMultiplicity = 1; } else if (fLookupType[i]==kDataMember) { TFormLeafInfo * leafinfo = GetLeafInfo(i); TStreamerElement * elem = leafinfo->fElement; if (fMultiplicity!=1) { if (leafinfo->HasCounter() ) fMultiplicity = 1; else if (elem && elem->GetArrayDim()>0) fMultiplicity = 2; else if (leaf->GetLenStatic()>1) fMultiplicity = 2; } } else { if (leaf->GetLenStatic()>1 && fMultiplicity!=1) fMultiplicity = 2; } if (fMultiplicity!=1) { // If the leaf belongs to a friend tree which has an index, we might // be in the case where some entry do not exist. TTree *realtree = fTree ? fTree->GetTree() : 0; TTree *tleaf = leaf->GetBranch()->GetTree(); if (tleaf && tleaf != realtree && tleaf->GetTreeIndex()) { // Reset the multiplicity if we have a friend tree with an index. fMultiplicity = 1; } } Int_t virt_dim2 = 0; for (k = 0; k < fNdimensions[i]; k++) { // At this point fCumulSizes[i][k] actually contain the physical // dimension of the k-th dimensions. if ( (fCumulSizes[i][k]>=0) && (fIndexes[i][k] >= fCumulSizes[i][k]) ) { // unreacheable element requested: fManager->CancelDimension(virt_dim2); // fCumulUsedSizes[virt_dim2] = 0; } if ( fIndexes[i][k] < 0 ) virt_dim2++; fFixedSizes[i][k] = fCumulSizes[i][k]; } // Add up the cumulative size for (k = fNdimensions[i]; (k > 0); k--) { // NOTE: When support for inside variable dimension is added this // will become inacurate (since one of the value in the middle of the chain // is unknown until GetNdata is called. fCumulSizes[i][k-1] *= TMath::Abs(fCumulSizes[i][k]); } // NOTE: We assume that the inside variable dimensions are dictated by the // first index. if (fCumulSizes[i][0]>0) fNdata[i] = fCumulSizes[i][0]; //for (k = 0; k<kMAXFORMDIM; k++) { // if (fVarIndexes[i][k]) fManager->Add(fVarIndexes[i][k]); //} } } //______________________________________________________________________________ void TTreeFormula::LoadBranches() { // Make sure that all the branches have been loaded properly. Int_t i; for (i=0; i<fNoper ; ++i) { TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(i); if (leaf==0) continue; TBranch *br = leaf->GetBranch(); Long64_t treeEntry = br->GetTree()->GetReadEntry(); R__LoadBranch(br,treeEntry,kTRUE); TTreeFormula *alias = (TTreeFormula*)fAliases.UncheckedAt(i); if (alias) alias->LoadBranches(); Int_t max_dim = fNdimensions[i]; for (Int_t dim = 0; dim < max_dim; ++dim) { if (fVarIndexes[i][dim]) fVarIndexes[i][dim]->LoadBranches(); } } } //______________________________________________________________________________ Bool_t TTreeFormula::LoadCurrentDim() { // Calculate the actual dimension for the current entry. Int_t size; Bool_t outofbounds = kFALSE; for (Int_t i=0;i<fNcodes;i++) { if (fCodes[i] < 0) continue; // NOTE: Currently only the leafcount can indicates a dimension that // is physically variable. So only the left-most dimension is variable. // When an API is introduced to be able to determine a variable inside dimensions // one would need to add a way to recalculate the values of fCumulSizes for this // leaf. This would probably require the addition of a new data member // fSizes[kMAXCODES][kMAXFORMDIM]; // Also note that EvalInstance expect all the values (but the very first one) // of fCumulSizes to be positive. So indicating that a physical dimension is // variable (expected for the first one) can NOT be done via negative values of // fCumulSizes. TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(i); if (!leaf) { switch(fLookupType[i]) { case kDirect: case kMethod: case kTreeMember: case kDataMember: fNdata[i] = 0; outofbounds = kTRUE; } continue; } TTree *realtree = fTree->GetTree(); TTree *tleaf = leaf->GetBranch()->GetTree(); if (tleaf && tleaf != realtree && tleaf->GetTreeIndex()) { if (tleaf->GetReadEntry() < 0) { fNdata[i] = 0; outofbounds = kTRUE; continue; } else { fNdata[i] = fCumulSizes[i][0]; } } Bool_t hasBranchCount2 = kFALSE; if (leaf->GetLeafCount()) { TLeaf* leafcount = leaf->GetLeafCount(); TBranch *branchcount = leafcount->GetBranch(); TFormLeafInfo * info = 0; if (leaf->IsA() == TLeafElement::Class()) { //if branchcount address not yet set, GetEntry will set the address // read branchcount value Long64_t readentry = leaf->GetBranch()->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; if (!branchcount->GetAddress()) { R__LoadBranch(branchcount, readentry, fQuickLoad); } else { // Since we do not read the full branch let's reset the read entry number // so that a subsequent read from TTreeFormula will properly load the full // object even if fQuickLoad is true. branchcount->TBranch::GetEntry(readentry); branchcount->ResetReadEntry(); } size = ((TBranchElement*)branchcount)->GetNdata(); // Reading the size as above is correct only when the branchcount // is of streamer type kCounter which require the underlying data // member to be signed integral type. TBranchElement* branch = (TBranchElement*) leaf->GetBranch(); // NOTE: could be sped up if (fHasMultipleVarDim[i]) {// info && info->GetVarDim()>=0) { info = (TFormLeafInfo* )fDataMembers.At(i); if (branch->GetBranchCount2()) R__LoadBranch(branch->GetBranchCount2(),readentry,fQuickLoad); else R__LoadBranch(branch,readentry,fQuickLoad); // Here we need to add the code to take in consideration the // double variable length // We fill up the array of sizes in the TLeafInfo: info->LoadSizes(branch); hasBranchCount2 = kTRUE; if (info->GetVirtVarDim()>=0) info->UpdateSizes(fManager->fVarDims[info->GetVirtVarDim()]); // Refresh the fCumulSizes[i] to have '1' for the // double variable dimensions Int_t vdim = info->GetVarDim(); fCumulSizes[i][vdim] = fCumulSizes[i][vdim+1]; for(Int_t k=vdim -1; k>=0; k--) { fCumulSizes[i][k] = fCumulSizes[i][k+1]*fFixedSizes[i][k]; } // Update fCumulUsedSizes // UpdateMultiVarSizes(vdim,info,i) //Int_t fixed = fCumulSizes[i][vdim+1]; //for(Int_t k=vdim - 1; k>=0; k++) { // Int_t fixed *= fFixedSizes[i][k]; // for(Int_t l=0;l<size; l++) { // fCumulSizes[i][k] += info->GetSize(l) * fixed; //} } } else { Long64_t readentry = leaf->GetBranch()->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; R__LoadBranch(branchcount,readentry,fQuickLoad); size = leaf->GetLen() / leaf->GetLenStatic(); } if (hasBranchCount2) { // We assume that fCumulSizes[i][1] contains the product of the fixed sizes fNdata[i] = fCumulSizes[i][1] * ((TFormLeafInfo *)fDataMembers.At(i))->GetSumOfSizes(); } else { fNdata[i] = size * fCumulSizes[i][1]; } if (fIndexes[i][0]==-1) { // Case where the index is not specified AND the 1st dimension has a variable // size. if (fManager->fUsedSizes[0]==1 || (size<fManager->fUsedSizes[0]) ) fManager->fUsedSizes[0] = size; if (info && fIndexes[i][info->GetVarDim()]>=0) { for(Int_t j=0; j<size; j++) { if (fIndexes[i][info->GetVarDim()] >= info->GetSize(j)) { info->SetSize(j,0); if (size>fManager->fCumulUsedVarDims->GetSize()) fManager->fCumulUsedVarDims->Set(size); fManager->fCumulUsedVarDims->AddAt(-1,j); } else if (fIndexes[i][info->GetVarDim()]>=0) { // There is an index and it is not too large info->SetSize(j,1); if (size>fManager->fCumulUsedVarDims->GetSize()) fManager->fCumulUsedVarDims->Set(size); fManager->fCumulUsedVarDims->AddAt(1,j); } } } } else if (fIndexes[i][0] >= size) { // unreacheable element requested: fManager->fUsedSizes[0] = 0; fNdata[i] = 0; outofbounds = kTRUE; } else if (hasBranchCount2) { TFormLeafInfo *info2; info2 = (TFormLeafInfo *)fDataMembers.At(i); if (fIndexes[i][0]<0 || fIndexes[i][info2->GetVarDim()] >= info2->GetSize(fIndexes[i][0])) { // unreacheable element requested: fManager->fUsedSizes[0] = 0; fNdata[i] = 0; outofbounds = kTRUE; } } } else if (fLookupType[i]==kDataMember) { TFormLeafInfo *leafinfo = (TFormLeafInfo*)fDataMembers.UncheckedAt(i); if (leafinfo->HasCounter()) { TBranch *branch = leaf->GetBranch(); Long64_t readentry = branch->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; R__LoadBranch(branch,readentry,fQuickLoad); size = (Int_t) leafinfo->GetCounterValue(leaf); if (fIndexes[i][0]==-1) { // Case where the index is not specified AND the 1st dimension has a variable // size. if (fManager->fUsedSizes[0]==1 || (size<fManager->fUsedSizes[0]) ) { fManager->fUsedSizes[0] = size; } } else if (fIndexes[i][0] >= size) { // unreacheable element requested: fManager->fUsedSizes[0] = 0; fNdata[i] = 0; outofbounds = kTRUE; } else { fNdata[i] = size*fCumulSizes[i][1]; } Int_t vdim = leafinfo->GetVarDim(); if (vdim>=0) { // Here we need to add the code to take in consideration the // double variable length // We fill up the array of sizes in the TLeafInfo: // here we can assume that branch is a TBranch element because the other style does NOT support this type // of complexity. leafinfo->LoadSizes(branch); hasBranchCount2 = kTRUE; if (fIndexes[i][0]==-1&&fIndexes[i][vdim] >= 0) { for(int z=0; z<size; ++z) { if (fIndexes[i][vdim] >= leafinfo->GetSize(z)) { leafinfo->SetSize(z,0); // --fManager->fUsedSizes[0]; } else if (fIndexes[i][vdim] >= 0 ) { leafinfo->SetSize(z,1); } } } leafinfo->UpdateSizes(fManager->fVarDims[vdim]); // Refresh the fCumulSizes[i] to have '1' for the // double variable dimensions fCumulSizes[i][vdim] = fCumulSizes[i][vdim+1]; for(Int_t k=vdim -1; k>=0; k--) { fCumulSizes[i][k] = fCumulSizes[i][k+1]*fFixedSizes[i][k]; } fNdata[i] = fCumulSizes[i][1] * leafinfo->GetSumOfSizes(); } else { fNdata[i] = size * fCumulSizes[i][1]; } } else if (leafinfo->GetMultiplicity()==-1) { TBranch *branch = leaf->GetBranch(); Long64_t readentry = branch->GetTree()->GetReadEntry(); if (readentry < 0) readentry=0; R__LoadBranch(branch,readentry,fQuickLoad); if (leafinfo->GetNdata(leaf)==0) { outofbounds = kTRUE; } } } // However we allow several dimensions that virtually vary via the size of their // index variables. So we have code to recalculate fCumulUsedSizes. Int_t index; TFormLeafInfo * info = 0; if (fLookupType[i]!=kDirect) { info = (TFormLeafInfo *)fDataMembers.At(i); } for(Int_t k=0, virt_dim=0; k < fNdimensions[i]; k++) { if (fIndexes[i][k]<0) { if (fIndexes[i][k]==-2 && fManager->fVirtUsedSizes[virt_dim]<0) { // if fVirtUsedSize[virt_dim] is positive then VarIndexes[i][k]->GetNdata() // is always the same and has already been factored in fUsedSize[virt_dim] index = fVarIndexes[i][k]->GetNdata(); if (index==1) { // We could either have a variable size array which is currently of size one // or a single element that might or not might not be present (and is currently present!) if (fVarIndexes[i][k]->GetManager()->GetMultiplicity()==1) { if (index<fManager->fUsedSizes[virt_dim]) fManager->fUsedSizes[virt_dim] = index; } } else if (fManager->fUsedSizes[virt_dim]==-fManager->fVirtUsedSizes[virt_dim] || index<fManager->fUsedSizes[virt_dim]) { fManager->fUsedSizes[virt_dim] = index; } } else if (hasBranchCount2 && info && k==info->GetVarDim()) { // NOTE: We assume the indexing of variable sizes on the first index! if (fIndexes[i][0]>=0) { index = info->GetSize(fIndexes[i][0]); if (fManager->fUsedSizes[virt_dim]==1 || (index!=1 && index<fManager->fUsedSizes[virt_dim]) ) fManager->fUsedSizes[virt_dim] = index; } } virt_dim++; } else if (hasBranchCount2 && info && k==info->GetVarDim()) { // nothing to do, at some point I thought this might be useful: // if (fIndexes[i][k]>=0) { // index = info->GetSize(fIndexes[i][k]); // if (fManager->fUsedSizes[virt_dim]==1 || (index!=1 && index<fManager->fUsedSizes[virt_dim]) ) // fManager->fUsedSizes[virt_dim] = index; // virt_dim++; // } } } } return ! outofbounds; } void TTreeFormula::Convert(UInt_t oldversion) { // Convert the fOper of a TTTreeFormula version fromVersion to the current in memory version enum { kOldAlias = /*TFormula::kVariable*/ 100000+10000+1, kOldAliasString = kOldAlias+1, kOldAlternate = kOldAlias+2, kOldAlternateString = kOldAliasString+2 }; for (int k=0; k<fNoper; k++) { // First hide from TFormula convertion Int_t action = GetOper()[k]; switch (action) { case kOldAlias: GetOper()[k] = -kOldAlias; break; case kOldAliasString: GetOper()[k] = -kOldAliasString; break; case kOldAlternate: GetOper()[k] = -kOldAlternate; break; case kOldAlternateString: GetOper()[k] = -kOldAlternateString; break; } } TFormula::Convert(oldversion); for (int i=0,offset=0; i<fNoper; i++) { Int_t action = GetOper()[i+offset]; switch (action) { case -kOldAlias: SetAction(i, kAlias, 0); break; case -kOldAliasString: SetAction(i, kAliasString, 0); break; case -kOldAlternate: SetAction(i, kAlternate, 0); break; case -kOldAlternateString: SetAction(i, kAlternateString, 0); break; } } } //______________________________________________________________________________ Bool_t TTreeFormula::SwitchToFormLeafInfo(Int_t code) { // Convert the underlying lookup method from the direct technique // (dereferencing the address held by the branch) to the method using // TFormLeafInfo. This is in particular usefull in the case where we // need to append an additional TFormLeafInfo (for example to call a // method). // Return false if the switch was unsuccessfull (basically in the // case of an old style split tree). TFormLeafInfo *last = 0; TLeaf *leaf = (TLeaf*)fLeaves.At(code); if (!leaf) return kFALSE; if (fLookupType[code]==kDirect) { if (leaf->InheritsFrom(TLeafElement::Class())) { TBranchElement * br = (TBranchElement*)leaf->GetBranch(); if (br->GetType()==31) { // sub branch of a TClonesArray TStreamerInfo *info = br->GetInfo(); TClass* cl = info->GetClass(); TStreamerElement *element = (TStreamerElement *)info->GetElems()[br->GetID()]; TFormLeafInfo* clonesinfo = new TFormLeafInfoClones(cl, 0, element, kTRUE); Int_t offset; info->GetStreamerElement(element->GetName(),offset); clonesinfo->fNext = new TFormLeafInfo(cl,offset+br->GetOffset(),element); last = clonesinfo->fNext; fDataMembers.AddAtAndExpand(clonesinfo,code); fLookupType[code]=kDataMember; } else if (br->GetType()==41) { // sub branch of a Collection TBranchElement *count = br->GetBranchCount(); TFormLeafInfo* collectioninfo; if ( count->GetID() >= 0 ) { TStreamerElement *collectionElement = (TStreamerElement *)count->GetInfo()->GetElems()[count->GetID()]; TClass *collectionCl = collectionElement->GetClassPointer(); collectioninfo = new TFormLeafInfoCollection(collectionCl, 0, collectionElement, kTRUE); } else { TClass *collectionCl = TClass::GetClass(count->GetClassName()); collectioninfo = new TFormLeafInfoCollection(collectionCl, 0, collectionCl, kTRUE); } TStreamerInfo *info = br->GetInfo(); TClass* cl = info->GetClass(); TStreamerElement *element = (TStreamerElement *)info->GetElems()[br->GetID()]; Int_t offset; info->GetStreamerElement(element->GetName(),offset); collectioninfo->fNext = new TFormLeafInfo(cl,offset+br->GetOffset(),element); last = collectioninfo->fNext; fDataMembers.AddAtAndExpand(collectioninfo,code); fLookupType[code]=kDataMember; } else if (br->GetID()<0) { return kFALSE; } else { last = new TFormLeafInfoDirect(br); fDataMembers.AddAtAndExpand(last,code); fLookupType[code]=kDataMember; } } else { //last = new TFormLeafInfoDirect(br); //fDataMembers.AddAtAndExpand(last,code); //fLookupType[code]=kDataMember; return kFALSE; } } return kTRUE; }
/*************************************************************************/ /* editor_settings.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "editor_settings.h" #include "core/config/project_settings.h" #include "core/input/input_map.h" #include "core/io/certs_compressed.gen.h" #include "core/io/compression.h" #include "core/io/config_file.h" #include "core/io/file_access_memory.h" #include "core/io/ip.h" #include "core/io/resource_loader.h" #include "core/io/resource_saver.h" #include "core/io/translation_loader_po.h" #include "core/os/dir_access.h" #include "core/os/file_access.h" #include "core/os/keyboard.h" #include "core/os/os.h" #include "core/version.h" #include "editor/doc_translations.gen.h" #include "editor/editor_node.h" #include "editor/editor_translations.gen.h" #include "scene/main/node.h" #include "scene/main/scene_tree.h" #include "scene/main/window.h" // PRIVATE METHODS Ref<EditorSettings> EditorSettings::singleton = nullptr; // Properties bool EditorSettings::_set(const StringName &p_name, const Variant &p_value) { _THREAD_SAFE_METHOD_ bool changed = _set_only(p_name, p_value); if (changed) { emit_signal("settings_changed"); } return true; } bool EditorSettings::_set_only(const StringName &p_name, const Variant &p_value) { _THREAD_SAFE_METHOD_ if (p_name == "shortcuts") { Array arr = p_value; ERR_FAIL_COND_V(arr.size() && arr.size() & 1, true); for (int i = 0; i < arr.size(); i += 2) { String name = arr[i]; Ref<InputEvent> shortcut = arr[i + 1]; Ref<Shortcut> sc; sc.instance(); sc->set_shortcut(shortcut); add_shortcut(name, sc); } return false; } else if (p_name == "builtin_action_overrides") { Array actions_arr = p_value; for (int i = 0; i < actions_arr.size(); i++) { Dictionary action_dict = actions_arr[i]; String name = action_dict["name"]; Array events = action_dict["events"]; InputMap *im = InputMap::get_singleton(); im->action_erase_events(name); builtin_action_overrides[name].clear(); for (int ev_idx = 0; ev_idx < events.size(); ev_idx++) { im->action_add_event(name, events[ev_idx]); builtin_action_overrides[name].push_back(events[ev_idx]); } } return false; } bool changed = false; if (p_value.get_type() == Variant::NIL) { if (props.has(p_name)) { props.erase(p_name); changed = true; } } else { if (props.has(p_name)) { if (p_value != props[p_name].variant) { props[p_name].variant = p_value; changed = true; } } else { props[p_name] = VariantContainer(p_value, last_order++); changed = true; } if (save_changed_setting) { if (!props[p_name].save) { props[p_name].save = true; changed = true; } } } return changed; } bool EditorSettings::_get(const StringName &p_name, Variant &r_ret) const { _THREAD_SAFE_METHOD_ if (p_name == "shortcuts") { Array arr; for (const Map<String, Ref<Shortcut>>::Element *E = shortcuts.front(); E; E = E->next()) { Ref<Shortcut> sc = E->get(); if (builtin_action_overrides.has(E->key())) { // This shortcut was auto-generated from built in actions: don't save. continue; } if (optimize_save) { if (!sc->has_meta("original")) { continue; //this came from settings but is not any longer used } Ref<InputEvent> original = sc->get_meta("original"); if (sc->is_shortcut(original) || (original.is_null() && sc->get_shortcut().is_null())) { continue; //not changed from default, don't save } } arr.push_back(E->key()); arr.push_back(sc->get_shortcut()); } r_ret = arr; return true; } else if (p_name == "builtin_action_overrides") { Array actions_arr; for (Map<String, List<Ref<InputEvent>>>::Element *E = builtin_action_overrides.front(); E; E = E->next()) { List<Ref<InputEvent>> events = E->get(); // TODO: skip actions which are the same as the builtin. Dictionary action_dict; action_dict["name"] = E->key(); Array events_arr; for (List<Ref<InputEvent>>::Element *I = events.front(); I; I = I->next()) { events_arr.push_back(I->get()); } action_dict["events"] = events_arr; actions_arr.push_back(action_dict); } r_ret = actions_arr; return true; } const VariantContainer *v = props.getptr(p_name); if (!v) { WARN_PRINT("EditorSettings::_get - Property not found: " + String(p_name)); return false; } r_ret = v->variant; return true; } void EditorSettings::_initial_set(const StringName &p_name, const Variant &p_value) { set(p_name, p_value); props[p_name].initial = p_value; props[p_name].has_default_value = true; } struct _EVCSort { String name; Variant::Type type = Variant::Type::NIL; int order = 0; bool save = false; bool restart_if_changed = false; bool operator<(const _EVCSort &p_vcs) const { return order < p_vcs.order; } }; void EditorSettings::_get_property_list(List<PropertyInfo> *p_list) const { _THREAD_SAFE_METHOD_ const String *k = nullptr; Set<_EVCSort> vclist; while ((k = props.next(k))) { const VariantContainer *v = props.getptr(*k); if (v->hide_from_editor) { continue; } _EVCSort vc; vc.name = *k; vc.order = v->order; vc.type = v->variant.get_type(); vc.save = v->save; /*if (vc.save) { this should be implemented, but lets do after 3.1 is out. if (v->initial.get_type() != Variant::NIL && v->initial == v->variant) { vc.save = false; } }*/ vc.restart_if_changed = v->restart_if_changed; vclist.insert(vc); } for (Set<_EVCSort>::Element *E = vclist.front(); E; E = E->next()) { int pinfo = 0; if (E->get().save || !optimize_save) { pinfo |= PROPERTY_USAGE_STORAGE; } if (!E->get().name.begins_with("_") && !E->get().name.begins_with("projects/")) { pinfo |= PROPERTY_USAGE_EDITOR; } else { pinfo |= PROPERTY_USAGE_STORAGE; //hiddens must always be saved } PropertyInfo pi(E->get().type, E->get().name); pi.usage = pinfo; if (hints.has(E->get().name)) { pi = hints[E->get().name]; } if (E->get().restart_if_changed) { pi.usage |= PROPERTY_USAGE_RESTART_IF_CHANGED; } p_list->push_back(pi); } p_list->push_back(PropertyInfo(Variant::ARRAY, "shortcuts", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL)); //do not edit p_list->push_back(PropertyInfo(Variant::ARRAY, "builtin_action_overrides", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL)); } void EditorSettings::_add_property_info_bind(const Dictionary &p_info) { ERR_FAIL_COND(!p_info.has("name")); ERR_FAIL_COND(!p_info.has("type")); PropertyInfo pinfo; pinfo.name = p_info["name"]; ERR_FAIL_COND(!props.has(pinfo.name)); pinfo.type = Variant::Type(p_info["type"].operator int()); ERR_FAIL_INDEX(pinfo.type, Variant::VARIANT_MAX); if (p_info.has("hint")) { pinfo.hint = PropertyHint(p_info["hint"].operator int()); } if (p_info.has("hint_string")) { pinfo.hint_string = p_info["hint_string"]; } add_property_hint(pinfo); } // Default configs bool EditorSettings::has_default_value(const String &p_setting) const { _THREAD_SAFE_METHOD_ if (!props.has(p_setting)) { return false; } return props[p_setting].has_default_value; } void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) { _THREAD_SAFE_METHOD_ /* Languages */ { String lang_hint = "en"; String host_lang = OS::get_singleton()->get_locale(); host_lang = TranslationServer::standardize_locale(host_lang); // Skip locales if Text server lack required features. Vector<String> locales_to_skip; if (!TS->has_feature(TextServer::FEATURE_BIDI_LAYOUT) || !TS->has_feature(TextServer::FEATURE_SHAPING)) { locales_to_skip.push_back("ar"); // Arabic locales_to_skip.push_back("fa"); // Persian locales_to_skip.push_back("ur"); // Urdu } if (!TS->has_feature(TextServer::FEATURE_BIDI_LAYOUT)) { locales_to_skip.push_back("he"); // Hebrew } if (!TS->has_feature(TextServer::FEATURE_SHAPING)) { locales_to_skip.push_back("bn"); // Bengali locales_to_skip.push_back("hi"); // Hindi locales_to_skip.push_back("ml"); // Malayalam locales_to_skip.push_back("si"); // Sinhala locales_to_skip.push_back("ta"); // Tamil locales_to_skip.push_back("te"); // Telugu } if (!locales_to_skip.is_empty()) { WARN_PRINT("Some locales are not properly supported by selected Text Server and are disabled."); } String best; EditorTranslationList *etl = _editor_translations; while (etl->data) { const String &locale = etl->lang; // Skip locales which we can't render properly (see above comment). // Test against language code without regional variants (e.g. ur_PK). String lang_code = locale.get_slice("_", 0); if (locales_to_skip.find(lang_code) != -1) { etl++; continue; } lang_hint += ","; lang_hint += locale; if (host_lang == locale) { best = locale; } if (best == String() && host_lang.begins_with(locale)) { best = locale; } etl++; } if (best == String()) { best = "en"; } _initial_set("interface/editor/editor_language", best); set_restart_if_changed("interface/editor/editor_language", true); hints["interface/editor/editor_language"] = PropertyInfo(Variant::STRING, "interface/editor/editor_language", PROPERTY_HINT_ENUM, lang_hint, PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); } /* Interface */ // Editor _initial_set("interface/editor/display_scale", 0); // Display what the Auto display scale setting effectively corresponds to. // The code below is adapted in `editor/editor_node.cpp` and `editor/project_manager.cpp`. // Make sure to update those when modifying the code below. #ifdef OSX_ENABLED float scale = DisplayServer::get_singleton()->screen_get_max_scale(); #else const int screen = DisplayServer::get_singleton()->window_get_current_screen(); float scale; if (DisplayServer::get_singleton()->screen_get_dpi(screen) >= 192 && DisplayServer::get_singleton()->screen_get_size(screen).y >= 1400) { // hiDPI display. scale = 2.0; } else if (DisplayServer::get_singleton()->screen_get_size(screen).y >= 1700) { // Likely a hiDPI display, but we aren't certain due to the returned DPI. // Use an intermediate scale to handle this situation. scale = 1.5; } else if (DisplayServer::get_singleton()->screen_get_size(screen).y <= 800) { // Small loDPI display. Use a smaller display scale so that editor elements fit more easily. // Icons won't look great, but this is better than having editor elements overflow from its window. scale = 0.75; } else { scale = 1.0; } #endif hints["interface/editor/display_scale"] = PropertyInfo(Variant::INT, "interface/editor/display_scale", PROPERTY_HINT_ENUM, vformat("Auto (%d%%),75%%,100%%,125%%,150%%,175%%,200%%,Custom", Math::round(scale * 100)), PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/custom_display_scale", 1.0f); hints["interface/editor/custom_display_scale"] = PropertyInfo(Variant::FLOAT, "interface/editor/custom_display_scale", PROPERTY_HINT_RANGE, "0.5,3,0.01", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/main_font_size", 14); hints["interface/editor/main_font_size"] = PropertyInfo(Variant::INT, "interface/editor/main_font_size", PROPERTY_HINT_RANGE, "8,48,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/code_font_size", 14); hints["interface/editor/code_font_size"] = PropertyInfo(Variant::INT, "interface/editor/code_font_size", PROPERTY_HINT_RANGE, "8,48,1", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/code_font_contextual_ligatures", 0); hints["interface/editor/code_font_contextual_ligatures"] = PropertyInfo(Variant::INT, "interface/editor/code_font_contextual_ligatures", PROPERTY_HINT_ENUM, "Default,Disable Contextual Alternates (Coding Ligatures),Use Custom OpenType Feature Set", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/code_font_custom_opentype_features", ""); _initial_set("interface/editor/code_font_custom_variations", ""); _initial_set("interface/editor/font_antialiased", true); _initial_set("interface/editor/font_hinting", 0); #ifdef OSX_ENABLED hints["interface/editor/font_hinting"] = PropertyInfo(Variant::INT, "interface/editor/font_hinting", PROPERTY_HINT_ENUM, "Auto (None),None,Light,Normal", PROPERTY_USAGE_DEFAULT); #else hints["interface/editor/font_hinting"] = PropertyInfo(Variant::INT, "interface/editor/font_hinting", PROPERTY_HINT_ENUM, "Auto (Light),None,Light,Normal", PROPERTY_USAGE_DEFAULT); #endif _initial_set("interface/editor/main_font", ""); hints["interface/editor/main_font"] = PropertyInfo(Variant::STRING, "interface/editor/main_font", PROPERTY_HINT_GLOBAL_FILE, "*.ttf,*.otf", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/main_font_bold", ""); hints["interface/editor/main_font_bold"] = PropertyInfo(Variant::STRING, "interface/editor/main_font_bold", PROPERTY_HINT_GLOBAL_FILE, "*.ttf,*.otf", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/code_font", ""); hints["interface/editor/code_font"] = PropertyInfo(Variant::STRING, "interface/editor/code_font", PROPERTY_HINT_GLOBAL_FILE, "*.ttf,*.otf", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/dim_editor_on_dialog_popup", true); _initial_set("interface/editor/low_processor_mode_sleep_usec", 6900); // ~144 FPS hints["interface/editor/low_processor_mode_sleep_usec"] = PropertyInfo(Variant::FLOAT, "interface/editor/low_processor_mode_sleep_usec", PROPERTY_HINT_RANGE, "1,100000,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/unfocused_low_processor_mode_sleep_usec", 50000); // 20 FPS hints["interface/editor/unfocused_low_processor_mode_sleep_usec"] = PropertyInfo(Variant::FLOAT, "interface/editor/unfocused_low_processor_mode_sleep_usec", PROPERTY_HINT_RANGE, "1,100000,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/separate_distraction_mode", false); _initial_set("interface/editor/automatically_open_screenshots", true); _initial_set("interface/editor/single_window_mode", false); hints["interface/editor/single_window_mode"] = PropertyInfo(Variant::BOOL, "interface/editor/single_window_mode", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/hide_console_window", false); _initial_set("interface/editor/save_each_scene_on_quit", true); // Regression // Inspector _initial_set("interface/inspector/max_array_dictionary_items_per_page", 20); hints["interface/inspector/max_array_dictionary_items_per_page"] = PropertyInfo(Variant::INT, "interface/inspector/max_array_dictionary_items_per_page", PROPERTY_HINT_RANGE, "10,100,1", PROPERTY_USAGE_DEFAULT); // Theme _initial_set("interface/theme/preset", "Default"); hints["interface/theme/preset"] = PropertyInfo(Variant::STRING, "interface/theme/preset", PROPERTY_HINT_ENUM, "Default,Alien,Arc,Godot 2,Grey,Light,Solarized (Dark),Solarized (Light),Custom", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/icon_and_font_color", 0); hints["interface/theme/icon_and_font_color"] = PropertyInfo(Variant::INT, "interface/theme/icon_and_font_color", PROPERTY_HINT_ENUM, "Auto,Dark,Light", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/base_color", Color(0.2, 0.23, 0.31)); hints["interface/theme/base_color"] = PropertyInfo(Variant::COLOR, "interface/theme/base_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/accent_color", Color(0.41, 0.61, 0.91)); hints["interface/theme/accent_color"] = PropertyInfo(Variant::COLOR, "interface/theme/accent_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/contrast", 0.25); hints["interface/theme/contrast"] = PropertyInfo(Variant::FLOAT, "interface/theme/contrast", PROPERTY_HINT_RANGE, "0.01, 1, 0.01"); _initial_set("interface/theme/icon_saturation", 1.0); hints["interface/theme/icon_saturation"] = PropertyInfo(Variant::FLOAT, "interface/theme/icon_saturation", PROPERTY_HINT_RANGE, "0,2,0.01", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/relationship_line_opacity", 0.1); hints["interface/theme/relationship_line_opacity"] = PropertyInfo(Variant::FLOAT, "interface/theme/relationship_line_opacity", PROPERTY_HINT_RANGE, "0.00, 1, 0.01"); _initial_set("interface/theme/highlight_tabs", false); _initial_set("interface/theme/border_size", 1); _initial_set("interface/theme/use_graph_node_headers", false); hints["interface/theme/border_size"] = PropertyInfo(Variant::INT, "interface/theme/border_size", PROPERTY_HINT_RANGE, "0,2,1", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/additional_spacing", 0); hints["interface/theme/additional_spacing"] = PropertyInfo(Variant::FLOAT, "interface/theme/additional_spacing", PROPERTY_HINT_RANGE, "0,5,0.1", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/custom_theme", ""); hints["interface/theme/custom_theme"] = PropertyInfo(Variant::STRING, "interface/theme/custom_theme", PROPERTY_HINT_GLOBAL_FILE, "*.res,*.tres,*.theme", PROPERTY_USAGE_DEFAULT); // Scene tabs _initial_set("interface/scene_tabs/show_thumbnail_on_hover", true); _initial_set("interface/scene_tabs/resize_if_many_tabs", true); _initial_set("interface/scene_tabs/minimum_width", 50); hints["interface/scene_tabs/minimum_width"] = PropertyInfo(Variant::INT, "interface/scene_tabs/minimum_width", PROPERTY_HINT_RANGE, "50,500,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/scene_tabs/show_script_button", false); /* Filesystem */ // Directories _initial_set("filesystem/directories/autoscan_project_path", ""); hints["filesystem/directories/autoscan_project_path"] = PropertyInfo(Variant::STRING, "filesystem/directories/autoscan_project_path", PROPERTY_HINT_GLOBAL_DIR); _initial_set("filesystem/directories/default_project_path", OS::get_singleton()->has_environment("HOME") ? OS::get_singleton()->get_environment("HOME") : OS::get_singleton()->get_system_dir(OS::SYSTEM_DIR_DOCUMENTS)); hints["filesystem/directories/default_project_path"] = PropertyInfo(Variant::STRING, "filesystem/directories/default_project_path", PROPERTY_HINT_GLOBAL_DIR); // On save _initial_set("filesystem/on_save/compress_binary_resources", true); _initial_set("filesystem/on_save/safe_save_on_backup_then_rename", true); // File dialog _initial_set("filesystem/file_dialog/show_hidden_files", false); _initial_set("filesystem/file_dialog/display_mode", 0); hints["filesystem/file_dialog/display_mode"] = PropertyInfo(Variant::INT, "filesystem/file_dialog/display_mode", PROPERTY_HINT_ENUM, "Thumbnails,List"); _initial_set("filesystem/file_dialog/thumbnail_size", 64); hints["filesystem/file_dialog/thumbnail_size"] = PropertyInfo(Variant::INT, "filesystem/file_dialog/thumbnail_size", PROPERTY_HINT_RANGE, "32,128,16"); /* Docks */ // SceneTree _initial_set("docks/scene_tree/start_create_dialog_fully_expanded", false); // FileSystem _initial_set("docks/filesystem/thumbnail_size", 64); hints["docks/filesystem/thumbnail_size"] = PropertyInfo(Variant::INT, "docks/filesystem/thumbnail_size", PROPERTY_HINT_RANGE, "32,128,16"); _initial_set("docks/filesystem/always_show_folders", true); // Property editor _initial_set("docks/property_editor/auto_refresh_interval", 0.2); //update 5 times per second by default _initial_set("docks/property_editor/subresource_hue_tint", 0.75); hints["docks/property_editor/subresource_hue_tint"] = PropertyInfo(Variant::FLOAT, "docks/property_editor/subresource_hue_tint", PROPERTY_HINT_RANGE, "0,1,0.01", PROPERTY_USAGE_DEFAULT); /* Text editor */ // Theme _initial_set("text_editor/theme/color_theme", "Adaptive"); hints["text_editor/theme/color_theme"] = PropertyInfo(Variant::STRING, "text_editor/theme/color_theme", PROPERTY_HINT_ENUM, "Adaptive,Default,Custom"); _initial_set("text_editor/theme/line_spacing", 6); hints["text_editor/theme/line_spacing"] = PropertyInfo(Variant::INT, "text_editor/theme/line_spacing", PROPERTY_HINT_RANGE, "0,50,1"); _load_default_text_editor_theme(); // Highlighting _initial_set("text_editor/highlighting/highlight_all_occurrences", true); _initial_set("text_editor/highlighting/highlight_current_line", true); _initial_set("text_editor/highlighting/highlight_type_safe_lines", true); // Indent _initial_set("text_editor/indent/type", 0); hints["text_editor/indent/type"] = PropertyInfo(Variant::INT, "text_editor/indent/type", PROPERTY_HINT_ENUM, "Tabs,Spaces"); _initial_set("text_editor/indent/size", 4); hints["text_editor/indent/size"] = PropertyInfo(Variant::INT, "text_editor/indent/size", PROPERTY_HINT_RANGE, "1, 64, 1"); // size of 0 crashes. _initial_set("text_editor/indent/auto_indent", true); _initial_set("text_editor/indent/convert_indent_on_save", true); _initial_set("text_editor/indent/draw_tabs", true); _initial_set("text_editor/indent/draw_spaces", false); // Navigation _initial_set("text_editor/navigation/smooth_scrolling", true); _initial_set("text_editor/navigation/v_scroll_speed", 80); _initial_set("text_editor/navigation/show_minimap", true); _initial_set("text_editor/navigation/minimap_width", 80); hints["text_editor/navigation/minimap_width"] = PropertyInfo(Variant::INT, "text_editor/navigation/minimap_width", PROPERTY_HINT_RANGE, "50,250,1"); // Appearance _initial_set("text_editor/appearance/show_line_numbers", true); _initial_set("text_editor/appearance/line_numbers_zero_padded", false); _initial_set("text_editor/appearance/show_bookmark_gutter", true); _initial_set("text_editor/appearance/show_info_gutter", true); _initial_set("text_editor/appearance/code_folding", true); _initial_set("text_editor/appearance/word_wrap", false); _initial_set("text_editor/appearance/show_line_length_guidelines", true); _initial_set("text_editor/appearance/line_length_guideline_soft_column", 80); hints["text_editor/appearance/line_length_guideline_soft_column"] = PropertyInfo(Variant::INT, "text_editor/appearance/line_length_guideline_soft_column", PROPERTY_HINT_RANGE, "20, 160, 1"); _initial_set("text_editor/appearance/line_length_guideline_hard_column", 100); hints["text_editor/appearance/line_length_guideline_hard_column"] = PropertyInfo(Variant::INT, "text_editor/appearance/line_length_guideline_hard_column", PROPERTY_HINT_RANGE, "20, 160, 1"); // Script list _initial_set("text_editor/script_list/show_members_overview", true); // Files _initial_set("text_editor/files/trim_trailing_whitespace_on_save", false); _initial_set("text_editor/files/autosave_interval_secs", 0); _initial_set("text_editor/files/restore_scripts_on_load", true); // Tools _initial_set("text_editor/tools/create_signal_callbacks", true); _initial_set("text_editor/tools/sort_members_outline_alphabetically", false); // Cursor _initial_set("text_editor/cursor/scroll_past_end_of_file", false); _initial_set("text_editor/cursor/block_caret", false); _initial_set("text_editor/cursor/caret_blink", true); _initial_set("text_editor/cursor/caret_blink_speed", 0.5); hints["text_editor/cursor/caret_blink_speed"] = PropertyInfo(Variant::FLOAT, "text_editor/cursor/caret_blink_speed", PROPERTY_HINT_RANGE, "0.1, 10, 0.01"); _initial_set("text_editor/cursor/right_click_moves_caret", true); // Completion _initial_set("text_editor/completion/idle_parse_delay", 2.0); hints["text_editor/completion/idle_parse_delay"] = PropertyInfo(Variant::FLOAT, "text_editor/completion/idle_parse_delay", PROPERTY_HINT_RANGE, "0.1, 10, 0.01"); _initial_set("text_editor/completion/auto_brace_complete", true); _initial_set("text_editor/completion/code_complete_delay", 0.3); hints["text_editor/completion/code_complete_delay"] = PropertyInfo(Variant::FLOAT, "text_editor/completion/code_complete_delay", PROPERTY_HINT_RANGE, "0.01, 5, 0.01"); _initial_set("text_editor/completion/put_callhint_tooltip_below_current_line", true); _initial_set("text_editor/completion/callhint_tooltip_offset", Vector2()); _initial_set("text_editor/completion/complete_file_paths", true); _initial_set("text_editor/completion/add_type_hints", false); _initial_set("text_editor/completion/use_single_quotes", false); // Help _initial_set("text_editor/help/show_help_index", true); _initial_set("text_editor/help/help_font_size", 15); hints["text_editor/help/help_font_size"] = PropertyInfo(Variant::INT, "text_editor/help/help_font_size", PROPERTY_HINT_RANGE, "8,48,1"); _initial_set("text_editor/help/help_source_font_size", 14); hints["text_editor/help/help_source_font_size"] = PropertyInfo(Variant::INT, "text_editor/help/help_source_font_size", PROPERTY_HINT_RANGE, "8,48,1"); _initial_set("text_editor/help/help_title_font_size", 23); hints["text_editor/help/help_title_font_size"] = PropertyInfo(Variant::INT, "text_editor/help/help_title_font_size", PROPERTY_HINT_RANGE, "8,48,1"); _initial_set("text_editor/help/class_reference_examples", 0); hints["text_editor/help/class_reference_examples"] = PropertyInfo(Variant::INT, "text_editor/help/class_reference_examples", PROPERTY_HINT_ENUM, "GDScript,C#,GDScript and C#"); /* Editors */ // GridMap _initial_set("editors/grid_map/pick_distance", 5000.0); // 3D _initial_set("editors/3d/primary_grid_color", Color(0.56, 0.56, 0.56, 0.5)); hints["editors/3d/primary_grid_color"] = PropertyInfo(Variant::COLOR, "editors/3d/primary_grid_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT); _initial_set("editors/3d/secondary_grid_color", Color(0.38, 0.38, 0.38, 0.5)); hints["editors/3d/secondary_grid_color"] = PropertyInfo(Variant::COLOR, "editors/3d/secondary_grid_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT); // Use a similar color to the 2D editor selection. _initial_set("editors/3d/selection_box_color", Color(1.0, 0.5, 0)); hints["editors/3d/selection_box_color"] = PropertyInfo(Variant::COLOR, "editors/3d/selection_box_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); // If a line is a multiple of this, it uses the primary grid color. // Use a power of 2 value by default as it's more common to use powers of 2 in level design. _initial_set("editors/3d/primary_grid_steps", 8); hints["editors/3d/primary_grid_steps"] = PropertyInfo(Variant::INT, "editors/3d/primary_grid_steps", PROPERTY_HINT_RANGE, "1,100,1", PROPERTY_USAGE_DEFAULT); // At 1000, the grid mostly looks like it has no edge. _initial_set("editors/3d/grid_size", 200); hints["editors/3d/grid_size"] = PropertyInfo(Variant::INT, "editors/3d/grid_size", PROPERTY_HINT_RANGE, "1,2000,1", PROPERTY_USAGE_DEFAULT); // Default largest grid size is 100m, 10^2 (primary grid lines are 1km apart when primary_grid_steps is 10). _initial_set("editors/3d/grid_division_level_max", 2); // Higher values produce graphical artifacts when far away unless View Z-Far // is increased significantly more than it really should need to be. hints["editors/3d/grid_division_level_max"] = PropertyInfo(Variant::INT, "editors/3d/grid_division_level_max", PROPERTY_HINT_RANGE, "-1,3,1", PROPERTY_USAGE_DEFAULT); // Default smallest grid size is 1m, 10^0. _initial_set("editors/3d/grid_division_level_min", 0); // Lower values produce graphical artifacts regardless of view clipping planes, so limit to -2 as a lower bound. hints["editors/3d/grid_division_level_min"] = PropertyInfo(Variant::INT, "editors/3d/grid_division_level_min", PROPERTY_HINT_RANGE, "-2,2,1", PROPERTY_USAGE_DEFAULT); // -0.2 seems like a sensible default. -1.0 gives Blender-like behavior, 0.5 gives huge grids. _initial_set("editors/3d/grid_division_level_bias", -0.2); hints["editors/3d/grid_division_level_bias"] = PropertyInfo(Variant::FLOAT, "editors/3d/grid_division_level_bias", PROPERTY_HINT_RANGE, "-1.0,0.5,0.1", PROPERTY_USAGE_DEFAULT); _initial_set("editors/3d/grid_xz_plane", true); _initial_set("editors/3d/grid_xy_plane", false); _initial_set("editors/3d/grid_yz_plane", false); // Use a lower default FOV for the 3D camera compared to the // Camera3D node as the 3D viewport doesn't span the whole screen. // This means it's technically viewed from a further distance, which warrants a narrower FOV. _initial_set("editors/3d/default_fov", 70.0); hints["editors/3d/default_fov"] = PropertyInfo(Variant::FLOAT, "editors/3d/default_fov", PROPERTY_HINT_RANGE, "1,179,0.1"); _initial_set("editors/3d/default_z_near", 0.05); hints["editors/3d/default_z_near"] = PropertyInfo(Variant::FLOAT, "editors/3d/default_z_near", PROPERTY_HINT_RANGE, "0.01,10,0.01,or_greater"); _initial_set("editors/3d/default_z_far", 4000.0); hints["editors/3d/default_z_far"] = PropertyInfo(Variant::FLOAT, "editors/3d/default_z_far", PROPERTY_HINT_RANGE, "0.1,4000,0.1,or_greater"); // 3D: Navigation _initial_set("editors/3d/navigation/navigation_scheme", 0); _initial_set("editors/3d/navigation/invert_y_axis", false); _initial_set("editors/3d/navigation/invert_x_axis", false); hints["editors/3d/navigation/navigation_scheme"] = PropertyInfo(Variant::INT, "editors/3d/navigation/navigation_scheme", PROPERTY_HINT_ENUM, "Godot,Maya,Modo"); _initial_set("editors/3d/navigation/zoom_style", 0); hints["editors/3d/navigation/zoom_style"] = PropertyInfo(Variant::INT, "editors/3d/navigation/zoom_style", PROPERTY_HINT_ENUM, "Vertical, Horizontal"); _initial_set("editors/3d/navigation/emulate_3_button_mouse", false); _initial_set("editors/3d/navigation/orbit_modifier", 0); hints["editors/3d/navigation/orbit_modifier"] = PropertyInfo(Variant::INT, "editors/3d/navigation/orbit_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl"); _initial_set("editors/3d/navigation/pan_modifier", 1); hints["editors/3d/navigation/pan_modifier"] = PropertyInfo(Variant::INT, "editors/3d/navigation/pan_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl"); _initial_set("editors/3d/navigation/zoom_modifier", 4); hints["editors/3d/navigation/zoom_modifier"] = PropertyInfo(Variant::INT, "editors/3d/navigation/zoom_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl"); _initial_set("editors/3d/navigation/warped_mouse_panning", true); // 3D: Navigation feel _initial_set("editors/3d/navigation_feel/orbit_sensitivity", 0.4); hints["editors/3d/navigation_feel/orbit_sensitivity"] = PropertyInfo(Variant::FLOAT, "editors/3d/navigation_feel/orbit_sensitivity", PROPERTY_HINT_RANGE, "0.0, 2, 0.01"); _initial_set("editors/3d/navigation_feel/orbit_inertia", 0.05); hints["editors/3d/navigation_feel/orbit_inertia"] = PropertyInfo(Variant::FLOAT, "editors/3d/navigation_feel/orbit_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/navigation_feel/translation_inertia", 0.15); hints["editors/3d/navigation_feel/translation_inertia"] = PropertyInfo(Variant::FLOAT, "editors/3d/navigation_feel/translation_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/navigation_feel/zoom_inertia", 0.075); hints["editors/3d/navigation_feel/zoom_inertia"] = PropertyInfo(Variant::FLOAT, "editors/3d/navigation_feel/zoom_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/navigation_feel/manipulation_orbit_inertia", 0.075); hints["editors/3d/navigation_feel/manipulation_orbit_inertia"] = PropertyInfo(Variant::FLOAT, "editors/3d/navigation_feel/manipulation_orbit_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/navigation_feel/manipulation_translation_inertia", 0.075); hints["editors/3d/navigation_feel/manipulation_translation_inertia"] = PropertyInfo(Variant::FLOAT, "editors/3d/navigation_feel/manipulation_translation_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); // 3D: Freelook _initial_set("editors/3d/freelook/freelook_navigation_scheme", false); hints["editors/3d/freelook/freelook_navigation_scheme"] = PropertyInfo(Variant::INT, "editors/3d/freelook/freelook_navigation_scheme", PROPERTY_HINT_ENUM, "Default,Partially Axis-Locked (id Tech),Fully Axis-Locked (Minecraft)"); _initial_set("editors/3d/freelook/freelook_sensitivity", 0.4); hints["editors/3d/freelook/freelook_sensitivity"] = PropertyInfo(Variant::FLOAT, "editors/3d/freelook/freelook_sensitivity", PROPERTY_HINT_RANGE, "0.0, 2, 0.01"); _initial_set("editors/3d/freelook/freelook_inertia", 0.1); hints["editors/3d/freelook/freelook_inertia"] = PropertyInfo(Variant::FLOAT, "editors/3d/freelook/freelook_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/freelook/freelook_base_speed", 5.0); hints["editors/3d/freelook/freelook_base_speed"] = PropertyInfo(Variant::FLOAT, "editors/3d/freelook/freelook_base_speed", PROPERTY_HINT_RANGE, "0.0, 10, 0.01"); _initial_set("editors/3d/freelook/freelook_activation_modifier", 0); hints["editors/3d/freelook/freelook_activation_modifier"] = PropertyInfo(Variant::INT, "editors/3d/freelook/freelook_activation_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl"); _initial_set("editors/3d/freelook/freelook_speed_zoom_link", false); // 2D _initial_set("editors/2d/grid_color", Color(1.0, 1.0, 1.0, 0.07)); _initial_set("editors/2d/guides_color", Color(0.6, 0.0, 0.8)); _initial_set("editors/2d/smart_snapping_line_color", Color(0.9, 0.1, 0.1)); _initial_set("editors/2d/bone_width", 5); _initial_set("editors/2d/bone_color1", Color(1.0, 1.0, 1.0, 0.9)); _initial_set("editors/2d/bone_color2", Color(0.6, 0.6, 0.6, 0.9)); _initial_set("editors/2d/bone_selected_color", Color(0.9, 0.45, 0.45, 0.9)); _initial_set("editors/2d/bone_ik_color", Color(0.9, 0.9, 0.45, 0.9)); _initial_set("editors/2d/bone_outline_color", Color(0.35, 0.35, 0.35)); _initial_set("editors/2d/bone_outline_size", 2); _initial_set("editors/2d/viewport_border_color", Color(0.4, 0.4, 1.0, 0.4)); _initial_set("editors/2d/constrain_editor_view", true); _initial_set("editors/2d/warped_mouse_panning", true); _initial_set("editors/2d/simple_panning", false); _initial_set("editors/2d/scroll_to_pan", false); _initial_set("editors/2d/pan_speed", 20); // Polygon editor _initial_set("editors/poly_editor/point_grab_radius", 8); _initial_set("editors/poly_editor/show_previous_outline", true); // Animation _initial_set("editors/animation/autorename_animation_tracks", true); _initial_set("editors/animation/confirm_insert_track", true); _initial_set("editors/animation/default_create_bezier_tracks", false); _initial_set("editors/animation/default_create_reset_tracks", true); _initial_set("editors/animation/onion_layers_past_color", Color(1, 0, 0)); _initial_set("editors/animation/onion_layers_future_color", Color(0, 1, 0)); // Visual editors _initial_set("editors/visual_editors/minimap_opacity", 0.85); hints["editors/visual_editors/minimap_opacity"] = PropertyInfo(Variant::FLOAT, "editors/visual_editors/minimap_opacity", PROPERTY_HINT_RANGE, "0.0,1.0,0.01", PROPERTY_USAGE_DEFAULT); /* Run */ // Window placement _initial_set("run/window_placement/rect", 1); hints["run/window_placement/rect"] = PropertyInfo(Variant::INT, "run/window_placement/rect", PROPERTY_HINT_ENUM, "Top Left,Centered,Custom Position,Force Maximized,Force Fullscreen"); String screen_hints = "Same as Editor,Previous Monitor,Next Monitor"; for (int i = 0; i < DisplayServer::get_singleton()->get_screen_count(); i++) { screen_hints += ",Monitor " + itos(i + 1); } _initial_set("run/window_placement/rect_custom_position", Vector2()); _initial_set("run/window_placement/screen", 0); hints["run/window_placement/screen"] = PropertyInfo(Variant::INT, "run/window_placement/screen", PROPERTY_HINT_ENUM, screen_hints); // Auto save _initial_set("run/auto_save/save_before_running", true); // Output _initial_set("run/output/font_size", 13); hints["run/output/font_size"] = PropertyInfo(Variant::INT, "run/output/font_size", PROPERTY_HINT_RANGE, "8,48,1"); _initial_set("run/output/always_clear_output_on_play", true); _initial_set("run/output/always_open_output_on_play", true); _initial_set("run/output/always_close_output_on_stop", false); /* Network */ // Debug _initial_set("network/debug/remote_host", "127.0.0.1"); // Hints provided in setup_network _initial_set("network/debug/remote_port", 6007); hints["network/debug/remote_port"] = PropertyInfo(Variant::INT, "network/debug/remote_port", PROPERTY_HINT_RANGE, "1,65535,1"); // SSL _initial_set("network/ssl/editor_ssl_certificates", _SYSTEM_CERTS_PATH); hints["network/ssl/editor_ssl_certificates"] = PropertyInfo(Variant::STRING, "network/ssl/editor_ssl_certificates", PROPERTY_HINT_GLOBAL_FILE, "*.crt,*.pem"); /* Extra config */ _initial_set("project_manager/sorting_order", 0); hints["project_manager/sorting_order"] = PropertyInfo(Variant::INT, "project_manager/sorting_order", PROPERTY_HINT_ENUM, "Name,Path,Last Edited"); if (p_extra_config.is_valid()) { if (p_extra_config->has_section("init_projects") && p_extra_config->has_section_key("init_projects", "list")) { Vector<String> list = p_extra_config->get_value("init_projects", "list"); for (int i = 0; i < list.size(); i++) { String name = list[i].replace("/", "::"); set("projects/" + name, list[i]); }; }; if (p_extra_config->has_section("presets")) { List<String> keys; p_extra_config->get_section_keys("presets", &keys); for (List<String>::Element *E = keys.front(); E; E = E->next()) { String key = E->get(); Variant val = p_extra_config->get_value("presets", key); set(key, val); }; }; }; } void EditorSettings::_load_default_text_editor_theme() { bool dark_theme = is_dark_theme(); _initial_set("text_editor/highlighting/symbol_color", Color(0.73, 0.87, 1.0)); _initial_set("text_editor/highlighting/keyword_color", Color(1.0, 1.0, 0.7)); _initial_set("text_editor/highlighting/base_type_color", Color(0.64, 1.0, 0.83)); _initial_set("text_editor/highlighting/engine_type_color", Color(0.51, 0.83, 1.0)); _initial_set("text_editor/highlighting/user_type_color", Color(0.42, 0.67, 0.93)); _initial_set("text_editor/highlighting/comment_color", Color(0.4, 0.4, 0.4)); _initial_set("text_editor/highlighting/string_color", Color(0.94, 0.43, 0.75)); _initial_set("text_editor/highlighting/background_color", dark_theme ? Color(0.0, 0.0, 0.0, 0.23) : Color(0.2, 0.23, 0.31)); _initial_set("text_editor/highlighting/completion_background_color", Color(0.17, 0.16, 0.2)); _initial_set("text_editor/highlighting/completion_selected_color", Color(0.26, 0.26, 0.27)); _initial_set("text_editor/highlighting/completion_existing_color", Color(0.13, 0.87, 0.87, 0.87)); _initial_set("text_editor/highlighting/completion_scroll_color", Color(1, 1, 1)); _initial_set("text_editor/highlighting/completion_font_color", Color(0.67, 0.67, 0.67)); _initial_set("text_editor/highlighting/text_color", Color(0.67, 0.67, 0.67)); _initial_set("text_editor/highlighting/line_number_color", Color(0.67, 0.67, 0.67, 0.4)); _initial_set("text_editor/highlighting/safe_line_number_color", Color(0.67, 0.78, 0.67, 0.6)); _initial_set("text_editor/highlighting/caret_color", Color(0.67, 0.67, 0.67)); _initial_set("text_editor/highlighting/caret_background_color", Color(0, 0, 0)); _initial_set("text_editor/highlighting/text_selected_color", Color(0, 0, 0)); _initial_set("text_editor/highlighting/selection_color", Color(0.41, 0.61, 0.91, 0.35)); _initial_set("text_editor/highlighting/brace_mismatch_color", Color(1, 0.2, 0.2)); _initial_set("text_editor/highlighting/current_line_color", Color(0.3, 0.5, 0.8, 0.15)); _initial_set("text_editor/highlighting/line_length_guideline_color", Color(0.3, 0.5, 0.8, 0.1)); _initial_set("text_editor/highlighting/word_highlighted_color", Color(0.8, 0.9, 0.9, 0.15)); _initial_set("text_editor/highlighting/number_color", Color(0.92, 0.58, 0.2)); _initial_set("text_editor/highlighting/function_color", Color(0.4, 0.64, 0.81)); _initial_set("text_editor/highlighting/member_variable_color", Color(0.9, 0.31, 0.35)); _initial_set("text_editor/highlighting/mark_color", Color(1.0, 0.4, 0.4, 0.4)); _initial_set("text_editor/highlighting/bookmark_color", Color(0.08, 0.49, 0.98)); _initial_set("text_editor/highlighting/breakpoint_color", Color(0.9, 0.29, 0.3)); _initial_set("text_editor/highlighting/executing_line_color", Color(0.98, 0.89, 0.27)); _initial_set("text_editor/highlighting/code_folding_color", Color(0.8, 0.8, 0.8, 0.8)); _initial_set("text_editor/highlighting/search_result_color", Color(0.05, 0.25, 0.05, 1)); _initial_set("text_editor/highlighting/search_result_border_color", Color(0.41, 0.61, 0.91, 0.38)); } bool EditorSettings::_save_text_editor_theme(String p_file) { String theme_section = "color_theme"; Ref<ConfigFile> cf = memnew(ConfigFile); // hex is better? List<String> keys; props.get_key_list(&keys); keys.sort(); for (const List<String>::Element *E = keys.front(); E; E = E->next()) { const String &key = E->get(); if (key.begins_with("text_editor/highlighting/") && key.find("color") >= 0) { cf->set_value(theme_section, key.replace("text_editor/highlighting/", ""), ((Color)props[key].variant).to_html()); } } Error err = cf->save(p_file); return err == OK; } bool EditorSettings::_is_default_text_editor_theme(String p_theme_name) { return p_theme_name == "default" || p_theme_name == "adaptive" || p_theme_name == "custom"; } static Dictionary _get_builtin_script_templates() { Dictionary templates; // No Comments templates["no_comments.gd"] = "extends %BASE%\n" "\n" "\n" "func _ready()%VOID_RETURN%:\n" "%TS%pass\n"; // Empty templates["empty.gd"] = "extends %BASE%" "\n" "\n"; return templates; } static void _create_script_templates(const String &p_path) { Dictionary templates = _get_builtin_script_templates(); List<Variant> keys; templates.get_key_list(&keys); FileAccess *file = FileAccess::create(FileAccess::ACCESS_FILESYSTEM); DirAccess *dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); dir->change_dir(p_path); for (int i = 0; i < keys.size(); i++) { if (!dir->file_exists(keys[i])) { Error err = file->reopen(p_path.plus_file((String)keys[i]), FileAccess::WRITE); ERR_FAIL_COND(err != OK); file->store_string(templates[keys[i]]); file->close(); } } memdelete(dir); memdelete(file); } // PUBLIC METHODS EditorSettings *EditorSettings::get_singleton() { return singleton.ptr(); } void EditorSettings::create() { if (singleton.ptr()) { return; //pointless } DirAccess *dir = nullptr; String data_path; String data_dir; String config_path; String config_dir; String cache_path; String cache_dir; Ref<ConfigFile> extra_config = memnew(ConfigFile); String exe_path = OS::get_singleton()->get_executable_path().get_base_dir(); DirAccess *d = DirAccess::create_for_path(exe_path); bool self_contained = false; if (d->file_exists(exe_path + "/._sc_")) { self_contained = true; Error err = extra_config->load(exe_path + "/._sc_"); if (err != OK) { ERR_PRINT("Can't load config from path '" + exe_path + "/._sc_'."); } } else if (d->file_exists(exe_path + "/_sc_")) { self_contained = true; Error err = extra_config->load(exe_path + "/_sc_"); if (err != OK) { ERR_PRINT("Can't load config from path '" + exe_path + "/_sc_'."); } } memdelete(d); if (self_contained) { // editor is self contained, all in same folder data_path = exe_path; data_dir = data_path.plus_file("editor_data"); config_path = exe_path; config_dir = data_dir; cache_path = exe_path; cache_dir = data_dir.plus_file("cache"); } else { // Typically XDG_DATA_HOME or %APPDATA% data_path = OS::get_singleton()->get_data_path(); data_dir = data_path.plus_file(OS::get_singleton()->get_godot_dir_name()); // Can be different from data_path e.g. on Linux or macOS config_path = OS::get_singleton()->get_config_path(); config_dir = config_path.plus_file(OS::get_singleton()->get_godot_dir_name()); // Can be different from above paths, otherwise a subfolder of data_dir cache_path = OS::get_singleton()->get_cache_path(); if (cache_path == data_path) { cache_dir = data_dir.plus_file("cache"); } else { cache_dir = cache_path.plus_file(OS::get_singleton()->get_godot_dir_name()); } } ClassDB::register_class<EditorSettings>(); //otherwise it can't be unserialized String config_file_path; if (data_path != "" && config_path != "" && cache_path != "") { // Validate/create data dir and subdirectories dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); if (dir->change_dir(data_dir) != OK) { dir->make_dir_recursive(data_dir); if (dir->change_dir(data_dir) != OK) { ERR_PRINT("Cannot create data directory!"); memdelete(dir); goto fail; } } if (dir->change_dir("templates") != OK) { dir->make_dir("templates"); } else { dir->change_dir(".."); } // Validate/create cache dir if (dir->change_dir(cache_dir) != OK) { dir->make_dir_recursive(cache_dir); if (dir->change_dir(cache_dir) != OK) { ERR_PRINT("Cannot create cache directory!"); memdelete(dir); goto fail; } } // Validate/create config dir and subdirectories if (dir->change_dir(config_dir) != OK) { dir->make_dir_recursive(config_dir); if (dir->change_dir(config_dir) != OK) { ERR_PRINT("Cannot create config directory!"); memdelete(dir); goto fail; } } if (dir->change_dir("text_editor_themes") != OK) { dir->make_dir("text_editor_themes"); } else { dir->change_dir(".."); } if (dir->change_dir("script_templates") != OK) { dir->make_dir("script_templates"); } else { dir->change_dir(".."); } if (dir->change_dir("feature_profiles") != OK) { dir->make_dir("feature_profiles"); } else { dir->change_dir(".."); } _create_script_templates(dir->get_current_dir().plus_file("script_templates")); { // Validate/create project-specific editor settings dir. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (da->change_dir(EditorSettings::PROJECT_EDITOR_SETTINGS_PATH) != OK) { Error err = da->make_dir_recursive(EditorSettings::PROJECT_EDITOR_SETTINGS_PATH); if (err || da->change_dir(EditorSettings::PROJECT_EDITOR_SETTINGS_PATH) != OK) { ERR_FAIL_MSG("Failed to create '" + EditorSettings::PROJECT_EDITOR_SETTINGS_PATH + "' folder."); } } } // Validate editor config file String config_file_name = "editor_settings-" + itos(VERSION_MAJOR) + ".tres"; config_file_path = config_dir.plus_file(config_file_name); if (!dir->file_exists(config_file_name)) { memdelete(dir); goto fail; } memdelete(dir); singleton = ResourceLoader::load(config_file_path, "EditorSettings"); if (singleton.is_null()) { WARN_PRINT("Could not open config file."); goto fail; } singleton->save_changed_setting = true; singleton->config_file_path = config_file_path; singleton->settings_dir = config_dir; singleton->data_dir = data_dir; singleton->cache_dir = cache_dir; print_verbose("EditorSettings: Load OK!"); singleton->setup_language(); singleton->setup_network(); singleton->load_favorites(); singleton->list_text_editor_themes(); return; } fail: // patch init projects if (extra_config->has_section("init_projects")) { Vector<String> list = extra_config->get_value("init_projects", "list"); for (int i = 0; i < list.size(); i++) { list.write[i] = exe_path.plus_file(list[i]); }; extra_config->set_value("init_projects", "list", list); }; singleton = Ref<EditorSettings>(memnew(EditorSettings)); singleton->save_changed_setting = true; singleton->config_file_path = config_file_path; singleton->settings_dir = config_dir; singleton->data_dir = data_dir; singleton->cache_dir = cache_dir; singleton->_load_defaults(extra_config); singleton->setup_language(); singleton->setup_network(); singleton->list_text_editor_themes(); } void EditorSettings::setup_language() { String lang = get("interface/editor/editor_language"); if (lang == "en") { return; // Default, nothing to do. } // Load editor translation for configured/detected locale. EditorTranslationList *etl = _editor_translations; while (etl->data) { if (etl->lang == lang) { Vector<uint8_t> data; data.resize(etl->uncomp_size); Compression::decompress(data.ptrw(), etl->uncomp_size, etl->data, etl->comp_size, Compression::MODE_DEFLATE); FileAccessMemory *fa = memnew(FileAccessMemory); fa->open_custom(data.ptr(), data.size()); Ref<Translation> tr = TranslationLoaderPO::load_translation(fa); if (tr.is_valid()) { tr->set_locale(etl->lang); TranslationServer::get_singleton()->set_tool_translation(tr); break; } } etl++; } // Load class reference translation. DocTranslationList *dtl = _doc_translations; while (dtl->data) { if (dtl->lang == lang) { Vector<uint8_t> data; data.resize(dtl->uncomp_size); Compression::decompress(data.ptrw(), dtl->uncomp_size, dtl->data, dtl->comp_size, Compression::MODE_DEFLATE); FileAccessMemory *fa = memnew(FileAccessMemory); fa->open_custom(data.ptr(), data.size()); Ref<Translation> tr = TranslationLoaderPO::load_translation(fa); if (tr.is_valid()) { tr->set_locale(dtl->lang); TranslationServer::get_singleton()->set_doc_translation(tr); break; } } dtl++; } } void EditorSettings::setup_network() { List<IP_Address> local_ip; IP::get_singleton()->get_local_addresses(&local_ip); String hint; String current = has_setting("network/debug/remote_host") ? get("network/debug/remote_host") : ""; String selected = "127.0.0.1"; // Check that current remote_host is a valid interface address and populate hints. for (List<IP_Address>::Element *E = local_ip.front(); E; E = E->next()) { String ip = E->get(); // link-local IPv6 addresses don't work, skipping them if (ip.begins_with("fe80:0:0:0:")) { // fe80::/64 continue; } // Same goes for IPv4 link-local (APIPA) addresses. if (ip.begins_with("169.254.")) { // 169.254.0.0/16 continue; } // Select current IP (found) if (ip == current) { selected = ip; } if (hint != "") { hint += ","; } hint += ip; } // Add hints with valid IP addresses to remote_host property. add_property_hint(PropertyInfo(Variant::STRING, "network/debug/remote_host", PROPERTY_HINT_ENUM, hint)); // Fix potentially invalid remote_host due to network change. set("network/debug/remote_host", selected); } void EditorSettings::save() { //_THREAD_SAFE_METHOD_ if (!singleton.ptr()) { return; } if (singleton->config_file_path == "") { ERR_PRINT("Cannot save EditorSettings config, no valid path"); return; } Error err = ResourceSaver::save(singleton->config_file_path, singleton); if (err != OK) { ERR_PRINT("Error saving editor settings to " + singleton->config_file_path); } else { print_verbose("EditorSettings: Save OK!"); } } void EditorSettings::destroy() { if (!singleton.ptr()) { return; } save(); singleton = Ref<EditorSettings>(); } void EditorSettings::set_optimize_save(bool p_optimize) { optimize_save = p_optimize; } // Properties void EditorSettings::set_setting(const String &p_setting, const Variant &p_value) { _THREAD_SAFE_METHOD_ set(p_setting, p_value); } Variant EditorSettings::get_setting(const String &p_setting) const { _THREAD_SAFE_METHOD_ return get(p_setting); } bool EditorSettings::has_setting(const String &p_setting) const { _THREAD_SAFE_METHOD_ return props.has(p_setting); } void EditorSettings::erase(const String &p_setting) { _THREAD_SAFE_METHOD_ props.erase(p_setting); } void EditorSettings::raise_order(const String &p_setting) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND(!props.has(p_setting)); props[p_setting].order = ++last_order; } void EditorSettings::set_restart_if_changed(const StringName &p_setting, bool p_restart) { _THREAD_SAFE_METHOD_ if (!props.has(p_setting)) { return; } props[p_setting].restart_if_changed = p_restart; } void EditorSettings::set_initial_value(const StringName &p_setting, const Variant &p_value, bool p_update_current) { _THREAD_SAFE_METHOD_ if (!props.has(p_setting)) { return; } props[p_setting].initial = p_value; props[p_setting].has_default_value = true; if (p_update_current) { set(p_setting, p_value); } } Variant _EDITOR_DEF(const String &p_setting, const Variant &p_default, bool p_restart_if_changed) { Variant ret = p_default; if (EditorSettings::get_singleton()->has_setting(p_setting)) { ret = EditorSettings::get_singleton()->get(p_setting); } else { EditorSettings::get_singleton()->set_manually(p_setting, p_default); EditorSettings::get_singleton()->set_restart_if_changed(p_setting, p_restart_if_changed); } if (!EditorSettings::get_singleton()->has_default_value(p_setting)) { EditorSettings::get_singleton()->set_initial_value(p_setting, p_default); } return ret; } Variant _EDITOR_GET(const String &p_setting) { ERR_FAIL_COND_V(!EditorSettings::get_singleton()->has_setting(p_setting), Variant()); return EditorSettings::get_singleton()->get(p_setting); } bool EditorSettings::property_can_revert(const String &p_setting) { if (!props.has(p_setting)) { return false; } if (!props[p_setting].has_default_value) { return false; } return props[p_setting].initial != props[p_setting].variant; } Variant EditorSettings::property_get_revert(const String &p_setting) { if (!props.has(p_setting) || !props[p_setting].has_default_value) { return Variant(); } return props[p_setting].initial; } void EditorSettings::add_property_hint(const PropertyInfo &p_hint) { _THREAD_SAFE_METHOD_ hints[p_hint.name] = p_hint; } // Data directories String EditorSettings::get_data_dir() const { return data_dir; } String EditorSettings::get_templates_dir() const { return get_data_dir().plus_file("templates"); } // Config directories String EditorSettings::get_settings_dir() const { return settings_dir; } String EditorSettings::get_project_settings_dir() const { return EditorSettings::PROJECT_EDITOR_SETTINGS_PATH; } String EditorSettings::get_text_editor_themes_dir() const { return get_settings_dir().plus_file("text_editor_themes"); } String EditorSettings::get_script_templates_dir() const { return get_settings_dir().plus_file("script_templates"); } String EditorSettings::get_project_script_templates_dir() const { return ProjectSettings::get_singleton()->get("editor/script/templates_search_path"); } // Cache directory String EditorSettings::get_cache_dir() const { return cache_dir; } String EditorSettings::get_feature_profiles_dir() const { return get_settings_dir().plus_file("feature_profiles"); } // Metadata void EditorSettings::set_project_metadata(const String &p_section, const String &p_key, Variant p_data) { Ref<ConfigFile> cf = memnew(ConfigFile); String path = get_project_settings_dir().plus_file("project_metadata.cfg"); Error err; err = cf->load(path); ERR_FAIL_COND_MSG(err != OK && err != ERR_FILE_NOT_FOUND, "Cannot load editor settings from file '" + path + "'."); cf->set_value(p_section, p_key, p_data); err = cf->save(path); ERR_FAIL_COND_MSG(err != OK, "Cannot save editor settings to file '" + path + "'."); } Variant EditorSettings::get_project_metadata(const String &p_section, const String &p_key, Variant p_default) const { Ref<ConfigFile> cf = memnew(ConfigFile); String path = get_project_settings_dir().plus_file("project_metadata.cfg"); Error err = cf->load(path); if (err != OK) { return p_default; } return cf->get_value(p_section, p_key, p_default); } void EditorSettings::set_favorites(const Vector<String> &p_favorites) { favorites = p_favorites; FileAccess *f = FileAccess::open(get_project_settings_dir().plus_file("favorites"), FileAccess::WRITE); if (f) { for (int i = 0; i < favorites.size(); i++) { f->store_line(favorites[i]); } memdelete(f); } } Vector<String> EditorSettings::get_favorites() const { return favorites; } void EditorSettings::set_recent_dirs(const Vector<String> &p_recent_dirs) { recent_dirs = p_recent_dirs; FileAccess *f = FileAccess::open(get_project_settings_dir().plus_file("recent_dirs"), FileAccess::WRITE); if (f) { for (int i = 0; i < recent_dirs.size(); i++) { f->store_line(recent_dirs[i]); } memdelete(f); } } Vector<String> EditorSettings::get_recent_dirs() const { return recent_dirs; } void EditorSettings::load_favorites() { FileAccess *f = FileAccess::open(get_project_settings_dir().plus_file("favorites"), FileAccess::READ); if (f) { String line = f->get_line().strip_edges(); while (line != "") { favorites.push_back(line); line = f->get_line().strip_edges(); } memdelete(f); } f = FileAccess::open(get_project_settings_dir().plus_file("recent_dirs"), FileAccess::READ); if (f) { String line = f->get_line().strip_edges(); while (line != "") { recent_dirs.push_back(line); line = f->get_line().strip_edges(); } memdelete(f); } } bool EditorSettings::is_dark_theme() { int AUTO_COLOR = 0; int LIGHT_COLOR = 2; Color base_color = get("interface/theme/base_color"); int icon_font_color_setting = get("interface/theme/icon_and_font_color"); return (icon_font_color_setting == AUTO_COLOR && ((base_color.r + base_color.g + base_color.b) / 3.0) < 0.5) || icon_font_color_setting == LIGHT_COLOR; } void EditorSettings::list_text_editor_themes() { String themes = "Adaptive,Default,Custom"; DirAccess *d = DirAccess::open(get_text_editor_themes_dir()); if (d) { List<String> custom_themes; d->list_dir_begin(); String file = d->get_next(); while (file != String()) { if (file.get_extension() == "tet" && !_is_default_text_editor_theme(file.get_basename().to_lower())) { custom_themes.push_back(file.get_basename()); } file = d->get_next(); } d->list_dir_end(); memdelete(d); custom_themes.sort(); for (List<String>::Element *E = custom_themes.front(); E; E = E->next()) { themes += "," + E->get(); } } add_property_hint(PropertyInfo(Variant::STRING, "text_editor/theme/color_theme", PROPERTY_HINT_ENUM, themes)); } void EditorSettings::load_text_editor_theme() { String p_file = get("text_editor/theme/color_theme"); if (_is_default_text_editor_theme(p_file.get_file().to_lower())) { if (p_file == "Default") { _load_default_text_editor_theme(); } return; // sorry for "Settings changed" console spam } String theme_path = get_text_editor_themes_dir().plus_file(p_file + ".tet"); Ref<ConfigFile> cf = memnew(ConfigFile); Error err = cf->load(theme_path); if (err != OK) { return; } List<String> keys; cf->get_section_keys("color_theme", &keys); for (List<String>::Element *E = keys.front(); E; E = E->next()) { String key = E->get(); String val = cf->get_value("color_theme", key); // don't load if it's not already there! if (has_setting("text_editor/highlighting/" + key)) { // make sure it is actually a color if (val.is_valid_html_color() && key.find("color") >= 0) { props["text_editor/highlighting/" + key].variant = Color::html(val); // change manually to prevent "Settings changed" console spam } } } emit_signal("settings_changed"); // if it doesn't load just use what is currently loaded } bool EditorSettings::import_text_editor_theme(String p_file) { if (!p_file.ends_with(".tet")) { return false; } else { if (p_file.get_file().to_lower() == "default.tet") { return false; } DirAccess *d = DirAccess::open(get_text_editor_themes_dir()); if (d) { d->copy(p_file, get_text_editor_themes_dir().plus_file(p_file.get_file())); memdelete(d); return true; } } return false; } bool EditorSettings::save_text_editor_theme() { String p_file = get("text_editor/theme/color_theme"); if (_is_default_text_editor_theme(p_file.get_file().to_lower())) { return false; } String theme_path = get_text_editor_themes_dir().plus_file(p_file + ".tet"); return _save_text_editor_theme(theme_path); } bool EditorSettings::save_text_editor_theme_as(String p_file) { if (!p_file.ends_with(".tet")) { p_file += ".tet"; } if (_is_default_text_editor_theme(p_file.get_file().to_lower().trim_suffix(".tet"))) { return false; } if (_save_text_editor_theme(p_file)) { // switch to theme is saved in the theme directory list_text_editor_themes(); String theme_name = p_file.substr(0, p_file.length() - 4).get_file(); if (p_file.get_base_dir() == get_text_editor_themes_dir()) { _initial_set("text_editor/theme/color_theme", theme_name); load_text_editor_theme(); } return true; } return false; } bool EditorSettings::is_default_text_editor_theme() { String p_file = get("text_editor/theme/color_theme"); return _is_default_text_editor_theme(p_file.get_file().to_lower()); } Vector<String> EditorSettings::get_script_templates(const String &p_extension, const String &p_custom_path) { Vector<String> templates; String template_dir = get_script_templates_dir(); if (!p_custom_path.is_empty()) { template_dir = p_custom_path; } DirAccess *d = DirAccess::open(template_dir); if (d) { d->list_dir_begin(); String file = d->get_next(); while (file != String()) { if (file.get_extension() == p_extension) { templates.push_back(file.get_basename()); } file = d->get_next(); } d->list_dir_end(); memdelete(d); } return templates; } String EditorSettings::get_editor_layouts_config() const { return get_settings_dir().plus_file("editor_layouts.cfg"); } // Shortcuts void EditorSettings::add_shortcut(const String &p_name, Ref<Shortcut> &p_shortcut) { shortcuts[p_name] = p_shortcut; } bool EditorSettings::is_shortcut(const String &p_name, const Ref<InputEvent> &p_event) const { const Map<String, Ref<Shortcut>>::Element *E = shortcuts.find(p_name); ERR_FAIL_COND_V_MSG(!E, false, "Unknown Shortcut: " + p_name + "."); return E->get()->is_shortcut(p_event); } Ref<Shortcut> EditorSettings::get_shortcut(const String &p_name) const { const Map<String, Ref<Shortcut>>::Element *SC = shortcuts.find(p_name); if (SC) { return SC->get(); } // If no shortcut with the provided name is found in the list, check the built-in shortcuts. // Use the first item in the action list for the shortcut event, since a shortcut can only have 1 linked event. Ref<Shortcut> sc; const Map<String, List<Ref<InputEvent>>>::Element *builtin_override = builtin_action_overrides.find(p_name); if (builtin_override) { sc.instance(); sc->set_shortcut(builtin_override->get().front()->get()); sc->set_name(InputMap::get_singleton()->get_builtin_display_name(p_name)); } // If there was no override, check the default builtins to see if it has an InputEvent for the provided name. if (sc.is_null()) { const OrderedHashMap<String, List<Ref<InputEvent>>>::ConstElement builtin_default = InputMap::get_singleton()->get_builtins().find(p_name); if (builtin_default) { sc.instance(); sc->set_shortcut(builtin_default.get().front()->get()); sc->set_name(InputMap::get_singleton()->get_builtin_display_name(p_name)); } } if (sc.is_valid()) { // Add the shortcut to the list. shortcuts[p_name] = sc; return sc; } return Ref<Shortcut>(); } void EditorSettings::get_shortcut_list(List<String> *r_shortcuts) { for (const Map<String, Ref<Shortcut>>::Element *E = shortcuts.front(); E; E = E->next()) { r_shortcuts->push_back(E->key()); } } Ref<Shortcut> ED_GET_SHORTCUT(const String &p_path) { if (!EditorSettings::get_singleton()) { return nullptr; } Ref<Shortcut> sc = EditorSettings::get_singleton()->get_shortcut(p_path); ERR_FAIL_COND_V_MSG(!sc.is_valid(), sc, "Used ED_GET_SHORTCUT with invalid shortcut: " + p_path + "."); return sc; } Ref<Shortcut> ED_SHORTCUT(const String &p_path, const String &p_name, uint32_t p_keycode) { #ifdef OSX_ENABLED // Use Cmd+Backspace as a general replacement for Delete shortcuts on macOS if (p_keycode == KEY_DELETE) { p_keycode = KEY_MASK_CMD | KEY_BACKSPACE; } #endif Ref<InputEventKey> ie; if (p_keycode) { ie.instance(); ie->set_unicode(p_keycode & KEY_CODE_MASK); ie->set_keycode(p_keycode & KEY_CODE_MASK); ie->set_shift(bool(p_keycode & KEY_MASK_SHIFT)); ie->set_alt(bool(p_keycode & KEY_MASK_ALT)); ie->set_control(bool(p_keycode & KEY_MASK_CTRL)); ie->set_metakey(bool(p_keycode & KEY_MASK_META)); } if (!EditorSettings::get_singleton()) { Ref<Shortcut> sc; sc.instance(); sc->set_name(p_name); sc->set_shortcut(ie); sc->set_meta("original", ie); return sc; } Ref<Shortcut> sc = EditorSettings::get_singleton()->get_shortcut(p_path); if (sc.is_valid()) { sc->set_name(p_name); //keep name (the ones that come from disk have no name) sc->set_meta("original", ie); //to compare against changes return sc; } sc.instance(); sc->set_name(p_name); sc->set_shortcut(ie); sc->set_meta("original", ie); //to compare against changes EditorSettings::get_singleton()->add_shortcut(p_path, sc); return sc; } void EditorSettings::set_builtin_action_override(const String &p_name, const Array &p_events) { List<Ref<InputEvent>> event_list; // Override the whole list, since events may have their order changed or be added, removed or edited. InputMap::get_singleton()->action_erase_events(p_name); for (int i = 0; i < p_events.size(); i++) { event_list.push_back(p_events[i]); InputMap::get_singleton()->action_add_event(p_name, p_events[i]); } // Check if the provided event array is same as built-in. If it is, it does not need to be added to the overrides. // Note that event order must also be the same. bool same_as_builtin = true; OrderedHashMap<String, List<Ref<InputEvent>>>::ConstElement builtin_default = InputMap::get_singleton()->get_builtins().find(p_name); if (builtin_default) { List<Ref<InputEvent>> builtin_events = builtin_default.get(); if (p_events.size() == builtin_events.size()) { int event_idx = 0; // Check equality of each event. for (List<Ref<InputEvent>>::Element *E = builtin_events.front(); E; E = E->next()) { if (!E->get()->shortcut_match(p_events[event_idx])) { same_as_builtin = false; break; } event_idx++; } } else { same_as_builtin = false; } } if (same_as_builtin && builtin_action_overrides.has(p_name)) { builtin_action_overrides.erase(p_name); } else { builtin_action_overrides[p_name] = event_list; } // Update the shortcut (if it is used somewhere in the editor) to be the first event of the new list. if (shortcuts.has(p_name)) { shortcuts[p_name]->set_shortcut(event_list.front()->get()); } } const Array EditorSettings::get_builtin_action_overrides(const String &p_name) const { const Map<String, List<Ref<InputEvent>>>::Element *AO = builtin_action_overrides.find(p_name); if (AO) { Array event_array; List<Ref<InputEvent>> events_list = AO->get(); for (List<Ref<InputEvent>>::Element *E = events_list.front(); E; E = E->next()) { event_array.push_back(E->get()); } return event_array; } return Array(); } void EditorSettings::notify_changes() { _THREAD_SAFE_METHOD_ SceneTree *sml = Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop()); if (!sml) { return; } Node *root = sml->get_root()->get_child(0); if (!root) { return; } root->propagate_notification(NOTIFICATION_EDITOR_SETTINGS_CHANGED); } void EditorSettings::_bind_methods() { ClassDB::bind_method(D_METHOD("has_setting", "name"), &EditorSettings::has_setting); ClassDB::bind_method(D_METHOD("set_setting", "name", "value"), &EditorSettings::set_setting); ClassDB::bind_method(D_METHOD("get_setting", "name"), &EditorSettings::get_setting); ClassDB::bind_method(D_METHOD("erase", "property"), &EditorSettings::erase); ClassDB::bind_method(D_METHOD("set_initial_value", "name", "value", "update_current"), &EditorSettings::set_initial_value); ClassDB::bind_method(D_METHOD("property_can_revert", "name"), &EditorSettings::property_can_revert); ClassDB::bind_method(D_METHOD("property_get_revert", "name"), &EditorSettings::property_get_revert); ClassDB::bind_method(D_METHOD("add_property_info", "info"), &EditorSettings::_add_property_info_bind); ClassDB::bind_method(D_METHOD("get_settings_dir"), &EditorSettings::get_settings_dir); ClassDB::bind_method(D_METHOD("get_project_settings_dir"), &EditorSettings::get_project_settings_dir); ClassDB::bind_method(D_METHOD("set_project_metadata", "section", "key", "data"), &EditorSettings::set_project_metadata); ClassDB::bind_method(D_METHOD("get_project_metadata", "section", "key", "default"), &EditorSettings::get_project_metadata, DEFVAL(Variant())); ClassDB::bind_method(D_METHOD("set_favorites", "dirs"), &EditorSettings::set_favorites); ClassDB::bind_method(D_METHOD("get_favorites"), &EditorSettings::get_favorites); ClassDB::bind_method(D_METHOD("set_recent_dirs", "dirs"), &EditorSettings::set_recent_dirs); ClassDB::bind_method(D_METHOD("get_recent_dirs"), &EditorSettings::get_recent_dirs); ClassDB::bind_method(D_METHOD("set_builtin_action_override", "name", "actions_list"), &EditorSettings::set_builtin_action_override); ADD_SIGNAL(MethodInfo("settings_changed")); BIND_CONSTANT(NOTIFICATION_EDITOR_SETTINGS_CHANGED); } EditorSettings::EditorSettings() { last_order = 0; optimize_save = true; save_changed_setting = true; _load_defaults(); } EditorSettings::~EditorSettings() { } Decrease the editor FPS limit when unfocused from 20 to 10 This provides better power savings compared to the previous value. This also speeds up project execution slightly while the editor is running in the background. The setting hint can now go as low as 1 FPS (1 million microseconds per frame), for those who really need the best possible power savings. This will make previewing animated shaders or particles impossible when the editor window isn't focused though. /*************************************************************************/ /* editor_settings.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "editor_settings.h" #include "core/config/project_settings.h" #include "core/input/input_map.h" #include "core/io/certs_compressed.gen.h" #include "core/io/compression.h" #include "core/io/config_file.h" #include "core/io/file_access_memory.h" #include "core/io/ip.h" #include "core/io/resource_loader.h" #include "core/io/resource_saver.h" #include "core/io/translation_loader_po.h" #include "core/os/dir_access.h" #include "core/os/file_access.h" #include "core/os/keyboard.h" #include "core/os/os.h" #include "core/version.h" #include "editor/doc_translations.gen.h" #include "editor/editor_node.h" #include "editor/editor_translations.gen.h" #include "scene/main/node.h" #include "scene/main/scene_tree.h" #include "scene/main/window.h" // PRIVATE METHODS Ref<EditorSettings> EditorSettings::singleton = nullptr; // Properties bool EditorSettings::_set(const StringName &p_name, const Variant &p_value) { _THREAD_SAFE_METHOD_ bool changed = _set_only(p_name, p_value); if (changed) { emit_signal("settings_changed"); } return true; } bool EditorSettings::_set_only(const StringName &p_name, const Variant &p_value) { _THREAD_SAFE_METHOD_ if (p_name == "shortcuts") { Array arr = p_value; ERR_FAIL_COND_V(arr.size() && arr.size() & 1, true); for (int i = 0; i < arr.size(); i += 2) { String name = arr[i]; Ref<InputEvent> shortcut = arr[i + 1]; Ref<Shortcut> sc; sc.instance(); sc->set_shortcut(shortcut); add_shortcut(name, sc); } return false; } else if (p_name == "builtin_action_overrides") { Array actions_arr = p_value; for (int i = 0; i < actions_arr.size(); i++) { Dictionary action_dict = actions_arr[i]; String name = action_dict["name"]; Array events = action_dict["events"]; InputMap *im = InputMap::get_singleton(); im->action_erase_events(name); builtin_action_overrides[name].clear(); for (int ev_idx = 0; ev_idx < events.size(); ev_idx++) { im->action_add_event(name, events[ev_idx]); builtin_action_overrides[name].push_back(events[ev_idx]); } } return false; } bool changed = false; if (p_value.get_type() == Variant::NIL) { if (props.has(p_name)) { props.erase(p_name); changed = true; } } else { if (props.has(p_name)) { if (p_value != props[p_name].variant) { props[p_name].variant = p_value; changed = true; } } else { props[p_name] = VariantContainer(p_value, last_order++); changed = true; } if (save_changed_setting) { if (!props[p_name].save) { props[p_name].save = true; changed = true; } } } return changed; } bool EditorSettings::_get(const StringName &p_name, Variant &r_ret) const { _THREAD_SAFE_METHOD_ if (p_name == "shortcuts") { Array arr; for (const Map<String, Ref<Shortcut>>::Element *E = shortcuts.front(); E; E = E->next()) { Ref<Shortcut> sc = E->get(); if (builtin_action_overrides.has(E->key())) { // This shortcut was auto-generated from built in actions: don't save. continue; } if (optimize_save) { if (!sc->has_meta("original")) { continue; //this came from settings but is not any longer used } Ref<InputEvent> original = sc->get_meta("original"); if (sc->is_shortcut(original) || (original.is_null() && sc->get_shortcut().is_null())) { continue; //not changed from default, don't save } } arr.push_back(E->key()); arr.push_back(sc->get_shortcut()); } r_ret = arr; return true; } else if (p_name == "builtin_action_overrides") { Array actions_arr; for (Map<String, List<Ref<InputEvent>>>::Element *E = builtin_action_overrides.front(); E; E = E->next()) { List<Ref<InputEvent>> events = E->get(); // TODO: skip actions which are the same as the builtin. Dictionary action_dict; action_dict["name"] = E->key(); Array events_arr; for (List<Ref<InputEvent>>::Element *I = events.front(); I; I = I->next()) { events_arr.push_back(I->get()); } action_dict["events"] = events_arr; actions_arr.push_back(action_dict); } r_ret = actions_arr; return true; } const VariantContainer *v = props.getptr(p_name); if (!v) { WARN_PRINT("EditorSettings::_get - Property not found: " + String(p_name)); return false; } r_ret = v->variant; return true; } void EditorSettings::_initial_set(const StringName &p_name, const Variant &p_value) { set(p_name, p_value); props[p_name].initial = p_value; props[p_name].has_default_value = true; } struct _EVCSort { String name; Variant::Type type = Variant::Type::NIL; int order = 0; bool save = false; bool restart_if_changed = false; bool operator<(const _EVCSort &p_vcs) const { return order < p_vcs.order; } }; void EditorSettings::_get_property_list(List<PropertyInfo> *p_list) const { _THREAD_SAFE_METHOD_ const String *k = nullptr; Set<_EVCSort> vclist; while ((k = props.next(k))) { const VariantContainer *v = props.getptr(*k); if (v->hide_from_editor) { continue; } _EVCSort vc; vc.name = *k; vc.order = v->order; vc.type = v->variant.get_type(); vc.save = v->save; /*if (vc.save) { this should be implemented, but lets do after 3.1 is out. if (v->initial.get_type() != Variant::NIL && v->initial == v->variant) { vc.save = false; } }*/ vc.restart_if_changed = v->restart_if_changed; vclist.insert(vc); } for (Set<_EVCSort>::Element *E = vclist.front(); E; E = E->next()) { int pinfo = 0; if (E->get().save || !optimize_save) { pinfo |= PROPERTY_USAGE_STORAGE; } if (!E->get().name.begins_with("_") && !E->get().name.begins_with("projects/")) { pinfo |= PROPERTY_USAGE_EDITOR; } else { pinfo |= PROPERTY_USAGE_STORAGE; //hiddens must always be saved } PropertyInfo pi(E->get().type, E->get().name); pi.usage = pinfo; if (hints.has(E->get().name)) { pi = hints[E->get().name]; } if (E->get().restart_if_changed) { pi.usage |= PROPERTY_USAGE_RESTART_IF_CHANGED; } p_list->push_back(pi); } p_list->push_back(PropertyInfo(Variant::ARRAY, "shortcuts", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL)); //do not edit p_list->push_back(PropertyInfo(Variant::ARRAY, "builtin_action_overrides", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL)); } void EditorSettings::_add_property_info_bind(const Dictionary &p_info) { ERR_FAIL_COND(!p_info.has("name")); ERR_FAIL_COND(!p_info.has("type")); PropertyInfo pinfo; pinfo.name = p_info["name"]; ERR_FAIL_COND(!props.has(pinfo.name)); pinfo.type = Variant::Type(p_info["type"].operator int()); ERR_FAIL_INDEX(pinfo.type, Variant::VARIANT_MAX); if (p_info.has("hint")) { pinfo.hint = PropertyHint(p_info["hint"].operator int()); } if (p_info.has("hint_string")) { pinfo.hint_string = p_info["hint_string"]; } add_property_hint(pinfo); } // Default configs bool EditorSettings::has_default_value(const String &p_setting) const { _THREAD_SAFE_METHOD_ if (!props.has(p_setting)) { return false; } return props[p_setting].has_default_value; } void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) { _THREAD_SAFE_METHOD_ /* Languages */ { String lang_hint = "en"; String host_lang = OS::get_singleton()->get_locale(); host_lang = TranslationServer::standardize_locale(host_lang); // Skip locales if Text server lack required features. Vector<String> locales_to_skip; if (!TS->has_feature(TextServer::FEATURE_BIDI_LAYOUT) || !TS->has_feature(TextServer::FEATURE_SHAPING)) { locales_to_skip.push_back("ar"); // Arabic locales_to_skip.push_back("fa"); // Persian locales_to_skip.push_back("ur"); // Urdu } if (!TS->has_feature(TextServer::FEATURE_BIDI_LAYOUT)) { locales_to_skip.push_back("he"); // Hebrew } if (!TS->has_feature(TextServer::FEATURE_SHAPING)) { locales_to_skip.push_back("bn"); // Bengali locales_to_skip.push_back("hi"); // Hindi locales_to_skip.push_back("ml"); // Malayalam locales_to_skip.push_back("si"); // Sinhala locales_to_skip.push_back("ta"); // Tamil locales_to_skip.push_back("te"); // Telugu } if (!locales_to_skip.is_empty()) { WARN_PRINT("Some locales are not properly supported by selected Text Server and are disabled."); } String best; EditorTranslationList *etl = _editor_translations; while (etl->data) { const String &locale = etl->lang; // Skip locales which we can't render properly (see above comment). // Test against language code without regional variants (e.g. ur_PK). String lang_code = locale.get_slice("_", 0); if (locales_to_skip.find(lang_code) != -1) { etl++; continue; } lang_hint += ","; lang_hint += locale; if (host_lang == locale) { best = locale; } if (best == String() && host_lang.begins_with(locale)) { best = locale; } etl++; } if (best == String()) { best = "en"; } _initial_set("interface/editor/editor_language", best); set_restart_if_changed("interface/editor/editor_language", true); hints["interface/editor/editor_language"] = PropertyInfo(Variant::STRING, "interface/editor/editor_language", PROPERTY_HINT_ENUM, lang_hint, PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); } /* Interface */ // Editor _initial_set("interface/editor/display_scale", 0); // Display what the Auto display scale setting effectively corresponds to. // The code below is adapted in `editor/editor_node.cpp` and `editor/project_manager.cpp`. // Make sure to update those when modifying the code below. #ifdef OSX_ENABLED float scale = DisplayServer::get_singleton()->screen_get_max_scale(); #else const int screen = DisplayServer::get_singleton()->window_get_current_screen(); float scale; if (DisplayServer::get_singleton()->screen_get_dpi(screen) >= 192 && DisplayServer::get_singleton()->screen_get_size(screen).y >= 1400) { // hiDPI display. scale = 2.0; } else if (DisplayServer::get_singleton()->screen_get_size(screen).y >= 1700) { // Likely a hiDPI display, but we aren't certain due to the returned DPI. // Use an intermediate scale to handle this situation. scale = 1.5; } else if (DisplayServer::get_singleton()->screen_get_size(screen).y <= 800) { // Small loDPI display. Use a smaller display scale so that editor elements fit more easily. // Icons won't look great, but this is better than having editor elements overflow from its window. scale = 0.75; } else { scale = 1.0; } #endif hints["interface/editor/display_scale"] = PropertyInfo(Variant::INT, "interface/editor/display_scale", PROPERTY_HINT_ENUM, vformat("Auto (%d%%),75%%,100%%,125%%,150%%,175%%,200%%,Custom", Math::round(scale * 100)), PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/custom_display_scale", 1.0f); hints["interface/editor/custom_display_scale"] = PropertyInfo(Variant::FLOAT, "interface/editor/custom_display_scale", PROPERTY_HINT_RANGE, "0.5,3,0.01", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/main_font_size", 14); hints["interface/editor/main_font_size"] = PropertyInfo(Variant::INT, "interface/editor/main_font_size", PROPERTY_HINT_RANGE, "8,48,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/code_font_size", 14); hints["interface/editor/code_font_size"] = PropertyInfo(Variant::INT, "interface/editor/code_font_size", PROPERTY_HINT_RANGE, "8,48,1", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/code_font_contextual_ligatures", 0); hints["interface/editor/code_font_contextual_ligatures"] = PropertyInfo(Variant::INT, "interface/editor/code_font_contextual_ligatures", PROPERTY_HINT_ENUM, "Default,Disable Contextual Alternates (Coding Ligatures),Use Custom OpenType Feature Set", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/code_font_custom_opentype_features", ""); _initial_set("interface/editor/code_font_custom_variations", ""); _initial_set("interface/editor/font_antialiased", true); _initial_set("interface/editor/font_hinting", 0); #ifdef OSX_ENABLED hints["interface/editor/font_hinting"] = PropertyInfo(Variant::INT, "interface/editor/font_hinting", PROPERTY_HINT_ENUM, "Auto (None),None,Light,Normal", PROPERTY_USAGE_DEFAULT); #else hints["interface/editor/font_hinting"] = PropertyInfo(Variant::INT, "interface/editor/font_hinting", PROPERTY_HINT_ENUM, "Auto (Light),None,Light,Normal", PROPERTY_USAGE_DEFAULT); #endif _initial_set("interface/editor/main_font", ""); hints["interface/editor/main_font"] = PropertyInfo(Variant::STRING, "interface/editor/main_font", PROPERTY_HINT_GLOBAL_FILE, "*.ttf,*.otf", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/main_font_bold", ""); hints["interface/editor/main_font_bold"] = PropertyInfo(Variant::STRING, "interface/editor/main_font_bold", PROPERTY_HINT_GLOBAL_FILE, "*.ttf,*.otf", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/code_font", ""); hints["interface/editor/code_font"] = PropertyInfo(Variant::STRING, "interface/editor/code_font", PROPERTY_HINT_GLOBAL_FILE, "*.ttf,*.otf", PROPERTY_USAGE_DEFAULT); _initial_set("interface/editor/dim_editor_on_dialog_popup", true); _initial_set("interface/editor/low_processor_mode_sleep_usec", 6900); // ~144 FPS hints["interface/editor/low_processor_mode_sleep_usec"] = PropertyInfo(Variant::FLOAT, "interface/editor/low_processor_mode_sleep_usec", PROPERTY_HINT_RANGE, "1,100000,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/unfocused_low_processor_mode_sleep_usec", 100000); // 10 FPS // Allow an unfocused FPS limit as low as 1 FPS for those who really need low power usage // (but don't need to preview particles or shaders while the editor is unfocused). // With very low FPS limits, the editor can take a small while to become usable after being focused again, // so this should be used at the user's discretion. hints["interface/editor/unfocused_low_processor_mode_sleep_usec"] = PropertyInfo(Variant::FLOAT, "interface/editor/unfocused_low_processor_mode_sleep_usec", PROPERTY_HINT_RANGE, "1,1000000,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/separate_distraction_mode", false); _initial_set("interface/editor/automatically_open_screenshots", true); _initial_set("interface/editor/single_window_mode", false); hints["interface/editor/single_window_mode"] = PropertyInfo(Variant::BOOL, "interface/editor/single_window_mode", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/editor/hide_console_window", false); _initial_set("interface/editor/save_each_scene_on_quit", true); // Regression // Inspector _initial_set("interface/inspector/max_array_dictionary_items_per_page", 20); hints["interface/inspector/max_array_dictionary_items_per_page"] = PropertyInfo(Variant::INT, "interface/inspector/max_array_dictionary_items_per_page", PROPERTY_HINT_RANGE, "10,100,1", PROPERTY_USAGE_DEFAULT); // Theme _initial_set("interface/theme/preset", "Default"); hints["interface/theme/preset"] = PropertyInfo(Variant::STRING, "interface/theme/preset", PROPERTY_HINT_ENUM, "Default,Alien,Arc,Godot 2,Grey,Light,Solarized (Dark),Solarized (Light),Custom", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/icon_and_font_color", 0); hints["interface/theme/icon_and_font_color"] = PropertyInfo(Variant::INT, "interface/theme/icon_and_font_color", PROPERTY_HINT_ENUM, "Auto,Dark,Light", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/base_color", Color(0.2, 0.23, 0.31)); hints["interface/theme/base_color"] = PropertyInfo(Variant::COLOR, "interface/theme/base_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/accent_color", Color(0.41, 0.61, 0.91)); hints["interface/theme/accent_color"] = PropertyInfo(Variant::COLOR, "interface/theme/accent_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/contrast", 0.25); hints["interface/theme/contrast"] = PropertyInfo(Variant::FLOAT, "interface/theme/contrast", PROPERTY_HINT_RANGE, "0.01, 1, 0.01"); _initial_set("interface/theme/icon_saturation", 1.0); hints["interface/theme/icon_saturation"] = PropertyInfo(Variant::FLOAT, "interface/theme/icon_saturation", PROPERTY_HINT_RANGE, "0,2,0.01", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/relationship_line_opacity", 0.1); hints["interface/theme/relationship_line_opacity"] = PropertyInfo(Variant::FLOAT, "interface/theme/relationship_line_opacity", PROPERTY_HINT_RANGE, "0.00, 1, 0.01"); _initial_set("interface/theme/highlight_tabs", false); _initial_set("interface/theme/border_size", 1); _initial_set("interface/theme/use_graph_node_headers", false); hints["interface/theme/border_size"] = PropertyInfo(Variant::INT, "interface/theme/border_size", PROPERTY_HINT_RANGE, "0,2,1", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/additional_spacing", 0); hints["interface/theme/additional_spacing"] = PropertyInfo(Variant::FLOAT, "interface/theme/additional_spacing", PROPERTY_HINT_RANGE, "0,5,0.1", PROPERTY_USAGE_DEFAULT); _initial_set("interface/theme/custom_theme", ""); hints["interface/theme/custom_theme"] = PropertyInfo(Variant::STRING, "interface/theme/custom_theme", PROPERTY_HINT_GLOBAL_FILE, "*.res,*.tres,*.theme", PROPERTY_USAGE_DEFAULT); // Scene tabs _initial_set("interface/scene_tabs/show_thumbnail_on_hover", true); _initial_set("interface/scene_tabs/resize_if_many_tabs", true); _initial_set("interface/scene_tabs/minimum_width", 50); hints["interface/scene_tabs/minimum_width"] = PropertyInfo(Variant::INT, "interface/scene_tabs/minimum_width", PROPERTY_HINT_RANGE, "50,500,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); _initial_set("interface/scene_tabs/show_script_button", false); /* Filesystem */ // Directories _initial_set("filesystem/directories/autoscan_project_path", ""); hints["filesystem/directories/autoscan_project_path"] = PropertyInfo(Variant::STRING, "filesystem/directories/autoscan_project_path", PROPERTY_HINT_GLOBAL_DIR); _initial_set("filesystem/directories/default_project_path", OS::get_singleton()->has_environment("HOME") ? OS::get_singleton()->get_environment("HOME") : OS::get_singleton()->get_system_dir(OS::SYSTEM_DIR_DOCUMENTS)); hints["filesystem/directories/default_project_path"] = PropertyInfo(Variant::STRING, "filesystem/directories/default_project_path", PROPERTY_HINT_GLOBAL_DIR); // On save _initial_set("filesystem/on_save/compress_binary_resources", true); _initial_set("filesystem/on_save/safe_save_on_backup_then_rename", true); // File dialog _initial_set("filesystem/file_dialog/show_hidden_files", false); _initial_set("filesystem/file_dialog/display_mode", 0); hints["filesystem/file_dialog/display_mode"] = PropertyInfo(Variant::INT, "filesystem/file_dialog/display_mode", PROPERTY_HINT_ENUM, "Thumbnails,List"); _initial_set("filesystem/file_dialog/thumbnail_size", 64); hints["filesystem/file_dialog/thumbnail_size"] = PropertyInfo(Variant::INT, "filesystem/file_dialog/thumbnail_size", PROPERTY_HINT_RANGE, "32,128,16"); /* Docks */ // SceneTree _initial_set("docks/scene_tree/start_create_dialog_fully_expanded", false); // FileSystem _initial_set("docks/filesystem/thumbnail_size", 64); hints["docks/filesystem/thumbnail_size"] = PropertyInfo(Variant::INT, "docks/filesystem/thumbnail_size", PROPERTY_HINT_RANGE, "32,128,16"); _initial_set("docks/filesystem/always_show_folders", true); // Property editor _initial_set("docks/property_editor/auto_refresh_interval", 0.2); //update 5 times per second by default _initial_set("docks/property_editor/subresource_hue_tint", 0.75); hints["docks/property_editor/subresource_hue_tint"] = PropertyInfo(Variant::FLOAT, "docks/property_editor/subresource_hue_tint", PROPERTY_HINT_RANGE, "0,1,0.01", PROPERTY_USAGE_DEFAULT); /* Text editor */ // Theme _initial_set("text_editor/theme/color_theme", "Adaptive"); hints["text_editor/theme/color_theme"] = PropertyInfo(Variant::STRING, "text_editor/theme/color_theme", PROPERTY_HINT_ENUM, "Adaptive,Default,Custom"); _initial_set("text_editor/theme/line_spacing", 6); hints["text_editor/theme/line_spacing"] = PropertyInfo(Variant::INT, "text_editor/theme/line_spacing", PROPERTY_HINT_RANGE, "0,50,1"); _load_default_text_editor_theme(); // Highlighting _initial_set("text_editor/highlighting/highlight_all_occurrences", true); _initial_set("text_editor/highlighting/highlight_current_line", true); _initial_set("text_editor/highlighting/highlight_type_safe_lines", true); // Indent _initial_set("text_editor/indent/type", 0); hints["text_editor/indent/type"] = PropertyInfo(Variant::INT, "text_editor/indent/type", PROPERTY_HINT_ENUM, "Tabs,Spaces"); _initial_set("text_editor/indent/size", 4); hints["text_editor/indent/size"] = PropertyInfo(Variant::INT, "text_editor/indent/size", PROPERTY_HINT_RANGE, "1, 64, 1"); // size of 0 crashes. _initial_set("text_editor/indent/auto_indent", true); _initial_set("text_editor/indent/convert_indent_on_save", true); _initial_set("text_editor/indent/draw_tabs", true); _initial_set("text_editor/indent/draw_spaces", false); // Navigation _initial_set("text_editor/navigation/smooth_scrolling", true); _initial_set("text_editor/navigation/v_scroll_speed", 80); _initial_set("text_editor/navigation/show_minimap", true); _initial_set("text_editor/navigation/minimap_width", 80); hints["text_editor/navigation/minimap_width"] = PropertyInfo(Variant::INT, "text_editor/navigation/minimap_width", PROPERTY_HINT_RANGE, "50,250,1"); // Appearance _initial_set("text_editor/appearance/show_line_numbers", true); _initial_set("text_editor/appearance/line_numbers_zero_padded", false); _initial_set("text_editor/appearance/show_bookmark_gutter", true); _initial_set("text_editor/appearance/show_info_gutter", true); _initial_set("text_editor/appearance/code_folding", true); _initial_set("text_editor/appearance/word_wrap", false); _initial_set("text_editor/appearance/show_line_length_guidelines", true); _initial_set("text_editor/appearance/line_length_guideline_soft_column", 80); hints["text_editor/appearance/line_length_guideline_soft_column"] = PropertyInfo(Variant::INT, "text_editor/appearance/line_length_guideline_soft_column", PROPERTY_HINT_RANGE, "20, 160, 1"); _initial_set("text_editor/appearance/line_length_guideline_hard_column", 100); hints["text_editor/appearance/line_length_guideline_hard_column"] = PropertyInfo(Variant::INT, "text_editor/appearance/line_length_guideline_hard_column", PROPERTY_HINT_RANGE, "20, 160, 1"); // Script list _initial_set("text_editor/script_list/show_members_overview", true); // Files _initial_set("text_editor/files/trim_trailing_whitespace_on_save", false); _initial_set("text_editor/files/autosave_interval_secs", 0); _initial_set("text_editor/files/restore_scripts_on_load", true); // Tools _initial_set("text_editor/tools/create_signal_callbacks", true); _initial_set("text_editor/tools/sort_members_outline_alphabetically", false); // Cursor _initial_set("text_editor/cursor/scroll_past_end_of_file", false); _initial_set("text_editor/cursor/block_caret", false); _initial_set("text_editor/cursor/caret_blink", true); _initial_set("text_editor/cursor/caret_blink_speed", 0.5); hints["text_editor/cursor/caret_blink_speed"] = PropertyInfo(Variant::FLOAT, "text_editor/cursor/caret_blink_speed", PROPERTY_HINT_RANGE, "0.1, 10, 0.01"); _initial_set("text_editor/cursor/right_click_moves_caret", true); // Completion _initial_set("text_editor/completion/idle_parse_delay", 2.0); hints["text_editor/completion/idle_parse_delay"] = PropertyInfo(Variant::FLOAT, "text_editor/completion/idle_parse_delay", PROPERTY_HINT_RANGE, "0.1, 10, 0.01"); _initial_set("text_editor/completion/auto_brace_complete", true); _initial_set("text_editor/completion/code_complete_delay", 0.3); hints["text_editor/completion/code_complete_delay"] = PropertyInfo(Variant::FLOAT, "text_editor/completion/code_complete_delay", PROPERTY_HINT_RANGE, "0.01, 5, 0.01"); _initial_set("text_editor/completion/put_callhint_tooltip_below_current_line", true); _initial_set("text_editor/completion/callhint_tooltip_offset", Vector2()); _initial_set("text_editor/completion/complete_file_paths", true); _initial_set("text_editor/completion/add_type_hints", false); _initial_set("text_editor/completion/use_single_quotes", false); // Help _initial_set("text_editor/help/show_help_index", true); _initial_set("text_editor/help/help_font_size", 15); hints["text_editor/help/help_font_size"] = PropertyInfo(Variant::INT, "text_editor/help/help_font_size", PROPERTY_HINT_RANGE, "8,48,1"); _initial_set("text_editor/help/help_source_font_size", 14); hints["text_editor/help/help_source_font_size"] = PropertyInfo(Variant::INT, "text_editor/help/help_source_font_size", PROPERTY_HINT_RANGE, "8,48,1"); _initial_set("text_editor/help/help_title_font_size", 23); hints["text_editor/help/help_title_font_size"] = PropertyInfo(Variant::INT, "text_editor/help/help_title_font_size", PROPERTY_HINT_RANGE, "8,48,1"); _initial_set("text_editor/help/class_reference_examples", 0); hints["text_editor/help/class_reference_examples"] = PropertyInfo(Variant::INT, "text_editor/help/class_reference_examples", PROPERTY_HINT_ENUM, "GDScript,C#,GDScript and C#"); /* Editors */ // GridMap _initial_set("editors/grid_map/pick_distance", 5000.0); // 3D _initial_set("editors/3d/primary_grid_color", Color(0.56, 0.56, 0.56, 0.5)); hints["editors/3d/primary_grid_color"] = PropertyInfo(Variant::COLOR, "editors/3d/primary_grid_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT); _initial_set("editors/3d/secondary_grid_color", Color(0.38, 0.38, 0.38, 0.5)); hints["editors/3d/secondary_grid_color"] = PropertyInfo(Variant::COLOR, "editors/3d/secondary_grid_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT); // Use a similar color to the 2D editor selection. _initial_set("editors/3d/selection_box_color", Color(1.0, 0.5, 0)); hints["editors/3d/selection_box_color"] = PropertyInfo(Variant::COLOR, "editors/3d/selection_box_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); // If a line is a multiple of this, it uses the primary grid color. // Use a power of 2 value by default as it's more common to use powers of 2 in level design. _initial_set("editors/3d/primary_grid_steps", 8); hints["editors/3d/primary_grid_steps"] = PropertyInfo(Variant::INT, "editors/3d/primary_grid_steps", PROPERTY_HINT_RANGE, "1,100,1", PROPERTY_USAGE_DEFAULT); // At 1000, the grid mostly looks like it has no edge. _initial_set("editors/3d/grid_size", 200); hints["editors/3d/grid_size"] = PropertyInfo(Variant::INT, "editors/3d/grid_size", PROPERTY_HINT_RANGE, "1,2000,1", PROPERTY_USAGE_DEFAULT); // Default largest grid size is 100m, 10^2 (primary grid lines are 1km apart when primary_grid_steps is 10). _initial_set("editors/3d/grid_division_level_max", 2); // Higher values produce graphical artifacts when far away unless View Z-Far // is increased significantly more than it really should need to be. hints["editors/3d/grid_division_level_max"] = PropertyInfo(Variant::INT, "editors/3d/grid_division_level_max", PROPERTY_HINT_RANGE, "-1,3,1", PROPERTY_USAGE_DEFAULT); // Default smallest grid size is 1m, 10^0. _initial_set("editors/3d/grid_division_level_min", 0); // Lower values produce graphical artifacts regardless of view clipping planes, so limit to -2 as a lower bound. hints["editors/3d/grid_division_level_min"] = PropertyInfo(Variant::INT, "editors/3d/grid_division_level_min", PROPERTY_HINT_RANGE, "-2,2,1", PROPERTY_USAGE_DEFAULT); // -0.2 seems like a sensible default. -1.0 gives Blender-like behavior, 0.5 gives huge grids. _initial_set("editors/3d/grid_division_level_bias", -0.2); hints["editors/3d/grid_division_level_bias"] = PropertyInfo(Variant::FLOAT, "editors/3d/grid_division_level_bias", PROPERTY_HINT_RANGE, "-1.0,0.5,0.1", PROPERTY_USAGE_DEFAULT); _initial_set("editors/3d/grid_xz_plane", true); _initial_set("editors/3d/grid_xy_plane", false); _initial_set("editors/3d/grid_yz_plane", false); // Use a lower default FOV for the 3D camera compared to the // Camera3D node as the 3D viewport doesn't span the whole screen. // This means it's technically viewed from a further distance, which warrants a narrower FOV. _initial_set("editors/3d/default_fov", 70.0); hints["editors/3d/default_fov"] = PropertyInfo(Variant::FLOAT, "editors/3d/default_fov", PROPERTY_HINT_RANGE, "1,179,0.1"); _initial_set("editors/3d/default_z_near", 0.05); hints["editors/3d/default_z_near"] = PropertyInfo(Variant::FLOAT, "editors/3d/default_z_near", PROPERTY_HINT_RANGE, "0.01,10,0.01,or_greater"); _initial_set("editors/3d/default_z_far", 4000.0); hints["editors/3d/default_z_far"] = PropertyInfo(Variant::FLOAT, "editors/3d/default_z_far", PROPERTY_HINT_RANGE, "0.1,4000,0.1,or_greater"); // 3D: Navigation _initial_set("editors/3d/navigation/navigation_scheme", 0); _initial_set("editors/3d/navigation/invert_y_axis", false); _initial_set("editors/3d/navigation/invert_x_axis", false); hints["editors/3d/navigation/navigation_scheme"] = PropertyInfo(Variant::INT, "editors/3d/navigation/navigation_scheme", PROPERTY_HINT_ENUM, "Godot,Maya,Modo"); _initial_set("editors/3d/navigation/zoom_style", 0); hints["editors/3d/navigation/zoom_style"] = PropertyInfo(Variant::INT, "editors/3d/navigation/zoom_style", PROPERTY_HINT_ENUM, "Vertical, Horizontal"); _initial_set("editors/3d/navigation/emulate_3_button_mouse", false); _initial_set("editors/3d/navigation/orbit_modifier", 0); hints["editors/3d/navigation/orbit_modifier"] = PropertyInfo(Variant::INT, "editors/3d/navigation/orbit_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl"); _initial_set("editors/3d/navigation/pan_modifier", 1); hints["editors/3d/navigation/pan_modifier"] = PropertyInfo(Variant::INT, "editors/3d/navigation/pan_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl"); _initial_set("editors/3d/navigation/zoom_modifier", 4); hints["editors/3d/navigation/zoom_modifier"] = PropertyInfo(Variant::INT, "editors/3d/navigation/zoom_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl"); _initial_set("editors/3d/navigation/warped_mouse_panning", true); // 3D: Navigation feel _initial_set("editors/3d/navigation_feel/orbit_sensitivity", 0.4); hints["editors/3d/navigation_feel/orbit_sensitivity"] = PropertyInfo(Variant::FLOAT, "editors/3d/navigation_feel/orbit_sensitivity", PROPERTY_HINT_RANGE, "0.0, 2, 0.01"); _initial_set("editors/3d/navigation_feel/orbit_inertia", 0.05); hints["editors/3d/navigation_feel/orbit_inertia"] = PropertyInfo(Variant::FLOAT, "editors/3d/navigation_feel/orbit_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/navigation_feel/translation_inertia", 0.15); hints["editors/3d/navigation_feel/translation_inertia"] = PropertyInfo(Variant::FLOAT, "editors/3d/navigation_feel/translation_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/navigation_feel/zoom_inertia", 0.075); hints["editors/3d/navigation_feel/zoom_inertia"] = PropertyInfo(Variant::FLOAT, "editors/3d/navigation_feel/zoom_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/navigation_feel/manipulation_orbit_inertia", 0.075); hints["editors/3d/navigation_feel/manipulation_orbit_inertia"] = PropertyInfo(Variant::FLOAT, "editors/3d/navigation_feel/manipulation_orbit_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/navigation_feel/manipulation_translation_inertia", 0.075); hints["editors/3d/navigation_feel/manipulation_translation_inertia"] = PropertyInfo(Variant::FLOAT, "editors/3d/navigation_feel/manipulation_translation_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); // 3D: Freelook _initial_set("editors/3d/freelook/freelook_navigation_scheme", false); hints["editors/3d/freelook/freelook_navigation_scheme"] = PropertyInfo(Variant::INT, "editors/3d/freelook/freelook_navigation_scheme", PROPERTY_HINT_ENUM, "Default,Partially Axis-Locked (id Tech),Fully Axis-Locked (Minecraft)"); _initial_set("editors/3d/freelook/freelook_sensitivity", 0.4); hints["editors/3d/freelook/freelook_sensitivity"] = PropertyInfo(Variant::FLOAT, "editors/3d/freelook/freelook_sensitivity", PROPERTY_HINT_RANGE, "0.0, 2, 0.01"); _initial_set("editors/3d/freelook/freelook_inertia", 0.1); hints["editors/3d/freelook/freelook_inertia"] = PropertyInfo(Variant::FLOAT, "editors/3d/freelook/freelook_inertia", PROPERTY_HINT_RANGE, "0.0, 1, 0.01"); _initial_set("editors/3d/freelook/freelook_base_speed", 5.0); hints["editors/3d/freelook/freelook_base_speed"] = PropertyInfo(Variant::FLOAT, "editors/3d/freelook/freelook_base_speed", PROPERTY_HINT_RANGE, "0.0, 10, 0.01"); _initial_set("editors/3d/freelook/freelook_activation_modifier", 0); hints["editors/3d/freelook/freelook_activation_modifier"] = PropertyInfo(Variant::INT, "editors/3d/freelook/freelook_activation_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl"); _initial_set("editors/3d/freelook/freelook_speed_zoom_link", false); // 2D _initial_set("editors/2d/grid_color", Color(1.0, 1.0, 1.0, 0.07)); _initial_set("editors/2d/guides_color", Color(0.6, 0.0, 0.8)); _initial_set("editors/2d/smart_snapping_line_color", Color(0.9, 0.1, 0.1)); _initial_set("editors/2d/bone_width", 5); _initial_set("editors/2d/bone_color1", Color(1.0, 1.0, 1.0, 0.9)); _initial_set("editors/2d/bone_color2", Color(0.6, 0.6, 0.6, 0.9)); _initial_set("editors/2d/bone_selected_color", Color(0.9, 0.45, 0.45, 0.9)); _initial_set("editors/2d/bone_ik_color", Color(0.9, 0.9, 0.45, 0.9)); _initial_set("editors/2d/bone_outline_color", Color(0.35, 0.35, 0.35)); _initial_set("editors/2d/bone_outline_size", 2); _initial_set("editors/2d/viewport_border_color", Color(0.4, 0.4, 1.0, 0.4)); _initial_set("editors/2d/constrain_editor_view", true); _initial_set("editors/2d/warped_mouse_panning", true); _initial_set("editors/2d/simple_panning", false); _initial_set("editors/2d/scroll_to_pan", false); _initial_set("editors/2d/pan_speed", 20); // Polygon editor _initial_set("editors/poly_editor/point_grab_radius", 8); _initial_set("editors/poly_editor/show_previous_outline", true); // Animation _initial_set("editors/animation/autorename_animation_tracks", true); _initial_set("editors/animation/confirm_insert_track", true); _initial_set("editors/animation/default_create_bezier_tracks", false); _initial_set("editors/animation/default_create_reset_tracks", true); _initial_set("editors/animation/onion_layers_past_color", Color(1, 0, 0)); _initial_set("editors/animation/onion_layers_future_color", Color(0, 1, 0)); // Visual editors _initial_set("editors/visual_editors/minimap_opacity", 0.85); hints["editors/visual_editors/minimap_opacity"] = PropertyInfo(Variant::FLOAT, "editors/visual_editors/minimap_opacity", PROPERTY_HINT_RANGE, "0.0,1.0,0.01", PROPERTY_USAGE_DEFAULT); /* Run */ // Window placement _initial_set("run/window_placement/rect", 1); hints["run/window_placement/rect"] = PropertyInfo(Variant::INT, "run/window_placement/rect", PROPERTY_HINT_ENUM, "Top Left,Centered,Custom Position,Force Maximized,Force Fullscreen"); String screen_hints = "Same as Editor,Previous Monitor,Next Monitor"; for (int i = 0; i < DisplayServer::get_singleton()->get_screen_count(); i++) { screen_hints += ",Monitor " + itos(i + 1); } _initial_set("run/window_placement/rect_custom_position", Vector2()); _initial_set("run/window_placement/screen", 0); hints["run/window_placement/screen"] = PropertyInfo(Variant::INT, "run/window_placement/screen", PROPERTY_HINT_ENUM, screen_hints); // Auto save _initial_set("run/auto_save/save_before_running", true); // Output _initial_set("run/output/font_size", 13); hints["run/output/font_size"] = PropertyInfo(Variant::INT, "run/output/font_size", PROPERTY_HINT_RANGE, "8,48,1"); _initial_set("run/output/always_clear_output_on_play", true); _initial_set("run/output/always_open_output_on_play", true); _initial_set("run/output/always_close_output_on_stop", false); /* Network */ // Debug _initial_set("network/debug/remote_host", "127.0.0.1"); // Hints provided in setup_network _initial_set("network/debug/remote_port", 6007); hints["network/debug/remote_port"] = PropertyInfo(Variant::INT, "network/debug/remote_port", PROPERTY_HINT_RANGE, "1,65535,1"); // SSL _initial_set("network/ssl/editor_ssl_certificates", _SYSTEM_CERTS_PATH); hints["network/ssl/editor_ssl_certificates"] = PropertyInfo(Variant::STRING, "network/ssl/editor_ssl_certificates", PROPERTY_HINT_GLOBAL_FILE, "*.crt,*.pem"); /* Extra config */ _initial_set("project_manager/sorting_order", 0); hints["project_manager/sorting_order"] = PropertyInfo(Variant::INT, "project_manager/sorting_order", PROPERTY_HINT_ENUM, "Name,Path,Last Edited"); if (p_extra_config.is_valid()) { if (p_extra_config->has_section("init_projects") && p_extra_config->has_section_key("init_projects", "list")) { Vector<String> list = p_extra_config->get_value("init_projects", "list"); for (int i = 0; i < list.size(); i++) { String name = list[i].replace("/", "::"); set("projects/" + name, list[i]); }; }; if (p_extra_config->has_section("presets")) { List<String> keys; p_extra_config->get_section_keys("presets", &keys); for (List<String>::Element *E = keys.front(); E; E = E->next()) { String key = E->get(); Variant val = p_extra_config->get_value("presets", key); set(key, val); }; }; }; } void EditorSettings::_load_default_text_editor_theme() { bool dark_theme = is_dark_theme(); _initial_set("text_editor/highlighting/symbol_color", Color(0.73, 0.87, 1.0)); _initial_set("text_editor/highlighting/keyword_color", Color(1.0, 1.0, 0.7)); _initial_set("text_editor/highlighting/base_type_color", Color(0.64, 1.0, 0.83)); _initial_set("text_editor/highlighting/engine_type_color", Color(0.51, 0.83, 1.0)); _initial_set("text_editor/highlighting/user_type_color", Color(0.42, 0.67, 0.93)); _initial_set("text_editor/highlighting/comment_color", Color(0.4, 0.4, 0.4)); _initial_set("text_editor/highlighting/string_color", Color(0.94, 0.43, 0.75)); _initial_set("text_editor/highlighting/background_color", dark_theme ? Color(0.0, 0.0, 0.0, 0.23) : Color(0.2, 0.23, 0.31)); _initial_set("text_editor/highlighting/completion_background_color", Color(0.17, 0.16, 0.2)); _initial_set("text_editor/highlighting/completion_selected_color", Color(0.26, 0.26, 0.27)); _initial_set("text_editor/highlighting/completion_existing_color", Color(0.13, 0.87, 0.87, 0.87)); _initial_set("text_editor/highlighting/completion_scroll_color", Color(1, 1, 1)); _initial_set("text_editor/highlighting/completion_font_color", Color(0.67, 0.67, 0.67)); _initial_set("text_editor/highlighting/text_color", Color(0.67, 0.67, 0.67)); _initial_set("text_editor/highlighting/line_number_color", Color(0.67, 0.67, 0.67, 0.4)); _initial_set("text_editor/highlighting/safe_line_number_color", Color(0.67, 0.78, 0.67, 0.6)); _initial_set("text_editor/highlighting/caret_color", Color(0.67, 0.67, 0.67)); _initial_set("text_editor/highlighting/caret_background_color", Color(0, 0, 0)); _initial_set("text_editor/highlighting/text_selected_color", Color(0, 0, 0)); _initial_set("text_editor/highlighting/selection_color", Color(0.41, 0.61, 0.91, 0.35)); _initial_set("text_editor/highlighting/brace_mismatch_color", Color(1, 0.2, 0.2)); _initial_set("text_editor/highlighting/current_line_color", Color(0.3, 0.5, 0.8, 0.15)); _initial_set("text_editor/highlighting/line_length_guideline_color", Color(0.3, 0.5, 0.8, 0.1)); _initial_set("text_editor/highlighting/word_highlighted_color", Color(0.8, 0.9, 0.9, 0.15)); _initial_set("text_editor/highlighting/number_color", Color(0.92, 0.58, 0.2)); _initial_set("text_editor/highlighting/function_color", Color(0.4, 0.64, 0.81)); _initial_set("text_editor/highlighting/member_variable_color", Color(0.9, 0.31, 0.35)); _initial_set("text_editor/highlighting/mark_color", Color(1.0, 0.4, 0.4, 0.4)); _initial_set("text_editor/highlighting/bookmark_color", Color(0.08, 0.49, 0.98)); _initial_set("text_editor/highlighting/breakpoint_color", Color(0.9, 0.29, 0.3)); _initial_set("text_editor/highlighting/executing_line_color", Color(0.98, 0.89, 0.27)); _initial_set("text_editor/highlighting/code_folding_color", Color(0.8, 0.8, 0.8, 0.8)); _initial_set("text_editor/highlighting/search_result_color", Color(0.05, 0.25, 0.05, 1)); _initial_set("text_editor/highlighting/search_result_border_color", Color(0.41, 0.61, 0.91, 0.38)); } bool EditorSettings::_save_text_editor_theme(String p_file) { String theme_section = "color_theme"; Ref<ConfigFile> cf = memnew(ConfigFile); // hex is better? List<String> keys; props.get_key_list(&keys); keys.sort(); for (const List<String>::Element *E = keys.front(); E; E = E->next()) { const String &key = E->get(); if (key.begins_with("text_editor/highlighting/") && key.find("color") >= 0) { cf->set_value(theme_section, key.replace("text_editor/highlighting/", ""), ((Color)props[key].variant).to_html()); } } Error err = cf->save(p_file); return err == OK; } bool EditorSettings::_is_default_text_editor_theme(String p_theme_name) { return p_theme_name == "default" || p_theme_name == "adaptive" || p_theme_name == "custom"; } static Dictionary _get_builtin_script_templates() { Dictionary templates; // No Comments templates["no_comments.gd"] = "extends %BASE%\n" "\n" "\n" "func _ready()%VOID_RETURN%:\n" "%TS%pass\n"; // Empty templates["empty.gd"] = "extends %BASE%" "\n" "\n"; return templates; } static void _create_script_templates(const String &p_path) { Dictionary templates = _get_builtin_script_templates(); List<Variant> keys; templates.get_key_list(&keys); FileAccess *file = FileAccess::create(FileAccess::ACCESS_FILESYSTEM); DirAccess *dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); dir->change_dir(p_path); for (int i = 0; i < keys.size(); i++) { if (!dir->file_exists(keys[i])) { Error err = file->reopen(p_path.plus_file((String)keys[i]), FileAccess::WRITE); ERR_FAIL_COND(err != OK); file->store_string(templates[keys[i]]); file->close(); } } memdelete(dir); memdelete(file); } // PUBLIC METHODS EditorSettings *EditorSettings::get_singleton() { return singleton.ptr(); } void EditorSettings::create() { if (singleton.ptr()) { return; //pointless } DirAccess *dir = nullptr; String data_path; String data_dir; String config_path; String config_dir; String cache_path; String cache_dir; Ref<ConfigFile> extra_config = memnew(ConfigFile); String exe_path = OS::get_singleton()->get_executable_path().get_base_dir(); DirAccess *d = DirAccess::create_for_path(exe_path); bool self_contained = false; if (d->file_exists(exe_path + "/._sc_")) { self_contained = true; Error err = extra_config->load(exe_path + "/._sc_"); if (err != OK) { ERR_PRINT("Can't load config from path '" + exe_path + "/._sc_'."); } } else if (d->file_exists(exe_path + "/_sc_")) { self_contained = true; Error err = extra_config->load(exe_path + "/_sc_"); if (err != OK) { ERR_PRINT("Can't load config from path '" + exe_path + "/_sc_'."); } } memdelete(d); if (self_contained) { // editor is self contained, all in same folder data_path = exe_path; data_dir = data_path.plus_file("editor_data"); config_path = exe_path; config_dir = data_dir; cache_path = exe_path; cache_dir = data_dir.plus_file("cache"); } else { // Typically XDG_DATA_HOME or %APPDATA% data_path = OS::get_singleton()->get_data_path(); data_dir = data_path.plus_file(OS::get_singleton()->get_godot_dir_name()); // Can be different from data_path e.g. on Linux or macOS config_path = OS::get_singleton()->get_config_path(); config_dir = config_path.plus_file(OS::get_singleton()->get_godot_dir_name()); // Can be different from above paths, otherwise a subfolder of data_dir cache_path = OS::get_singleton()->get_cache_path(); if (cache_path == data_path) { cache_dir = data_dir.plus_file("cache"); } else { cache_dir = cache_path.plus_file(OS::get_singleton()->get_godot_dir_name()); } } ClassDB::register_class<EditorSettings>(); //otherwise it can't be unserialized String config_file_path; if (data_path != "" && config_path != "" && cache_path != "") { // Validate/create data dir and subdirectories dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); if (dir->change_dir(data_dir) != OK) { dir->make_dir_recursive(data_dir); if (dir->change_dir(data_dir) != OK) { ERR_PRINT("Cannot create data directory!"); memdelete(dir); goto fail; } } if (dir->change_dir("templates") != OK) { dir->make_dir("templates"); } else { dir->change_dir(".."); } // Validate/create cache dir if (dir->change_dir(cache_dir) != OK) { dir->make_dir_recursive(cache_dir); if (dir->change_dir(cache_dir) != OK) { ERR_PRINT("Cannot create cache directory!"); memdelete(dir); goto fail; } } // Validate/create config dir and subdirectories if (dir->change_dir(config_dir) != OK) { dir->make_dir_recursive(config_dir); if (dir->change_dir(config_dir) != OK) { ERR_PRINT("Cannot create config directory!"); memdelete(dir); goto fail; } } if (dir->change_dir("text_editor_themes") != OK) { dir->make_dir("text_editor_themes"); } else { dir->change_dir(".."); } if (dir->change_dir("script_templates") != OK) { dir->make_dir("script_templates"); } else { dir->change_dir(".."); } if (dir->change_dir("feature_profiles") != OK) { dir->make_dir("feature_profiles"); } else { dir->change_dir(".."); } _create_script_templates(dir->get_current_dir().plus_file("script_templates")); { // Validate/create project-specific editor settings dir. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (da->change_dir(EditorSettings::PROJECT_EDITOR_SETTINGS_PATH) != OK) { Error err = da->make_dir_recursive(EditorSettings::PROJECT_EDITOR_SETTINGS_PATH); if (err || da->change_dir(EditorSettings::PROJECT_EDITOR_SETTINGS_PATH) != OK) { ERR_FAIL_MSG("Failed to create '" + EditorSettings::PROJECT_EDITOR_SETTINGS_PATH + "' folder."); } } } // Validate editor config file String config_file_name = "editor_settings-" + itos(VERSION_MAJOR) + ".tres"; config_file_path = config_dir.plus_file(config_file_name); if (!dir->file_exists(config_file_name)) { memdelete(dir); goto fail; } memdelete(dir); singleton = ResourceLoader::load(config_file_path, "EditorSettings"); if (singleton.is_null()) { WARN_PRINT("Could not open config file."); goto fail; } singleton->save_changed_setting = true; singleton->config_file_path = config_file_path; singleton->settings_dir = config_dir; singleton->data_dir = data_dir; singleton->cache_dir = cache_dir; print_verbose("EditorSettings: Load OK!"); singleton->setup_language(); singleton->setup_network(); singleton->load_favorites(); singleton->list_text_editor_themes(); return; } fail: // patch init projects if (extra_config->has_section("init_projects")) { Vector<String> list = extra_config->get_value("init_projects", "list"); for (int i = 0; i < list.size(); i++) { list.write[i] = exe_path.plus_file(list[i]); }; extra_config->set_value("init_projects", "list", list); }; singleton = Ref<EditorSettings>(memnew(EditorSettings)); singleton->save_changed_setting = true; singleton->config_file_path = config_file_path; singleton->settings_dir = config_dir; singleton->data_dir = data_dir; singleton->cache_dir = cache_dir; singleton->_load_defaults(extra_config); singleton->setup_language(); singleton->setup_network(); singleton->list_text_editor_themes(); } void EditorSettings::setup_language() { String lang = get("interface/editor/editor_language"); if (lang == "en") { return; // Default, nothing to do. } // Load editor translation for configured/detected locale. EditorTranslationList *etl = _editor_translations; while (etl->data) { if (etl->lang == lang) { Vector<uint8_t> data; data.resize(etl->uncomp_size); Compression::decompress(data.ptrw(), etl->uncomp_size, etl->data, etl->comp_size, Compression::MODE_DEFLATE); FileAccessMemory *fa = memnew(FileAccessMemory); fa->open_custom(data.ptr(), data.size()); Ref<Translation> tr = TranslationLoaderPO::load_translation(fa); if (tr.is_valid()) { tr->set_locale(etl->lang); TranslationServer::get_singleton()->set_tool_translation(tr); break; } } etl++; } // Load class reference translation. DocTranslationList *dtl = _doc_translations; while (dtl->data) { if (dtl->lang == lang) { Vector<uint8_t> data; data.resize(dtl->uncomp_size); Compression::decompress(data.ptrw(), dtl->uncomp_size, dtl->data, dtl->comp_size, Compression::MODE_DEFLATE); FileAccessMemory *fa = memnew(FileAccessMemory); fa->open_custom(data.ptr(), data.size()); Ref<Translation> tr = TranslationLoaderPO::load_translation(fa); if (tr.is_valid()) { tr->set_locale(dtl->lang); TranslationServer::get_singleton()->set_doc_translation(tr); break; } } dtl++; } } void EditorSettings::setup_network() { List<IP_Address> local_ip; IP::get_singleton()->get_local_addresses(&local_ip); String hint; String current = has_setting("network/debug/remote_host") ? get("network/debug/remote_host") : ""; String selected = "127.0.0.1"; // Check that current remote_host is a valid interface address and populate hints. for (List<IP_Address>::Element *E = local_ip.front(); E; E = E->next()) { String ip = E->get(); // link-local IPv6 addresses don't work, skipping them if (ip.begins_with("fe80:0:0:0:")) { // fe80::/64 continue; } // Same goes for IPv4 link-local (APIPA) addresses. if (ip.begins_with("169.254.")) { // 169.254.0.0/16 continue; } // Select current IP (found) if (ip == current) { selected = ip; } if (hint != "") { hint += ","; } hint += ip; } // Add hints with valid IP addresses to remote_host property. add_property_hint(PropertyInfo(Variant::STRING, "network/debug/remote_host", PROPERTY_HINT_ENUM, hint)); // Fix potentially invalid remote_host due to network change. set("network/debug/remote_host", selected); } void EditorSettings::save() { //_THREAD_SAFE_METHOD_ if (!singleton.ptr()) { return; } if (singleton->config_file_path == "") { ERR_PRINT("Cannot save EditorSettings config, no valid path"); return; } Error err = ResourceSaver::save(singleton->config_file_path, singleton); if (err != OK) { ERR_PRINT("Error saving editor settings to " + singleton->config_file_path); } else { print_verbose("EditorSettings: Save OK!"); } } void EditorSettings::destroy() { if (!singleton.ptr()) { return; } save(); singleton = Ref<EditorSettings>(); } void EditorSettings::set_optimize_save(bool p_optimize) { optimize_save = p_optimize; } // Properties void EditorSettings::set_setting(const String &p_setting, const Variant &p_value) { _THREAD_SAFE_METHOD_ set(p_setting, p_value); } Variant EditorSettings::get_setting(const String &p_setting) const { _THREAD_SAFE_METHOD_ return get(p_setting); } bool EditorSettings::has_setting(const String &p_setting) const { _THREAD_SAFE_METHOD_ return props.has(p_setting); } void EditorSettings::erase(const String &p_setting) { _THREAD_SAFE_METHOD_ props.erase(p_setting); } void EditorSettings::raise_order(const String &p_setting) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND(!props.has(p_setting)); props[p_setting].order = ++last_order; } void EditorSettings::set_restart_if_changed(const StringName &p_setting, bool p_restart) { _THREAD_SAFE_METHOD_ if (!props.has(p_setting)) { return; } props[p_setting].restart_if_changed = p_restart; } void EditorSettings::set_initial_value(const StringName &p_setting, const Variant &p_value, bool p_update_current) { _THREAD_SAFE_METHOD_ if (!props.has(p_setting)) { return; } props[p_setting].initial = p_value; props[p_setting].has_default_value = true; if (p_update_current) { set(p_setting, p_value); } } Variant _EDITOR_DEF(const String &p_setting, const Variant &p_default, bool p_restart_if_changed) { Variant ret = p_default; if (EditorSettings::get_singleton()->has_setting(p_setting)) { ret = EditorSettings::get_singleton()->get(p_setting); } else { EditorSettings::get_singleton()->set_manually(p_setting, p_default); EditorSettings::get_singleton()->set_restart_if_changed(p_setting, p_restart_if_changed); } if (!EditorSettings::get_singleton()->has_default_value(p_setting)) { EditorSettings::get_singleton()->set_initial_value(p_setting, p_default); } return ret; } Variant _EDITOR_GET(const String &p_setting) { ERR_FAIL_COND_V(!EditorSettings::get_singleton()->has_setting(p_setting), Variant()); return EditorSettings::get_singleton()->get(p_setting); } bool EditorSettings::property_can_revert(const String &p_setting) { if (!props.has(p_setting)) { return false; } if (!props[p_setting].has_default_value) { return false; } return props[p_setting].initial != props[p_setting].variant; } Variant EditorSettings::property_get_revert(const String &p_setting) { if (!props.has(p_setting) || !props[p_setting].has_default_value) { return Variant(); } return props[p_setting].initial; } void EditorSettings::add_property_hint(const PropertyInfo &p_hint) { _THREAD_SAFE_METHOD_ hints[p_hint.name] = p_hint; } // Data directories String EditorSettings::get_data_dir() const { return data_dir; } String EditorSettings::get_templates_dir() const { return get_data_dir().plus_file("templates"); } // Config directories String EditorSettings::get_settings_dir() const { return settings_dir; } String EditorSettings::get_project_settings_dir() const { return EditorSettings::PROJECT_EDITOR_SETTINGS_PATH; } String EditorSettings::get_text_editor_themes_dir() const { return get_settings_dir().plus_file("text_editor_themes"); } String EditorSettings::get_script_templates_dir() const { return get_settings_dir().plus_file("script_templates"); } String EditorSettings::get_project_script_templates_dir() const { return ProjectSettings::get_singleton()->get("editor/script/templates_search_path"); } // Cache directory String EditorSettings::get_cache_dir() const { return cache_dir; } String EditorSettings::get_feature_profiles_dir() const { return get_settings_dir().plus_file("feature_profiles"); } // Metadata void EditorSettings::set_project_metadata(const String &p_section, const String &p_key, Variant p_data) { Ref<ConfigFile> cf = memnew(ConfigFile); String path = get_project_settings_dir().plus_file("project_metadata.cfg"); Error err; err = cf->load(path); ERR_FAIL_COND_MSG(err != OK && err != ERR_FILE_NOT_FOUND, "Cannot load editor settings from file '" + path + "'."); cf->set_value(p_section, p_key, p_data); err = cf->save(path); ERR_FAIL_COND_MSG(err != OK, "Cannot save editor settings to file '" + path + "'."); } Variant EditorSettings::get_project_metadata(const String &p_section, const String &p_key, Variant p_default) const { Ref<ConfigFile> cf = memnew(ConfigFile); String path = get_project_settings_dir().plus_file("project_metadata.cfg"); Error err = cf->load(path); if (err != OK) { return p_default; } return cf->get_value(p_section, p_key, p_default); } void EditorSettings::set_favorites(const Vector<String> &p_favorites) { favorites = p_favorites; FileAccess *f = FileAccess::open(get_project_settings_dir().plus_file("favorites"), FileAccess::WRITE); if (f) { for (int i = 0; i < favorites.size(); i++) { f->store_line(favorites[i]); } memdelete(f); } } Vector<String> EditorSettings::get_favorites() const { return favorites; } void EditorSettings::set_recent_dirs(const Vector<String> &p_recent_dirs) { recent_dirs = p_recent_dirs; FileAccess *f = FileAccess::open(get_project_settings_dir().plus_file("recent_dirs"), FileAccess::WRITE); if (f) { for (int i = 0; i < recent_dirs.size(); i++) { f->store_line(recent_dirs[i]); } memdelete(f); } } Vector<String> EditorSettings::get_recent_dirs() const { return recent_dirs; } void EditorSettings::load_favorites() { FileAccess *f = FileAccess::open(get_project_settings_dir().plus_file("favorites"), FileAccess::READ); if (f) { String line = f->get_line().strip_edges(); while (line != "") { favorites.push_back(line); line = f->get_line().strip_edges(); } memdelete(f); } f = FileAccess::open(get_project_settings_dir().plus_file("recent_dirs"), FileAccess::READ); if (f) { String line = f->get_line().strip_edges(); while (line != "") { recent_dirs.push_back(line); line = f->get_line().strip_edges(); } memdelete(f); } } bool EditorSettings::is_dark_theme() { int AUTO_COLOR = 0; int LIGHT_COLOR = 2; Color base_color = get("interface/theme/base_color"); int icon_font_color_setting = get("interface/theme/icon_and_font_color"); return (icon_font_color_setting == AUTO_COLOR && ((base_color.r + base_color.g + base_color.b) / 3.0) < 0.5) || icon_font_color_setting == LIGHT_COLOR; } void EditorSettings::list_text_editor_themes() { String themes = "Adaptive,Default,Custom"; DirAccess *d = DirAccess::open(get_text_editor_themes_dir()); if (d) { List<String> custom_themes; d->list_dir_begin(); String file = d->get_next(); while (file != String()) { if (file.get_extension() == "tet" && !_is_default_text_editor_theme(file.get_basename().to_lower())) { custom_themes.push_back(file.get_basename()); } file = d->get_next(); } d->list_dir_end(); memdelete(d); custom_themes.sort(); for (List<String>::Element *E = custom_themes.front(); E; E = E->next()) { themes += "," + E->get(); } } add_property_hint(PropertyInfo(Variant::STRING, "text_editor/theme/color_theme", PROPERTY_HINT_ENUM, themes)); } void EditorSettings::load_text_editor_theme() { String p_file = get("text_editor/theme/color_theme"); if (_is_default_text_editor_theme(p_file.get_file().to_lower())) { if (p_file == "Default") { _load_default_text_editor_theme(); } return; // sorry for "Settings changed" console spam } String theme_path = get_text_editor_themes_dir().plus_file(p_file + ".tet"); Ref<ConfigFile> cf = memnew(ConfigFile); Error err = cf->load(theme_path); if (err != OK) { return; } List<String> keys; cf->get_section_keys("color_theme", &keys); for (List<String>::Element *E = keys.front(); E; E = E->next()) { String key = E->get(); String val = cf->get_value("color_theme", key); // don't load if it's not already there! if (has_setting("text_editor/highlighting/" + key)) { // make sure it is actually a color if (val.is_valid_html_color() && key.find("color") >= 0) { props["text_editor/highlighting/" + key].variant = Color::html(val); // change manually to prevent "Settings changed" console spam } } } emit_signal("settings_changed"); // if it doesn't load just use what is currently loaded } bool EditorSettings::import_text_editor_theme(String p_file) { if (!p_file.ends_with(".tet")) { return false; } else { if (p_file.get_file().to_lower() == "default.tet") { return false; } DirAccess *d = DirAccess::open(get_text_editor_themes_dir()); if (d) { d->copy(p_file, get_text_editor_themes_dir().plus_file(p_file.get_file())); memdelete(d); return true; } } return false; } bool EditorSettings::save_text_editor_theme() { String p_file = get("text_editor/theme/color_theme"); if (_is_default_text_editor_theme(p_file.get_file().to_lower())) { return false; } String theme_path = get_text_editor_themes_dir().plus_file(p_file + ".tet"); return _save_text_editor_theme(theme_path); } bool EditorSettings::save_text_editor_theme_as(String p_file) { if (!p_file.ends_with(".tet")) { p_file += ".tet"; } if (_is_default_text_editor_theme(p_file.get_file().to_lower().trim_suffix(".tet"))) { return false; } if (_save_text_editor_theme(p_file)) { // switch to theme is saved in the theme directory list_text_editor_themes(); String theme_name = p_file.substr(0, p_file.length() - 4).get_file(); if (p_file.get_base_dir() == get_text_editor_themes_dir()) { _initial_set("text_editor/theme/color_theme", theme_name); load_text_editor_theme(); } return true; } return false; } bool EditorSettings::is_default_text_editor_theme() { String p_file = get("text_editor/theme/color_theme"); return _is_default_text_editor_theme(p_file.get_file().to_lower()); } Vector<String> EditorSettings::get_script_templates(const String &p_extension, const String &p_custom_path) { Vector<String> templates; String template_dir = get_script_templates_dir(); if (!p_custom_path.is_empty()) { template_dir = p_custom_path; } DirAccess *d = DirAccess::open(template_dir); if (d) { d->list_dir_begin(); String file = d->get_next(); while (file != String()) { if (file.get_extension() == p_extension) { templates.push_back(file.get_basename()); } file = d->get_next(); } d->list_dir_end(); memdelete(d); } return templates; } String EditorSettings::get_editor_layouts_config() const { return get_settings_dir().plus_file("editor_layouts.cfg"); } // Shortcuts void EditorSettings::add_shortcut(const String &p_name, Ref<Shortcut> &p_shortcut) { shortcuts[p_name] = p_shortcut; } bool EditorSettings::is_shortcut(const String &p_name, const Ref<InputEvent> &p_event) const { const Map<String, Ref<Shortcut>>::Element *E = shortcuts.find(p_name); ERR_FAIL_COND_V_MSG(!E, false, "Unknown Shortcut: " + p_name + "."); return E->get()->is_shortcut(p_event); } Ref<Shortcut> EditorSettings::get_shortcut(const String &p_name) const { const Map<String, Ref<Shortcut>>::Element *SC = shortcuts.find(p_name); if (SC) { return SC->get(); } // If no shortcut with the provided name is found in the list, check the built-in shortcuts. // Use the first item in the action list for the shortcut event, since a shortcut can only have 1 linked event. Ref<Shortcut> sc; const Map<String, List<Ref<InputEvent>>>::Element *builtin_override = builtin_action_overrides.find(p_name); if (builtin_override) { sc.instance(); sc->set_shortcut(builtin_override->get().front()->get()); sc->set_name(InputMap::get_singleton()->get_builtin_display_name(p_name)); } // If there was no override, check the default builtins to see if it has an InputEvent for the provided name. if (sc.is_null()) { const OrderedHashMap<String, List<Ref<InputEvent>>>::ConstElement builtin_default = InputMap::get_singleton()->get_builtins().find(p_name); if (builtin_default) { sc.instance(); sc->set_shortcut(builtin_default.get().front()->get()); sc->set_name(InputMap::get_singleton()->get_builtin_display_name(p_name)); } } if (sc.is_valid()) { // Add the shortcut to the list. shortcuts[p_name] = sc; return sc; } return Ref<Shortcut>(); } void EditorSettings::get_shortcut_list(List<String> *r_shortcuts) { for (const Map<String, Ref<Shortcut>>::Element *E = shortcuts.front(); E; E = E->next()) { r_shortcuts->push_back(E->key()); } } Ref<Shortcut> ED_GET_SHORTCUT(const String &p_path) { if (!EditorSettings::get_singleton()) { return nullptr; } Ref<Shortcut> sc = EditorSettings::get_singleton()->get_shortcut(p_path); ERR_FAIL_COND_V_MSG(!sc.is_valid(), sc, "Used ED_GET_SHORTCUT with invalid shortcut: " + p_path + "."); return sc; } Ref<Shortcut> ED_SHORTCUT(const String &p_path, const String &p_name, uint32_t p_keycode) { #ifdef OSX_ENABLED // Use Cmd+Backspace as a general replacement for Delete shortcuts on macOS if (p_keycode == KEY_DELETE) { p_keycode = KEY_MASK_CMD | KEY_BACKSPACE; } #endif Ref<InputEventKey> ie; if (p_keycode) { ie.instance(); ie->set_unicode(p_keycode & KEY_CODE_MASK); ie->set_keycode(p_keycode & KEY_CODE_MASK); ie->set_shift(bool(p_keycode & KEY_MASK_SHIFT)); ie->set_alt(bool(p_keycode & KEY_MASK_ALT)); ie->set_control(bool(p_keycode & KEY_MASK_CTRL)); ie->set_metakey(bool(p_keycode & KEY_MASK_META)); } if (!EditorSettings::get_singleton()) { Ref<Shortcut> sc; sc.instance(); sc->set_name(p_name); sc->set_shortcut(ie); sc->set_meta("original", ie); return sc; } Ref<Shortcut> sc = EditorSettings::get_singleton()->get_shortcut(p_path); if (sc.is_valid()) { sc->set_name(p_name); //keep name (the ones that come from disk have no name) sc->set_meta("original", ie); //to compare against changes return sc; } sc.instance(); sc->set_name(p_name); sc->set_shortcut(ie); sc->set_meta("original", ie); //to compare against changes EditorSettings::get_singleton()->add_shortcut(p_path, sc); return sc; } void EditorSettings::set_builtin_action_override(const String &p_name, const Array &p_events) { List<Ref<InputEvent>> event_list; // Override the whole list, since events may have their order changed or be added, removed or edited. InputMap::get_singleton()->action_erase_events(p_name); for (int i = 0; i < p_events.size(); i++) { event_list.push_back(p_events[i]); InputMap::get_singleton()->action_add_event(p_name, p_events[i]); } // Check if the provided event array is same as built-in. If it is, it does not need to be added to the overrides. // Note that event order must also be the same. bool same_as_builtin = true; OrderedHashMap<String, List<Ref<InputEvent>>>::ConstElement builtin_default = InputMap::get_singleton()->get_builtins().find(p_name); if (builtin_default) { List<Ref<InputEvent>> builtin_events = builtin_default.get(); if (p_events.size() == builtin_events.size()) { int event_idx = 0; // Check equality of each event. for (List<Ref<InputEvent>>::Element *E = builtin_events.front(); E; E = E->next()) { if (!E->get()->shortcut_match(p_events[event_idx])) { same_as_builtin = false; break; } event_idx++; } } else { same_as_builtin = false; } } if (same_as_builtin && builtin_action_overrides.has(p_name)) { builtin_action_overrides.erase(p_name); } else { builtin_action_overrides[p_name] = event_list; } // Update the shortcut (if it is used somewhere in the editor) to be the first event of the new list. if (shortcuts.has(p_name)) { shortcuts[p_name]->set_shortcut(event_list.front()->get()); } } const Array EditorSettings::get_builtin_action_overrides(const String &p_name) const { const Map<String, List<Ref<InputEvent>>>::Element *AO = builtin_action_overrides.find(p_name); if (AO) { Array event_array; List<Ref<InputEvent>> events_list = AO->get(); for (List<Ref<InputEvent>>::Element *E = events_list.front(); E; E = E->next()) { event_array.push_back(E->get()); } return event_array; } return Array(); } void EditorSettings::notify_changes() { _THREAD_SAFE_METHOD_ SceneTree *sml = Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop()); if (!sml) { return; } Node *root = sml->get_root()->get_child(0); if (!root) { return; } root->propagate_notification(NOTIFICATION_EDITOR_SETTINGS_CHANGED); } void EditorSettings::_bind_methods() { ClassDB::bind_method(D_METHOD("has_setting", "name"), &EditorSettings::has_setting); ClassDB::bind_method(D_METHOD("set_setting", "name", "value"), &EditorSettings::set_setting); ClassDB::bind_method(D_METHOD("get_setting", "name"), &EditorSettings::get_setting); ClassDB::bind_method(D_METHOD("erase", "property"), &EditorSettings::erase); ClassDB::bind_method(D_METHOD("set_initial_value", "name", "value", "update_current"), &EditorSettings::set_initial_value); ClassDB::bind_method(D_METHOD("property_can_revert", "name"), &EditorSettings::property_can_revert); ClassDB::bind_method(D_METHOD("property_get_revert", "name"), &EditorSettings::property_get_revert); ClassDB::bind_method(D_METHOD("add_property_info", "info"), &EditorSettings::_add_property_info_bind); ClassDB::bind_method(D_METHOD("get_settings_dir"), &EditorSettings::get_settings_dir); ClassDB::bind_method(D_METHOD("get_project_settings_dir"), &EditorSettings::get_project_settings_dir); ClassDB::bind_method(D_METHOD("set_project_metadata", "section", "key", "data"), &EditorSettings::set_project_metadata); ClassDB::bind_method(D_METHOD("get_project_metadata", "section", "key", "default"), &EditorSettings::get_project_metadata, DEFVAL(Variant())); ClassDB::bind_method(D_METHOD("set_favorites", "dirs"), &EditorSettings::set_favorites); ClassDB::bind_method(D_METHOD("get_favorites"), &EditorSettings::get_favorites); ClassDB::bind_method(D_METHOD("set_recent_dirs", "dirs"), &EditorSettings::set_recent_dirs); ClassDB::bind_method(D_METHOD("get_recent_dirs"), &EditorSettings::get_recent_dirs); ClassDB::bind_method(D_METHOD("set_builtin_action_override", "name", "actions_list"), &EditorSettings::set_builtin_action_override); ADD_SIGNAL(MethodInfo("settings_changed")); BIND_CONSTANT(NOTIFICATION_EDITOR_SETTINGS_CHANGED); } EditorSettings::EditorSettings() { last_order = 0; optimize_save = true; save_changed_setting = true; _load_defaults(); } EditorSettings::~EditorSettings() { }
#include "SGDP4.h" #include "Vector.h" #include "SatelliteException.h" #include <cmath> #include <iomanip> #define AE (1.0) #define Q0 (120.0) #define S0 (78.0) #define XKMPER (6378.135) #define XJ2 (1.082616e-3) #define XJ3 (-2.53881e-6) #define XJ4 (-1.65597e-6) #define XKE (7.43669161331734132e-2) #define CK2 (0.5 * XJ2 * AE * AE) #define CK4 (-0.375 * XJ4 * AE * AE * AE * AE) #define QOMS2T (1.880279159015270643865e-9) #define S (AE * (1.0 + S0 / XKMPER)) #define PI (3.14159265358979323846264338327950288419716939937510582) #define TWOPI (2.0 * PI) #define TWOTHIRD (2.0 / 3.0) #define THDT (4.37526908801129966e-3) SGDP4::SGDP4(void) { first_run_ = true; } SGDP4::~SGDP4(void) { } void SGDP4::SetTle(const Tle& tle) { /* * reset all constants etc */ ResetGlobalVariables(); /* * extract and format tle data */ mean_anomoly_ = tle.GetField(Tle::FLD_M, Tle::U_RAD); ascending_node_ = tle.GetField(Tle::FLD_RAAN, Tle::U_RAD); argument_perigee_ = tle.GetField(Tle::FLD_ARGPER, Tle::U_RAD); eccentricity_ = tle.GetField(Tle::FLD_E); inclination_ = tle.GetField(Tle::FLD_I, Tle::U_RAD); mean_motion_ = tle.GetField(Tle::FLD_MMOTION) * TWOPI / Globals::MIN_PER_DAY(); bstar_ = tle.GetField(Tle::FLD_BSTAR); epoch_ = tle.GetEpoch(); /* * error checks */ if (eccentricity_ < 0.0 || eccentricity_ > 1.0 - 1.0e-3) { throw new SatelliteException("Eccentricity out of range"); } if (inclination_ < 0.0 || eccentricity_ > PI) { throw new SatelliteException("Inclination out of range"); } /* * recover original mean motion (xnodp) and semimajor axis (aodp) * from input elements */ const double a1 = pow(XKE / MeanMotion(), TWOTHIRD); i_cosio_ = cos(Inclination()); i_sinio_ = sin(Inclination()); const double theta2 = i_cosio_ * i_cosio_; i_x3thm1_ = 3.0 * theta2 - 1.0; const double eosq = Eccentricity() * Eccentricity(); const double betao2 = 1.0 - eosq; const double betao = sqrt(betao2); const double temp = (1.5 * CK2) * i_x3thm1_ / (betao * betao2); const double del1 = temp / (a1 * a1); const double a0 = a1 * (1.0 - del1 * (1.0 / 3.0 + del1 * (1.0 + del1 * 134.0 / 81.0))); const double del0 = temp / (a0 * a0); recovered_mean_motion_ = MeanMotion() / (1.0 + del0); recovered_semi_major_axis_ = a0 / (1.0 - del0); /* * find perigee and period */ perigee_ = (RecoveredSemiMajorAxis() * (1.0 - Eccentricity()) - AE) * XKMPER; period_ = TWOPI / RecoveredMeanMotion(); Initialize(theta2, betao2, betao, eosq); } void SGDP4::Initialize(const double& theta2, const double& betao2, const double& betao, const double& eosq) { if (Period() >= 225.0) { i_use_deep_space_ = true; } else { i_use_deep_space_ = false; i_use_simple_model_ = false; /* * for perigee less than 220 kilometers, the simple_model flag is set and * the equations are truncated to linear variation in sqrt a and * quadratic variation in mean anomly. also, the c3 term, the * delta omega term and the delta m term are dropped */ if (Perigee() < 220.0) { i_use_simple_model_ = true; } } /* * for perigee below 156km, the values of * s4 and qoms2t are altered */ double s4 = S; double qoms24 = QOMS2T; if (Perigee() < 156.0) { s4 = Perigee() - 78.0; if (Perigee() < 98.0) { s4 = 20.0; } qoms24 = pow((120.0 - s4) * AE / XKMPER, 4.0); s4 = s4 / XKMPER + AE; } /* * generate constants */ const double pinvsq = 1.0 / (RecoveredSemiMajorAxis() * RecoveredSemiMajorAxis() * betao2 * betao2); const double tsi = 1.0 / (RecoveredSemiMajorAxis() - s4); i_eta_ = RecoveredSemiMajorAxis() * Eccentricity() * tsi; const double etasq = i_eta_ * i_eta_; const double eeta = Eccentricity() * i_eta_; const double psisq = fabs(1.0 - etasq); const double coef = qoms24 * pow(tsi, 4.0); const double coef1 = coef / pow(psisq, 3.5); const double c2 = coef1 * RecoveredMeanMotion() * (RecoveredSemiMajorAxis() * (1.0 + 1.5 * etasq + eeta * (4.0 + etasq)) + 0.75 * CK2 * tsi / psisq * i_x3thm1_ * (8.0 + 3.0 * etasq * (8.0 + etasq))); i_c1_ = BStar() * c2; i_a3ovk2_ = -XJ3 / CK2 * pow(AE, 3.0); i_x1mth2_ = 1.0 - theta2; i_c4_ = 2.0 * RecoveredMeanMotion() * coef1 * RecoveredSemiMajorAxis() * betao2 * (i_eta_ * (2.0 + 0.5 * etasq) + Eccentricity() * (0.5 + 2.0 * etasq) - 2.0 * CK2 * tsi / (RecoveredSemiMajorAxis() * psisq) * (-3.0 * i_x3thm1_ * (1.0 - 2.0 * eeta + etasq * (1.5 - 0.5 * eeta)) + 0.75 * i_x1mth2_ * (2.0 * etasq - eeta * (1.0 + etasq)) * cos(2.0 * ArgumentPerigee()))); const double theta4 = theta2 * theta2; const double temp1 = 3.0 * CK2 * pinvsq * RecoveredMeanMotion(); const double temp2 = temp1 * CK2 * pinvsq; const double temp3 = 1.25 * CK4 * pinvsq * pinvsq * RecoveredMeanMotion(); i_xmdot_ = RecoveredMeanMotion() + 0.5 * temp1 * betao * i_x3thm1_ + 0.0625 * temp2 * betao * (13.0 - 78.0 * theta2 + 137.0 * theta4); const double x1m5th = 1.0 - 5.0 * theta2; i_omgdot_ = -0.5 * temp1 * x1m5th + 0.0625 * temp2 * (7.0 - 114.0 * theta2 + 395.0 * theta4) + temp3 * (3.0 - 36.0 * theta2 + 49.0 * theta4); const double xhdot1_ = -temp1 * i_cosio_; i_xnodot_ = xhdot1_ + (0.5 * temp2 * (4.0 - 19.0 * theta2) + 2.0 * temp3 * (3.0 - 7.0 * theta2)) * i_cosio_; i_xnodcf_ = 3.5 * betao2 * xhdot1_ * i_c1_; i_t2cof_ = 1.5 * i_c1_; if (fabs(i_cosio_ + 1.0) > 1.5e-12) i_xlcof_ = 0.125 * i_a3ovk2_ * i_sinio_ * (3.0 + 5.0 * i_cosio_) / (1.0 + i_cosio_); else i_xlcof_ = 0.125 * i_a3ovk2_ * i_sinio_ * (3.0 + 5.0 * i_cosio_) / 1.5e-12; i_aycof_ = 0.25 * i_a3ovk2_ * i_sinio_; i_x7thm1_ = 7.0 * theta2 - 1.0; if (i_use_deep_space_) { d_gsto_ = Epoch().ToGreenwichSiderealTime(); DeepSpaceInitialize(eosq, i_sinio_, i_cosio_, betao, theta2, betao2, i_xmdot_, i_omgdot_, i_xnodot_); } else { double c3 = 0.0; if (Eccentricity() > 1.0e-4) { c3 = coef * tsi * i_a3ovk2_ * RecoveredMeanMotion() * AE * i_sinio_ / Eccentricity(); } n_c5_ = 2.0 * coef1 * RecoveredSemiMajorAxis() * betao2 * (1.0 + 2.75 * (etasq + eeta) + eeta * etasq); n_omgcof_ = BStar() * c3 * cos(ArgumentPerigee()); n_xmcof_ = 0.0; if (Eccentricity() > 1.0e-4) n_xmcof_ = -TWOTHIRD * coef * BStar() * AE / eeta; n_delmo_ = pow(1.0 + i_eta_ * (cos(MeanAnomoly())), 3.0); n_sinmo_ = sin(MeanAnomoly()); if (!i_use_simple_model_) { const double c1sq = i_c1_ * i_c1_; n_d2_ = 4.0 * RecoveredSemiMajorAxis() * tsi * c1sq; const double temp = n_d2_ * tsi * i_c1_ / 3.0; n_d3_ = (17.0 * RecoveredSemiMajorAxis() + s4) * temp; n_d4_ = 0.5 * temp * RecoveredSemiMajorAxis() * tsi * (221.0 * RecoveredSemiMajorAxis() + 31.0 * s4) * i_c1_; n_t3cof_ = n_d2_ + 2.0 * c1sq; n_t4cof_ = 0.25 * (3.0 * n_d3_ + i_c1_ * (12.0 * n_d2_ + 10.0 * c1sq)); n_t5cof_ = 0.2 * (3.0 * n_d4_ + 12.0 * i_c1_ * n_d3_ + 6.0 * n_d2_ * n_d2_ + 15.0 * c1sq * (2.0 * n_d2_ + c1sq)); } } first_run_ = false; } void SGDP4::FindPosition(Eci& eci, double tsince) { Julian tsince_epoch = Epoch(); tsince_epoch.AddMin(tsince); double actual_tsince = tsince_epoch.SpanMin(Epoch()); if (i_use_deep_space_) FindPositionSDP4(eci, actual_tsince); else FindPositionSGP4(eci, actual_tsince); } void SGDP4::FindPositionSDP4(Eci& eci, double tsince) const { /* * the final values */ double e; double a; double omega; double xl; double xnode; double xincl; /* * update for secular gravity and atmospheric drag */ double xmdf = MeanAnomoly() + i_xmdot_ * tsince; double omgadf = ArgumentPerigee() + i_omgdot_ * tsince; const double xnoddf = AscendingNode() + i_xnodot_ * tsince; const double tsq = tsince * tsince; xnode = xnoddf + i_xnodcf_ * tsq; double tempa = 1.0 - i_c1_ * tsince; double tempe = BStar() * i_c4_ * tsince; double templ = i_t2cof_ * tsq; double xn = RecoveredMeanMotion(); e = Eccentricity(); xincl = Inclination(); DeepSpaceSecular(tsince, xmdf, omgadf, xnode, e, xincl, xn); if (xn <= 0.0) { throw new SatelliteException("Error: 2 (xn <= 0.0)"); } a = pow(XKE / xn, TWOTHIRD) * pow(tempa, 2.0); e = e - tempe; /* * fix tolerance for error recognition */ if (e >= 1.0 || e < -0.001) { throw new SatelliteException("Error: 1 (e >= 1.0 || e < -0.001)"); } /* * fix tolerance to avoid a divide by zero */ if (e < 1.0e-6) e = 1.0e-6; /* xmdf += RecoveredMeanMotion() * templ; double xlm = xmdf + omgadf + xnode; xnode = fmod(xnode, TWOPI); omgadf = fmod(omgadf, TWOPI); xlm = fmod(xlm, TWOPI); double xmam = fmod(xlm - omgadf - xnode, TWOPI); */ double xmam = xmdf + RecoveredMeanMotion() * templ; DeepSpacePeriodics(tsince, e, xincl, omgadf, xnode, xmam); /* * keeping xincl positive important unless you need to display xincl * and dislike negative inclinations */ if (xincl < 0.0) { xincl = -xincl; xnode += PI; omgadf = omgadf - PI; } xl = xmam + omgadf + xnode; omega = omgadf; if (e < 0.0 || e > 1.0) { throw new SatelliteException("Error: 3 (e < 0.0 || e > 1.0)"); } /* * re-compute the perturbed values */ const double perturbed_sinio = sin(xincl); const double perturbed_cosio = cos(xincl); const double perturbed_theta2 = perturbed_cosio * perturbed_cosio; const double perturbed_x3thm1 = 3.0 * perturbed_theta2 - 1.0; const double perturbed_x1mth2 = 1.0 - perturbed_theta2; const double perturbed_x7thm1 = 7.0 * perturbed_theta2 - 1.0; double perturbed_xlcof; if (fabs(perturbed_cosio + 1.0) > 1.5e-12) perturbed_xlcof = 0.125 * i_a3ovk2_ * perturbed_sinio * (3.0 + 5.0 * perturbed_cosio) / (1.0 + perturbed_cosio); else perturbed_xlcof = 0.125 * i_a3ovk2_ * perturbed_sinio * (3.0 + 5.0 * perturbed_cosio) / 1.5e-12; const double perturbed_aycof = 0.25 * i_a3ovk2_ * perturbed_sinio; /* * using calculated values, find position and velocity */ CalculateFinalPositionVelocity(eci, tsince, e, a, omega, xl, xnode, xincl, perturbed_xlcof, perturbed_aycof, perturbed_x3thm1, perturbed_x1mth2, perturbed_x7thm1, perturbed_cosio, perturbed_sinio); } void SGDP4::FindPositionSGP4(Eci& eci, double tsince) const { /* * the final values */ double e; double a; double omega; double xl; double xnode; double xincl; /* * update for secular gravity and atmospheric drag */ const double xmdf = MeanAnomoly() + i_xmdot_ * tsince; const double omgadf = ArgumentPerigee() + i_omgdot_ * tsince; const double xnoddf = AscendingNode() + i_xnodot_ * tsince; const double tsq = tsince * tsince; xnode = xnoddf + i_xnodcf_ * tsq; double tempa = 1.0 - i_c1_ * tsince; double tempe = BStar() * i_c4_ * tsince; double templ = i_t2cof_ * tsq; xincl = Inclination(); omega = omgadf; double xmp = xmdf; if (!i_use_simple_model_) { const double delomg = n_omgcof_ * tsince; const double delm = n_xmcof_ * (pow(1.0 + i_eta_ * cos(xmdf), 3.0) - n_delmo_); const double temp = delomg + delm; xmp += temp; omega = omega - temp; const double tcube = tsq * tsince; const double tfour = tsince * tcube; tempa = tempa - n_d2_ * tsq - n_d3_ * tcube - n_d4_ * tfour; tempe += BStar() * n_c5_ * (sin(xmp) - n_sinmo_); templ += n_t3cof_ * tcube + tfour * (n_t4cof_ + tsince * n_t5cof_); } a = RecoveredSemiMajorAxis() * pow(tempa, 2.0); e = Eccentricity() - tempe; xl = xmp + omega + xnode + RecoveredMeanMotion() * templ; /* * using calculated values, find position and velocity * we can pass in constants from Initialize() as these dont change */ CalculateFinalPositionVelocity(eci, tsince, e, a, omega, xl, xnode, xincl, i_xlcof_, i_aycof_, i_x3thm1_, i_x1mth2_, i_x7thm1_, i_cosio_, i_sinio_); } void SGDP4::CalculateFinalPositionVelocity(Eci& eci, const double& tsince, const double& e, const double& a, const double& omega, const double& xl, const double& xnode, const double& xincl, const double& xlcof, const double& aycof, const double& x3thm1, const double& x1mth2, const double& x7thm1, const double& cosio, const double& sinio) const { double temp; double temp1; double temp2; double temp3; if (a < 1.0) { throw new SatelliteException("Error: Satellite crashed (a < 1.0)"); } if (e < -1.0e-3) { throw new SatelliteException("Error: Modified eccentricity too low (e < -1.0e-3)"); } const double beta = sqrt(1.0 - e * e); const double xn = XKE / pow(a, 1.5); /* * long period periodics */ const double axn = e * cos(omega); temp = 1.0 / (a * beta * beta); const double xll = temp * xlcof * axn; const double aynl = temp * aycof; const double xlt = xl + xll; const double ayn = e * sin(omega) + aynl; const double elsq = axn * axn + ayn * ayn; if (elsq >= 1.0) { throw new SatelliteException("Error: sqrt(e) >= 1 (elsq >= 1.0)"); } /* * solve keplers equation * - solve using Newton-Raphson root solving * - here capu is almost the mean anomoly * - initialise the eccentric anomaly term epw * - The fmod saves reduction of angle to +/-2pi in sin/cos() and prevents * convergence problems. */ const double capu = fmod(xlt - xnode, TWOPI); double epw = capu; double sinepw = 0.0; double cosepw = 0.0; double ecose = 0.0; double esine = 0.0; /* * sensibility check for N-R correction */ const double max_newton_naphson = 1.25 * fabs(sqrt(elsq)); bool kepler_running = true; for (int i = 0; i < 10 && kepler_running; i++) { sinepw = sin(epw); cosepw = cos(epw); ecose = axn * cosepw + ayn * sinepw; esine = axn * sinepw - ayn * cosepw; double f = capu - epw + esine; if (fabs(f) < 1.0e-12) { kepler_running = false; } else { /* * 1st order Newton-Raphson correction */ const double fdot = 1.0 - ecose; double delta_epw = f / fdot; /* * 2nd order Newton-Raphson correction. * f / (fdot - 0.5 * d2f * f/fdot) */ if (i == 0) { if (delta_epw > max_newton_naphson) delta_epw = max_newton_naphson; else if (delta_epw < -max_newton_naphson) delta_epw = -max_newton_naphson; } else { delta_epw = f / (fdot + 0.5 * esine * delta_epw); } /* * Newton-Raphson correction of -F/DF */ epw += delta_epw; } } /* * short period preliminary quantities */ temp = 1.0 - elsq; const double pl = a * temp; const double r = a * (1.0 - ecose); temp1 = 1.0 / r; const double rdot = XKE * sqrt(a) * esine * temp1; const double rfdot = XKE * sqrt(pl) * temp1; temp2 = a * temp1; const double betal = sqrt(temp); temp3 = 1.0 / (1.0 + betal); const double cosu = temp2 * (cosepw - axn + ayn * esine * temp3); const double sinu = temp2 * (sinepw - ayn - axn * esine * temp3); const double u = atan2(sinu, cosu); const double sin2u = 2.0 * sinu * cosu; const double cos2u = 2.0 * cosu * cosu - 1.0; temp = 1.0 / pl; temp1 = CK2 * temp; temp2 = temp1 * temp; /* * update for short periodics */ const double rk = r * (1.0 - 1.5 * temp2 * betal * x3thm1) + 0.5 * temp1 * x1mth2 * cos2u; const double uk = u - 0.25 * temp2 * x7thm1 * sin2u; const double xnodek = xnode + 1.5 * temp2 * cosio * sin2u; const double xinck = xincl + 1.5 * temp2 * cosio * sinio * cos2u; const double rdotk = rdot - xn * temp1 * x1mth2 * sin2u; const double rfdotk = rfdot + xn * temp1 * (x1mth2 * cos2u + 1.5 * x3thm1); if (rk < 0.0) { throw new SatelliteException("Error: satellite decayed (rk < 0.0)"); } /* * orientation vectors */ const double sinuk = sin(uk); const double cosuk = cos(uk); const double sinik = sin(xinck); const double cosik = cos(xinck); const double sinnok = sin(xnodek); const double cosnok = cos(xnodek); const double xmx = -sinnok * cosik; const double xmy = cosnok * cosik; const double ux = xmx * sinuk + cosnok * cosuk; const double uy = xmy * sinuk + sinnok * cosuk; const double uz = sinik * sinuk; const double vx = xmx * cosuk - cosnok * sinuk; const double vy = xmy * cosuk - sinnok * sinuk; const double vz = sinik * cosuk; /* * position and velocity */ const double x = rk * ux * XKMPER; const double y = rk * uy * XKMPER; const double z = rk * uz * XKMPER; Vector position(x, y, z); const double xdot = (rdotk * ux + rfdotk * vx) * XKMPER / 60.0; const double ydot = (rdotk * uy + rfdotk * vy) * XKMPER / 60.0; const double zdot = (rdotk * uz + rfdotk * vz) * XKMPER / 60.0; Vector velocity(xdot, ydot, zdot); Julian julian = Epoch(); julian.AddMin(tsince); eci = Eci(julian, position, velocity); } /* * deep space initialization */ void SGDP4::DeepSpaceInitialize(const double& eosq, const double& sinio, const double& cosio, const double& betao, const double& theta2, const double& betao2, const double& xmdot, const double& omgdot, const double& xnodot) { double se = 0.0; double si = 0.0; double sl = 0.0; double sgh = 0.0; double shdq = 0.0; double bfact = 0.0; static const double ZNS = 1.19459E-5; static const double C1SS = 2.9864797E-6; static const double ZES = 0.01675; static const double ZNL = 1.5835218E-4; static const double C1L = 4.7968065E-7; static const double ZEL = 0.05490; static const double ZCOSIS = 0.91744867; static const double ZSINI = 0.39785416; static const double ZSINGS = -0.98088458; static const double ZCOSGS = 0.1945905; static const double Q22 = 1.7891679E-6; static const double Q31 = 2.1460748E-6; static const double Q33 = 2.2123015E-7; static const double ROOT22 = 1.7891679E-6; static const double ROOT32 = 3.7393792E-7; static const double ROOT44 = 7.3636953E-9; static const double ROOT52 = 1.1428639E-7; static const double ROOT54 = 2.1765803E-9; const double aqnv = 1.0 / RecoveredSemiMajorAxis(); const double xpidot = omgdot + xnodot; const double sinq = sin(AscendingNode()); const double cosq = cos(AscendingNode()); const double sing = sin(ArgumentPerigee()); const double cosg = cos(ArgumentPerigee()); /* * initialize lunar / solar terms */ const double d_day_ = Epoch().FromJan1_12h_1900(); const double xnodce = 4.5236020 - 9.2422029e-4 * d_day_; const double xnodce_temp = fmod(xnodce, TWOPI); const double stem = sin(xnodce_temp); const double ctem = cos(xnodce_temp); const double zcosil = 0.91375164 - 0.03568096 * ctem; const double zsinil = sqrt(1.0 - zcosil * zcosil); const double zsinhl = 0.089683511 * stem / zsinil; const double zcoshl = sqrt(1.0 - zsinhl * zsinhl); const double c = 4.7199672 + 0.22997150 * d_day_; const double gam = 5.8351514 + 0.0019443680 * d_day_; d_zmol_ = Globals::Fmod2p(c - gam); double zx = 0.39785416 * stem / zsinil; double zy = zcoshl * ctem + 0.91744867 * zsinhl * stem; zx = atan2(zx, zy); zx = fmod(gam + zx - xnodce, TWOPI); const double zcosgl = cos(zx); const double zsingl = sin(zx); d_zmos_ = Globals::Fmod2p(6.2565837 + 0.017201977 * d_day_); /* * do solar terms */ double zcosg = ZCOSGS; double zsing = ZSINGS; double zcosi = ZCOSIS; double zsini = ZSINI; double zcosh = cosq; double zsinh = sinq; double cc = C1SS; double zn = ZNS; double ze = ZES; const double xnoi = 1.0 / RecoveredMeanMotion(); for (int cnt = 0; cnt < 2; cnt++) { /* * solar terms are done a second time after lunar terms are done */ const double a1 = zcosg * zcosh + zsing * zcosi * zsinh; const double a3 = -zsing * zcosh + zcosg * zcosi * zsinh; const double a7 = -zcosg * zsinh + zsing * zcosi * zcosh; const double a8 = zsing * zsini; const double a9 = zsing * zsinh + zcosg * zcosi*zcosh; const double a10 = zcosg * zsini; const double a2 = cosio * a7 + sinio * a8; const double a4 = cosio * a9 + sinio * a10; const double a5 = -sinio * a7 + cosio * a8; const double a6 = -sinio * a9 + cosio * a10; const double x1 = a1 * cosg + a2 * sing; const double x2 = a3 * cosg + a4 * sing; const double x3 = -a1 * sing + a2 * cosg; const double x4 = -a3 * sing + a4 * cosg; const double x5 = a5 * sing; const double x6 = a6 * sing; const double x7 = a5 * cosg; const double x8 = a6 * cosg; const double z31 = 12.0 * x1 * x1 - 3. * x3 * x3; const double z32 = 24.0 * x1 * x2 - 6. * x3 * x4; const double z33 = 12.0 * x2 * x2 - 3. * x4 * x4; double z1 = 3.0 * (a1 * a1 + a2 * a2) + z31 * eosq; double z2 = 6.0 * (a1 * a3 + a2 * a4) + z32 * eosq; double z3 = 3.0 * (a3 * a3 + a4 * a4) + z33 * eosq; const double z11 = -6.0 * a1 * a5 + eosq * (-24. * x1 * x7 - 6. * x3 * x5); const double z12 = -6.0 * (a1 * a6 + a3 * a5) + eosq * (-24. * (x2 * x7 + x1 * x8) - 6. * (x3 * x6 + x4 * x5)); const double z13 = -6.0 * a3 * a6 + eosq * (-24. * x2 * x8 - 6. * x4 * x6); const double z21 = 6.0 * a2 * a5 + eosq * (24. * x1 * x5 - 6. * x3 * x7); const double z22 = 6.0 * (a4 * a5 + a2 * a6) + eosq * (24. * (x2 * x5 + x1 * x6) - 6. * (x4 * x7 + x3 * x8)); const double z23 = 6.0 * a4 * a6 + eosq * (24. * x2 * x6 - 6. * x4 * x8); z1 = z1 + z1 + betao2 * z31; z2 = z2 + z2 + betao2 * z32; z3 = z3 + z3 + betao2 * z33; const double s3 = cc * xnoi; const double s2 = -0.5 * s3 / betao; const double s4 = s3 * betao; const double s1 = -15.0 * Eccentricity() * s4; const double s5 = x1 * x3 + x2 * x4; const double s6 = x2 * x3 + x1 * x4; const double s7 = x2 * x4 - x1 * x3; se = s1 * zn * s5; si = s2 * zn * (z11 + z13); sl = -zn * s3 * (z1 + z3 - 14.0 - 6.0 * eosq); sgh = s4 * zn * (z31 + z33 - 6.0); /* * replaced * sh = -zn * s2 * (z21 + z23 * with * shdq = (-zn * s2 * (z21 + z23)) / sinio */ if (Inclination() < 5.2359877e-2 || Inclination() > PI - 5.2359877e-2) { shdq = 0.0; } else { shdq = (-zn * s2 * (z21 + z23)) / sinio; } d_ee2_ = 2.0 * s1 * s6; d_e3_ = 2.0 * s1 * s7; d_xi2_ = 2.0 * s2 * z12; d_xi3_ = 2.0 * s2 * (z13 - z11); d_xl2_ = -2.0 * s3 * z2; d_xl3_ = -2.0 * s3 * (z3 - z1); d_xl4_ = -2.0 * s3 * (-21.0 - 9.0 * eosq) * ze; d_xgh2_ = 2.0 * s4 * z32; d_xgh3_ = 2.0 * s4 * (z33 - z31); d_xgh4_ = -18.0 * s4 * ze; d_xh2_ = -2.0 * s2 * z22; d_xh3_ = -2.0 * s2 * (z23 - z21); if (cnt == 1) break; /* * do lunar terms */ d_sse_ = se; d_ssi_ = si; d_ssl_ = sl; d_ssh_ = shdq; d_ssg_ = sgh - cosio * d_ssh_; d_se2_ = d_ee2_; d_si2_ = d_xi2_; d_sl2_ = d_xl2_; d_sgh2_ = d_xgh2_; d_sh2_ = d_xh2_; d_se3_ = d_e3_; d_si3_ = d_xi3_; d_sl3_ = d_xl3_; d_sgh3_ = d_xgh3_; d_sh3_ = d_xh3_; d_sl4_ = d_xl4_; d_sgh4_ = d_xgh4_; zcosg = zcosgl; zsing = zsingl; zcosi = zcosil; zsini = zsinil; zcosh = zcoshl * cosq + zsinhl * sinq; zsinh = sinq * zcoshl - cosq * zsinhl; zn = ZNL; cc = C1L; ze = ZEL; } d_sse_ += se; d_ssi_ += si; d_ssl_ += sl; d_ssg_ += sgh - cosio * shdq; d_ssh_ += shdq; d_resonance_flag_ = false; d_synchronous_flag_ = false; bool initialize_integrator = true; if (RecoveredMeanMotion() < 0.0052359877 && RecoveredMeanMotion() > 0.0034906585) { /* * 24h synchronous resonance terms initialization */ d_resonance_flag_ = true; d_synchronous_flag_ = true; const double g200 = 1.0 + eosq * (-2.5 + 0.8125 * eosq); const double g310 = 1.0 + 2.0 * eosq; const double g300 = 1.0 + eosq * (-6.0 + 6.60937 * eosq); const double f220 = 0.75 * (1.0 + cosio) * (1.0 + cosio); const double f311 = 0.9375 * sinio * sinio * (1.0 + 3.0 * cosio) - 0.75 * (1.0 + cosio); double f330 = 1.0 + cosio; f330 = 1.875 * f330 * f330 * f330; d_del1_ = 3.0 * RecoveredMeanMotion() * RecoveredMeanMotion() * aqnv * aqnv; d_del2_ = 2.0 * d_del1_ * f220 * g200 * Q22; d_del3_ = 3.0 * d_del1_ * f330 * g300 * Q33 * aqnv; d_del1_ = d_del1_ * f311 * g310 * Q31 * aqnv; d_fasx2_ = 0.13130908; d_fasx4_ = 2.8843198; d_fasx6_ = 0.37448087; d_xlamo_ = MeanAnomoly() + AscendingNode() + ArgumentPerigee() - d_gsto_; bfact = xmdot + xpidot - THDT; bfact += d_ssl_ + d_ssg_ + d_ssh_; } else if (RecoveredMeanMotion() < 8.26e-3 || RecoveredMeanMotion() > 9.24e-3 || Eccentricity() < 0.5) { initialize_integrator = false; } else { /* * geopotential resonance initialization for 12 hour orbits */ d_resonance_flag_ = true; const double eoc = Eccentricity() * eosq; double g211; double g310; double g322; double g410; double g422; double g520; double g201 = -0.306 - (Eccentricity() - 0.64) * 0.440; if (Eccentricity() <= 0.65) { g211 = 3.616 - 13.247 * Eccentricity() + 16.290 * eosq; g310 = -19.302 + 117.390 * Eccentricity() - 228.419 * eosq + 156.591 * eoc; g322 = -18.9068 + 109.7927 * Eccentricity() - 214.6334 * eosq + 146.5816 * eoc; g410 = -41.122 + 242.694 * Eccentricity() - 471.094 * eosq + 313.953 * eoc; g422 = -146.407 + 841.880 * Eccentricity() - 1629.014 * eosq + 1083.435 * eoc; g520 = -532.114 + 3017.977 * Eccentricity() - 5740 * eosq + 3708.276 * eoc; } else { g211 = -72.099 + 331.819 * Eccentricity() - 508.738 * eosq + 266.724 * eoc; g310 = -346.844 + 1582.851 * Eccentricity() - 2415.925 * eosq + 1246.113 * eoc; g322 = -342.585 + 1554.908 * Eccentricity() - 2366.899 * eosq + 1215.972 * eoc; g410 = -1052.797 + 4758.686 * Eccentricity() - 7193.992 * eosq + 3651.957 * eoc; g422 = -3581.69 + 16178.11 * Eccentricity() - 24462.77 * eosq + 12422.52 * eoc; if (Eccentricity() <= 0.715) { g520 = 1464.74 - 4664.75 * Eccentricity() + 3763.64 * eosq; } else { g520 = -5149.66 + 29936.92 * Eccentricity() - 54087.36 * eosq + 31324.56 * eoc; } } double g533; double g521; double g532; if (Eccentricity() < 0.7) { g533 = -919.2277 + 4988.61 * Eccentricity() - 9064.77 * eosq + 5542.21 * eoc; g521 = -822.71072 + 4568.6173 * Eccentricity() - 8491.4146 * eosq + 5337.524 * eoc; g532 = -853.666 + 4690.25 * Eccentricity() - 8624.77 * eosq + 5341.4 * eoc; } else { g533 = -37995.78 + 161616.52 * Eccentricity() - 229838.2 * eosq + 109377.94 * eoc; g521 = -51752.104 + 218913.95 * Eccentricity() - 309468.16 * eosq + 146349.42 * eoc; g532 = -40023.88 + 170470.89 * Eccentricity() - 242699.48 * eosq + 115605.82 * eoc; } const double sini2 = sinio * sinio; const double f220 = 0.75 * (1.0 + 2.0 * cosio + theta2); const double f221 = 1.5 * sini2; const double f321 = 1.875 * sinio * (1.0 - 2.0 * cosio - 3.0 * theta2); const double f322 = -1.875 * sinio * (1.0 + 2.0 * cosio - 3.0 * theta2); const double f441 = 35.0 * sini2 * f220; const double f442 = 39.3750 * sini2 * sini2; const double f522 = 9.84375 * sinio * (sini2 * (1.0 - 2.0 * cosio - 5.0 * theta2) + 0.33333333 * (-2.0 + 4.0 * cosio + 6.0 * theta2)); const double f523 = sinio * (4.92187512 * sini2 * (-2.0 - 4.0 * cosio + 10.0 * theta2) + 6.56250012 * (1.0 + 2.0 * cosio - 3.0 * theta2)); const double f542 = 29.53125 * sinio * (2.0 - 8.0 * cosio + theta2 * (-12.0 + 8.0 * cosio + 10.0 * theta2)); const double f543 = 29.53125 * sinio * (-2.0 - 8.0 * cosio + theta2 * (12.0 + 8.0 * cosio - 10.0 * theta2)); const double xno2 = RecoveredMeanMotion() * RecoveredMeanMotion(); const double ainv2 = aqnv * aqnv; double temp1 = 3.0 * xno2 * ainv2; double temp = temp1 * ROOT22; d_d2201_ = temp * f220 * g201; d_d2211_ = temp * f221 * g211; temp1 = temp1 * aqnv; temp = temp1 * ROOT32; d_d3210_ = temp * f321 * g310; d_d3222_ = temp * f322 * g322; temp1 = temp1 * aqnv; temp = 2.0 * temp1 * ROOT44; d_d4410_ = temp * f441 * g410; d_d4422_ = temp * f442 * g422; temp1 = temp1 * aqnv; temp = temp1 * ROOT52; d_d5220_ = temp * f522 * g520; d_d5232_ = temp * f523 * g532; temp = 2.0 * temp1 * ROOT54; d_d5421_ = temp * f542 * g521; d_d5433_ = temp * f543 * g533; d_xlamo_ = MeanAnomoly() + AscendingNode() + AscendingNode() - d_gsto_ - d_gsto_; bfact = xmdot + xnodot + xnodot - THDT - THDT; bfact = bfact + d_ssl_ + d_ssh_ + d_ssh_; } if (initialize_integrator) { /* * initialize integrator */ d_xfact_ = bfact - RecoveredMeanMotion(); d_atime_ = 0.0; d_xni_ = RecoveredMeanMotion(); d_xli_ = d_xlamo_; } } void SGDP4::DeepSpaceCalculateLunarSolarTerms(const double t, double& pe, double& pinc, double& pl, double& pgh, double& ph) const { static const double ZES = 0.01675; static const double ZNS = 1.19459E-5; static const double ZNL = 1.5835218E-4; static const double ZEL = 0.05490; /* * calculate solar terms for time t */ double zm = d_zmos_ + ZNS * t; if (first_run_) zm = d_zmos_; double zf = zm + 2.0 * ZES * sin(zm); double sinzf = sin(zf); double f2 = 0.5 * sinzf * sinzf - 0.25; double f3 = -0.5 * sinzf * cos(zf); const double ses = d_se2_ * f2 + d_se3_ * f3; const double sis = d_si2_ * f2 + d_si3_ * f3; const double sls = d_sl2_ * f2 + d_sl3_ * f3 + d_sl4_ * sinzf; const double sghs = d_sgh2_ * f2 + d_sgh3_ * f3 + d_sgh4_ * sinzf; const double shs = d_sh2_ * f2 + d_sh3_ * f3; /* * calculate lunar terms for time t */ zm = d_zmol_ + ZNL * t; if (first_run_) zm = d_zmol_; zf = zm + 2.0 * ZEL * sin(zm); sinzf = sin(zf); f2 = 0.5 * sinzf * sinzf - 0.25; f3 = -0.5 * sinzf * cos(zf); const double sel = d_ee2_ * f2 + d_e3_ * f3; const double sil = d_xi2_ * f2 + d_xi3_ * f3; const double sll = d_xl2_ * f2 + d_xl3_ * f3 + d_xl4_ * sinzf; const double sghl = d_xgh2_ * f2 + d_xgh3_ * f3 + d_xgh4_ * sinzf; const double shl = d_xh2_ * f2 + d_xh3_ * f3; /* * merge calculated values */ pe = ses + sel; pinc = sis + sil; pl = sls + sll; pgh = sghs + sghl; ph = shs + shl; } /* * calculate lunar / solar periodics and apply */ void SGDP4::DeepSpacePeriodics(const double& t, double& em, double& xinc, double& omgasm, double& xnodes, double& xll) const { /* * storage for lunar / solar terms set by DeepSpaceCalculateLunarSolarTerms() */ double pe = 0.0; double pinc = 0.0; double pl = 0.0; double pgh = 0.0; double ph = 0.0; /* * calculate lunar / solar terms for current time */ DeepSpaceCalculateLunarSolarTerms(t, pe, pinc, pl, pgh, ph); if (!first_run_) { xinc += pinc; em += pe; /* Spacetrack report #3 has sin/cos from before perturbations * added to xinc (oldxinc), but apparently report # 6 has then * from after they are added. * use for strn3 * if (Inclination() >= 0.2) * use for gsfc * if (xinc >= 0.2) * (moved from start of function) */ const double sinis = sin(xinc); const double cosis = cos(xinc); if (xinc >= 0.2) { /* * apply periodics directly */ const double tmp_ph = ph / sinis; omgasm += pgh - cosis * tmp_ph; xnodes += tmp_ph; xll += pl; } else { /* * apply periodics with lyddane modification */ const double sinok = sin(xnodes); const double cosok = cos(xnodes); double alfdp = sinis * sinok; double betdp = sinis * cosok; const double dalf = ph * cosok + pinc * cosis * sinok; const double dbet = -ph * sinok + pinc * cosis * cosok; alfdp += dalf; betdp += dbet; double xls = xll + omgasm + cosis * xnodes; double dls = pl + pgh - pinc * xnodes * sinis; xls += dls; /* * save old xnodes value */ const double oldxnodes = xnodes; xnodes = atan2(alfdp, betdp); /* * Get perturbed xnodes in to same quadrant as original. * RAAN is in the range of 0 to 360 degrees * atan2 is in the range of -180 to 180 degrees */ if (fabs(oldxnodes - xnodes) > PI) { if (xnodes < oldxnodes) xnodes += TWOPI; else xnodes = xnodes - TWOPI; } xll += pl; omgasm = xls - xll - cosis * xnodes; } } } /* * deep space secular effects */ void SGDP4::DeepSpaceSecular(const double& t, double& xll, double& omgasm, double& xnodes, double& em, double& xinc, double& xn) const { static const double STEP2 = 259200.0; static const double STEP = 720.0; double xldot = 0.0; double xndot = 0.0; double xnddt = 0.0; xll += d_ssl_ * t; omgasm += d_ssg_ * t; xnodes += d_ssh_ * t; em += d_sse_ * t; xinc += d_ssi_ * t; if (!d_resonance_flag_) return; /* * 1st condition (if t is less than one time step from epoch) * 2nd condition (if d_atime_ and t are of opposite signs, so zero crossing required) * 3rd condition (if t is closer to zero than d_atime_) */ if (fabs(t) < STEP || t * d_atime_ <= 0.0 || fabs(t) < fabs(d_atime_)) { /* * restart from epoch */ d_atime_ = 0.0; d_xni_ = RecoveredMeanMotion(); d_xli_ = d_xlamo_; } double ft = t - d_atime_; /* * if time difference (ft) is greater than the time step (720.0) * loop around until d_atime_ is within one time step of t */ if (fabs(ft) >= STEP) { /* * calculate step direction to allow d_atime_ * to catch up with t */ double delt = -STEP; if (ft >= 0.0) delt = STEP; do { DeepSpaceCalcIntegrator(delt, STEP2, xndot, xnddt, xldot); ft = t - d_atime_; } while (fabs(ft) >= STEP); } /* * calculate dot terms */ DeepSpaceCalcDotTerms(xndot, xnddt, xldot); /* * integrator */ xn = d_xni_ + xndot * ft + xnddt * ft * ft * 0.5; const double xl = d_xli_ + xldot * ft + xndot * ft * ft * 0.5; const double temp = -xnodes + d_gsto_ + t * THDT; if (d_synchronous_flag_) xll = xl + temp - omgasm; else xll = xl + temp + temp; } /* * calculate dot terms */ void SGDP4::DeepSpaceCalcDotTerms(double& xndot, double& xnddt, double& xldot) const { static const double G22 = 5.7686396; static const double G32 = 0.95240898; static const double G44 = 1.8014998; static const double G52 = 1.0508330; static const double G54 = 4.4108898; if (d_synchronous_flag_) { xndot = d_del1_ * sin(d_xli_ - d_fasx2_) + d_del2_ * sin(2.0 * (d_xli_ - d_fasx4_)) + d_del3_ * sin(3.0 * (d_xli_ - d_fasx6_)); xnddt = d_del1_ * cos(d_xli_ - d_fasx2_) + 2.0 * d_del2_ * cos(2.0 * (d_xli_ - d_fasx4_)) + 3.0 * d_del3_ * cos(3.0 * (d_xli_ - d_fasx6_)); } else { const double xomi = ArgumentPerigee() + i_omgdot_ * d_atime_; const double x2omi = xomi + xomi; const double x2li = d_xli_ + d_xli_; xndot = d_d2201_ * sin(x2omi + d_xli_ - G22) + d_d2211_ * sin(d_xli_ - G22) + d_d3210_ * sin(xomi + d_xli_ - G32) + d_d3222_ * sin(-xomi + d_xli_ - G32) + d_d4410_ * sin(x2omi + x2li - G44) + d_d4422_ * sin(x2li - G44) + d_d5220_ * sin(xomi + d_xli_ - G52) + d_d5232_ * sin(-xomi + d_xli_ - G52) + d_d5421_ * sin(xomi + x2li - G54) + d_d5433_ * sin(-xomi + x2li - G54); xnddt = d_d2201_ * cos(x2omi + d_xli_ - G22) + d_d2211_ * cos(d_xli_ - G22) + d_d3210_ * cos(xomi + d_xli_ - G32) + d_d3222_ * cos(-xomi + d_xli_ - G32) + d_d5220_ * cos(xomi + d_xli_ - G52) + d_d5232_ * cos(-xomi + d_xli_ - G52) + 2.0 * (d_d4410_ * cos(x2omi + x2li - G44) + d_d4422_ * cos(x2li - G44) + d_d5421_ * cos(xomi + x2li - G54) + d_d5433_ * cos(-xomi + x2li - G54)); } xldot = d_xni_ + d_xfact_; xnddt = xnddt * xldot; } /* * deep space integrator for time period of delt */ void SGDP4::DeepSpaceCalcIntegrator(const double& delt, const double& step2, double& xndot, double& xnddt, double& xldot) const { /* * calculate dot terms */ DeepSpaceCalcDotTerms(xndot, xnddt, xldot); /* * integrator */ d_xli_ += xldot * delt + xndot * step2; d_xni_ += xndot * delt + xnddt * step2; /* * increment integrator time */ d_atime_ += delt; } void SGDP4::ResetGlobalVariables() { /* * common variables */ first_run_ = true; i_use_simple_model_ = false; i_use_deep_space_ = false; i_cosio_ = i_sinio_ = i_eta_ = i_t2cof_ = i_a3ovk2_ = i_x1mth2_ = i_x3thm1_ = i_x7thm1_ = i_aycof_ = i_xlcof_ = i_xnodcf_ = i_c1_ = i_c4_ = i_omgdot_ = i_xnodot_ = i_xmdot_ = 0.0; /* * near space variables */ n_c5_ = n_omgcof_ = n_xmcof_ = n_delmo_ = n_sinmo_ = n_d2_ = n_d3_ = n_d4_ = n_t3cof_ = n_t4cof_ = n_t5cof_ = 0.0; /* * deep space variables */ d_gsto_ = d_zmol_ = d_zmos_ = 0.0; d_resonance_flag_ = false; d_synchronous_flag_ = false; d_sse_ = d_ssi_ = d_ssl_ = d_ssg_ = d_ssh_ = 0.0; d_se2_ = d_si2_ = d_sl2_ = d_sgh2_ = d_sh2_ = d_se3_ = d_si3_ = d_sl3_ = d_sgh3_ = d_sh3_ = d_sl4_ = d_sgh4_ = d_ee2_ = d_e3_ = d_xi2_ = d_xi3_ = d_xl2_ = d_xl3_ = d_xl4_ = d_xgh2_ = d_xgh3_ = d_xgh4_ = d_xh2_ = d_xh3_ = 0.0; d_d2201_ = d_d2211_ = d_d3210_ = d_d3222_ = d_d4410_ = d_d4422_ = d_d5220_ = d_d5232_ = d_d5421_ = d_d5433_ = d_del1_ = d_del2_ = d_del3_ = d_fasx2_ = d_fasx4_ = d_fasx6_ = 0.0; d_xfact_ = d_xlamo_ = d_xli_ = d_xni_ = d_atime_ = 0.0; mean_anomoly_ = ascending_node_ = argument_perigee_ = eccentricity_ = inclination_ = mean_motion_ = bstar_ = recovered_semi_major_axis_ = recovered_mean_motion_ = perigee_ = period_ = 0.0; epoch_ = Julian(); } Incorrect value #include "SGDP4.h" #include "Vector.h" #include "SatelliteException.h" #include <cmath> #include <iomanip> #define AE (1.0) #define Q0 (120.0) #define S0 (78.0) #define XKMPER (6378.135) #define XJ2 (1.082616e-3) #define XJ3 (-2.53881e-6) #define XJ4 (-1.65597e-6) #define XKE (7.43669161331734132e-2) #define CK2 (0.5 * XJ2 * AE * AE) #define CK4 (-0.375 * XJ4 * AE * AE * AE * AE) #define QOMS2T (1.880279159015270643865e-9) #define S (AE * (1.0 + S0 / XKMPER)) #define PI (3.14159265358979323846264338327950288419716939937510582) #define TWOPI (2.0 * PI) #define TWOTHIRD (2.0 / 3.0) #define THDT (4.37526908801129966e-3) SGDP4::SGDP4(void) { first_run_ = true; } SGDP4::~SGDP4(void) { } void SGDP4::SetTle(const Tle& tle) { /* * reset all constants etc */ ResetGlobalVariables(); /* * extract and format tle data */ mean_anomoly_ = tle.GetField(Tle::FLD_M, Tle::U_RAD); ascending_node_ = tle.GetField(Tle::FLD_RAAN, Tle::U_RAD); argument_perigee_ = tle.GetField(Tle::FLD_ARGPER, Tle::U_RAD); eccentricity_ = tle.GetField(Tle::FLD_E); inclination_ = tle.GetField(Tle::FLD_I, Tle::U_RAD); mean_motion_ = tle.GetField(Tle::FLD_MMOTION) * TWOPI / Globals::MIN_PER_DAY(); bstar_ = tle.GetField(Tle::FLD_BSTAR); epoch_ = tle.GetEpoch(); /* * error checks */ if (eccentricity_ < 0.0 || eccentricity_ > 1.0 - 1.0e-3) { throw new SatelliteException("Eccentricity out of range"); } if (inclination_ < 0.0 || eccentricity_ > PI) { throw new SatelliteException("Inclination out of range"); } /* * recover original mean motion (xnodp) and semimajor axis (aodp) * from input elements */ const double a1 = pow(XKE / MeanMotion(), TWOTHIRD); i_cosio_ = cos(Inclination()); i_sinio_ = sin(Inclination()); const double theta2 = i_cosio_ * i_cosio_; i_x3thm1_ = 3.0 * theta2 - 1.0; const double eosq = Eccentricity() * Eccentricity(); const double betao2 = 1.0 - eosq; const double betao = sqrt(betao2); const double temp = (1.5 * CK2) * i_x3thm1_ / (betao * betao2); const double del1 = temp / (a1 * a1); const double a0 = a1 * (1.0 - del1 * (1.0 / 3.0 + del1 * (1.0 + del1 * 134.0 / 81.0))); const double del0 = temp / (a0 * a0); recovered_mean_motion_ = MeanMotion() / (1.0 + del0); recovered_semi_major_axis_ = a0 / (1.0 - del0); /* * find perigee and period */ perigee_ = (RecoveredSemiMajorAxis() * (1.0 - Eccentricity()) - AE) * XKMPER; period_ = TWOPI / RecoveredMeanMotion(); Initialize(theta2, betao2, betao, eosq); } void SGDP4::Initialize(const double& theta2, const double& betao2, const double& betao, const double& eosq) { if (Period() >= 225.0) { i_use_deep_space_ = true; } else { i_use_deep_space_ = false; i_use_simple_model_ = false; /* * for perigee less than 220 kilometers, the simple_model flag is set and * the equations are truncated to linear variation in sqrt a and * quadratic variation in mean anomly. also, the c3 term, the * delta omega term and the delta m term are dropped */ if (Perigee() < 220.0) { i_use_simple_model_ = true; } } /* * for perigee below 156km, the values of * s4 and qoms2t are altered */ double s4 = S; double qoms24 = QOMS2T; if (Perigee() < 156.0) { s4 = Perigee() - 78.0; if (Perigee() < 98.0) { s4 = 20.0; } qoms24 = pow((120.0 - s4) * AE / XKMPER, 4.0); s4 = s4 / XKMPER + AE; } /* * generate constants */ const double pinvsq = 1.0 / (RecoveredSemiMajorAxis() * RecoveredSemiMajorAxis() * betao2 * betao2); const double tsi = 1.0 / (RecoveredSemiMajorAxis() - s4); i_eta_ = RecoveredSemiMajorAxis() * Eccentricity() * tsi; const double etasq = i_eta_ * i_eta_; const double eeta = Eccentricity() * i_eta_; const double psisq = fabs(1.0 - etasq); const double coef = qoms24 * pow(tsi, 4.0); const double coef1 = coef / pow(psisq, 3.5); const double c2 = coef1 * RecoveredMeanMotion() * (RecoveredSemiMajorAxis() * (1.0 + 1.5 * etasq + eeta * (4.0 + etasq)) + 0.75 * CK2 * tsi / psisq * i_x3thm1_ * (8.0 + 3.0 * etasq * (8.0 + etasq))); i_c1_ = BStar() * c2; i_a3ovk2_ = -XJ3 / CK2 * pow(AE, 3.0); i_x1mth2_ = 1.0 - theta2; i_c4_ = 2.0 * RecoveredMeanMotion() * coef1 * RecoveredSemiMajorAxis() * betao2 * (i_eta_ * (2.0 + 0.5 * etasq) + Eccentricity() * (0.5 + 2.0 * etasq) - 2.0 * CK2 * tsi / (RecoveredSemiMajorAxis() * psisq) * (-3.0 * i_x3thm1_ * (1.0 - 2.0 * eeta + etasq * (1.5 - 0.5 * eeta)) + 0.75 * i_x1mth2_ * (2.0 * etasq - eeta * (1.0 + etasq)) * cos(2.0 * ArgumentPerigee()))); const double theta4 = theta2 * theta2; const double temp1 = 3.0 * CK2 * pinvsq * RecoveredMeanMotion(); const double temp2 = temp1 * CK2 * pinvsq; const double temp3 = 1.25 * CK4 * pinvsq * pinvsq * RecoveredMeanMotion(); i_xmdot_ = RecoveredMeanMotion() + 0.5 * temp1 * betao * i_x3thm1_ + 0.0625 * temp2 * betao * (13.0 - 78.0 * theta2 + 137.0 * theta4); const double x1m5th = 1.0 - 5.0 * theta2; i_omgdot_ = -0.5 * temp1 * x1m5th + 0.0625 * temp2 * (7.0 - 114.0 * theta2 + 395.0 * theta4) + temp3 * (3.0 - 36.0 * theta2 + 49.0 * theta4); const double xhdot1_ = -temp1 * i_cosio_; i_xnodot_ = xhdot1_ + (0.5 * temp2 * (4.0 - 19.0 * theta2) + 2.0 * temp3 * (3.0 - 7.0 * theta2)) * i_cosio_; i_xnodcf_ = 3.5 * betao2 * xhdot1_ * i_c1_; i_t2cof_ = 1.5 * i_c1_; if (fabs(i_cosio_ + 1.0) > 1.5e-12) i_xlcof_ = 0.125 * i_a3ovk2_ * i_sinio_ * (3.0 + 5.0 * i_cosio_) / (1.0 + i_cosio_); else i_xlcof_ = 0.125 * i_a3ovk2_ * i_sinio_ * (3.0 + 5.0 * i_cosio_) / 1.5e-12; i_aycof_ = 0.25 * i_a3ovk2_ * i_sinio_; i_x7thm1_ = 7.0 * theta2 - 1.0; if (i_use_deep_space_) { d_gsto_ = Epoch().ToGreenwichSiderealTime(); DeepSpaceInitialize(eosq, i_sinio_, i_cosio_, betao, theta2, betao2, i_xmdot_, i_omgdot_, i_xnodot_); } else { double c3 = 0.0; if (Eccentricity() > 1.0e-4) { c3 = coef * tsi * i_a3ovk2_ * RecoveredMeanMotion() * AE * i_sinio_ / Eccentricity(); } n_c5_ = 2.0 * coef1 * RecoveredSemiMajorAxis() * betao2 * (1.0 + 2.75 * (etasq + eeta) + eeta * etasq); n_omgcof_ = BStar() * c3 * cos(ArgumentPerigee()); n_xmcof_ = 0.0; if (Eccentricity() > 1.0e-4) n_xmcof_ = -TWOTHIRD * coef * BStar() * AE / eeta; n_delmo_ = pow(1.0 + i_eta_ * (cos(MeanAnomoly())), 3.0); n_sinmo_ = sin(MeanAnomoly()); if (!i_use_simple_model_) { const double c1sq = i_c1_ * i_c1_; n_d2_ = 4.0 * RecoveredSemiMajorAxis() * tsi * c1sq; const double temp = n_d2_ * tsi * i_c1_ / 3.0; n_d3_ = (17.0 * RecoveredSemiMajorAxis() + s4) * temp; n_d4_ = 0.5 * temp * RecoveredSemiMajorAxis() * tsi * (221.0 * RecoveredSemiMajorAxis() + 31.0 * s4) * i_c1_; n_t3cof_ = n_d2_ + 2.0 * c1sq; n_t4cof_ = 0.25 * (3.0 * n_d3_ + i_c1_ * (12.0 * n_d2_ + 10.0 * c1sq)); n_t5cof_ = 0.2 * (3.0 * n_d4_ + 12.0 * i_c1_ * n_d3_ + 6.0 * n_d2_ * n_d2_ + 15.0 * c1sq * (2.0 * n_d2_ + c1sq)); } } first_run_ = false; } void SGDP4::FindPosition(Eci& eci, double tsince) { Julian tsince_epoch = Epoch(); tsince_epoch.AddMin(tsince); double actual_tsince = tsince_epoch.SpanMin(Epoch()); if (i_use_deep_space_) FindPositionSDP4(eci, actual_tsince); else FindPositionSGP4(eci, actual_tsince); } void SGDP4::FindPositionSDP4(Eci& eci, double tsince) const { /* * the final values */ double e; double a; double omega; double xl; double xnode; double xincl; /* * update for secular gravity and atmospheric drag */ double xmdf = MeanAnomoly() + i_xmdot_ * tsince; double omgadf = ArgumentPerigee() + i_omgdot_ * tsince; const double xnoddf = AscendingNode() + i_xnodot_ * tsince; const double tsq = tsince * tsince; xnode = xnoddf + i_xnodcf_ * tsq; double tempa = 1.0 - i_c1_ * tsince; double tempe = BStar() * i_c4_ * tsince; double templ = i_t2cof_ * tsq; double xn = RecoveredMeanMotion(); e = Eccentricity(); xincl = Inclination(); DeepSpaceSecular(tsince, xmdf, omgadf, xnode, e, xincl, xn); if (xn <= 0.0) { throw new SatelliteException("Error: 2 (xn <= 0.0)"); } a = pow(XKE / xn, TWOTHIRD) * pow(tempa, 2.0); e = e - tempe; /* * fix tolerance for error recognition */ if (e >= 1.0 || e < -0.001) { throw new SatelliteException("Error: 1 (e >= 1.0 || e < -0.001)"); } /* * fix tolerance to avoid a divide by zero */ if (e < 1.0e-6) e = 1.0e-6; /* xmdf += RecoveredMeanMotion() * templ; double xlm = xmdf + omgadf + xnode; xnode = fmod(xnode, TWOPI); omgadf = fmod(omgadf, TWOPI); xlm = fmod(xlm, TWOPI); double xmam = fmod(xlm - omgadf - xnode, TWOPI); */ double xmam = xmdf + RecoveredMeanMotion() * templ; DeepSpacePeriodics(tsince, e, xincl, omgadf, xnode, xmam); /* * keeping xincl positive important unless you need to display xincl * and dislike negative inclinations */ if (xincl < 0.0) { xincl = -xincl; xnode += PI; omgadf = omgadf - PI; } xl = xmam + omgadf + xnode; omega = omgadf; if (e < 0.0 || e > 1.0) { throw new SatelliteException("Error: 3 (e < 0.0 || e > 1.0)"); } /* * re-compute the perturbed values */ const double perturbed_sinio = sin(xincl); const double perturbed_cosio = cos(xincl); const double perturbed_theta2 = perturbed_cosio * perturbed_cosio; const double perturbed_x3thm1 = 3.0 * perturbed_theta2 - 1.0; const double perturbed_x1mth2 = 1.0 - perturbed_theta2; const double perturbed_x7thm1 = 7.0 * perturbed_theta2 - 1.0; double perturbed_xlcof; if (fabs(perturbed_cosio + 1.0) > 1.5e-12) perturbed_xlcof = 0.125 * i_a3ovk2_ * perturbed_sinio * (3.0 + 5.0 * perturbed_cosio) / (1.0 + perturbed_cosio); else perturbed_xlcof = 0.125 * i_a3ovk2_ * perturbed_sinio * (3.0 + 5.0 * perturbed_cosio) / 1.5e-12; const double perturbed_aycof = 0.25 * i_a3ovk2_ * perturbed_sinio; /* * using calculated values, find position and velocity */ CalculateFinalPositionVelocity(eci, tsince, e, a, omega, xl, xnode, xincl, perturbed_xlcof, perturbed_aycof, perturbed_x3thm1, perturbed_x1mth2, perturbed_x7thm1, perturbed_cosio, perturbed_sinio); } void SGDP4::FindPositionSGP4(Eci& eci, double tsince) const { /* * the final values */ double e; double a; double omega; double xl; double xnode; double xincl; /* * update for secular gravity and atmospheric drag */ const double xmdf = MeanAnomoly() + i_xmdot_ * tsince; const double omgadf = ArgumentPerigee() + i_omgdot_ * tsince; const double xnoddf = AscendingNode() + i_xnodot_ * tsince; const double tsq = tsince * tsince; xnode = xnoddf + i_xnodcf_ * tsq; double tempa = 1.0 - i_c1_ * tsince; double tempe = BStar() * i_c4_ * tsince; double templ = i_t2cof_ * tsq; xincl = Inclination(); omega = omgadf; double xmp = xmdf; if (!i_use_simple_model_) { const double delomg = n_omgcof_ * tsince; const double delm = n_xmcof_ * (pow(1.0 + i_eta_ * cos(xmdf), 3.0) - n_delmo_); const double temp = delomg + delm; xmp += temp; omega = omega - temp; const double tcube = tsq * tsince; const double tfour = tsince * tcube; tempa = tempa - n_d2_ * tsq - n_d3_ * tcube - n_d4_ * tfour; tempe += BStar() * n_c5_ * (sin(xmp) - n_sinmo_); templ += n_t3cof_ * tcube + tfour * (n_t4cof_ + tsince * n_t5cof_); } a = RecoveredSemiMajorAxis() * pow(tempa, 2.0); e = Eccentricity() - tempe; xl = xmp + omega + xnode + RecoveredMeanMotion() * templ; /* * using calculated values, find position and velocity * we can pass in constants from Initialize() as these dont change */ CalculateFinalPositionVelocity(eci, tsince, e, a, omega, xl, xnode, xincl, i_xlcof_, i_aycof_, i_x3thm1_, i_x1mth2_, i_x7thm1_, i_cosio_, i_sinio_); } void SGDP4::CalculateFinalPositionVelocity(Eci& eci, const double& tsince, const double& e, const double& a, const double& omega, const double& xl, const double& xnode, const double& xincl, const double& xlcof, const double& aycof, const double& x3thm1, const double& x1mth2, const double& x7thm1, const double& cosio, const double& sinio) const { double temp; double temp1; double temp2; double temp3; if (a < 1.0) { throw new SatelliteException("Error: Satellite crashed (a < 1.0)"); } if (e < -1.0e-3) { throw new SatelliteException("Error: Modified eccentricity too low (e < -1.0e-3)"); } const double beta = sqrt(1.0 - e * e); const double xn = XKE / pow(a, 1.5); /* * long period periodics */ const double axn = e * cos(omega); temp = 1.0 / (a * beta * beta); const double xll = temp * xlcof * axn; const double aynl = temp * aycof; const double xlt = xl + xll; const double ayn = e * sin(omega) + aynl; const double elsq = axn * axn + ayn * ayn; if (elsq >= 1.0) { throw new SatelliteException("Error: sqrt(e) >= 1 (elsq >= 1.0)"); } /* * solve keplers equation * - solve using Newton-Raphson root solving * - here capu is almost the mean anomoly * - initialise the eccentric anomaly term epw * - The fmod saves reduction of angle to +/-2pi in sin/cos() and prevents * convergence problems. */ const double capu = fmod(xlt - xnode, TWOPI); double epw = capu; double sinepw = 0.0; double cosepw = 0.0; double ecose = 0.0; double esine = 0.0; /* * sensibility check for N-R correction */ const double max_newton_naphson = 1.25 * fabs(sqrt(elsq)); bool kepler_running = true; for (int i = 0; i < 10 && kepler_running; i++) { sinepw = sin(epw); cosepw = cos(epw); ecose = axn * cosepw + ayn * sinepw; esine = axn * sinepw - ayn * cosepw; double f = capu - epw + esine; if (fabs(f) < 1.0e-12) { kepler_running = false; } else { /* * 1st order Newton-Raphson correction */ const double fdot = 1.0 - ecose; double delta_epw = f / fdot; /* * 2nd order Newton-Raphson correction. * f / (fdot - 0.5 * d2f * f/fdot) */ if (i == 0) { if (delta_epw > max_newton_naphson) delta_epw = max_newton_naphson; else if (delta_epw < -max_newton_naphson) delta_epw = -max_newton_naphson; } else { delta_epw = f / (fdot + 0.5 * esine * delta_epw); } /* * Newton-Raphson correction of -F/DF */ epw += delta_epw; } } /* * short period preliminary quantities */ temp = 1.0 - elsq; const double pl = a * temp; const double r = a * (1.0 - ecose); temp1 = 1.0 / r; const double rdot = XKE * sqrt(a) * esine * temp1; const double rfdot = XKE * sqrt(pl) * temp1; temp2 = a * temp1; const double betal = sqrt(temp); temp3 = 1.0 / (1.0 + betal); const double cosu = temp2 * (cosepw - axn + ayn * esine * temp3); const double sinu = temp2 * (sinepw - ayn - axn * esine * temp3); const double u = atan2(sinu, cosu); const double sin2u = 2.0 * sinu * cosu; const double cos2u = 2.0 * cosu * cosu - 1.0; temp = 1.0 / pl; temp1 = CK2 * temp; temp2 = temp1 * temp; /* * update for short periodics */ const double rk = r * (1.0 - 1.5 * temp2 * betal * x3thm1) + 0.5 * temp1 * x1mth2 * cos2u; const double uk = u - 0.25 * temp2 * x7thm1 * sin2u; const double xnodek = xnode + 1.5 * temp2 * cosio * sin2u; const double xinck = xincl + 1.5 * temp2 * cosio * sinio * cos2u; const double rdotk = rdot - xn * temp1 * x1mth2 * sin2u; const double rfdotk = rfdot + xn * temp1 * (x1mth2 * cos2u + 1.5 * x3thm1); if (rk < 0.0) { throw new SatelliteException("Error: satellite decayed (rk < 0.0)"); } /* * orientation vectors */ const double sinuk = sin(uk); const double cosuk = cos(uk); const double sinik = sin(xinck); const double cosik = cos(xinck); const double sinnok = sin(xnodek); const double cosnok = cos(xnodek); const double xmx = -sinnok * cosik; const double xmy = cosnok * cosik; const double ux = xmx * sinuk + cosnok * cosuk; const double uy = xmy * sinuk + sinnok * cosuk; const double uz = sinik * sinuk; const double vx = xmx * cosuk - cosnok * sinuk; const double vy = xmy * cosuk - sinnok * sinuk; const double vz = sinik * cosuk; /* * position and velocity */ const double x = rk * ux * XKMPER; const double y = rk * uy * XKMPER; const double z = rk * uz * XKMPER; Vector position(x, y, z); const double xdot = (rdotk * ux + rfdotk * vx) * XKMPER / 60.0; const double ydot = (rdotk * uy + rfdotk * vy) * XKMPER / 60.0; const double zdot = (rdotk * uz + rfdotk * vz) * XKMPER / 60.0; Vector velocity(xdot, ydot, zdot); Julian julian = Epoch(); julian.AddMin(tsince); eci = Eci(julian, position, velocity); } /* * deep space initialization */ void SGDP4::DeepSpaceInitialize(const double& eosq, const double& sinio, const double& cosio, const double& betao, const double& theta2, const double& betao2, const double& xmdot, const double& omgdot, const double& xnodot) { double se = 0.0; double si = 0.0; double sl = 0.0; double sgh = 0.0; double shdq = 0.0; double bfact = 0.0; static const double ZNS = 1.19459E-5; static const double C1SS = 2.9864797E-6; static const double ZES = 0.01675; static const double ZNL = 1.5835218E-4; static const double C1L = 4.7968065E-7; static const double ZEL = 0.05490; static const double ZCOSIS = 0.91744867; static const double ZSINI = 0.39785416; static const double ZSINGS = -0.98088458; static const double ZCOSGS = 0.1945905; static const double Q22 = 1.7891679E-6; static const double Q31 = 2.1460748E-6; static const double Q33 = 2.2123015E-7; static const double ROOT22 = 1.7891679E-6; static const double ROOT32 = 3.7393792E-7; static const double ROOT44 = 7.3636953E-9; static const double ROOT52 = 1.1428639E-7; static const double ROOT54 = 2.1765803E-9; const double aqnv = 1.0 / RecoveredSemiMajorAxis(); const double xpidot = omgdot + xnodot; const double sinq = sin(AscendingNode()); const double cosq = cos(AscendingNode()); const double sing = sin(ArgumentPerigee()); const double cosg = cos(ArgumentPerigee()); /* * initialize lunar / solar terms */ const double d_day_ = Epoch().FromJan1_12h_1900(); const double xnodce = 4.5236020 - 9.2422029e-4 * d_day_; const double xnodce_temp = fmod(xnodce, TWOPI); const double stem = sin(xnodce_temp); const double ctem = cos(xnodce_temp); const double zcosil = 0.91375164 - 0.03568096 * ctem; const double zsinil = sqrt(1.0 - zcosil * zcosil); const double zsinhl = 0.089683511 * stem / zsinil; const double zcoshl = sqrt(1.0 - zsinhl * zsinhl); const double c = 4.7199672 + 0.22997150 * d_day_; const double gam = 5.8351514 + 0.0019443680 * d_day_; d_zmol_ = Globals::Fmod2p(c - gam); double zx = 0.39785416 * stem / zsinil; double zy = zcoshl * ctem + 0.91744867 * zsinhl * stem; zx = atan2(zx, zy); zx = fmod(gam + zx - xnodce, TWOPI); const double zcosgl = cos(zx); const double zsingl = sin(zx); d_zmos_ = Globals::Fmod2p(6.2565837 + 0.017201977 * d_day_); /* * do solar terms */ double zcosg = ZCOSGS; double zsing = ZSINGS; double zcosi = ZCOSIS; double zsini = ZSINI; double zcosh = cosq; double zsinh = sinq; double cc = C1SS; double zn = ZNS; double ze = ZES; const double xnoi = 1.0 / RecoveredMeanMotion(); for (int cnt = 0; cnt < 2; cnt++) { /* * solar terms are done a second time after lunar terms are done */ const double a1 = zcosg * zcosh + zsing * zcosi * zsinh; const double a3 = -zsing * zcosh + zcosg * zcosi * zsinh; const double a7 = -zcosg * zsinh + zsing * zcosi * zcosh; const double a8 = zsing * zsini; const double a9 = zsing * zsinh + zcosg * zcosi*zcosh; const double a10 = zcosg * zsini; const double a2 = cosio * a7 + sinio * a8; const double a4 = cosio * a9 + sinio * a10; const double a5 = -sinio * a7 + cosio * a8; const double a6 = -sinio * a9 + cosio * a10; const double x1 = a1 * cosg + a2 * sing; const double x2 = a3 * cosg + a4 * sing; const double x3 = -a1 * sing + a2 * cosg; const double x4 = -a3 * sing + a4 * cosg; const double x5 = a5 * sing; const double x6 = a6 * sing; const double x7 = a5 * cosg; const double x8 = a6 * cosg; const double z31 = 12.0 * x1 * x1 - 3. * x3 * x3; const double z32 = 24.0 * x1 * x2 - 6. * x3 * x4; const double z33 = 12.0 * x2 * x2 - 3. * x4 * x4; double z1 = 3.0 * (a1 * a1 + a2 * a2) + z31 * eosq; double z2 = 6.0 * (a1 * a3 + a2 * a4) + z32 * eosq; double z3 = 3.0 * (a3 * a3 + a4 * a4) + z33 * eosq; const double z11 = -6.0 * a1 * a5 + eosq * (-24. * x1 * x7 - 6. * x3 * x5); const double z12 = -6.0 * (a1 * a6 + a3 * a5) + eosq * (-24. * (x2 * x7 + x1 * x8) - 6. * (x3 * x6 + x4 * x5)); const double z13 = -6.0 * a3 * a6 + eosq * (-24. * x2 * x8 - 6. * x4 * x6); const double z21 = 6.0 * a2 * a5 + eosq * (24. * x1 * x5 - 6. * x3 * x7); const double z22 = 6.0 * (a4 * a5 + a2 * a6) + eosq * (24. * (x2 * x5 + x1 * x6) - 6. * (x4 * x7 + x3 * x8)); const double z23 = 6.0 * a4 * a6 + eosq * (24. * x2 * x6 - 6. * x4 * x8); z1 = z1 + z1 + betao2 * z31; z2 = z2 + z2 + betao2 * z32; z3 = z3 + z3 + betao2 * z33; const double s3 = cc * xnoi; const double s2 = -0.5 * s3 / betao; const double s4 = s3 * betao; const double s1 = -15.0 * Eccentricity() * s4; const double s5 = x1 * x3 + x2 * x4; const double s6 = x2 * x3 + x1 * x4; const double s7 = x2 * x4 - x1 * x3; se = s1 * zn * s5; si = s2 * zn * (z11 + z13); sl = -zn * s3 * (z1 + z3 - 14.0 - 6.0 * eosq); sgh = s4 * zn * (z31 + z33 - 6.0); /* * replaced * sh = -zn * s2 * (z21 + z23 * with * shdq = (-zn * s2 * (z21 + z23)) / sinio */ if (Inclination() < 5.2359877e-2 || Inclination() > PI - 5.2359877e-2) { shdq = 0.0; } else { shdq = (-zn * s2 * (z21 + z23)) / sinio; } d_ee2_ = 2.0 * s1 * s6; d_e3_ = 2.0 * s1 * s7; d_xi2_ = 2.0 * s2 * z12; d_xi3_ = 2.0 * s2 * (z13 - z11); d_xl2_ = -2.0 * s3 * z2; d_xl3_ = -2.0 * s3 * (z3 - z1); d_xl4_ = -2.0 * s3 * (-21.0 - 9.0 * eosq) * ze; d_xgh2_ = 2.0 * s4 * z32; d_xgh3_ = 2.0 * s4 * (z33 - z31); d_xgh4_ = -18.0 * s4 * ze; d_xh2_ = -2.0 * s2 * z22; d_xh3_ = -2.0 * s2 * (z23 - z21); if (cnt == 1) break; /* * do lunar terms */ d_sse_ = se; d_ssi_ = si; d_ssl_ = sl; d_ssh_ = shdq; d_ssg_ = sgh - cosio * d_ssh_; d_se2_ = d_ee2_; d_si2_ = d_xi2_; d_sl2_ = d_xl2_; d_sgh2_ = d_xgh2_; d_sh2_ = d_xh2_; d_se3_ = d_e3_; d_si3_ = d_xi3_; d_sl3_ = d_xl3_; d_sgh3_ = d_xgh3_; d_sh3_ = d_xh3_; d_sl4_ = d_xl4_; d_sgh4_ = d_xgh4_; zcosg = zcosgl; zsing = zsingl; zcosi = zcosil; zsini = zsinil; zcosh = zcoshl * cosq + zsinhl * sinq; zsinh = sinq * zcoshl - cosq * zsinhl; zn = ZNL; cc = C1L; ze = ZEL; } d_sse_ += se; d_ssi_ += si; d_ssl_ += sl; d_ssg_ += sgh - cosio * shdq; d_ssh_ += shdq; d_resonance_flag_ = false; d_synchronous_flag_ = false; bool initialize_integrator = true; if (RecoveredMeanMotion() < 0.0052359877 && RecoveredMeanMotion() > 0.0034906585) { /* * 24h synchronous resonance terms initialization */ d_resonance_flag_ = true; d_synchronous_flag_ = true; const double g200 = 1.0 + eosq * (-2.5 + 0.8125 * eosq); const double g310 = 1.0 + 2.0 * eosq; const double g300 = 1.0 + eosq * (-6.0 + 6.60937 * eosq); const double f220 = 0.75 * (1.0 + cosio) * (1.0 + cosio); const double f311 = 0.9375 * sinio * sinio * (1.0 + 3.0 * cosio) - 0.75 * (1.0 + cosio); double f330 = 1.0 + cosio; f330 = 1.875 * f330 * f330 * f330; d_del1_ = 3.0 * RecoveredMeanMotion() * RecoveredMeanMotion() * aqnv * aqnv; d_del2_ = 2.0 * d_del1_ * f220 * g200 * Q22; d_del3_ = 3.0 * d_del1_ * f330 * g300 * Q33 * aqnv; d_del1_ = d_del1_ * f311 * g310 * Q31 * aqnv; d_fasx2_ = 0.13130908; d_fasx4_ = 2.8843198; d_fasx6_ = 0.37448087; d_xlamo_ = MeanAnomoly() + AscendingNode() + ArgumentPerigee() - d_gsto_; bfact = xmdot + xpidot - THDT; bfact += d_ssl_ + d_ssg_ + d_ssh_; } else if (RecoveredMeanMotion() < 8.26e-3 || RecoveredMeanMotion() > 9.24e-3 || Eccentricity() < 0.5) { initialize_integrator = false; } else { /* * geopotential resonance initialization for 12 hour orbits */ d_resonance_flag_ = true; const double eoc = Eccentricity() * eosq; double g211; double g310; double g322; double g410; double g422; double g520; double g201 = -0.306 - (Eccentricity() - 0.64) * 0.440; if (Eccentricity() <= 0.65) { g211 = 3.616 - 13.247 * Eccentricity() + 16.290 * eosq; g310 = -19.302 + 117.390 * Eccentricity() - 228.419 * eosq + 156.591 * eoc; g322 = -18.9068 + 109.7927 * Eccentricity() - 214.6334 * eosq + 146.5816 * eoc; g410 = -41.122 + 242.694 * Eccentricity() - 471.094 * eosq + 313.953 * eoc; g422 = -146.407 + 841.880 * Eccentricity() - 1629.014 * eosq + 1083.435 * eoc; g520 = -532.114 + 3017.977 * Eccentricity() - 5740.032 * eosq + 3708.276 * eoc; } else { g211 = -72.099 + 331.819 * Eccentricity() - 508.738 * eosq + 266.724 * eoc; g310 = -346.844 + 1582.851 * Eccentricity() - 2415.925 * eosq + 1246.113 * eoc; g322 = -342.585 + 1554.908 * Eccentricity() - 2366.899 * eosq + 1215.972 * eoc; g410 = -1052.797 + 4758.686 * Eccentricity() - 7193.992 * eosq + 3651.957 * eoc; g422 = -3581.69 + 16178.11 * Eccentricity() - 24462.77 * eosq + 12422.52 * eoc; if (Eccentricity() <= 0.715) { g520 = 1464.74 - 4664.75 * Eccentricity() + 3763.64 * eosq; } else { g520 = -5149.66 + 29936.92 * Eccentricity() - 54087.36 * eosq + 31324.56 * eoc; } } double g533; double g521; double g532; if (Eccentricity() < 0.7) { g533 = -919.2277 + 4988.61 * Eccentricity() - 9064.77 * eosq + 5542.21 * eoc; g521 = -822.71072 + 4568.6173 * Eccentricity() - 8491.4146 * eosq + 5337.524 * eoc; g532 = -853.666 + 4690.25 * Eccentricity() - 8624.77 * eosq + 5341.4 * eoc; } else { g533 = -37995.78 + 161616.52 * Eccentricity() - 229838.2 * eosq + 109377.94 * eoc; g521 = -51752.104 + 218913.95 * Eccentricity() - 309468.16 * eosq + 146349.42 * eoc; g532 = -40023.88 + 170470.89 * Eccentricity() - 242699.48 * eosq + 115605.82 * eoc; } const double sini2 = sinio * sinio; const double f220 = 0.75 * (1.0 + 2.0 * cosio + theta2); const double f221 = 1.5 * sini2; const double f321 = 1.875 * sinio * (1.0 - 2.0 * cosio - 3.0 * theta2); const double f322 = -1.875 * sinio * (1.0 + 2.0 * cosio - 3.0 * theta2); const double f441 = 35.0 * sini2 * f220; const double f442 = 39.3750 * sini2 * sini2; const double f522 = 9.84375 * sinio * (sini2 * (1.0 - 2.0 * cosio - 5.0 * theta2) + 0.33333333 * (-2.0 + 4.0 * cosio + 6.0 * theta2)); const double f523 = sinio * (4.92187512 * sini2 * (-2.0 - 4.0 * cosio + 10.0 * theta2) + 6.56250012 * (1.0 + 2.0 * cosio - 3.0 * theta2)); const double f542 = 29.53125 * sinio * (2.0 - 8.0 * cosio + theta2 * (-12.0 + 8.0 * cosio + 10.0 * theta2)); const double f543 = 29.53125 * sinio * (-2.0 - 8.0 * cosio + theta2 * (12.0 + 8.0 * cosio - 10.0 * theta2)); const double xno2 = RecoveredMeanMotion() * RecoveredMeanMotion(); const double ainv2 = aqnv * aqnv; double temp1 = 3.0 * xno2 * ainv2; double temp = temp1 * ROOT22; d_d2201_ = temp * f220 * g201; d_d2211_ = temp * f221 * g211; temp1 = temp1 * aqnv; temp = temp1 * ROOT32; d_d3210_ = temp * f321 * g310; d_d3222_ = temp * f322 * g322; temp1 = temp1 * aqnv; temp = 2.0 * temp1 * ROOT44; d_d4410_ = temp * f441 * g410; d_d4422_ = temp * f442 * g422; temp1 = temp1 * aqnv; temp = temp1 * ROOT52; d_d5220_ = temp * f522 * g520; d_d5232_ = temp * f523 * g532; temp = 2.0 * temp1 * ROOT54; d_d5421_ = temp * f542 * g521; d_d5433_ = temp * f543 * g533; d_xlamo_ = MeanAnomoly() + AscendingNode() + AscendingNode() - d_gsto_ - d_gsto_; bfact = xmdot + xnodot + xnodot - THDT - THDT; bfact = bfact + d_ssl_ + d_ssh_ + d_ssh_; } if (initialize_integrator) { /* * initialize integrator */ d_xfact_ = bfact - RecoveredMeanMotion(); d_atime_ = 0.0; d_xni_ = RecoveredMeanMotion(); d_xli_ = d_xlamo_; } } void SGDP4::DeepSpaceCalculateLunarSolarTerms(const double t, double& pe, double& pinc, double& pl, double& pgh, double& ph) const { static const double ZES = 0.01675; static const double ZNS = 1.19459E-5; static const double ZNL = 1.5835218E-4; static const double ZEL = 0.05490; /* * calculate solar terms for time t */ double zm = d_zmos_ + ZNS * t; if (first_run_) zm = d_zmos_; double zf = zm + 2.0 * ZES * sin(zm); double sinzf = sin(zf); double f2 = 0.5 * sinzf * sinzf - 0.25; double f3 = -0.5 * sinzf * cos(zf); const double ses = d_se2_ * f2 + d_se3_ * f3; const double sis = d_si2_ * f2 + d_si3_ * f3; const double sls = d_sl2_ * f2 + d_sl3_ * f3 + d_sl4_ * sinzf; const double sghs = d_sgh2_ * f2 + d_sgh3_ * f3 + d_sgh4_ * sinzf; const double shs = d_sh2_ * f2 + d_sh3_ * f3; /* * calculate lunar terms for time t */ zm = d_zmol_ + ZNL * t; if (first_run_) zm = d_zmol_; zf = zm + 2.0 * ZEL * sin(zm); sinzf = sin(zf); f2 = 0.5 * sinzf * sinzf - 0.25; f3 = -0.5 * sinzf * cos(zf); const double sel = d_ee2_ * f2 + d_e3_ * f3; const double sil = d_xi2_ * f2 + d_xi3_ * f3; const double sll = d_xl2_ * f2 + d_xl3_ * f3 + d_xl4_ * sinzf; const double sghl = d_xgh2_ * f2 + d_xgh3_ * f3 + d_xgh4_ * sinzf; const double shl = d_xh2_ * f2 + d_xh3_ * f3; /* * merge calculated values */ pe = ses + sel; pinc = sis + sil; pl = sls + sll; pgh = sghs + sghl; ph = shs + shl; } /* * calculate lunar / solar periodics and apply */ void SGDP4::DeepSpacePeriodics(const double& t, double& em, double& xinc, double& omgasm, double& xnodes, double& xll) const { /* * storage for lunar / solar terms set by DeepSpaceCalculateLunarSolarTerms() */ double pe = 0.0; double pinc = 0.0; double pl = 0.0; double pgh = 0.0; double ph = 0.0; /* * calculate lunar / solar terms for current time */ DeepSpaceCalculateLunarSolarTerms(t, pe, pinc, pl, pgh, ph); if (!first_run_) { xinc += pinc; em += pe; /* Spacetrack report #3 has sin/cos from before perturbations * added to xinc (oldxinc), but apparently report # 6 has then * from after they are added. * use for strn3 * if (Inclination() >= 0.2) * use for gsfc * if (xinc >= 0.2) * (moved from start of function) */ const double sinis = sin(xinc); const double cosis = cos(xinc); if (xinc >= 0.2) { /* * apply periodics directly */ const double tmp_ph = ph / sinis; omgasm += pgh - cosis * tmp_ph; xnodes += tmp_ph; xll += pl; } else { /* * apply periodics with lyddane modification */ const double sinok = sin(xnodes); const double cosok = cos(xnodes); double alfdp = sinis * sinok; double betdp = sinis * cosok; const double dalf = ph * cosok + pinc * cosis * sinok; const double dbet = -ph * sinok + pinc * cosis * cosok; alfdp += dalf; betdp += dbet; double xls = xll + omgasm + cosis * xnodes; double dls = pl + pgh - pinc * xnodes * sinis; xls += dls; /* * save old xnodes value */ const double oldxnodes = xnodes; xnodes = atan2(alfdp, betdp); /* * Get perturbed xnodes in to same quadrant as original. * RAAN is in the range of 0 to 360 degrees * atan2 is in the range of -180 to 180 degrees */ if (fabs(oldxnodes - xnodes) > PI) { if (xnodes < oldxnodes) xnodes += TWOPI; else xnodes = xnodes - TWOPI; } xll += pl; omgasm = xls - xll - cosis * xnodes; } } } /* * deep space secular effects */ void SGDP4::DeepSpaceSecular(const double& t, double& xll, double& omgasm, double& xnodes, double& em, double& xinc, double& xn) const { static const double STEP2 = 259200.0; static const double STEP = 720.0; double xldot = 0.0; double xndot = 0.0; double xnddt = 0.0; xll += d_ssl_ * t; omgasm += d_ssg_ * t; xnodes += d_ssh_ * t; em += d_sse_ * t; xinc += d_ssi_ * t; if (!d_resonance_flag_) return; /* * 1st condition (if t is less than one time step from epoch) * 2nd condition (if d_atime_ and t are of opposite signs, so zero crossing required) * 3rd condition (if t is closer to zero than d_atime_) */ if (fabs(t) < STEP || t * d_atime_ <= 0.0 || fabs(t) < fabs(d_atime_)) { /* * restart from epoch */ d_atime_ = 0.0; d_xni_ = RecoveredMeanMotion(); d_xli_ = d_xlamo_; } double ft = t - d_atime_; /* * if time difference (ft) is greater than the time step (720.0) * loop around until d_atime_ is within one time step of t */ if (fabs(ft) >= STEP) { /* * calculate step direction to allow d_atime_ * to catch up with t */ double delt = -STEP; if (ft >= 0.0) delt = STEP; do { DeepSpaceCalcIntegrator(delt, STEP2, xndot, xnddt, xldot); ft = t - d_atime_; } while (fabs(ft) >= STEP); } /* * calculate dot terms */ DeepSpaceCalcDotTerms(xndot, xnddt, xldot); /* * integrator */ xn = d_xni_ + xndot * ft + xnddt * ft * ft * 0.5; const double xl = d_xli_ + xldot * ft + xndot * ft * ft * 0.5; const double temp = -xnodes + d_gsto_ + t * THDT; if (d_synchronous_flag_) xll = xl + temp - omgasm; else xll = xl + temp + temp; } /* * calculate dot terms */ void SGDP4::DeepSpaceCalcDotTerms(double& xndot, double& xnddt, double& xldot) const { static const double G22 = 5.7686396; static const double G32 = 0.95240898; static const double G44 = 1.8014998; static const double G52 = 1.0508330; static const double G54 = 4.4108898; if (d_synchronous_flag_) { xndot = d_del1_ * sin(d_xli_ - d_fasx2_) + d_del2_ * sin(2.0 * (d_xli_ - d_fasx4_)) + d_del3_ * sin(3.0 * (d_xli_ - d_fasx6_)); xnddt = d_del1_ * cos(d_xli_ - d_fasx2_) + 2.0 * d_del2_ * cos(2.0 * (d_xli_ - d_fasx4_)) + 3.0 * d_del3_ * cos(3.0 * (d_xli_ - d_fasx6_)); } else { const double xomi = ArgumentPerigee() + i_omgdot_ * d_atime_; const double x2omi = xomi + xomi; const double x2li = d_xli_ + d_xli_; xndot = d_d2201_ * sin(x2omi + d_xli_ - G22) + d_d2211_ * sin(d_xli_ - G22) + d_d3210_ * sin(xomi + d_xli_ - G32) + d_d3222_ * sin(-xomi + d_xli_ - G32) + d_d4410_ * sin(x2omi + x2li - G44) + d_d4422_ * sin(x2li - G44) + d_d5220_ * sin(xomi + d_xli_ - G52) + d_d5232_ * sin(-xomi + d_xli_ - G52) + d_d5421_ * sin(xomi + x2li - G54) + d_d5433_ * sin(-xomi + x2li - G54); xnddt = d_d2201_ * cos(x2omi + d_xli_ - G22) + d_d2211_ * cos(d_xli_ - G22) + d_d3210_ * cos(xomi + d_xli_ - G32) + d_d3222_ * cos(-xomi + d_xli_ - G32) + d_d5220_ * cos(xomi + d_xli_ - G52) + d_d5232_ * cos(-xomi + d_xli_ - G52) + 2.0 * (d_d4410_ * cos(x2omi + x2li - G44) + d_d4422_ * cos(x2li - G44) + d_d5421_ * cos(xomi + x2li - G54) + d_d5433_ * cos(-xomi + x2li - G54)); } xldot = d_xni_ + d_xfact_; xnddt = xnddt * xldot; } /* * deep space integrator for time period of delt */ void SGDP4::DeepSpaceCalcIntegrator(const double& delt, const double& step2, double& xndot, double& xnddt, double& xldot) const { /* * calculate dot terms */ DeepSpaceCalcDotTerms(xndot, xnddt, xldot); /* * integrator */ d_xli_ += xldot * delt + xndot * step2; d_xni_ += xndot * delt + xnddt * step2; /* * increment integrator time */ d_atime_ += delt; } void SGDP4::ResetGlobalVariables() { /* * common variables */ first_run_ = true; i_use_simple_model_ = false; i_use_deep_space_ = false; i_cosio_ = i_sinio_ = i_eta_ = i_t2cof_ = i_a3ovk2_ = i_x1mth2_ = i_x3thm1_ = i_x7thm1_ = i_aycof_ = i_xlcof_ = i_xnodcf_ = i_c1_ = i_c4_ = i_omgdot_ = i_xnodot_ = i_xmdot_ = 0.0; /* * near space variables */ n_c5_ = n_omgcof_ = n_xmcof_ = n_delmo_ = n_sinmo_ = n_d2_ = n_d3_ = n_d4_ = n_t3cof_ = n_t4cof_ = n_t5cof_ = 0.0; /* * deep space variables */ d_gsto_ = d_zmol_ = d_zmos_ = 0.0; d_resonance_flag_ = false; d_synchronous_flag_ = false; d_sse_ = d_ssi_ = d_ssl_ = d_ssg_ = d_ssh_ = 0.0; d_se2_ = d_si2_ = d_sl2_ = d_sgh2_ = d_sh2_ = d_se3_ = d_si3_ = d_sl3_ = d_sgh3_ = d_sh3_ = d_sl4_ = d_sgh4_ = d_ee2_ = d_e3_ = d_xi2_ = d_xi3_ = d_xl2_ = d_xl3_ = d_xl4_ = d_xgh2_ = d_xgh3_ = d_xgh4_ = d_xh2_ = d_xh3_ = 0.0; d_d2201_ = d_d2211_ = d_d3210_ = d_d3222_ = d_d4410_ = d_d4422_ = d_d5220_ = d_d5232_ = d_d5421_ = d_d5433_ = d_del1_ = d_del2_ = d_del3_ = d_fasx2_ = d_fasx4_ = d_fasx6_ = 0.0; d_xfact_ = d_xlamo_ = d_xli_ = d_xni_ = d_atime_ = 0.0; mean_anomoly_ = ascending_node_ = argument_perigee_ = eccentricity_ = inclination_ = mean_motion_ = bstar_ = recovered_semi_major_axis_ = recovered_mean_motion_ = perigee_ = period_ = 0.0; epoch_ = Julian(); }
/*************************************************************************/ /* filesystem_dock.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "filesystem_dock.h" #include "core/os/keyboard.h" #include "editor_node.h" #include "editor_settings.h" #include "io/resource_loader.h" #include "os/dir_access.h" #include "os/file_access.h" #include "os/os.h" #include "project_settings.h" #include "scene/main/viewport.h" bool FileSystemDock::_create_tree(TreeItem *p_parent, EditorFileSystemDirectory *p_dir, Vector<String> &uncollapsed_paths) { TreeItem *item = tree->create_item(p_parent); String dname = p_dir->get_name(); if (dname == "") dname = "res://"; item->set_text(0, dname); item->set_icon(0, get_icon("Folder", "EditorIcons")); item->set_selectable(0, true); String lpath = p_dir->get_path(); if (lpath != "res://" && lpath.ends_with("/")) { lpath = lpath.substr(0, lpath.length() - 1); } item->set_metadata(0, lpath); if (lpath == path) { item->select(0); } if ((path.begins_with(lpath) && path != lpath)) { item->set_collapsed(false); } else { bool is_collapsed = true; for (int i = 0; i < uncollapsed_paths.size(); i++) { if (lpath == uncollapsed_paths[i]) { is_collapsed = false; break; } } item->set_collapsed(is_collapsed); } for (int i = 0; i < p_dir->get_subdir_count(); i++) _create_tree(item, p_dir->get_subdir(i), uncollapsed_paths); return true; } void FileSystemDock::_update_tree(bool keep_collapse_state, bool p_uncollapse_root) { Vector<String> uncollapsed_paths; if (keep_collapse_state) { TreeItem *root = tree->get_root(); if (root) { TreeItem *resTree = root->get_children()->get_next(); Vector<TreeItem *> needs_check; needs_check.push_back(resTree); while (needs_check.size()) { if (!needs_check[0]->is_collapsed()) { uncollapsed_paths.push_back(needs_check[0]->get_metadata(0)); TreeItem *child = needs_check[0]->get_children(); while (child) { needs_check.push_back(child); child = child->get_next(); } } needs_check.remove(0); } } } tree->clear(); updating_tree = true; TreeItem *root = tree->create_item(); TreeItem *favorites = tree->create_item(root); favorites->set_icon(0, get_icon("Favorites", "EditorIcons")); favorites->set_text(0, TTR("Favorites:")); favorites->set_selectable(0, false); Vector<String> favorite_paths = EditorSettings::get_singleton()->get_favorite_dirs(); String res_path = "res://"; Ref<Texture> folder_icon = get_icon("Folder", "EditorIcons"); for (int i = 0; i < favorite_paths.size(); i++) { String fave = favorite_paths[i]; if (!fave.begins_with(res_path)) continue; TreeItem *ti = tree->create_item(favorites); if (fave == res_path) ti->set_text(0, "/"); else ti->set_text(0, fave.get_file()); ti->set_icon(0, folder_icon); ti->set_selectable(0, true); ti->set_metadata(0, fave); } if (p_uncollapse_root) { uncollapsed_paths.push_back("res://"); } _create_tree(root, EditorFileSystem::get_singleton()->get_filesystem(), uncollapsed_paths); tree->ensure_cursor_is_visible(); updating_tree = false; } void FileSystemDock::_notification(int p_what) { switch (p_what) { case NOTIFICATION_RESIZED: { bool new_mode = get_size().height < get_viewport_rect().size.height / 2; if (new_mode != low_height_mode) { low_height_mode = new_mode; if (low_height_mode) { tree->hide(); tree->set_v_size_flags(SIZE_EXPAND_FILL); button_tree->show(); } else { tree->set_v_size_flags(SIZE_FILL); button_tree->hide(); if (!tree->is_visible()) { tree->show(); button_favorite->show(); _update_tree(true); } tree->ensure_cursor_is_visible(); if (!file_list_vb->is_visible()) { file_list_vb->show(); _update_files(true); } } } } break; case NOTIFICATION_ENTER_TREE: { if (initialized) return; initialized = true; EditorFileSystem::get_singleton()->connect("filesystem_changed", this, "_fs_changed"); EditorResourcePreview::get_singleton()->connect("preview_invalidated", this, "_preview_invalidated"); String ei = "EditorIcons"; button_reload->set_icon(get_icon("Reload", ei)); button_favorite->set_icon(get_icon("Favorites", ei)); //button_instance->set_icon(get_icon("Add", ei)); //button_open->set_icon(get_icon("Folder", ei)); button_tree->set_icon(get_icon("Filesystem", ei)); _update_file_display_toggle_button(); button_display_mode->connect("pressed", this, "_change_file_display"); //file_options->set_icon( get_icon("Tools","ei")); files->connect("item_activated", this, "_select_file"); button_hist_next->connect("pressed", this, "_fw_history"); button_hist_prev->connect("pressed", this, "_bw_history"); search_box->add_icon_override("right_icon", get_icon("Search", ei)); button_hist_next->set_icon(get_icon("Forward", ei)); button_hist_prev->set_icon(get_icon("Back", ei)); file_options->connect("id_pressed", this, "_file_option"); folder_options->connect("id_pressed", this, "_folder_option"); button_tree->connect("pressed", this, "_go_to_tree", varray(), CONNECT_DEFERRED); current_path->connect("text_entered", this, "navigate_to_path"); if (EditorFileSystem::get_singleton()->is_scanning()) { _set_scanning_mode(); } else { _update_tree(false, true); } } break; case NOTIFICATION_PROCESS: { if (EditorFileSystem::get_singleton()->is_scanning()) { scanning_progress->set_value(EditorFileSystem::get_singleton()->get_scanning_progress() * 100); } } break; case NOTIFICATION_EXIT_TREE: { } break; case NOTIFICATION_DRAG_BEGIN: { Dictionary dd = get_viewport()->gui_get_drag_data(); if (tree->is_visible_in_tree() && dd.has("type")) { if ((String(dd["type"]) == "files") || (String(dd["type"]) == "files_and_dirs") || (String(dd["type"]) == "resource")) { tree->set_drop_mode_flags(Tree::DROP_MODE_ON_ITEM); } else if ((String(dd["type"]) == "favorite")) { tree->set_drop_mode_flags(Tree::DROP_MODE_INBETWEEN); } } } break; case NOTIFICATION_DRAG_END: { tree->set_drop_mode_flags(0); } break; case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { String ei = "EditorIcons"; int new_mode = int(EditorSettings::get_singleton()->get("docks/filesystem/display_mode")); //_update_icons button_reload->set_icon(get_icon("Reload", ei)); button_favorite->set_icon(get_icon("Favorites", ei)); button_tree->set_icon(get_icon("Filesystem", ei)); button_hist_next->set_icon(get_icon("Forward", ei)); button_hist_prev->set_icon(get_icon("Back", ei)); search_box->add_icon_override("right_icon", get_icon("Search", ei)); if (new_mode != display_mode) { set_display_mode(new_mode); } else { _update_file_display_toggle_button(); _update_files(true); } _update_tree(true); } break; } } void FileSystemDock::_dir_selected() { TreeItem *sel = tree->get_selected(); if (!sel) return; path = sel->get_metadata(0); bool found = false; Vector<String> favorites = EditorSettings::get_singleton()->get_favorite_dirs(); for (int i = 0; i < favorites.size(); i++) { if (favorites[i] == path) { found = true; break; } } button_favorite->set_pressed(found); current_path->set_text(path); _push_to_history(); if (!low_height_mode) { _update_files(false); } } void FileSystemDock::_favorites_pressed() { TreeItem *sel = tree->get_selected(); if (!sel) return; path = sel->get_metadata(0); int idx = -1; Vector<String> favorites = EditorSettings::get_singleton()->get_favorite_dirs(); for (int i = 0; i < favorites.size(); i++) { if (favorites[i] == path) { idx = i; break; } } if (idx == -1) { favorites.push_back(path); } else { favorites.remove(idx); } EditorSettings::get_singleton()->set_favorite_dirs(favorites); _update_tree(true); } String FileSystemDock::get_selected_path() const { TreeItem *sel = tree->get_selected(); if (!sel) return ""; return sel->get_metadata(0); } String FileSystemDock::get_current_path() const { return path; } void FileSystemDock::navigate_to_path(const String &p_path) { // If the path is a file, do not only go to the directory in the tree, also select the file in the file list. String file_name = ""; DirAccess *dirAccess = DirAccess::open("res://"); if (dirAccess->file_exists(p_path)) { path = p_path.get_base_dir(); file_name = p_path.get_file(); } else if (dirAccess->dir_exists(p_path)) { path = p_path; } else { ERR_EXPLAIN(vformat(TTR("Cannot navigate to '%s' as it has not been found in the file system!"), p_path)); ERR_FAIL(); } current_path->set_text(path); _push_to_history(); if (!low_height_mode) { _update_tree(true); _update_files(false); } else { _go_to_file_list(); } if (!file_name.empty()) { for (int i = 0; i < files->get_item_count(); i++) { if (files->get_item_text(i) == file_name) { files->select(i, true); files->ensure_current_is_visible(); break; } } } } void FileSystemDock::_thumbnail_done(const String &p_path, const Ref<Texture> &p_preview, const Variant &p_udata) { if ((file_list_vb->is_visible_in_tree() || path == p_path.get_base_dir()) && p_preview.is_valid()) { Array uarr = p_udata; int idx = uarr[0]; String file = uarr[1]; if (idx < files->get_item_count() && files->get_item_text(idx) == file && files->get_item_metadata(idx) == p_path) files->set_item_icon(idx, p_preview); } } void FileSystemDock::_update_file_display_toggle_button() { if (button_display_mode->is_pressed()) { display_mode = DISPLAY_LIST; button_display_mode->set_icon(get_icon("FileThumbnail", "EditorIcons")); button_display_mode->set_tooltip(TTR("View items as a grid of thumbnails")); } else { display_mode = DISPLAY_THUMBNAILS; button_display_mode->set_icon(get_icon("FileList", "EditorIcons")); button_display_mode->set_tooltip(TTR("View items as a list")); } } void FileSystemDock::_change_file_display() { _update_file_display_toggle_button(); EditorSettings::get_singleton()->set("docks/filesystem/display_mode", display_mode); _update_files(true); } void FileSystemDock::_search(EditorFileSystemDirectory *p_path, List<FileInfo> *matches, int p_max_items) { if (matches->size() > p_max_items) return; for (int i = 0; i < p_path->get_subdir_count(); i++) { _search(p_path->get_subdir(i), matches, p_max_items); } String match = search_box->get_text().to_lower(); for (int i = 0; i < p_path->get_file_count(); i++) { String file = p_path->get_file(i); if (file.to_lower().find(match) != -1) { FileInfo fi; fi.name = file; fi.type = p_path->get_file_type(i); fi.path = p_path->get_file_path(i); fi.import_broken = !p_path->get_file_import_is_valid(i); fi.import_status = 0; matches->push_back(fi); if (matches->size() > p_max_items) return; } } } void FileSystemDock::_update_files(bool p_keep_selection) { Set<String> cselection; if (p_keep_selection) { for (int i = 0; i < files->get_item_count(); i++) { if (files->is_selected(i)) cselection.insert(files->get_item_text(i)); } } files->clear(); current_path->set_text(path); EditorFileSystemDirectory *efd = EditorFileSystem::get_singleton()->get_filesystem_path(path); if (!efd) return; String ei = "EditorIcons"; int thumbnail_size = EditorSettings::get_singleton()->get("docks/filesystem/thumbnail_size"); thumbnail_size *= EDSCALE; Ref<Texture> folder_thumbnail; Ref<Texture> file_thumbnail; Ref<Texture> file_thumbnail_broken; bool always_show_folders = EditorSettings::get_singleton()->get("docks/filesystem/always_show_folders"); bool use_thumbnails = (display_mode == DISPLAY_THUMBNAILS); bool use_folders = search_box->get_text().length() == 0 && (low_height_mode || always_show_folders); if (use_thumbnails) { files->set_max_columns(0); files->set_icon_mode(ItemList::ICON_MODE_TOP); files->set_fixed_column_width(thumbnail_size * 3 / 2); files->set_max_text_lines(2); files->set_fixed_icon_size(Size2(thumbnail_size, thumbnail_size)); if (thumbnail_size < 64) { folder_thumbnail = get_icon("FolderMediumThumb", ei); file_thumbnail = get_icon("FileMediumThumb", ei); file_thumbnail_broken = get_icon("FileDeadMediumThumb", ei); } else { folder_thumbnail = get_icon("FolderBigThumb", ei); file_thumbnail = get_icon("FileBigThumb", ei); file_thumbnail_broken = get_icon("FileDeadBigThumb", ei); } } else { files->set_icon_mode(ItemList::ICON_MODE_LEFT); files->set_max_columns(1); files->set_max_text_lines(1); files->set_fixed_column_width(0); files->set_fixed_icon_size(Size2()); } if (use_folders) { Ref<Texture> folderIcon = (use_thumbnails) ? folder_thumbnail : get_icon("folder", "FileDialog"); if (path != "res://") { files->add_item("..", folderIcon, true); String bd = path.get_base_dir(); if (bd != "res://" && !bd.ends_with("/")) bd += "/"; files->set_item_metadata(files->get_item_count() - 1, bd); } for (int i = 0; i < efd->get_subdir_count(); i++) { String dname = efd->get_subdir(i)->get_name(); files->add_item(dname, folderIcon, true); files->set_item_metadata(files->get_item_count() - 1, path.plus_file(dname) + "/"); if (cselection.has(dname)) files->select(files->get_item_count() - 1, false); } } List<FileInfo> filelist; if (search_box->get_text().length() > 0) { _search(EditorFileSystem::get_singleton()->get_filesystem(), &filelist, 128); filelist.sort(); } else { for (int i = 0; i < efd->get_file_count(); i++) { FileInfo fi; fi.name = efd->get_file(i); fi.path = path.plus_file(fi.name); fi.type = efd->get_file_type(i); fi.import_broken = !efd->get_file_import_is_valid(i); fi.import_status = 0; filelist.push_back(fi); } } String oi = "Object"; for (List<FileInfo>::Element *E = filelist.front(); E; E = E->next()) { FileInfo *finfo = &(E->get()); String fname = finfo->name; String fpath = finfo->path; String ftype = finfo->type; Ref<Texture> type_icon; Ref<Texture> big_icon; String tooltip = fname; if (!finfo->import_broken) { type_icon = (has_icon(ftype, ei)) ? get_icon(ftype, ei) : get_icon(oi, ei); big_icon = file_thumbnail; } else { type_icon = get_icon("ImportFail", ei); big_icon = file_thumbnail_broken; tooltip += "\n" + TTR("Status: Import of file failed. Please fix file and reimport manually."); } int item_index; if (use_thumbnails) { files->add_item(fname, big_icon, true); item_index = files->get_item_count() - 1; files->set_item_metadata(item_index, fpath); files->set_item_tag_icon(item_index, type_icon); if (!finfo->import_broken) { Array udata; udata.resize(2); udata[0] = item_index; udata[1] = fname; EditorResourcePreview::get_singleton()->queue_resource_preview(fpath, this, "_thumbnail_done", udata); } } else { files->add_item(fname, type_icon, true); item_index = files->get_item_count() - 1; files->set_item_metadata(item_index, fpath); } if (cselection.has(fname)) files->select(item_index, false); if (finfo->sources.size()) { for (int j = 0; j < finfo->sources.size(); j++) { tooltip += "\nSource: " + finfo->sources[j]; } } files->set_item_tooltip(item_index, tooltip); } } void FileSystemDock::_select_file(int p_idx) { String fpath = files->get_item_metadata(p_idx); if (fpath.ends_with("/")) { if (fpath != "res://") { fpath = fpath.substr(0, fpath.length() - 1); } navigate_to_path(fpath); } else { if (ResourceLoader::get_resource_type(fpath) == "PackedScene") { editor->open_request(fpath); } else { editor->load_resource(fpath); } } } void FileSystemDock::_go_to_tree() { if (low_height_mode) { tree->show(); button_favorite->show(); file_list_vb->hide(); } _update_tree(true); tree->grab_focus(); tree->ensure_cursor_is_visible(); //button_open->hide(); //file_options->hide(); } void FileSystemDock::_preview_invalidated(const String &p_path) { if (display_mode == DISPLAY_THUMBNAILS && p_path.get_base_dir() == path && search_box->get_text() == String() && file_list_vb->is_visible_in_tree()) { for (int i = 0; i < files->get_item_count(); i++) { if (files->get_item_metadata(i) == p_path) { //re-request preview Array udata; udata.resize(2); udata[0] = i; udata[1] = files->get_item_text(i); EditorResourcePreview::get_singleton()->queue_resource_preview(p_path, this, "_thumbnail_done", udata); break; } } } } void FileSystemDock::_fs_changed() { button_hist_prev->set_disabled(history_pos == 0); button_hist_next->set_disabled(history_pos == history.size() - 1); scanning_vb->hide(); split_box->show(); if (tree->is_visible()) { _update_tree(true); } if (file_list_vb->is_visible()) { _update_files(true); } set_process(false); } void FileSystemDock::_set_scanning_mode() { button_hist_prev->set_disabled(true); button_hist_next->set_disabled(true); split_box->hide(); scanning_vb->show(); set_process(true); if (EditorFileSystem::get_singleton()->is_scanning()) { scanning_progress->set_value(EditorFileSystem::get_singleton()->get_scanning_progress() * 100); } else { scanning_progress->set_value(0); } } void FileSystemDock::_fw_history() { if (history_pos < history.size() - 1) history_pos++; _update_history(); } void FileSystemDock::_bw_history() { if (history_pos > 0) history_pos--; _update_history(); } void FileSystemDock::_update_history() { path = history[history_pos]; current_path->set_text(path); if (tree->is_visible()) { _update_tree(true); tree->grab_focus(); tree->ensure_cursor_is_visible(); } if (file_list_vb->is_visible()) { _update_files(false); } button_hist_prev->set_disabled(history_pos == 0); button_hist_next->set_disabled(history_pos == history.size() - 1); } void FileSystemDock::_push_to_history() { if (history[history_pos] != path) { history.resize(history_pos + 1); history.push_back(path); history_pos++; if (history.size() > history_max_size) { history.remove(0); history_pos = history_max_size - 1; } } button_hist_prev->set_disabled(history_pos == 0); button_hist_next->set_disabled(history_pos == history.size() - 1); } void FileSystemDock::_get_all_files_in_dir(EditorFileSystemDirectory *efsd, Vector<String> &files) const { if (efsd == NULL) return; for (int i = 0; i < efsd->get_subdir_count(); i++) { _get_all_files_in_dir(efsd->get_subdir(i), files); } for (int i = 0; i < efsd->get_file_count(); i++) { files.push_back(efsd->get_file_path(i)); } } void FileSystemDock::_find_remaps(EditorFileSystemDirectory *efsd, const Map<String, String> &renames, Vector<String> &to_remaps) const { for (int i = 0; i < efsd->get_subdir_count(); i++) { _find_remaps(efsd->get_subdir(i), renames, to_remaps); } for (int i = 0; i < efsd->get_file_count(); i++) { Vector<String> deps = efsd->get_file_deps(i); for (int j = 0; j < deps.size(); j++) { if (renames.has(deps[j])) { to_remaps.push_back(efsd->get_file_path(i)); break; } } } } void FileSystemDock::_try_move_item(const FileOrFolder &p_item, const String &p_new_path, Map<String, String> &p_renames) const { //Ensure folder paths end with "/" String old_path = (p_item.is_file || p_item.path.ends_with("/")) ? p_item.path : (p_item.path + "/"); String new_path = (p_item.is_file || p_new_path.ends_with("/")) ? p_new_path : (p_new_path + "/"); if (new_path == old_path) { return; } else if (old_path == "res://") { EditorNode::get_singleton()->add_io_error(TTR("Cannot move/rename resources root.")); return; } else if (!p_item.is_file && new_path.begins_with(old_path)) { //This check doesn't erroneously catch renaming to a longer name as folder paths always end with "/" EditorNode::get_singleton()->add_io_error(TTR("Cannot move a folder into itself.") + "\n" + old_path + "\n"); return; } //Build a list of files which will have new paths as a result of this operation Vector<String> changed_paths; if (p_item.is_file) { changed_paths.push_back(old_path); } else { _get_all_files_in_dir(EditorFileSystem::get_singleton()->get_filesystem_path(old_path), changed_paths); } DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); print_line("Moving " + old_path + " -> " + new_path); Error err = da->rename(old_path, new_path); if (err == OK) { //Move/Rename any corresponding import settings too if (p_item.is_file && FileAccess::exists(old_path + ".import")) { err = da->rename(old_path + ".import", new_path + ".import"); if (err != OK) { EditorNode::get_singleton()->add_io_error(TTR("Error moving:") + "\n" + old_path + ".import\n"); } } // update scene if it is open for (int i = 0; i < changed_paths.size(); ++i) { String new_item_path = p_item.is_file ? new_path : changed_paths[i].replace_first(old_path, new_path); if (ResourceLoader::get_resource_type(new_item_path) == "PackedScene" && editor->is_scene_open(changed_paths[i])) { EditorData *ed = &editor->get_editor_data(); for (int j = 0; j < ed->get_edited_scene_count(); j++) { if (ed->get_scene_path(j) == changed_paths[i]) { ed->get_edited_scene_root(j)->set_filename(new_item_path); break; } } } } //Only treat as a changed dependency if it was successfully moved for (int i = 0; i < changed_paths.size(); ++i) { p_renames[changed_paths[i]] = changed_paths[i].replace_first(old_path, new_path); print_line(" Remap: " + changed_paths[i] + " -> " + p_renames[changed_paths[i]]); } } else { EditorNode::get_singleton()->add_io_error(TTR("Error moving:") + "\n" + old_path + "\n"); } memdelete(da); } void FileSystemDock::_try_duplicate_item(const FileOrFolder &p_item, const String &p_new_path) const { //Ensure folder paths end with "/" String old_path = (p_item.is_file || p_item.path.ends_with("/")) ? p_item.path : (p_item.path + "/"); String new_path = (p_item.is_file || p_new_path.ends_with("/")) ? p_new_path : (p_new_path + "/"); if (new_path == old_path) { return; } else if (old_path == "res://") { EditorNode::get_singleton()->add_io_error(TTR("Cannot move/rename resources root.")); return; } else if (!p_item.is_file && new_path.begins_with(old_path)) { //This check doesn't erroneously catch renaming to a longer name as folder paths always end with "/" EditorNode::get_singleton()->add_io_error(TTR("Cannot move a folder into itself.") + "\n" + old_path + "\n"); return; } DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); print_line("Duplicating " + old_path + " -> " + new_path); Error err = p_item.is_file ? da->copy(old_path, new_path) : da->copy_dir(old_path, new_path); if (err == OK) { //Move/Rename any corresponding import settings too if (p_item.is_file && FileAccess::exists(old_path + ".import")) { err = da->copy(old_path + ".import", new_path + ".import"); if (err != OK) { EditorNode::get_singleton()->add_io_error(TTR("Error duplicating:") + "\n" + old_path + ".import\n"); } } } else { EditorNode::get_singleton()->add_io_error(TTR("Error duplicating:") + "\n" + old_path + "\n"); } memdelete(da); } void FileSystemDock::_update_resource_paths_after_move(const Map<String, String> &p_renames) const { //Rename all resources loaded, be it subresources or actual resources List<Ref<Resource> > cached; ResourceCache::get_cached_resources(&cached); for (List<Ref<Resource> >::Element *E = cached.front(); E; E = E->next()) { Ref<Resource> r = E->get(); String base_path = r->get_path(); String extra_path; int sep_pos = r->get_path().find("::"); if (sep_pos >= 0) { extra_path = base_path.substr(sep_pos, base_path.length()); base_path = base_path.substr(0, sep_pos); } if (p_renames.has(base_path)) { base_path = p_renames[base_path]; } r->set_path(base_path + extra_path); } for (int i = 0; i < EditorNode::get_editor_data().get_edited_scene_count(); i++) { String path; if (i == EditorNode::get_editor_data().get_edited_scene()) { if (!get_tree()->get_edited_scene_root()) continue; path = get_tree()->get_edited_scene_root()->get_filename(); } else { path = EditorNode::get_editor_data().get_scene_path(i); } if (p_renames.has(path)) { path = p_renames[path]; } if (i == EditorNode::get_editor_data().get_edited_scene()) { get_tree()->get_edited_scene_root()->set_filename(path); } else { EditorNode::get_editor_data().set_scene_path(i, path); } } } void FileSystemDock::_update_dependencies_after_move(const Map<String, String> &p_renames) const { //The following code assumes that the following holds: // 1) EditorFileSystem contains the old paths/folder structure from before the rename/move. // 2) ResourceLoader can use the new paths without needing to call rescan. Vector<String> remaps; _find_remaps(EditorFileSystem::get_singleton()->get_filesystem(), p_renames, remaps); for (int i = 0; i < remaps.size(); ++i) { //Because we haven't called a rescan yet the found remap might still be an old path itself. String file = p_renames.has(remaps[i]) ? p_renames[remaps[i]] : remaps[i]; print_line("Remapping dependencies for: " + file); Error err = ResourceLoader::rename_dependencies(file, p_renames); if (err == OK) { if (ResourceLoader::get_resource_type(file) == "PackedScene") editor->reload_scene(file); } else { EditorNode::get_singleton()->add_io_error(TTR("Unable to update dependencies:") + "\n" + remaps[i] + "\n"); } } } void FileSystemDock::_make_dir_confirm() { String dir_name = make_dir_dialog_text->get_text().strip_edges(); if (dir_name.length() == 0) { EditorNode::get_singleton()->show_warning(TTR("No name provided")); return; } else if (dir_name.find("/") != -1 || dir_name.find("\\") != -1 || dir_name.find(":") != -1) { EditorNode::get_singleton()->show_warning(TTR("Provided name contains invalid characters")); return; } print_line("Making folder " + dir_name + " in " + path); DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); Error err = da->change_dir(path); if (err == OK) { err = da->make_dir(dir_name); } memdelete(da); if (err == OK) { print_line("call rescan!"); _rescan(); } else { EditorNode::get_singleton()->show_warning(TTR("Could not create folder.")); } } void FileSystemDock::_rename_operation_confirm() { String new_name = rename_dialog_text->get_text().strip_edges(); if (new_name.length() == 0) { EditorNode::get_singleton()->show_warning(TTR("No name provided.")); return; } else if (new_name.find("/") != -1 || new_name.find("\\") != -1 || new_name.find(":") != -1) { EditorNode::get_singleton()->show_warning(TTR("Name contains invalid characters.")); return; } String old_path = to_rename.path.ends_with("/") ? to_rename.path.substr(0, to_rename.path.length() - 1) : to_rename.path; String new_path = old_path.get_base_dir().plus_file(new_name); if (old_path == new_path) { return; } //Present a more user friendly warning for name conflict DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (da->file_exists(new_path) || da->dir_exists(new_path)) { EditorNode::get_singleton()->show_warning(TTR("A file or folder with this name already exists.")); memdelete(da); return; } memdelete(da); Map<String, String> renames; _try_move_item(to_rename, new_path, renames); _update_dependencies_after_move(renames); _update_resource_paths_after_move(renames); //Rescan everything print_line("call rescan!"); _rescan(); } void FileSystemDock::_duplicate_operation_confirm() { String new_name = duplicate_dialog_text->get_text().strip_edges(); if (new_name.length() == 0) { EditorNode::get_singleton()->show_warning(TTR("No name provided.")); return; } else if (new_name.find("/") != -1 || new_name.find("\\") != -1 || new_name.find(":") != -1) { EditorNode::get_singleton()->show_warning(TTR("Name contains invalid characters.")); return; } String new_path; String base_dir = to_duplicate.path.get_base_dir(); if (to_duplicate.is_file) { new_path = base_dir.plus_file(new_name); } else { new_path = base_dir.substr(0, base_dir.find_last("/")) + "/" + new_name; } //Present a more user friendly warning for name conflict DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (da->file_exists(new_path) || da->dir_exists(new_path)) { EditorNode::get_singleton()->show_warning(TTR("A file or folder with this name already exists.")); memdelete(da); return; } memdelete(da); _try_duplicate_item(to_duplicate, new_path); //Rescan everything print_line("call rescan!"); _rescan(); } void FileSystemDock::_move_operation_confirm(const String &p_to_path) { Map<String, String> renames; for (int i = 0; i < to_move.size(); i++) { String old_path = to_move[i].path.ends_with("/") ? to_move[i].path.substr(0, to_move[i].path.length() - 1) : to_move[i].path; String new_path = p_to_path.plus_file(old_path.get_file()); _try_move_item(to_move[i], new_path, renames); } _update_dependencies_after_move(renames); _update_resource_paths_after_move(renames); print_line("call rescan!"); _rescan(); } void FileSystemDock::_file_option(int p_option) { switch (p_option) { case FILE_SHOW_IN_EXPLORER: { String dir = ProjectSettings::get_singleton()->globalize_path(this->path); OS::get_singleton()->shell_open(String("file://") + dir); } break; case FILE_OPEN: { for (int i = 0; i < files->get_item_count(); i++) { if (files->is_selected(i)) { _select_file(i); } } } break; case FILE_INSTANCE: { Vector<String> paths; for (int i = 0; i < files->get_item_count(); i++) { if (!files->is_selected(i)) continue; String fpath = files->get_item_metadata(i); if (EditorFileSystem::get_singleton()->get_file_type(fpath) == "PackedScene") { paths.push_back(fpath); } } if (!paths.empty()) { emit_signal("instance", paths); } } break; case FILE_DEPENDENCIES: { int idx = files->get_current(); if (idx < 0 || idx >= files->get_item_count()) break; String fpath = files->get_item_metadata(idx); deps_editor->edit(fpath); } break; case FILE_OWNERS: { int idx = files->get_current(); if (idx < 0 || idx >= files->get_item_count()) break; String fpath = files->get_item_metadata(idx); owners_editor->show(fpath); } break; case FILE_MOVE: { to_move.clear(); for (int i = 0; i < files->get_item_count(); i++) { if (!files->is_selected(i)) continue; String fpath = files->get_item_metadata(i); to_move.push_back(FileOrFolder(fpath, !fpath.ends_with("/"))); } if (to_move.size() > 0) { move_dialog->popup_centered_ratio(); } } break; case FILE_RENAME: { int idx = files->get_current(); if (idx < 0 || idx >= files->get_item_count()) break; to_rename.path = files->get_item_metadata(idx); to_rename.is_file = !to_rename.path.ends_with("/"); if (to_rename.is_file) { String name = to_rename.path.get_file(); rename_dialog->set_title(TTR("Renaming file:") + " " + name); rename_dialog_text->set_text(name); rename_dialog_text->select(0, name.find_last(".")); } else { String name = to_rename.path.substr(0, to_rename.path.length() - 1).get_file(); rename_dialog->set_title(TTR("Renaming folder:") + " " + name); rename_dialog_text->set_text(name); rename_dialog_text->select(0, name.length()); } rename_dialog->popup_centered_minsize(Size2(250, 80) * EDSCALE); rename_dialog_text->grab_focus(); } break; case FILE_REMOVE: { Vector<String> remove_files; Vector<String> remove_folders; for (int i = 0; i < files->get_item_count(); i++) { String fpath = files->get_item_metadata(i); if (files->is_selected(i) && fpath != "res://") { if (fpath.ends_with("/")) { remove_folders.push_back(fpath); } else { remove_files.push_back(fpath); } } } if (remove_files.size() + remove_folders.size() > 0) { remove_dialog->show(remove_folders, remove_files); //1) find if used //2) warn } } break; case FILE_DUPLICATE: { int idx = files->get_current(); if (idx < 0 || idx >= files->get_item_count()) break; to_duplicate.path = files->get_item_metadata(idx); to_duplicate.is_file = !to_duplicate.path.ends_with("/"); if (to_duplicate.is_file) { String name = to_duplicate.path.get_file(); duplicate_dialog->set_title(TTR("Duplicating file:") + " " + name); duplicate_dialog_text->set_text(name); duplicate_dialog_text->select(0, name.find_last(".")); } else { String name = to_duplicate.path.substr(0, to_duplicate.path.length() - 1).get_file(); duplicate_dialog->set_title(TTR("Duplicating folder:") + " " + name); duplicate_dialog_text->set_text(name); duplicate_dialog_text->select(0, name.length()); } duplicate_dialog->popup_centered_minsize(Size2(250, 80) * EDSCALE); duplicate_dialog_text->grab_focus(); } break; case FILE_INFO: { } break; case FILE_REIMPORT: { Vector<String> reimport; for (int i = 0; i < files->get_item_count(); i++) { if (!files->is_selected(i)) continue; String fpath = files->get_item_metadata(i); reimport.push_back(fpath); } ERR_FAIL_COND(reimport.size() == 0); /* Ref<ResourceImportMetadata> rimd = ResourceLoader::load_import_metadata(reimport[0]); ERR_FAIL_COND(!rimd.is_valid()); String editor=rimd->get_editor(); if (editor.begins_with("texture_")) { //compatibility fix for old texture format editor="texture"; } Ref<EditorImportPlugin> rimp = EditorImportExport::get_singleton()->get_import_plugin_by_name(editor); ERR_FAIL_COND(!rimp.is_valid()); if (reimport.size()==1) { rimp->import_dialog(reimport[0]); } else { rimp->reimport_multiple_files(reimport); } */ } break; case FILE_NEW_FOLDER: { make_dir_dialog_text->set_text("new folder"); make_dir_dialog_text->select_all(); make_dir_dialog->popup_centered_minsize(Size2(250, 80) * EDSCALE); make_dir_dialog_text->grab_focus(); } break; case FILE_COPY_PATH: { int idx = files->get_current(); if (idx < 0 || idx >= files->get_item_count()) break; String fpath = files->get_item_metadata(idx); OS::get_singleton()->set_clipboard(fpath); } break; } } void FileSystemDock::_folder_option(int p_option) { TreeItem *selected = tree->get_selected(); switch (p_option) { case FOLDER_EXPAND_ALL: case FOLDER_COLLAPSE_ALL: { bool is_collapsed = (p_option == FOLDER_COLLAPSE_ALL); Vector<TreeItem *> needs_check; needs_check.push_back(selected); while (needs_check.size()) { needs_check[0]->set_collapsed(is_collapsed); TreeItem *child = needs_check[0]->get_children(); while (child) { needs_check.push_back(child); child = child->get_next(); } needs_check.remove(0); } } break; case FOLDER_MOVE: { to_move.clear(); String fpath = selected->get_metadata(tree->get_selected_column()); if (fpath != "res://") { fpath = fpath.ends_with("/") ? fpath.substr(0, fpath.length() - 1) : fpath; to_move.push_back(FileOrFolder(fpath, false)); move_dialog->popup_centered_ratio(); } } break; case FOLDER_RENAME: { to_rename.path = selected->get_metadata(tree->get_selected_column()); to_rename.is_file = false; if (to_rename.path != "res://") { String name = to_rename.path.ends_with("/") ? to_rename.path.substr(0, to_rename.path.length() - 1).get_file() : to_rename.path.get_file(); rename_dialog->set_title(TTR("Renaming folder:") + " " + name); rename_dialog_text->set_text(name); rename_dialog_text->select(0, name.length()); rename_dialog->popup_centered_minsize(Size2(250, 80) * EDSCALE); rename_dialog_text->grab_focus(); } } break; case FOLDER_REMOVE: { Vector<String> remove_folders; Vector<String> remove_files; String fpath = selected->get_metadata(tree->get_selected_column()); if (fpath != "res://") { remove_folders.push_back(fpath); remove_dialog->show(remove_folders, remove_files); } } break; case FOLDER_NEW_FOLDER: { make_dir_dialog_text->set_text("new folder"); make_dir_dialog_text->select_all(); make_dir_dialog->popup_centered_minsize(Size2(250, 80) * EDSCALE); make_dir_dialog_text->grab_focus(); } break; case FOLDER_COPY_PATH: { String fpath = selected->get_metadata(tree->get_selected_column()); OS::get_singleton()->set_clipboard(fpath); } break; case FOLDER_SHOW_IN_EXPLORER: { String fpath = selected->get_metadata(tree->get_selected_column()); String dir = ProjectSettings::get_singleton()->globalize_path(fpath); OS::get_singleton()->shell_open(String("file://") + dir); } break; } } void FileSystemDock::_go_to_file_list() { if (low_height_mode) { tree->hide(); file_list_vb->show(); button_favorite->hide(); } else { bool collapsed = tree->get_selected()->is_collapsed(); tree->get_selected()->set_collapsed(!collapsed); } //file_options->show(); _update_files(false); //emit_signal("open",path); } void FileSystemDock::_dir_rmb_pressed(const Vector2 &p_pos) { folder_options->clear(); folder_options->set_size(Size2(1, 1)); folder_options->add_item(TTR("Expand all"), FOLDER_EXPAND_ALL); folder_options->add_item(TTR("Collapse all"), FOLDER_COLLAPSE_ALL); TreeItem *item = tree->get_selected(); if (item) { String fpath = item->get_metadata(tree->get_selected_column()); folder_options->add_separator(); folder_options->add_item(TTR("Copy Path"), FOLDER_COPY_PATH); if (fpath != "res://") { folder_options->add_item(TTR("Rename.."), FOLDER_RENAME); folder_options->add_item(TTR("Move To.."), FOLDER_MOVE); folder_options->add_item(TTR("Delete"), FOLDER_REMOVE); } folder_options->add_separator(); folder_options->add_item(TTR("New Folder.."), FOLDER_NEW_FOLDER); folder_options->add_item(TTR("Show In File Manager"), FOLDER_SHOW_IN_EXPLORER); } folder_options->set_position(tree->get_global_position() + p_pos); folder_options->popup(); } void FileSystemDock::_search_changed(const String &p_text) { if (file_list_vb->is_visible()) _update_files(false); } void FileSystemDock::_rescan() { _set_scanning_mode(); EditorFileSystem::get_singleton()->scan(); } void FileSystemDock::fix_dependencies(const String &p_for_file) { deps_editor->edit(p_for_file); } void FileSystemDock::focus_on_filter() { if (low_height_mode && tree->is_visible()) { // Tree mode, switch to files list with search box tree->hide(); file_list_vb->show(); button_favorite->hide(); } search_box->grab_focus(); } void FileSystemDock::set_display_mode(int p_mode) { if (p_mode == display_mode) return; button_display_mode->set_pressed(p_mode == DISPLAY_LIST); _change_file_display(); } Variant FileSystemDock::get_drag_data_fw(const Point2 &p_point, Control *p_from) { bool is_favorite = false; Vector<String> paths; if (p_from == tree) { TreeItem *selected = tree->get_selected(); if (!selected) return Variant(); String folder = selected->get_metadata(0); if (folder == String()) return Variant(); paths.push_back(folder.ends_with("/") ? folder : (folder + "/")); is_favorite = selected->get_parent() != NULL && tree->get_root()->get_children() == selected->get_parent(); } else if (p_from == files) { for (int i = 0; i < files->get_item_count(); i++) { if (files->is_selected(i)) { paths.push_back(files->get_item_metadata(i)); } } } if (paths.empty()) return Variant(); Dictionary drag_data = EditorNode::get_singleton()->drag_files_and_dirs(paths, p_from); if (is_favorite) { drag_data["type"] = "favorite"; } return drag_data; } bool FileSystemDock::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const { Dictionary drag_data = p_data; if (drag_data.has("type") && String(drag_data["type"]) == "favorite") { //moving favorite around TreeItem *ti = tree->get_item_at_position(p_point); if (!ti) return false; int what = tree->get_drop_section_at_position(p_point); if (ti == tree->get_root()->get_children()) { return (what == 1); //the parent, first fav } if (ti->get_parent() && tree->get_root()->get_children() == ti->get_parent()) { return true; // a favorite } if (ti == tree->get_root()->get_children()->get_next()) { return (what == -1); //the tree, last fav } return false; } if (drag_data.has("type") && String(drag_data["type"]) == "resource") { String to_dir = _get_drag_target_folder(p_point, p_from); return !to_dir.empty(); } if (drag_data.has("type") && (String(drag_data["type"]) == "files" || String(drag_data["type"]) == "files_and_dirs")) { String to_dir = _get_drag_target_folder(p_point, p_from); if (to_dir.empty()) return false; //Attempting to move a folder into itself will fail later //Rather than bring up a message don't try to do it in the first place to_dir = to_dir.ends_with("/") ? to_dir : (to_dir + "/"); Vector<String> fnames = drag_data["files"]; for (int i = 0; i < fnames.size(); ++i) { if (fnames[i].ends_with("/") && to_dir.begins_with(fnames[i])) return false; } return true; } return false; } void FileSystemDock::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) { if (!can_drop_data_fw(p_point, p_data, p_from)) return; Dictionary drag_data = p_data; if (drag_data.has("type") && String(drag_data["type"]) == "favorite") { //moving favorite around TreeItem *ti = tree->get_item_at_position(p_point); if (!ti) return; Vector<String> files = drag_data["files"]; ERR_FAIL_COND(files.size() != 1); String swap = files[0]; if (swap != "res://" && swap.ends_with("/")) { swap = swap.substr(0, swap.length() - 1); } int what = tree->get_drop_section_at_position(p_point); TreeItem *swap_item = NULL; if (ti == tree->get_root()->get_children()) { swap_item = tree->get_root()->get_children()->get_children(); } else if (ti->get_parent() && tree->get_root()->get_children() == ti->get_parent()) { if (what == -1) { swap_item = ti; } else { swap_item = ti->get_next(); } } String swap_with; if (swap_item) { swap_with = swap_item->get_metadata(0); if (swap_with != "res://" && swap_with.ends_with("/")) { swap_with = swap_with.substr(0, swap_with.length() - 1); } } if (swap == swap_with) return; Vector<String> dirs = EditorSettings::get_singleton()->get_favorite_dirs(); ERR_FAIL_COND(dirs.find(swap) == -1); ERR_FAIL_COND(swap_with != String() && dirs.find(swap_with) == -1); dirs.erase(swap); if (swap_with == String()) { dirs.push_back(swap); } else { int idx = dirs.find(swap_with); dirs.insert(idx, swap); } EditorSettings::get_singleton()->set_favorite_dirs(dirs); _update_tree(true); return; } if (drag_data.has("type") && String(drag_data["type"]) == "resource") { Ref<Resource> res = drag_data["resource"]; String to_dir = _get_drag_target_folder(p_point, p_from); if (res.is_valid() && !to_dir.empty()) { EditorNode::get_singleton()->push_item(res.ptr()); EditorNode::get_singleton()->save_resource_as(res, to_dir); } } if (drag_data.has("type") && (String(drag_data["type"]) == "files" || String(drag_data["type"]) == "files_and_dirs")) { String to_dir = _get_drag_target_folder(p_point, p_from); if (!to_dir.empty()) { Vector<String> fnames = drag_data["files"]; to_move.clear(); for (int i = 0; i < fnames.size(); i++) { to_move.push_back(FileOrFolder(fnames[i], !fnames[i].ends_with("/"))); } _move_operation_confirm(to_dir); } } } String FileSystemDock::_get_drag_target_folder(const Point2 &p_point, Control *p_from) const { if (p_from == files) { int pos = files->get_item_at_position(p_point, true); if (pos == -1) return path; String target = files->get_item_metadata(pos); return target.ends_with("/") ? target : path; } if (p_from == tree) { TreeItem *ti = tree->get_item_at_position(p_point); if (ti && ti != tree->get_root()->get_children()) return ti->get_metadata(0); } return String(); } void FileSystemDock::_files_list_rmb_select(int p_item, const Vector2 &p_pos) { //Right clicking ".." should clear current selection if (files->get_item_text(p_item) == "..") { for (int i = 0; i < files->get_item_count(); i++) { files->unselect(i); } } Vector<String> filenames; Vector<String> foldernames; bool all_files = true; bool all_files_scenes = true; bool all_folders = true; for (int i = 0; i < files->get_item_count(); i++) { if (!files->is_selected(i)) { continue; } String fpath = files->get_item_metadata(i); if (fpath.ends_with("/")) { foldernames.push_back(fpath); all_files = false; } else { filenames.push_back(fpath); all_folders = false; all_files_scenes &= (EditorFileSystem::get_singleton()->get_file_type(fpath) == "PackedScene"); } } file_options->clear(); file_options->set_size(Size2(1, 1)); if (all_files) { if (all_files_scenes && filenames.size() >= 1) { file_options->add_item(TTR("Open Scene(s)"), FILE_OPEN); file_options->add_item(TTR("Instance"), FILE_INSTANCE); file_options->add_separator(); } if (!all_files_scenes && filenames.size() == 1) { file_options->add_item(TTR("Open"), FILE_OPEN); file_options->add_separator(); } if (filenames.size() == 1) { file_options->add_item(TTR("Edit Dependencies.."), FILE_DEPENDENCIES); file_options->add_item(TTR("View Owners.."), FILE_OWNERS); file_options->add_separator(); } } else if (all_folders && foldernames.size() > 0) { file_options->add_item(TTR("Open"), FILE_OPEN); file_options->add_separator(); } int num_items = filenames.size() + foldernames.size(); if (num_items >= 1) { if (num_items == 1) { file_options->add_item(TTR("Copy Path"), FILE_COPY_PATH); file_options->add_item(TTR("Rename.."), FILE_RENAME); file_options->add_item(TTR("Duplicate.."), FILE_DUPLICATE); } file_options->add_item(TTR("Move To.."), FILE_MOVE); file_options->add_item(TTR("Delete"), FILE_REMOVE); file_options->add_separator(); } file_options->add_item(TTR("New Folder.."), FILE_NEW_FOLDER); file_options->add_item(TTR("Show In File Manager"), FILE_SHOW_IN_EXPLORER); file_options->set_position(files->get_global_position() + p_pos); file_options->popup(); } void FileSystemDock::_rmb_pressed(const Vector2 &p_pos) { file_options->clear(); file_options->set_size(Size2(1, 1)); file_options->add_item(TTR("New Folder.."), FILE_NEW_FOLDER); file_options->add_item(TTR("Show In File Manager"), FILE_SHOW_IN_EXPLORER); file_options->set_position(files->get_global_position() + p_pos); file_options->popup(); } void FileSystemDock::select_file(const String &p_file) { navigate_to_path(p_file); } void FileSystemDock::_file_multi_selected(int p_index, bool p_selected) { import_dock_needs_update = true; call_deferred("_update_import_dock"); } void FileSystemDock::_files_gui_input(Ref<InputEvent> p_event) { if (get_viewport()->get_modal_stack_top()) return; //ignore because of modal window Ref<InputEventKey> key = p_event; if (key.is_valid() && key->is_pressed() && !key->is_echo()) { if (ED_IS_SHORTCUT("filesystem_dock/duplicate", p_event)) { _file_option(FILE_DUPLICATE); } else if (ED_IS_SHORTCUT("filesystem_dock/copy_path", p_event)) { _file_option(FILE_COPY_PATH); } else if (ED_IS_SHORTCUT("filesystem_dock/delete", p_event)) { _file_option(FILE_REMOVE); } } } void FileSystemDock::_file_selected() { import_dock_needs_update = true; _update_import_dock(); } void FileSystemDock::_update_import_dock() { if (!import_dock_needs_update) return; //check import Vector<String> imports; String import_type; for (int i = 0; i < files->get_item_count(); i++) { if (!files->is_selected(i)) continue; String fpath = files->get_item_metadata(i); if (!FileAccess::exists(fpath + ".import")) { imports.clear(); break; } Ref<ConfigFile> cf; cf.instance(); Error err = cf->load(fpath + ".import"); if (err != OK) { imports.clear(); break; } String type = cf->get_value("remap", "type"); if (import_type == "") { import_type = type; } else if (import_type != type) { //all should be the same type imports.clear(); break; } imports.push_back(fpath); } if (imports.size() == 0) { EditorNode::get_singleton()->get_import_dock()->clear(); } else if (imports.size() == 1) { EditorNode::get_singleton()->get_import_dock()->set_edit_path(imports[0]); } else { EditorNode::get_singleton()->get_import_dock()->set_edit_multiple_paths(imports); } import_dock_needs_update = false; } void FileSystemDock::_bind_methods() { ClassDB::bind_method(D_METHOD("_files_gui_input"), &FileSystemDock::_files_gui_input); ClassDB::bind_method(D_METHOD("_update_tree"), &FileSystemDock::_update_tree); ClassDB::bind_method(D_METHOD("_rescan"), &FileSystemDock::_rescan); ClassDB::bind_method(D_METHOD("_favorites_pressed"), &FileSystemDock::_favorites_pressed); //ClassDB::bind_method(D_METHOD("_instance_pressed"),&ScenesDock::_instance_pressed); ClassDB::bind_method(D_METHOD("_go_to_file_list"), &FileSystemDock::_go_to_file_list); ClassDB::bind_method(D_METHOD("_dir_rmb_pressed"), &FileSystemDock::_dir_rmb_pressed); ClassDB::bind_method(D_METHOD("_thumbnail_done"), &FileSystemDock::_thumbnail_done); ClassDB::bind_method(D_METHOD("_select_file"), &FileSystemDock::_select_file); ClassDB::bind_method(D_METHOD("_go_to_tree"), &FileSystemDock::_go_to_tree); ClassDB::bind_method(D_METHOD("navigate_to_path"), &FileSystemDock::navigate_to_path); ClassDB::bind_method(D_METHOD("_change_file_display"), &FileSystemDock::_change_file_display); ClassDB::bind_method(D_METHOD("_fw_history"), &FileSystemDock::_fw_history); ClassDB::bind_method(D_METHOD("_bw_history"), &FileSystemDock::_bw_history); ClassDB::bind_method(D_METHOD("_fs_changed"), &FileSystemDock::_fs_changed); ClassDB::bind_method(D_METHOD("_dir_selected"), &FileSystemDock::_dir_selected); ClassDB::bind_method(D_METHOD("_file_option"), &FileSystemDock::_file_option); ClassDB::bind_method(D_METHOD("_folder_option"), &FileSystemDock::_folder_option); ClassDB::bind_method(D_METHOD("_make_dir_confirm"), &FileSystemDock::_make_dir_confirm); ClassDB::bind_method(D_METHOD("_move_operation_confirm"), &FileSystemDock::_move_operation_confirm); ClassDB::bind_method(D_METHOD("_rename_operation_confirm"), &FileSystemDock::_rename_operation_confirm); ClassDB::bind_method(D_METHOD("_duplicate_operation_confirm"), &FileSystemDock::_duplicate_operation_confirm); ClassDB::bind_method(D_METHOD("_search_changed"), &FileSystemDock::_search_changed); ClassDB::bind_method(D_METHOD("get_drag_data_fw"), &FileSystemDock::get_drag_data_fw); ClassDB::bind_method(D_METHOD("can_drop_data_fw"), &FileSystemDock::can_drop_data_fw); ClassDB::bind_method(D_METHOD("drop_data_fw"), &FileSystemDock::drop_data_fw); ClassDB::bind_method(D_METHOD("_files_list_rmb_select"), &FileSystemDock::_files_list_rmb_select); ClassDB::bind_method(D_METHOD("_preview_invalidated"), &FileSystemDock::_preview_invalidated); ClassDB::bind_method(D_METHOD("_file_selected"), &FileSystemDock::_file_selected); ClassDB::bind_method(D_METHOD("_file_multi_selected"), &FileSystemDock::_file_multi_selected); ClassDB::bind_method(D_METHOD("_update_import_dock"), &FileSystemDock::_update_import_dock); ClassDB::bind_method(D_METHOD("_rmb_pressed"), &FileSystemDock::_rmb_pressed); ADD_SIGNAL(MethodInfo("instance", PropertyInfo(Variant::POOL_STRING_ARRAY, "files"))); ADD_SIGNAL(MethodInfo("open")); } FileSystemDock::FileSystemDock(EditorNode *p_editor) { set_name("FileSystem"); editor = p_editor; path = "res://"; ED_SHORTCUT("filesystem_dock/copy_path", TTR("Copy Path"), KEY_MASK_CMD | KEY_C); ED_SHORTCUT("filesystem_dock/duplicate", TTR("Duplicate..."), KEY_MASK_CMD | KEY_D); ED_SHORTCUT("filesystem_dock/delete", TTR("Delete"), KEY_DELETE); HBoxContainer *toolbar_hbc = memnew(HBoxContainer); add_child(toolbar_hbc); button_hist_prev = memnew(ToolButton); button_hist_prev->set_disabled(true); button_hist_prev->set_focus_mode(FOCUS_NONE); button_hist_prev->set_tooltip(TTR("Previous Directory")); toolbar_hbc->add_child(button_hist_prev); button_hist_next = memnew(ToolButton); button_hist_next->set_disabled(true); button_hist_next->set_focus_mode(FOCUS_NONE); button_hist_next->set_tooltip(TTR("Next Directory")); toolbar_hbc->add_child(button_hist_next); current_path = memnew(LineEdit); current_path->set_h_size_flags(SIZE_EXPAND_FILL); toolbar_hbc->add_child(current_path); button_reload = memnew(Button); button_reload->set_flat(true); button_reload->connect("pressed", this, "_rescan"); button_reload->set_focus_mode(FOCUS_NONE); button_reload->set_tooltip(TTR("Re-Scan Filesystem")); button_reload->hide(); toolbar_hbc->add_child(button_reload); //toolbar_hbc->add_spacer(); button_favorite = memnew(Button); button_favorite->set_flat(true); button_favorite->set_toggle_mode(true); button_favorite->connect("pressed", this, "_favorites_pressed"); button_favorite->set_tooltip(TTR("Toggle folder status as Favorite")); button_favorite->set_focus_mode(FOCUS_NONE); toolbar_hbc->add_child(button_favorite); //Control *spacer = memnew( Control); /* button_open = memnew( Button ); button_open->set_flat(true); button_open->connect("pressed",this,"_go_to_file_list"); toolbar_hbc->add_child(button_open); button_open->hide(); button_open->set_focus_mode(FOCUS_NONE); button_open->set_tooltip("Open the selected file.\nOpen as scene if a scene, or as resource otherwise."); button_instance = memnew( Button ); button_instance->set_flat(true); button_instance->connect("pressed",this,"_instance_pressed"); toolbar_hbc->add_child(button_instance); button_instance->hide(); button_instance->set_focus_mode(FOCUS_NONE); button_instance->set_tooltip(TTR("Instance the selected scene(s) as child of the selected node.")); */ file_options = memnew(PopupMenu); add_child(file_options); folder_options = memnew(PopupMenu); add_child(folder_options); split_box = memnew(VSplitContainer); split_box->set_v_size_flags(SIZE_EXPAND_FILL); add_child(split_box); tree = memnew(Tree); tree->set_hide_root(true); tree->set_drag_forwarding(this); tree->set_allow_rmb_select(true); tree->set_custom_minimum_size(Size2(0, 200 * EDSCALE)); split_box->add_child(tree); tree->connect("item_edited", this, "_favorite_toggled"); tree->connect("item_activated", this, "_go_to_file_list"); tree->connect("cell_selected", this, "_dir_selected"); tree->connect("item_rmb_selected", this, "_dir_rmb_pressed"); file_list_vb = memnew(VBoxContainer); file_list_vb->set_v_size_flags(SIZE_EXPAND_FILL); split_box->add_child(file_list_vb); path_hb = memnew(HBoxContainer); file_list_vb->add_child(path_hb); button_tree = memnew(ToolButton); button_tree->hide(); path_hb->add_child(button_tree); search_box = memnew(LineEdit); search_box->set_h_size_flags(SIZE_EXPAND_FILL); search_box->connect("text_changed", this, "_search_changed"); path_hb->add_child(search_box); button_display_mode = memnew(ToolButton); button_display_mode->set_toggle_mode(true); path_hb->add_child(button_display_mode); files = memnew(ItemList); files->set_v_size_flags(SIZE_EXPAND_FILL); files->set_select_mode(ItemList::SELECT_MULTI); files->set_drag_forwarding(this); files->connect("item_rmb_selected", this, "_files_list_rmb_select"); files->connect("gui_input", this, "_files_gui_input"); files->connect("item_selected", this, "_file_selected"); files->connect("multi_selected", this, "_file_multi_selected"); files->connect("rmb_clicked", this, "_rmb_pressed"); files->set_allow_rmb_select(true); file_list_vb->add_child(files); scanning_vb = memnew(VBoxContainer); scanning_vb->hide(); add_child(scanning_vb); Label *slabel = memnew(Label); slabel->set_text(TTR("Scanning Files,\nPlease Wait..")); slabel->set_align(Label::ALIGN_CENTER); scanning_vb->add_child(slabel); scanning_progress = memnew(ProgressBar); scanning_vb->add_child(scanning_progress); deps_editor = memnew(DependencyEditor); add_child(deps_editor); owners_editor = memnew(DependencyEditorOwners(editor)); add_child(owners_editor); remove_dialog = memnew(DependencyRemoveDialog); add_child(remove_dialog); move_dialog = memnew(EditorDirDialog); move_dialog->get_ok()->set_text(TTR("Move")); add_child(move_dialog); move_dialog->connect("dir_selected", this, "_move_operation_confirm"); rename_dialog = memnew(ConfirmationDialog); VBoxContainer *rename_dialog_vb = memnew(VBoxContainer); rename_dialog->add_child(rename_dialog_vb); rename_dialog_text = memnew(LineEdit); rename_dialog_vb->add_margin_child(TTR("Name:"), rename_dialog_text); rename_dialog->get_ok()->set_text(TTR("Rename")); add_child(rename_dialog); rename_dialog->register_text_enter(rename_dialog_text); rename_dialog->connect("confirmed", this, "_rename_operation_confirm"); duplicate_dialog = memnew(ConfirmationDialog); VBoxContainer *duplicate_dialog_vb = memnew(VBoxContainer); duplicate_dialog->add_child(duplicate_dialog_vb); duplicate_dialog_text = memnew(LineEdit); duplicate_dialog_vb->add_margin_child(TTR("Name:"), duplicate_dialog_text); duplicate_dialog->get_ok()->set_text(TTR("Duplicate")); add_child(duplicate_dialog); duplicate_dialog->register_text_enter(duplicate_dialog_text); duplicate_dialog->connect("confirmed", this, "_duplicate_operation_confirm"); make_dir_dialog = memnew(ConfirmationDialog); make_dir_dialog->set_title(TTR("Create Folder")); VBoxContainer *make_folder_dialog_vb = memnew(VBoxContainer); make_dir_dialog->add_child(make_folder_dialog_vb); make_dir_dialog_text = memnew(LineEdit); make_folder_dialog_vb->add_margin_child(TTR("Name:"), make_dir_dialog_text); add_child(make_dir_dialog); make_dir_dialog->register_text_enter(make_dir_dialog_text); make_dir_dialog->connect("confirmed", this, "_make_dir_confirm"); updating_tree = false; initialized = false; import_dock_needs_update = false; history_pos = 0; history_max_size = 20; history.push_back("res://"); low_height_mode = false; display_mode = DISPLAY_THUMBNAILS; } FileSystemDock::~FileSystemDock() { } Fixing folder/file case sensitive renaming issue Example: Could not rename "Objects" to "objects" or vice versa /*************************************************************************/ /* filesystem_dock.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "filesystem_dock.h" #include "core/os/keyboard.h" #include "editor_node.h" #include "editor_settings.h" #include "io/resource_loader.h" #include "os/dir_access.h" #include "os/file_access.h" #include "os/os.h" #include "project_settings.h" #include "scene/main/viewport.h" bool FileSystemDock::_create_tree(TreeItem *p_parent, EditorFileSystemDirectory *p_dir, Vector<String> &uncollapsed_paths) { TreeItem *item = tree->create_item(p_parent); String dname = p_dir->get_name(); if (dname == "") dname = "res://"; item->set_text(0, dname); item->set_icon(0, get_icon("Folder", "EditorIcons")); item->set_selectable(0, true); String lpath = p_dir->get_path(); if (lpath != "res://" && lpath.ends_with("/")) { lpath = lpath.substr(0, lpath.length() - 1); } item->set_metadata(0, lpath); if (lpath == path) { item->select(0); } if ((path.begins_with(lpath) && path != lpath)) { item->set_collapsed(false); } else { bool is_collapsed = true; for (int i = 0; i < uncollapsed_paths.size(); i++) { if (lpath == uncollapsed_paths[i]) { is_collapsed = false; break; } } item->set_collapsed(is_collapsed); } for (int i = 0; i < p_dir->get_subdir_count(); i++) _create_tree(item, p_dir->get_subdir(i), uncollapsed_paths); return true; } void FileSystemDock::_update_tree(bool keep_collapse_state, bool p_uncollapse_root) { Vector<String> uncollapsed_paths; if (keep_collapse_state) { TreeItem *root = tree->get_root(); if (root) { TreeItem *resTree = root->get_children()->get_next(); Vector<TreeItem *> needs_check; needs_check.push_back(resTree); while (needs_check.size()) { if (!needs_check[0]->is_collapsed()) { uncollapsed_paths.push_back(needs_check[0]->get_metadata(0)); TreeItem *child = needs_check[0]->get_children(); while (child) { needs_check.push_back(child); child = child->get_next(); } } needs_check.remove(0); } } } tree->clear(); updating_tree = true; TreeItem *root = tree->create_item(); TreeItem *favorites = tree->create_item(root); favorites->set_icon(0, get_icon("Favorites", "EditorIcons")); favorites->set_text(0, TTR("Favorites:")); favorites->set_selectable(0, false); Vector<String> favorite_paths = EditorSettings::get_singleton()->get_favorite_dirs(); String res_path = "res://"; Ref<Texture> folder_icon = get_icon("Folder", "EditorIcons"); for (int i = 0; i < favorite_paths.size(); i++) { String fave = favorite_paths[i]; if (!fave.begins_with(res_path)) continue; TreeItem *ti = tree->create_item(favorites); if (fave == res_path) ti->set_text(0, "/"); else ti->set_text(0, fave.get_file()); ti->set_icon(0, folder_icon); ti->set_selectable(0, true); ti->set_metadata(0, fave); } if (p_uncollapse_root) { uncollapsed_paths.push_back("res://"); } _create_tree(root, EditorFileSystem::get_singleton()->get_filesystem(), uncollapsed_paths); tree->ensure_cursor_is_visible(); updating_tree = false; } void FileSystemDock::_notification(int p_what) { switch (p_what) { case NOTIFICATION_RESIZED: { bool new_mode = get_size().height < get_viewport_rect().size.height / 2; if (new_mode != low_height_mode) { low_height_mode = new_mode; if (low_height_mode) { tree->hide(); tree->set_v_size_flags(SIZE_EXPAND_FILL); button_tree->show(); } else { tree->set_v_size_flags(SIZE_FILL); button_tree->hide(); if (!tree->is_visible()) { tree->show(); button_favorite->show(); _update_tree(true); } tree->ensure_cursor_is_visible(); if (!file_list_vb->is_visible()) { file_list_vb->show(); _update_files(true); } } } } break; case NOTIFICATION_ENTER_TREE: { if (initialized) return; initialized = true; EditorFileSystem::get_singleton()->connect("filesystem_changed", this, "_fs_changed"); EditorResourcePreview::get_singleton()->connect("preview_invalidated", this, "_preview_invalidated"); String ei = "EditorIcons"; button_reload->set_icon(get_icon("Reload", ei)); button_favorite->set_icon(get_icon("Favorites", ei)); //button_instance->set_icon(get_icon("Add", ei)); //button_open->set_icon(get_icon("Folder", ei)); button_tree->set_icon(get_icon("Filesystem", ei)); _update_file_display_toggle_button(); button_display_mode->connect("pressed", this, "_change_file_display"); //file_options->set_icon( get_icon("Tools","ei")); files->connect("item_activated", this, "_select_file"); button_hist_next->connect("pressed", this, "_fw_history"); button_hist_prev->connect("pressed", this, "_bw_history"); search_box->add_icon_override("right_icon", get_icon("Search", ei)); button_hist_next->set_icon(get_icon("Forward", ei)); button_hist_prev->set_icon(get_icon("Back", ei)); file_options->connect("id_pressed", this, "_file_option"); folder_options->connect("id_pressed", this, "_folder_option"); button_tree->connect("pressed", this, "_go_to_tree", varray(), CONNECT_DEFERRED); current_path->connect("text_entered", this, "navigate_to_path"); if (EditorFileSystem::get_singleton()->is_scanning()) { _set_scanning_mode(); } else { _update_tree(false, true); } } break; case NOTIFICATION_PROCESS: { if (EditorFileSystem::get_singleton()->is_scanning()) { scanning_progress->set_value(EditorFileSystem::get_singleton()->get_scanning_progress() * 100); } } break; case NOTIFICATION_EXIT_TREE: { } break; case NOTIFICATION_DRAG_BEGIN: { Dictionary dd = get_viewport()->gui_get_drag_data(); if (tree->is_visible_in_tree() && dd.has("type")) { if ((String(dd["type"]) == "files") || (String(dd["type"]) == "files_and_dirs") || (String(dd["type"]) == "resource")) { tree->set_drop_mode_flags(Tree::DROP_MODE_ON_ITEM); } else if ((String(dd["type"]) == "favorite")) { tree->set_drop_mode_flags(Tree::DROP_MODE_INBETWEEN); } } } break; case NOTIFICATION_DRAG_END: { tree->set_drop_mode_flags(0); } break; case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { String ei = "EditorIcons"; int new_mode = int(EditorSettings::get_singleton()->get("docks/filesystem/display_mode")); //_update_icons button_reload->set_icon(get_icon("Reload", ei)); button_favorite->set_icon(get_icon("Favorites", ei)); button_tree->set_icon(get_icon("Filesystem", ei)); button_hist_next->set_icon(get_icon("Forward", ei)); button_hist_prev->set_icon(get_icon("Back", ei)); search_box->add_icon_override("right_icon", get_icon("Search", ei)); if (new_mode != display_mode) { set_display_mode(new_mode); } else { _update_file_display_toggle_button(); _update_files(true); } _update_tree(true); } break; } } void FileSystemDock::_dir_selected() { TreeItem *sel = tree->get_selected(); if (!sel) return; path = sel->get_metadata(0); bool found = false; Vector<String> favorites = EditorSettings::get_singleton()->get_favorite_dirs(); for (int i = 0; i < favorites.size(); i++) { if (favorites[i] == path) { found = true; break; } } button_favorite->set_pressed(found); current_path->set_text(path); _push_to_history(); if (!low_height_mode) { _update_files(false); } } void FileSystemDock::_favorites_pressed() { TreeItem *sel = tree->get_selected(); if (!sel) return; path = sel->get_metadata(0); int idx = -1; Vector<String> favorites = EditorSettings::get_singleton()->get_favorite_dirs(); for (int i = 0; i < favorites.size(); i++) { if (favorites[i] == path) { idx = i; break; } } if (idx == -1) { favorites.push_back(path); } else { favorites.remove(idx); } EditorSettings::get_singleton()->set_favorite_dirs(favorites); _update_tree(true); } String FileSystemDock::get_selected_path() const { TreeItem *sel = tree->get_selected(); if (!sel) return ""; return sel->get_metadata(0); } String FileSystemDock::get_current_path() const { return path; } void FileSystemDock::navigate_to_path(const String &p_path) { // If the path is a file, do not only go to the directory in the tree, also select the file in the file list. String file_name = ""; DirAccess *dirAccess = DirAccess::open("res://"); if (dirAccess->file_exists(p_path)) { path = p_path.get_base_dir(); file_name = p_path.get_file(); } else if (dirAccess->dir_exists(p_path)) { path = p_path; } else { ERR_EXPLAIN(vformat(TTR("Cannot navigate to '%s' as it has not been found in the file system!"), p_path)); ERR_FAIL(); } current_path->set_text(path); _push_to_history(); if (!low_height_mode) { _update_tree(true); _update_files(false); } else { _go_to_file_list(); } if (!file_name.empty()) { for (int i = 0; i < files->get_item_count(); i++) { if (files->get_item_text(i) == file_name) { files->select(i, true); files->ensure_current_is_visible(); break; } } } } void FileSystemDock::_thumbnail_done(const String &p_path, const Ref<Texture> &p_preview, const Variant &p_udata) { if ((file_list_vb->is_visible_in_tree() || path == p_path.get_base_dir()) && p_preview.is_valid()) { Array uarr = p_udata; int idx = uarr[0]; String file = uarr[1]; if (idx < files->get_item_count() && files->get_item_text(idx) == file && files->get_item_metadata(idx) == p_path) files->set_item_icon(idx, p_preview); } } void FileSystemDock::_update_file_display_toggle_button() { if (button_display_mode->is_pressed()) { display_mode = DISPLAY_LIST; button_display_mode->set_icon(get_icon("FileThumbnail", "EditorIcons")); button_display_mode->set_tooltip(TTR("View items as a grid of thumbnails")); } else { display_mode = DISPLAY_THUMBNAILS; button_display_mode->set_icon(get_icon("FileList", "EditorIcons")); button_display_mode->set_tooltip(TTR("View items as a list")); } } void FileSystemDock::_change_file_display() { _update_file_display_toggle_button(); EditorSettings::get_singleton()->set("docks/filesystem/display_mode", display_mode); _update_files(true); } void FileSystemDock::_search(EditorFileSystemDirectory *p_path, List<FileInfo> *matches, int p_max_items) { if (matches->size() > p_max_items) return; for (int i = 0; i < p_path->get_subdir_count(); i++) { _search(p_path->get_subdir(i), matches, p_max_items); } String match = search_box->get_text().to_lower(); for (int i = 0; i < p_path->get_file_count(); i++) { String file = p_path->get_file(i); if (file.to_lower().find(match) != -1) { FileInfo fi; fi.name = file; fi.type = p_path->get_file_type(i); fi.path = p_path->get_file_path(i); fi.import_broken = !p_path->get_file_import_is_valid(i); fi.import_status = 0; matches->push_back(fi); if (matches->size() > p_max_items) return; } } } void FileSystemDock::_update_files(bool p_keep_selection) { Set<String> cselection; if (p_keep_selection) { for (int i = 0; i < files->get_item_count(); i++) { if (files->is_selected(i)) cselection.insert(files->get_item_text(i)); } } files->clear(); current_path->set_text(path); EditorFileSystemDirectory *efd = EditorFileSystem::get_singleton()->get_filesystem_path(path); if (!efd) return; String ei = "EditorIcons"; int thumbnail_size = EditorSettings::get_singleton()->get("docks/filesystem/thumbnail_size"); thumbnail_size *= EDSCALE; Ref<Texture> folder_thumbnail; Ref<Texture> file_thumbnail; Ref<Texture> file_thumbnail_broken; bool always_show_folders = EditorSettings::get_singleton()->get("docks/filesystem/always_show_folders"); bool use_thumbnails = (display_mode == DISPLAY_THUMBNAILS); bool use_folders = search_box->get_text().length() == 0 && (low_height_mode || always_show_folders); if (use_thumbnails) { files->set_max_columns(0); files->set_icon_mode(ItemList::ICON_MODE_TOP); files->set_fixed_column_width(thumbnail_size * 3 / 2); files->set_max_text_lines(2); files->set_fixed_icon_size(Size2(thumbnail_size, thumbnail_size)); if (thumbnail_size < 64) { folder_thumbnail = get_icon("FolderMediumThumb", ei); file_thumbnail = get_icon("FileMediumThumb", ei); file_thumbnail_broken = get_icon("FileDeadMediumThumb", ei); } else { folder_thumbnail = get_icon("FolderBigThumb", ei); file_thumbnail = get_icon("FileBigThumb", ei); file_thumbnail_broken = get_icon("FileDeadBigThumb", ei); } } else { files->set_icon_mode(ItemList::ICON_MODE_LEFT); files->set_max_columns(1); files->set_max_text_lines(1); files->set_fixed_column_width(0); files->set_fixed_icon_size(Size2()); } if (use_folders) { Ref<Texture> folderIcon = (use_thumbnails) ? folder_thumbnail : get_icon("folder", "FileDialog"); if (path != "res://") { files->add_item("..", folderIcon, true); String bd = path.get_base_dir(); if (bd != "res://" && !bd.ends_with("/")) bd += "/"; files->set_item_metadata(files->get_item_count() - 1, bd); } for (int i = 0; i < efd->get_subdir_count(); i++) { String dname = efd->get_subdir(i)->get_name(); files->add_item(dname, folderIcon, true); files->set_item_metadata(files->get_item_count() - 1, path.plus_file(dname) + "/"); if (cselection.has(dname)) files->select(files->get_item_count() - 1, false); } } List<FileInfo> filelist; if (search_box->get_text().length() > 0) { _search(EditorFileSystem::get_singleton()->get_filesystem(), &filelist, 128); filelist.sort(); } else { for (int i = 0; i < efd->get_file_count(); i++) { FileInfo fi; fi.name = efd->get_file(i); fi.path = path.plus_file(fi.name); fi.type = efd->get_file_type(i); fi.import_broken = !efd->get_file_import_is_valid(i); fi.import_status = 0; filelist.push_back(fi); } } String oi = "Object"; for (List<FileInfo>::Element *E = filelist.front(); E; E = E->next()) { FileInfo *finfo = &(E->get()); String fname = finfo->name; String fpath = finfo->path; String ftype = finfo->type; Ref<Texture> type_icon; Ref<Texture> big_icon; String tooltip = fname; if (!finfo->import_broken) { type_icon = (has_icon(ftype, ei)) ? get_icon(ftype, ei) : get_icon(oi, ei); big_icon = file_thumbnail; } else { type_icon = get_icon("ImportFail", ei); big_icon = file_thumbnail_broken; tooltip += "\n" + TTR("Status: Import of file failed. Please fix file and reimport manually."); } int item_index; if (use_thumbnails) { files->add_item(fname, big_icon, true); item_index = files->get_item_count() - 1; files->set_item_metadata(item_index, fpath); files->set_item_tag_icon(item_index, type_icon); if (!finfo->import_broken) { Array udata; udata.resize(2); udata[0] = item_index; udata[1] = fname; EditorResourcePreview::get_singleton()->queue_resource_preview(fpath, this, "_thumbnail_done", udata); } } else { files->add_item(fname, type_icon, true); item_index = files->get_item_count() - 1; files->set_item_metadata(item_index, fpath); } if (cselection.has(fname)) files->select(item_index, false); if (finfo->sources.size()) { for (int j = 0; j < finfo->sources.size(); j++) { tooltip += "\nSource: " + finfo->sources[j]; } } files->set_item_tooltip(item_index, tooltip); } } void FileSystemDock::_select_file(int p_idx) { String fpath = files->get_item_metadata(p_idx); if (fpath.ends_with("/")) { if (fpath != "res://") { fpath = fpath.substr(0, fpath.length() - 1); } navigate_to_path(fpath); } else { if (ResourceLoader::get_resource_type(fpath) == "PackedScene") { editor->open_request(fpath); } else { editor->load_resource(fpath); } } } void FileSystemDock::_go_to_tree() { if (low_height_mode) { tree->show(); button_favorite->show(); file_list_vb->hide(); } _update_tree(true); tree->grab_focus(); tree->ensure_cursor_is_visible(); //button_open->hide(); //file_options->hide(); } void FileSystemDock::_preview_invalidated(const String &p_path) { if (display_mode == DISPLAY_THUMBNAILS && p_path.get_base_dir() == path && search_box->get_text() == String() && file_list_vb->is_visible_in_tree()) { for (int i = 0; i < files->get_item_count(); i++) { if (files->get_item_metadata(i) == p_path) { //re-request preview Array udata; udata.resize(2); udata[0] = i; udata[1] = files->get_item_text(i); EditorResourcePreview::get_singleton()->queue_resource_preview(p_path, this, "_thumbnail_done", udata); break; } } } } void FileSystemDock::_fs_changed() { button_hist_prev->set_disabled(history_pos == 0); button_hist_next->set_disabled(history_pos == history.size() - 1); scanning_vb->hide(); split_box->show(); if (tree->is_visible()) { _update_tree(true); } if (file_list_vb->is_visible()) { _update_files(true); } set_process(false); } void FileSystemDock::_set_scanning_mode() { button_hist_prev->set_disabled(true); button_hist_next->set_disabled(true); split_box->hide(); scanning_vb->show(); set_process(true); if (EditorFileSystem::get_singleton()->is_scanning()) { scanning_progress->set_value(EditorFileSystem::get_singleton()->get_scanning_progress() * 100); } else { scanning_progress->set_value(0); } } void FileSystemDock::_fw_history() { if (history_pos < history.size() - 1) history_pos++; _update_history(); } void FileSystemDock::_bw_history() { if (history_pos > 0) history_pos--; _update_history(); } void FileSystemDock::_update_history() { path = history[history_pos]; current_path->set_text(path); if (tree->is_visible()) { _update_tree(true); tree->grab_focus(); tree->ensure_cursor_is_visible(); } if (file_list_vb->is_visible()) { _update_files(false); } button_hist_prev->set_disabled(history_pos == 0); button_hist_next->set_disabled(history_pos == history.size() - 1); } void FileSystemDock::_push_to_history() { if (history[history_pos] != path) { history.resize(history_pos + 1); history.push_back(path); history_pos++; if (history.size() > history_max_size) { history.remove(0); history_pos = history_max_size - 1; } } button_hist_prev->set_disabled(history_pos == 0); button_hist_next->set_disabled(history_pos == history.size() - 1); } void FileSystemDock::_get_all_files_in_dir(EditorFileSystemDirectory *efsd, Vector<String> &files) const { if (efsd == NULL) return; for (int i = 0; i < efsd->get_subdir_count(); i++) { _get_all_files_in_dir(efsd->get_subdir(i), files); } for (int i = 0; i < efsd->get_file_count(); i++) { files.push_back(efsd->get_file_path(i)); } } void FileSystemDock::_find_remaps(EditorFileSystemDirectory *efsd, const Map<String, String> &renames, Vector<String> &to_remaps) const { for (int i = 0; i < efsd->get_subdir_count(); i++) { _find_remaps(efsd->get_subdir(i), renames, to_remaps); } for (int i = 0; i < efsd->get_file_count(); i++) { Vector<String> deps = efsd->get_file_deps(i); for (int j = 0; j < deps.size(); j++) { if (renames.has(deps[j])) { to_remaps.push_back(efsd->get_file_path(i)); break; } } } } void FileSystemDock::_try_move_item(const FileOrFolder &p_item, const String &p_new_path, Map<String, String> &p_renames) const { //Ensure folder paths end with "/" String old_path = (p_item.is_file || p_item.path.ends_with("/")) ? p_item.path : (p_item.path + "/"); String new_path = (p_item.is_file || p_new_path.ends_with("/")) ? p_new_path : (p_new_path + "/"); if (new_path == old_path) { return; } else if (old_path == "res://") { EditorNode::get_singleton()->add_io_error(TTR("Cannot move/rename resources root.")); return; } else if (!p_item.is_file && new_path.begins_with(old_path)) { //This check doesn't erroneously catch renaming to a longer name as folder paths always end with "/" EditorNode::get_singleton()->add_io_error(TTR("Cannot move a folder into itself.") + "\n" + old_path + "\n"); return; } //Build a list of files which will have new paths as a result of this operation Vector<String> changed_paths; if (p_item.is_file) { changed_paths.push_back(old_path); } else { _get_all_files_in_dir(EditorFileSystem::get_singleton()->get_filesystem_path(old_path), changed_paths); } DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); print_line("Moving " + old_path + " -> " + new_path); Error err = da->rename(old_path, new_path); if (err == OK) { //Move/Rename any corresponding import settings too if (p_item.is_file && FileAccess::exists(old_path + ".import")) { err = da->rename(old_path + ".import", new_path + ".import"); if (err != OK) { EditorNode::get_singleton()->add_io_error(TTR("Error moving:") + "\n" + old_path + ".import\n"); } } // update scene if it is open for (int i = 0; i < changed_paths.size(); ++i) { String new_item_path = p_item.is_file ? new_path : changed_paths[i].replace_first(old_path, new_path); if (ResourceLoader::get_resource_type(new_item_path) == "PackedScene" && editor->is_scene_open(changed_paths[i])) { EditorData *ed = &editor->get_editor_data(); for (int j = 0; j < ed->get_edited_scene_count(); j++) { if (ed->get_scene_path(j) == changed_paths[i]) { ed->get_edited_scene_root(j)->set_filename(new_item_path); break; } } } } //Only treat as a changed dependency if it was successfully moved for (int i = 0; i < changed_paths.size(); ++i) { p_renames[changed_paths[i]] = changed_paths[i].replace_first(old_path, new_path); print_line(" Remap: " + changed_paths[i] + " -> " + p_renames[changed_paths[i]]); } } else { EditorNode::get_singleton()->add_io_error(TTR("Error moving:") + "\n" + old_path + "\n"); } memdelete(da); } void FileSystemDock::_try_duplicate_item(const FileOrFolder &p_item, const String &p_new_path) const { //Ensure folder paths end with "/" String old_path = (p_item.is_file || p_item.path.ends_with("/")) ? p_item.path : (p_item.path + "/"); String new_path = (p_item.is_file || p_new_path.ends_with("/")) ? p_new_path : (p_new_path + "/"); if (new_path == old_path) { return; } else if (old_path == "res://") { EditorNode::get_singleton()->add_io_error(TTR("Cannot move/rename resources root.")); return; } else if (!p_item.is_file && new_path.begins_with(old_path)) { //This check doesn't erroneously catch renaming to a longer name as folder paths always end with "/" EditorNode::get_singleton()->add_io_error(TTR("Cannot move a folder into itself.") + "\n" + old_path + "\n"); return; } DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); print_line("Duplicating " + old_path + " -> " + new_path); Error err = p_item.is_file ? da->copy(old_path, new_path) : da->copy_dir(old_path, new_path); if (err == OK) { //Move/Rename any corresponding import settings too if (p_item.is_file && FileAccess::exists(old_path + ".import")) { err = da->copy(old_path + ".import", new_path + ".import"); if (err != OK) { EditorNode::get_singleton()->add_io_error(TTR("Error duplicating:") + "\n" + old_path + ".import\n"); } } } else { EditorNode::get_singleton()->add_io_error(TTR("Error duplicating:") + "\n" + old_path + "\n"); } memdelete(da); } void FileSystemDock::_update_resource_paths_after_move(const Map<String, String> &p_renames) const { //Rename all resources loaded, be it subresources or actual resources List<Ref<Resource> > cached; ResourceCache::get_cached_resources(&cached); for (List<Ref<Resource> >::Element *E = cached.front(); E; E = E->next()) { Ref<Resource> r = E->get(); String base_path = r->get_path(); String extra_path; int sep_pos = r->get_path().find("::"); if (sep_pos >= 0) { extra_path = base_path.substr(sep_pos, base_path.length()); base_path = base_path.substr(0, sep_pos); } if (p_renames.has(base_path)) { base_path = p_renames[base_path]; } r->set_path(base_path + extra_path); } for (int i = 0; i < EditorNode::get_editor_data().get_edited_scene_count(); i++) { String path; if (i == EditorNode::get_editor_data().get_edited_scene()) { if (!get_tree()->get_edited_scene_root()) continue; path = get_tree()->get_edited_scene_root()->get_filename(); } else { path = EditorNode::get_editor_data().get_scene_path(i); } if (p_renames.has(path)) { path = p_renames[path]; } if (i == EditorNode::get_editor_data().get_edited_scene()) { get_tree()->get_edited_scene_root()->set_filename(path); } else { EditorNode::get_editor_data().set_scene_path(i, path); } } } void FileSystemDock::_update_dependencies_after_move(const Map<String, String> &p_renames) const { //The following code assumes that the following holds: // 1) EditorFileSystem contains the old paths/folder structure from before the rename/move. // 2) ResourceLoader can use the new paths without needing to call rescan. Vector<String> remaps; _find_remaps(EditorFileSystem::get_singleton()->get_filesystem(), p_renames, remaps); for (int i = 0; i < remaps.size(); ++i) { //Because we haven't called a rescan yet the found remap might still be an old path itself. String file = p_renames.has(remaps[i]) ? p_renames[remaps[i]] : remaps[i]; print_line("Remapping dependencies for: " + file); Error err = ResourceLoader::rename_dependencies(file, p_renames); if (err == OK) { if (ResourceLoader::get_resource_type(file) == "PackedScene") editor->reload_scene(file); } else { EditorNode::get_singleton()->add_io_error(TTR("Unable to update dependencies:") + "\n" + remaps[i] + "\n"); } } } void FileSystemDock::_make_dir_confirm() { String dir_name = make_dir_dialog_text->get_text().strip_edges(); if (dir_name.length() == 0) { EditorNode::get_singleton()->show_warning(TTR("No name provided")); return; } else if (dir_name.find("/") != -1 || dir_name.find("\\") != -1 || dir_name.find(":") != -1) { EditorNode::get_singleton()->show_warning(TTR("Provided name contains invalid characters")); return; } print_line("Making folder " + dir_name + " in " + path); DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); Error err = da->change_dir(path); if (err == OK) { err = da->make_dir(dir_name); } memdelete(da); if (err == OK) { print_line("call rescan!"); _rescan(); } else { EditorNode::get_singleton()->show_warning(TTR("Could not create folder.")); } } void FileSystemDock::_rename_operation_confirm() { String new_name = rename_dialog_text->get_text().strip_edges(); if (new_name.length() == 0) { EditorNode::get_singleton()->show_warning(TTR("No name provided.")); return; } else if (new_name.find("/") != -1 || new_name.find("\\") != -1 || new_name.find(":") != -1) { EditorNode::get_singleton()->show_warning(TTR("Name contains invalid characters.")); return; } String old_path = to_rename.path.ends_with("/") ? to_rename.path.substr(0, to_rename.path.length() - 1) : to_rename.path; String new_path = old_path.get_base_dir().plus_file(new_name); if (old_path == new_path) { return; } //Present a more user friendly warning for name conflict DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); #if defined(WINDOWS_ENABLED) || defined(UWP_ENABLED) // Workaround case insensitivity on Windows if ((da->file_exists(new_path) || da->dir_exists(new_path)) && new_path.to_lower() != old_path.to_lower()) { #else if (da->file_exists(new_path) || da->dir_exists(new_path)) { #endif EditorNode::get_singleton()->show_warning(TTR("A file or folder with this name already exists.")); memdelete(da); return; } memdelete(da); Map<String, String> renames; _try_move_item(to_rename, new_path, renames); _update_dependencies_after_move(renames); _update_resource_paths_after_move(renames); //Rescan everything print_line("call rescan!"); _rescan(); } void FileSystemDock::_duplicate_operation_confirm() { String new_name = duplicate_dialog_text->get_text().strip_edges(); if (new_name.length() == 0) { EditorNode::get_singleton()->show_warning(TTR("No name provided.")); return; } else if (new_name.find("/") != -1 || new_name.find("\\") != -1 || new_name.find(":") != -1) { EditorNode::get_singleton()->show_warning(TTR("Name contains invalid characters.")); return; } String new_path; String base_dir = to_duplicate.path.get_base_dir(); if (to_duplicate.is_file) { new_path = base_dir.plus_file(new_name); } else { new_path = base_dir.substr(0, base_dir.find_last("/")) + "/" + new_name; } //Present a more user friendly warning for name conflict DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (da->file_exists(new_path) || da->dir_exists(new_path)) { EditorNode::get_singleton()->show_warning(TTR("A file or folder with this name already exists.")); memdelete(da); return; } memdelete(da); _try_duplicate_item(to_duplicate, new_path); //Rescan everything print_line("call rescan!"); _rescan(); } void FileSystemDock::_move_operation_confirm(const String &p_to_path) { Map<String, String> renames; for (int i = 0; i < to_move.size(); i++) { String old_path = to_move[i].path.ends_with("/") ? to_move[i].path.substr(0, to_move[i].path.length() - 1) : to_move[i].path; String new_path = p_to_path.plus_file(old_path.get_file()); _try_move_item(to_move[i], new_path, renames); } _update_dependencies_after_move(renames); _update_resource_paths_after_move(renames); print_line("call rescan!"); _rescan(); } void FileSystemDock::_file_option(int p_option) { switch (p_option) { case FILE_SHOW_IN_EXPLORER: { String dir = ProjectSettings::get_singleton()->globalize_path(this->path); OS::get_singleton()->shell_open(String("file://") + dir); } break; case FILE_OPEN: { for (int i = 0; i < files->get_item_count(); i++) { if (files->is_selected(i)) { _select_file(i); } } } break; case FILE_INSTANCE: { Vector<String> paths; for (int i = 0; i < files->get_item_count(); i++) { if (!files->is_selected(i)) continue; String fpath = files->get_item_metadata(i); if (EditorFileSystem::get_singleton()->get_file_type(fpath) == "PackedScene") { paths.push_back(fpath); } } if (!paths.empty()) { emit_signal("instance", paths); } } break; case FILE_DEPENDENCIES: { int idx = files->get_current(); if (idx < 0 || idx >= files->get_item_count()) break; String fpath = files->get_item_metadata(idx); deps_editor->edit(fpath); } break; case FILE_OWNERS: { int idx = files->get_current(); if (idx < 0 || idx >= files->get_item_count()) break; String fpath = files->get_item_metadata(idx); owners_editor->show(fpath); } break; case FILE_MOVE: { to_move.clear(); for (int i = 0; i < files->get_item_count(); i++) { if (!files->is_selected(i)) continue; String fpath = files->get_item_metadata(i); to_move.push_back(FileOrFolder(fpath, !fpath.ends_with("/"))); } if (to_move.size() > 0) { move_dialog->popup_centered_ratio(); } } break; case FILE_RENAME: { int idx = files->get_current(); if (idx < 0 || idx >= files->get_item_count()) break; to_rename.path = files->get_item_metadata(idx); to_rename.is_file = !to_rename.path.ends_with("/"); if (to_rename.is_file) { String name = to_rename.path.get_file(); rename_dialog->set_title(TTR("Renaming file:") + " " + name); rename_dialog_text->set_text(name); rename_dialog_text->select(0, name.find_last(".")); } else { String name = to_rename.path.substr(0, to_rename.path.length() - 1).get_file(); rename_dialog->set_title(TTR("Renaming folder:") + " " + name); rename_dialog_text->set_text(name); rename_dialog_text->select(0, name.length()); } rename_dialog->popup_centered_minsize(Size2(250, 80) * EDSCALE); rename_dialog_text->grab_focus(); } break; case FILE_REMOVE: { Vector<String> remove_files; Vector<String> remove_folders; for (int i = 0; i < files->get_item_count(); i++) { String fpath = files->get_item_metadata(i); if (files->is_selected(i) && fpath != "res://") { if (fpath.ends_with("/")) { remove_folders.push_back(fpath); } else { remove_files.push_back(fpath); } } } if (remove_files.size() + remove_folders.size() > 0) { remove_dialog->show(remove_folders, remove_files); //1) find if used //2) warn } } break; case FILE_DUPLICATE: { int idx = files->get_current(); if (idx < 0 || idx >= files->get_item_count()) break; to_duplicate.path = files->get_item_metadata(idx); to_duplicate.is_file = !to_duplicate.path.ends_with("/"); if (to_duplicate.is_file) { String name = to_duplicate.path.get_file(); duplicate_dialog->set_title(TTR("Duplicating file:") + " " + name); duplicate_dialog_text->set_text(name); duplicate_dialog_text->select(0, name.find_last(".")); } else { String name = to_duplicate.path.substr(0, to_duplicate.path.length() - 1).get_file(); duplicate_dialog->set_title(TTR("Duplicating folder:") + " " + name); duplicate_dialog_text->set_text(name); duplicate_dialog_text->select(0, name.length()); } duplicate_dialog->popup_centered_minsize(Size2(250, 80) * EDSCALE); duplicate_dialog_text->grab_focus(); } break; case FILE_INFO: { } break; case FILE_REIMPORT: { Vector<String> reimport; for (int i = 0; i < files->get_item_count(); i++) { if (!files->is_selected(i)) continue; String fpath = files->get_item_metadata(i); reimport.push_back(fpath); } ERR_FAIL_COND(reimport.size() == 0); /* Ref<ResourceImportMetadata> rimd = ResourceLoader::load_import_metadata(reimport[0]); ERR_FAIL_COND(!rimd.is_valid()); String editor=rimd->get_editor(); if (editor.begins_with("texture_")) { //compatibility fix for old texture format editor="texture"; } Ref<EditorImportPlugin> rimp = EditorImportExport::get_singleton()->get_import_plugin_by_name(editor); ERR_FAIL_COND(!rimp.is_valid()); if (reimport.size()==1) { rimp->import_dialog(reimport[0]); } else { rimp->reimport_multiple_files(reimport); } */ } break; case FILE_NEW_FOLDER: { make_dir_dialog_text->set_text("new folder"); make_dir_dialog_text->select_all(); make_dir_dialog->popup_centered_minsize(Size2(250, 80) * EDSCALE); make_dir_dialog_text->grab_focus(); } break; case FILE_COPY_PATH: { int idx = files->get_current(); if (idx < 0 || idx >= files->get_item_count()) break; String fpath = files->get_item_metadata(idx); OS::get_singleton()->set_clipboard(fpath); } break; } } void FileSystemDock::_folder_option(int p_option) { TreeItem *selected = tree->get_selected(); switch (p_option) { case FOLDER_EXPAND_ALL: case FOLDER_COLLAPSE_ALL: { bool is_collapsed = (p_option == FOLDER_COLLAPSE_ALL); Vector<TreeItem *> needs_check; needs_check.push_back(selected); while (needs_check.size()) { needs_check[0]->set_collapsed(is_collapsed); TreeItem *child = needs_check[0]->get_children(); while (child) { needs_check.push_back(child); child = child->get_next(); } needs_check.remove(0); } } break; case FOLDER_MOVE: { to_move.clear(); String fpath = selected->get_metadata(tree->get_selected_column()); if (fpath != "res://") { fpath = fpath.ends_with("/") ? fpath.substr(0, fpath.length() - 1) : fpath; to_move.push_back(FileOrFolder(fpath, false)); move_dialog->popup_centered_ratio(); } } break; case FOLDER_RENAME: { to_rename.path = selected->get_metadata(tree->get_selected_column()); to_rename.is_file = false; if (to_rename.path != "res://") { String name = to_rename.path.ends_with("/") ? to_rename.path.substr(0, to_rename.path.length() - 1).get_file() : to_rename.path.get_file(); rename_dialog->set_title(TTR("Renaming folder:") + " " + name); rename_dialog_text->set_text(name); rename_dialog_text->select(0, name.length()); rename_dialog->popup_centered_minsize(Size2(250, 80) * EDSCALE); rename_dialog_text->grab_focus(); } } break; case FOLDER_REMOVE: { Vector<String> remove_folders; Vector<String> remove_files; String fpath = selected->get_metadata(tree->get_selected_column()); if (fpath != "res://") { remove_folders.push_back(fpath); remove_dialog->show(remove_folders, remove_files); } } break; case FOLDER_NEW_FOLDER: { make_dir_dialog_text->set_text("new folder"); make_dir_dialog_text->select_all(); make_dir_dialog->popup_centered_minsize(Size2(250, 80) * EDSCALE); make_dir_dialog_text->grab_focus(); } break; case FOLDER_COPY_PATH: { String fpath = selected->get_metadata(tree->get_selected_column()); OS::get_singleton()->set_clipboard(fpath); } break; case FOLDER_SHOW_IN_EXPLORER: { String fpath = selected->get_metadata(tree->get_selected_column()); String dir = ProjectSettings::get_singleton()->globalize_path(fpath); OS::get_singleton()->shell_open(String("file://") + dir); } break; } } void FileSystemDock::_go_to_file_list() { if (low_height_mode) { tree->hide(); file_list_vb->show(); button_favorite->hide(); } else { bool collapsed = tree->get_selected()->is_collapsed(); tree->get_selected()->set_collapsed(!collapsed); } //file_options->show(); _update_files(false); //emit_signal("open",path); } void FileSystemDock::_dir_rmb_pressed(const Vector2 &p_pos) { folder_options->clear(); folder_options->set_size(Size2(1, 1)); folder_options->add_item(TTR("Expand all"), FOLDER_EXPAND_ALL); folder_options->add_item(TTR("Collapse all"), FOLDER_COLLAPSE_ALL); TreeItem *item = tree->get_selected(); if (item) { String fpath = item->get_metadata(tree->get_selected_column()); folder_options->add_separator(); folder_options->add_item(TTR("Copy Path"), FOLDER_COPY_PATH); if (fpath != "res://") { folder_options->add_item(TTR("Rename.."), FOLDER_RENAME); folder_options->add_item(TTR("Move To.."), FOLDER_MOVE); folder_options->add_item(TTR("Delete"), FOLDER_REMOVE); } folder_options->add_separator(); folder_options->add_item(TTR("New Folder.."), FOLDER_NEW_FOLDER); folder_options->add_item(TTR("Show In File Manager"), FOLDER_SHOW_IN_EXPLORER); } folder_options->set_position(tree->get_global_position() + p_pos); folder_options->popup(); } void FileSystemDock::_search_changed(const String &p_text) { if (file_list_vb->is_visible()) _update_files(false); } void FileSystemDock::_rescan() { _set_scanning_mode(); EditorFileSystem::get_singleton()->scan(); } void FileSystemDock::fix_dependencies(const String &p_for_file) { deps_editor->edit(p_for_file); } void FileSystemDock::focus_on_filter() { if (low_height_mode && tree->is_visible()) { // Tree mode, switch to files list with search box tree->hide(); file_list_vb->show(); button_favorite->hide(); } search_box->grab_focus(); } void FileSystemDock::set_display_mode(int p_mode) { if (p_mode == display_mode) return; button_display_mode->set_pressed(p_mode == DISPLAY_LIST); _change_file_display(); } Variant FileSystemDock::get_drag_data_fw(const Point2 &p_point, Control *p_from) { bool is_favorite = false; Vector<String> paths; if (p_from == tree) { TreeItem *selected = tree->get_selected(); if (!selected) return Variant(); String folder = selected->get_metadata(0); if (folder == String()) return Variant(); paths.push_back(folder.ends_with("/") ? folder : (folder + "/")); is_favorite = selected->get_parent() != NULL && tree->get_root()->get_children() == selected->get_parent(); } else if (p_from == files) { for (int i = 0; i < files->get_item_count(); i++) { if (files->is_selected(i)) { paths.push_back(files->get_item_metadata(i)); } } } if (paths.empty()) return Variant(); Dictionary drag_data = EditorNode::get_singleton()->drag_files_and_dirs(paths, p_from); if (is_favorite) { drag_data["type"] = "favorite"; } return drag_data; } bool FileSystemDock::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const { Dictionary drag_data = p_data; if (drag_data.has("type") && String(drag_data["type"]) == "favorite") { //moving favorite around TreeItem *ti = tree->get_item_at_position(p_point); if (!ti) return false; int what = tree->get_drop_section_at_position(p_point); if (ti == tree->get_root()->get_children()) { return (what == 1); //the parent, first fav } if (ti->get_parent() && tree->get_root()->get_children() == ti->get_parent()) { return true; // a favorite } if (ti == tree->get_root()->get_children()->get_next()) { return (what == -1); //the tree, last fav } return false; } if (drag_data.has("type") && String(drag_data["type"]) == "resource") { String to_dir = _get_drag_target_folder(p_point, p_from); return !to_dir.empty(); } if (drag_data.has("type") && (String(drag_data["type"]) == "files" || String(drag_data["type"]) == "files_and_dirs")) { String to_dir = _get_drag_target_folder(p_point, p_from); if (to_dir.empty()) return false; //Attempting to move a folder into itself will fail later //Rather than bring up a message don't try to do it in the first place to_dir = to_dir.ends_with("/") ? to_dir : (to_dir + "/"); Vector<String> fnames = drag_data["files"]; for (int i = 0; i < fnames.size(); ++i) { if (fnames[i].ends_with("/") && to_dir.begins_with(fnames[i])) return false; } return true; } return false; } void FileSystemDock::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) { if (!can_drop_data_fw(p_point, p_data, p_from)) return; Dictionary drag_data = p_data; if (drag_data.has("type") && String(drag_data["type"]) == "favorite") { //moving favorite around TreeItem *ti = tree->get_item_at_position(p_point); if (!ti) return; Vector<String> files = drag_data["files"]; ERR_FAIL_COND(files.size() != 1); String swap = files[0]; if (swap != "res://" && swap.ends_with("/")) { swap = swap.substr(0, swap.length() - 1); } int what = tree->get_drop_section_at_position(p_point); TreeItem *swap_item = NULL; if (ti == tree->get_root()->get_children()) { swap_item = tree->get_root()->get_children()->get_children(); } else if (ti->get_parent() && tree->get_root()->get_children() == ti->get_parent()) { if (what == -1) { swap_item = ti; } else { swap_item = ti->get_next(); } } String swap_with; if (swap_item) { swap_with = swap_item->get_metadata(0); if (swap_with != "res://" && swap_with.ends_with("/")) { swap_with = swap_with.substr(0, swap_with.length() - 1); } } if (swap == swap_with) return; Vector<String> dirs = EditorSettings::get_singleton()->get_favorite_dirs(); ERR_FAIL_COND(dirs.find(swap) == -1); ERR_FAIL_COND(swap_with != String() && dirs.find(swap_with) == -1); dirs.erase(swap); if (swap_with == String()) { dirs.push_back(swap); } else { int idx = dirs.find(swap_with); dirs.insert(idx, swap); } EditorSettings::get_singleton()->set_favorite_dirs(dirs); _update_tree(true); return; } if (drag_data.has("type") && String(drag_data["type"]) == "resource") { Ref<Resource> res = drag_data["resource"]; String to_dir = _get_drag_target_folder(p_point, p_from); if (res.is_valid() && !to_dir.empty()) { EditorNode::get_singleton()->push_item(res.ptr()); EditorNode::get_singleton()->save_resource_as(res, to_dir); } } if (drag_data.has("type") && (String(drag_data["type"]) == "files" || String(drag_data["type"]) == "files_and_dirs")) { String to_dir = _get_drag_target_folder(p_point, p_from); if (!to_dir.empty()) { Vector<String> fnames = drag_data["files"]; to_move.clear(); for (int i = 0; i < fnames.size(); i++) { to_move.push_back(FileOrFolder(fnames[i], !fnames[i].ends_with("/"))); } _move_operation_confirm(to_dir); } } } String FileSystemDock::_get_drag_target_folder(const Point2 &p_point, Control *p_from) const { if (p_from == files) { int pos = files->get_item_at_position(p_point, true); if (pos == -1) return path; String target = files->get_item_metadata(pos); return target.ends_with("/") ? target : path; } if (p_from == tree) { TreeItem *ti = tree->get_item_at_position(p_point); if (ti && ti != tree->get_root()->get_children()) return ti->get_metadata(0); } return String(); } void FileSystemDock::_files_list_rmb_select(int p_item, const Vector2 &p_pos) { //Right clicking ".." should clear current selection if (files->get_item_text(p_item) == "..") { for (int i = 0; i < files->get_item_count(); i++) { files->unselect(i); } } Vector<String> filenames; Vector<String> foldernames; bool all_files = true; bool all_files_scenes = true; bool all_folders = true; for (int i = 0; i < files->get_item_count(); i++) { if (!files->is_selected(i)) { continue; } String fpath = files->get_item_metadata(i); if (fpath.ends_with("/")) { foldernames.push_back(fpath); all_files = false; } else { filenames.push_back(fpath); all_folders = false; all_files_scenes &= (EditorFileSystem::get_singleton()->get_file_type(fpath) == "PackedScene"); } } file_options->clear(); file_options->set_size(Size2(1, 1)); if (all_files) { if (all_files_scenes && filenames.size() >= 1) { file_options->add_item(TTR("Open Scene(s)"), FILE_OPEN); file_options->add_item(TTR("Instance"), FILE_INSTANCE); file_options->add_separator(); } if (!all_files_scenes && filenames.size() == 1) { file_options->add_item(TTR("Open"), FILE_OPEN); file_options->add_separator(); } if (filenames.size() == 1) { file_options->add_item(TTR("Edit Dependencies.."), FILE_DEPENDENCIES); file_options->add_item(TTR("View Owners.."), FILE_OWNERS); file_options->add_separator(); } } else if (all_folders && foldernames.size() > 0) { file_options->add_item(TTR("Open"), FILE_OPEN); file_options->add_separator(); } int num_items = filenames.size() + foldernames.size(); if (num_items >= 1) { if (num_items == 1) { file_options->add_item(TTR("Copy Path"), FILE_COPY_PATH); file_options->add_item(TTR("Rename.."), FILE_RENAME); file_options->add_item(TTR("Duplicate.."), FILE_DUPLICATE); } file_options->add_item(TTR("Move To.."), FILE_MOVE); file_options->add_item(TTR("Delete"), FILE_REMOVE); file_options->add_separator(); } file_options->add_item(TTR("New Folder.."), FILE_NEW_FOLDER); file_options->add_item(TTR("Show In File Manager"), FILE_SHOW_IN_EXPLORER); file_options->set_position(files->get_global_position() + p_pos); file_options->popup(); } void FileSystemDock::_rmb_pressed(const Vector2 &p_pos) { file_options->clear(); file_options->set_size(Size2(1, 1)); file_options->add_item(TTR("New Folder.."), FILE_NEW_FOLDER); file_options->add_item(TTR("Show In File Manager"), FILE_SHOW_IN_EXPLORER); file_options->set_position(files->get_global_position() + p_pos); file_options->popup(); } void FileSystemDock::select_file(const String &p_file) { navigate_to_path(p_file); } void FileSystemDock::_file_multi_selected(int p_index, bool p_selected) { import_dock_needs_update = true; call_deferred("_update_import_dock"); } void FileSystemDock::_files_gui_input(Ref<InputEvent> p_event) { if (get_viewport()->get_modal_stack_top()) return; //ignore because of modal window Ref<InputEventKey> key = p_event; if (key.is_valid() && key->is_pressed() && !key->is_echo()) { if (ED_IS_SHORTCUT("filesystem_dock/duplicate", p_event)) { _file_option(FILE_DUPLICATE); } else if (ED_IS_SHORTCUT("filesystem_dock/copy_path", p_event)) { _file_option(FILE_COPY_PATH); } else if (ED_IS_SHORTCUT("filesystem_dock/delete", p_event)) { _file_option(FILE_REMOVE); } } } void FileSystemDock::_file_selected() { import_dock_needs_update = true; _update_import_dock(); } void FileSystemDock::_update_import_dock() { if (!import_dock_needs_update) return; //check import Vector<String> imports; String import_type; for (int i = 0; i < files->get_item_count(); i++) { if (!files->is_selected(i)) continue; String fpath = files->get_item_metadata(i); if (!FileAccess::exists(fpath + ".import")) { imports.clear(); break; } Ref<ConfigFile> cf; cf.instance(); Error err = cf->load(fpath + ".import"); if (err != OK) { imports.clear(); break; } String type = cf->get_value("remap", "type"); if (import_type == "") { import_type = type; } else if (import_type != type) { //all should be the same type imports.clear(); break; } imports.push_back(fpath); } if (imports.size() == 0) { EditorNode::get_singleton()->get_import_dock()->clear(); } else if (imports.size() == 1) { EditorNode::get_singleton()->get_import_dock()->set_edit_path(imports[0]); } else { EditorNode::get_singleton()->get_import_dock()->set_edit_multiple_paths(imports); } import_dock_needs_update = false; } void FileSystemDock::_bind_methods() { ClassDB::bind_method(D_METHOD("_files_gui_input"), &FileSystemDock::_files_gui_input); ClassDB::bind_method(D_METHOD("_update_tree"), &FileSystemDock::_update_tree); ClassDB::bind_method(D_METHOD("_rescan"), &FileSystemDock::_rescan); ClassDB::bind_method(D_METHOD("_favorites_pressed"), &FileSystemDock::_favorites_pressed); //ClassDB::bind_method(D_METHOD("_instance_pressed"),&ScenesDock::_instance_pressed); ClassDB::bind_method(D_METHOD("_go_to_file_list"), &FileSystemDock::_go_to_file_list); ClassDB::bind_method(D_METHOD("_dir_rmb_pressed"), &FileSystemDock::_dir_rmb_pressed); ClassDB::bind_method(D_METHOD("_thumbnail_done"), &FileSystemDock::_thumbnail_done); ClassDB::bind_method(D_METHOD("_select_file"), &FileSystemDock::_select_file); ClassDB::bind_method(D_METHOD("_go_to_tree"), &FileSystemDock::_go_to_tree); ClassDB::bind_method(D_METHOD("navigate_to_path"), &FileSystemDock::navigate_to_path); ClassDB::bind_method(D_METHOD("_change_file_display"), &FileSystemDock::_change_file_display); ClassDB::bind_method(D_METHOD("_fw_history"), &FileSystemDock::_fw_history); ClassDB::bind_method(D_METHOD("_bw_history"), &FileSystemDock::_bw_history); ClassDB::bind_method(D_METHOD("_fs_changed"), &FileSystemDock::_fs_changed); ClassDB::bind_method(D_METHOD("_dir_selected"), &FileSystemDock::_dir_selected); ClassDB::bind_method(D_METHOD("_file_option"), &FileSystemDock::_file_option); ClassDB::bind_method(D_METHOD("_folder_option"), &FileSystemDock::_folder_option); ClassDB::bind_method(D_METHOD("_make_dir_confirm"), &FileSystemDock::_make_dir_confirm); ClassDB::bind_method(D_METHOD("_move_operation_confirm"), &FileSystemDock::_move_operation_confirm); ClassDB::bind_method(D_METHOD("_rename_operation_confirm"), &FileSystemDock::_rename_operation_confirm); ClassDB::bind_method(D_METHOD("_duplicate_operation_confirm"), &FileSystemDock::_duplicate_operation_confirm); ClassDB::bind_method(D_METHOD("_search_changed"), &FileSystemDock::_search_changed); ClassDB::bind_method(D_METHOD("get_drag_data_fw"), &FileSystemDock::get_drag_data_fw); ClassDB::bind_method(D_METHOD("can_drop_data_fw"), &FileSystemDock::can_drop_data_fw); ClassDB::bind_method(D_METHOD("drop_data_fw"), &FileSystemDock::drop_data_fw); ClassDB::bind_method(D_METHOD("_files_list_rmb_select"), &FileSystemDock::_files_list_rmb_select); ClassDB::bind_method(D_METHOD("_preview_invalidated"), &FileSystemDock::_preview_invalidated); ClassDB::bind_method(D_METHOD("_file_selected"), &FileSystemDock::_file_selected); ClassDB::bind_method(D_METHOD("_file_multi_selected"), &FileSystemDock::_file_multi_selected); ClassDB::bind_method(D_METHOD("_update_import_dock"), &FileSystemDock::_update_import_dock); ClassDB::bind_method(D_METHOD("_rmb_pressed"), &FileSystemDock::_rmb_pressed); ADD_SIGNAL(MethodInfo("instance", PropertyInfo(Variant::POOL_STRING_ARRAY, "files"))); ADD_SIGNAL(MethodInfo("open")); } FileSystemDock::FileSystemDock(EditorNode *p_editor) { set_name("FileSystem"); editor = p_editor; path = "res://"; ED_SHORTCUT("filesystem_dock/copy_path", TTR("Copy Path"), KEY_MASK_CMD | KEY_C); ED_SHORTCUT("filesystem_dock/duplicate", TTR("Duplicate..."), KEY_MASK_CMD | KEY_D); ED_SHORTCUT("filesystem_dock/delete", TTR("Delete"), KEY_DELETE); HBoxContainer *toolbar_hbc = memnew(HBoxContainer); add_child(toolbar_hbc); button_hist_prev = memnew(ToolButton); button_hist_prev->set_disabled(true); button_hist_prev->set_focus_mode(FOCUS_NONE); button_hist_prev->set_tooltip(TTR("Previous Directory")); toolbar_hbc->add_child(button_hist_prev); button_hist_next = memnew(ToolButton); button_hist_next->set_disabled(true); button_hist_next->set_focus_mode(FOCUS_NONE); button_hist_next->set_tooltip(TTR("Next Directory")); toolbar_hbc->add_child(button_hist_next); current_path = memnew(LineEdit); current_path->set_h_size_flags(SIZE_EXPAND_FILL); toolbar_hbc->add_child(current_path); button_reload = memnew(Button); button_reload->set_flat(true); button_reload->connect("pressed", this, "_rescan"); button_reload->set_focus_mode(FOCUS_NONE); button_reload->set_tooltip(TTR("Re-Scan Filesystem")); button_reload->hide(); toolbar_hbc->add_child(button_reload); //toolbar_hbc->add_spacer(); button_favorite = memnew(Button); button_favorite->set_flat(true); button_favorite->set_toggle_mode(true); button_favorite->connect("pressed", this, "_favorites_pressed"); button_favorite->set_tooltip(TTR("Toggle folder status as Favorite")); button_favorite->set_focus_mode(FOCUS_NONE); toolbar_hbc->add_child(button_favorite); //Control *spacer = memnew( Control); /* button_open = memnew( Button ); button_open->set_flat(true); button_open->connect("pressed",this,"_go_to_file_list"); toolbar_hbc->add_child(button_open); button_open->hide(); button_open->set_focus_mode(FOCUS_NONE); button_open->set_tooltip("Open the selected file.\nOpen as scene if a scene, or as resource otherwise."); button_instance = memnew( Button ); button_instance->set_flat(true); button_instance->connect("pressed",this,"_instance_pressed"); toolbar_hbc->add_child(button_instance); button_instance->hide(); button_instance->set_focus_mode(FOCUS_NONE); button_instance->set_tooltip(TTR("Instance the selected scene(s) as child of the selected node.")); */ file_options = memnew(PopupMenu); add_child(file_options); folder_options = memnew(PopupMenu); add_child(folder_options); split_box = memnew(VSplitContainer); split_box->set_v_size_flags(SIZE_EXPAND_FILL); add_child(split_box); tree = memnew(Tree); tree->set_hide_root(true); tree->set_drag_forwarding(this); tree->set_allow_rmb_select(true); tree->set_custom_minimum_size(Size2(0, 200 * EDSCALE)); split_box->add_child(tree); tree->connect("item_edited", this, "_favorite_toggled"); tree->connect("item_activated", this, "_go_to_file_list"); tree->connect("cell_selected", this, "_dir_selected"); tree->connect("item_rmb_selected", this, "_dir_rmb_pressed"); file_list_vb = memnew(VBoxContainer); file_list_vb->set_v_size_flags(SIZE_EXPAND_FILL); split_box->add_child(file_list_vb); path_hb = memnew(HBoxContainer); file_list_vb->add_child(path_hb); button_tree = memnew(ToolButton); button_tree->hide(); path_hb->add_child(button_tree); search_box = memnew(LineEdit); search_box->set_h_size_flags(SIZE_EXPAND_FILL); search_box->connect("text_changed", this, "_search_changed"); path_hb->add_child(search_box); button_display_mode = memnew(ToolButton); button_display_mode->set_toggle_mode(true); path_hb->add_child(button_display_mode); files = memnew(ItemList); files->set_v_size_flags(SIZE_EXPAND_FILL); files->set_select_mode(ItemList::SELECT_MULTI); files->set_drag_forwarding(this); files->connect("item_rmb_selected", this, "_files_list_rmb_select"); files->connect("gui_input", this, "_files_gui_input"); files->connect("item_selected", this, "_file_selected"); files->connect("multi_selected", this, "_file_multi_selected"); files->connect("rmb_clicked", this, "_rmb_pressed"); files->set_allow_rmb_select(true); file_list_vb->add_child(files); scanning_vb = memnew(VBoxContainer); scanning_vb->hide(); add_child(scanning_vb); Label *slabel = memnew(Label); slabel->set_text(TTR("Scanning Files,\nPlease Wait..")); slabel->set_align(Label::ALIGN_CENTER); scanning_vb->add_child(slabel); scanning_progress = memnew(ProgressBar); scanning_vb->add_child(scanning_progress); deps_editor = memnew(DependencyEditor); add_child(deps_editor); owners_editor = memnew(DependencyEditorOwners(editor)); add_child(owners_editor); remove_dialog = memnew(DependencyRemoveDialog); add_child(remove_dialog); move_dialog = memnew(EditorDirDialog); move_dialog->get_ok()->set_text(TTR("Move")); add_child(move_dialog); move_dialog->connect("dir_selected", this, "_move_operation_confirm"); rename_dialog = memnew(ConfirmationDialog); VBoxContainer *rename_dialog_vb = memnew(VBoxContainer); rename_dialog->add_child(rename_dialog_vb); rename_dialog_text = memnew(LineEdit); rename_dialog_vb->add_margin_child(TTR("Name:"), rename_dialog_text); rename_dialog->get_ok()->set_text(TTR("Rename")); add_child(rename_dialog); rename_dialog->register_text_enter(rename_dialog_text); rename_dialog->connect("confirmed", this, "_rename_operation_confirm"); duplicate_dialog = memnew(ConfirmationDialog); VBoxContainer *duplicate_dialog_vb = memnew(VBoxContainer); duplicate_dialog->add_child(duplicate_dialog_vb); duplicate_dialog_text = memnew(LineEdit); duplicate_dialog_vb->add_margin_child(TTR("Name:"), duplicate_dialog_text); duplicate_dialog->get_ok()->set_text(TTR("Duplicate")); add_child(duplicate_dialog); duplicate_dialog->register_text_enter(duplicate_dialog_text); duplicate_dialog->connect("confirmed", this, "_duplicate_operation_confirm"); make_dir_dialog = memnew(ConfirmationDialog); make_dir_dialog->set_title(TTR("Create Folder")); VBoxContainer *make_folder_dialog_vb = memnew(VBoxContainer); make_dir_dialog->add_child(make_folder_dialog_vb); make_dir_dialog_text = memnew(LineEdit); make_folder_dialog_vb->add_margin_child(TTR("Name:"), make_dir_dialog_text); add_child(make_dir_dialog); make_dir_dialog->register_text_enter(make_dir_dialog_text); make_dir_dialog->connect("confirmed", this, "_make_dir_confirm"); updating_tree = false; initialized = false; import_dock_needs_update = false; history_pos = 0; history_max_size = 20; history.push_back("res://"); low_height_mode = false; display_mode = DISPLAY_THUMBNAILS; } FileSystemDock::~FileSystemDock() { }
#include "SGDP4.h" #include "Vector.h" #include "SatelliteException.h" #include <cmath> #include <iomanip> SGDP4::SGDP4(void) { first_run_ = true; SetConstants(CONSTANTS_WGS72); } SGDP4::~SGDP4(void) { } void SGDP4::SetConstants(EnumConstants constants) { constants_.AE = 1.0; constants_.TWOTHRD = 2.0 / 3.0; switch (constants) { case CONSTANTS_WGS72_OLD: constants_.MU = 0.0; constants_.XKMPER = 6378.135; constants_.XKE = 0.0743669161; constants_.XJ2 = 0.001082616; constants_.XJ3 = -0.00000253881; constants_.XJ4 = -0.00000165597; constants_.J3OJ2 = constants_.XJ3 / constants_.XJ2; break; case CONSTANTS_WGS72: constants_.MU = 398600.8; constants_.XKMPER = 6378.135; constants_.XKE = 60.0 / sqrt(constants_.XKMPER * constants_.XKMPER * constants_.XKMPER / constants_.MU); constants_.XJ2 = 0.001082616; constants_.XJ3 = -0.00000253881; constants_.XJ4 = -0.00000165597; constants_.J3OJ2 = constants_.XJ3 / constants_.XJ2; break; case CONSTANTS_WGS84: constants_.MU = 398600.5; constants_.XKMPER = 6378.137; constants_.XKE = 60.0 / sqrt(constants_.XKMPER * constants_.XKMPER * constants_.XKMPER / constants_.MU); constants_.XJ2 = 0.00108262998905; constants_.XJ3 = -0.00000253215306; constants_.XJ4 = -0.00000161098761; constants_.J3OJ2 = constants_.XJ3 / constants_.XJ2; break; default: throw new SatelliteException("Unrecognised constant value"); break; } constants_.S = constants_.AE + 78.0 / constants_.XKMPER; constants_.CK2 = 0.5 * constants_.XJ2 * constants_.AE * constants_.AE; constants_.CK4 = -0.375 * constants_.XJ4 * constants_.AE * constants_.AE * constants_.AE * constants_.AE; constants_.QOMS2T = pow((120.0 - 78.0) * constants_.AE / constants_.XKMPER, 4.0); } void SGDP4::SetTle(const Tle& tle) { /* * extract and format tle data */ mean_anomoly_ = tle.GetField(Tle::FLD_M, Tle::U_RAD); ascending_node_ = tle.GetField(Tle::FLD_RAAN, Tle::U_RAD); argument_perigee_ = tle.GetField(Tle::FLD_ARGPER, Tle::U_RAD); eccentricity_ = tle.GetField(Tle::FLD_E); inclination_ = tle.GetField(Tle::FLD_I, Tle::U_RAD); mean_motion_ = tle.GetField(Tle::FLD_MMOTION) * Globals::TWOPI() / Globals::MIN_PER_DAY(); bstar_ = tle.GetField(Tle::FLD_BSTAR); epoch_ = tle.GetEpoch(); /* * error checks */ if (eccentricity_ < 0.0 || eccentricity_ > 1.0 - 1.0e-3) { throw new SatelliteException("Eccentricity out of range"); } if (inclination_ < 0.0 || eccentricity_ > Globals::PI()) { throw new SatelliteException("Inclination out of range"); } /* * recover original mean motion (xnodp) and semimajor axis (aodp) * from input elements */ double a1 = pow(constants_.XKE / MeanMotion(), constants_.TWOTHRD); i_cosio_ = cos(Inclination()); i_sinio_ = sin(Inclination()); double theta2 = i_cosio_ * i_cosio_; i_x3thm1_ = 3.0 * theta2 - 1.0; double eosq = Eccentricity() * Eccentricity(); double betao2 = 1.0 - eosq; double betao = sqrt(betao2); double temp = (1.5 * constants_.CK2) * i_x3thm1_ / (betao * betao2); double del1 = temp / (a1 * a1); double a0 = a1 * (1.0 - del1 * (1.0 / 3.0 + del1 * (1.0 + del1 * 134.0 / 81.0))); double del0 = temp / (a0 * a0); recovered_mean_motion_ = MeanMotion() / (1.0 + del0); recovered_semi_major_axis_ = a0 / (1.0 - del0); /* * find perigee and period */ perigee_ = (RecoveredSemiMajorAxis() * (1.0 - Eccentricity()) - constants_.AE) * constants_.XKMPER; period_ = Globals::TWOPI() / RecoveredMeanMotion(); Initialize(theta2, betao2, betao, eosq); } void SGDP4::Initialize(const double& theta2, const double& betao2, const double& betao, const double& eosq) { if (Period() >= 225.0) { i_use_deep_space_ = true; } else { i_use_deep_space_ = false; i_use_simple_model_ = false; /* * for perigee less than 220 kilometers, the simple_model flag is set and * the equations are truncated to linear variation in sqrt a and * quadratic variation in mean anomly. also, the c3 term, the * delta omega term and the delta m term are dropped */ if (Perigee() < 220.0) { i_use_simple_model_ = true; } } /* * for perigee below 156km, the values of * s4 and qoms2t are altered */ double s4 = constants_.S; double qoms24 = constants_.QOMS2T; if (Perigee() < 156.0) { s4 = Perigee() - 78.0; if (Perigee() < 98.0) { s4 = 20.0; } qoms24 = pow((120.0 - s4) * constants_.AE / constants_.XKMPER, 4.0); s4 = s4 / constants_.XKMPER + constants_.AE; } /* * generate constants */ double pinvsq = 1.0 / (RecoveredSemiMajorAxis() * RecoveredSemiMajorAxis() * betao2 * betao2); double tsi = 1.0 / (RecoveredSemiMajorAxis() - s4); i_eta_ = RecoveredSemiMajorAxis() * Eccentricity() * tsi; double etasq = i_eta_ * i_eta_; double eeta = Eccentricity() * i_eta_; double psisq = fabs(1.0 - etasq); double coef = qoms24 * pow(tsi, 4.0); double coef1 = coef / pow(psisq, 3.5); double c2 = coef1 * RecoveredMeanMotion() * (RecoveredSemiMajorAxis() * (1.0 + 1.5 * etasq + eeta * (4.0 + etasq)) + 0.75 * constants_.CK2 * tsi / psisq * i_x3thm1_ * (8.0 + 3.0 * etasq * (8.0 + etasq))); i_c1_ = BStar() * c2; i_a3ovk2_ = -constants_.XJ3 / constants_.CK2 * pow(constants_.AE, 3.0); i_x1mth2_ = 1.0 - theta2; i_c4_ = 2.0 * RecoveredMeanMotion() * coef1 * RecoveredSemiMajorAxis() * betao2 * (i_eta_ * (2.0 + 0.5 * etasq) + Eccentricity() * (0.5 + 2.0 * etasq) - 2.0 * constants_.CK2 * tsi / (RecoveredSemiMajorAxis() * psisq) * (-3.0 * i_x3thm1_ * (1.0 - 2.0 * eeta + etasq * (1.5 - 0.5 * eeta)) + 0.75 * i_x1mth2_ * (2.0 * etasq - eeta * (1.0 + etasq)) * cos(2.0 * ArgumentPerigee()))); double theta4 = theta2 * theta2; double temp1 = 3.0 * constants_.CK2 * pinvsq * RecoveredMeanMotion(); double temp2 = temp1 * constants_.CK2 * pinvsq; double temp3 = 1.25 * constants_.CK4 * pinvsq * pinvsq * RecoveredMeanMotion(); i_xmdot_ = RecoveredMeanMotion() + 0.5 * temp1 * betao * i_x3thm1_ + 0.0625 * temp2 * betao * (13.0 - 78.0 * theta2 + 137.0 * theta4); double x1m5th = 1.0 - 5.0 * theta2; i_omgdot_ = -0.5 * temp1 * x1m5th + 0.0625 * temp2 * (7.0 - 114.0 * theta2 + 395.0 * theta4) + temp3 * (3.0 - 36.0 * theta2 + 49.0 * theta4); double xhdot1_ = -temp1 * i_cosio_; i_xnodot_ = xhdot1_ + (0.5 * temp2 * (4.0 - 19.0 * theta2) + 2.0 * temp3 * (3.0 - 7.0 * theta2)) * i_cosio_; i_xnodcf_ = 3.5 * betao2 * xhdot1_ * i_c1_; i_t2cof_ = 1.5 * i_c1_; if (fabs(i_cosio_ + 1.0) > 1.5e-12) i_xlcof_ = 0.125 * i_a3ovk2_ * i_sinio_ * (3.0 + 5.0 * i_cosio_) / (1.0 + i_cosio_); else i_xlcof_ = 0.125 * i_a3ovk2_ * i_sinio_ * (3.0 + 5.0 * i_cosio_) / 1.5e-12; i_aycof_ = 0.25 * i_a3ovk2_ * i_sinio_; i_x7thm1_ = 7.0 * theta2 - 1.0; if (i_use_deep_space_) { const double sing = sin(ArgumentPerigee()); const double cosg = cos(ArgumentPerigee()); i_gsto_ = Epoch().ToGMST(); DeepSpaceInitialize(eosq, i_sinio_, i_cosio_, betao, theta2, sing, cosg, betao2, i_xmdot_, i_omgdot_, i_xnodot_); } else { double c3 = 0.0; if (Eccentricity() > 1.0e-4) { c3 = coef * tsi * i_a3ovk2_ * RecoveredMeanMotion() * constants_.AE * i_sinio_ / Eccentricity(); } i_c5_ = 2.0 * coef1 * RecoveredSemiMajorAxis() * betao2 * (1.0 + 2.75 * (etasq + eeta) + eeta * etasq); i_omgcof_ = BStar() * c3 * cos(ArgumentPerigee()); i_xmcof_ = 0.0; if (Eccentricity() > 1.0e-4) i_xmcof_ = -constants_.TWOTHRD * coef * BStar() * constants_.AE / eeta; i_delmo_ = pow(1.0 + i_eta_ * (cos(MeanAnomoly())), 3.0); i_sinmo_ = sin(MeanAnomoly()); if (!i_use_simple_model_) { double c1sq = i_c1_ * i_c1_; i_d2_ = 4.0 * RecoveredSemiMajorAxis() * tsi * c1sq; double temp = i_d2_ * tsi * i_c1_ / 3.0; i_d3_ = (17.0 * RecoveredSemiMajorAxis() + s4) * temp; i_d4_ = 0.5 * temp * RecoveredSemiMajorAxis() * tsi * (221.0 * RecoveredSemiMajorAxis() + 31.0 * s4) * i_c1_; i_t3cof_ = i_d2_ + 2.0 * c1sq; i_t4cof_ = 0.25 * (3.0 * i_d3_ + i_c1_ * (12.0 * i_d2_ + 10.0 * c1sq)); i_t5cof_ = 0.2 * (3.0 * i_d4_ + 12.0 * i_c1_ * i_d3_ + 6.0 * i_d2_ * i_d2_ + 15.0 * c1sq * (2.0 * i_d2_ + c1sq)); } } Eci eci; FindPosition(eci, 0.0); first_run_ = false; } void SGDP4::FindPosition(Eci& eci, double tsince) { if (i_use_deep_space_) FindPositionSDP4(eci, tsince); else FindPositionSGP4(eci, tsince); } void SGDP4::FindPositionSDP4(Eci& eci, double tsince) { /* * the final values */ double e = Eccentricity(); double a; double omega; double xl; double xnode; double xincl = Inclination(); /* * update for secular gravity and atmospheric drag */ double xmdf = MeanAnomoly() + i_xmdot_ * tsince; double omgadf = ArgumentPerigee() + i_omgdot_ * tsince; const double xnoddf = AscendingNode() + i_xnodot_ * tsince; omega = omgadf; const double tsq = tsince * tsince; xnode = xnoddf + i_xnodcf_ * tsq; double tempa = 1.0 - i_c1_ * tsince; double tempe = BStar() * i_c4_ * tsince; double templ = i_t2cof_ * tsq; double xn = RecoveredMeanMotion(); /* t, xll, omgasm, xnodes, em, xinc, xn */ DeepSpaceSecular(tsince, xmdf, omega, xnode, e, xincl, xn); if (xn <= 0.0) { throw new SatelliteException("Error: 2 (xn <= 0.0)"); } a = pow(constants_.XKE / xn, constants_.TWOTHRD) * pow(tempa, 2.0); e -= tempe; /* * fix tolerance for error recognition */ if (e >= 1.0 || e < -0.001) { throw new SatelliteException("Error: 1 (e >= 1.0 || e < -0.001)"); } /* * fix tolerance to avoid a divide by zero */ if (e < 1.0e-6) e = 1.0e-6; xmdf += RecoveredMeanMotion() * templ; double xlm = xmdf + omega + xnode; xnode = fmod(xnode, Globals::TWOPI()); omega = fmod(omega, Globals::TWOPI()); xlm = fmod(xlm, Globals::TWOPI()); double xmam = fmod(xlm - omega - xnode, Globals::TWOPI()); DeepSpacePeriodics(tsince, e, xincl, omega, xnode, xmam); if (xincl < 0.0) { xincl = -xincl; xnode += Globals::PI(); omega -= Globals::PI(); } xl = xmam + omega + xnode; if (e < 0.0 || e > 1.0) { throw new SatelliteException("Error: 3 (e < 0.0 || e > 1.0)"); } /* * re-compute the perturbed values */ const double perturbed_sinio = sin(xincl); const double perturbed_cosio = cos(xincl); const double perturbed_theta2 = perturbed_cosio * perturbed_cosio; const double perturbed_x3thm1 = 3.0 * perturbed_theta2 - 1.0; const double perturbed_x1mth2 = 1.0 - perturbed_theta2; const double perturbed_x7thm1 = 7.0 * perturbed_theta2 - 1.0; double perturbed_xlcof; if (fabs(perturbed_cosio + 1.0) > 1.5e-12) perturbed_xlcof = 0.125 * i_a3ovk2_ * perturbed_sinio * (3.0 + 5.0 * perturbed_cosio) / (1.0 + perturbed_cosio); else perturbed_xlcof = 0.125 * i_a3ovk2_ * perturbed_sinio * (3.0 + 5.0 * perturbed_cosio) / 1.5e-12; const double perturbed_aycof = 0.25 * i_a3ovk2_ * perturbed_sinio; /* * using calculated values, find position and velocity */ CalculateFinalPositionVelocity(eci, tsince, e, a, omega, xl, xnode, xincl, perturbed_xlcof, perturbed_aycof, perturbed_x3thm1, perturbed_x1mth2, perturbed_x7thm1, perturbed_cosio, perturbed_sinio); } void SGDP4::FindPositionSGP4(Eci& eci, double tsince) const { /* * the final values */ double e; double a; double omega; double xl; double xnode; double xincl; /* * update for secular gravity and atmospheric drag */ const double xmdf = MeanAnomoly() + i_xmdot_ * tsince; const double omgadf = ArgumentPerigee() + i_omgdot_ * tsince; const double xnoddf = AscendingNode() + i_xnodot_ * tsince; const double tsq = tsince * tsince; xnode = xnoddf + i_xnodcf_ * tsq; double tempa = 1.0 - i_c1_ * tsince; double tempe = BStar() * i_c4_ * tsince; double templ = i_t2cof_ * tsq; xincl = Inclination(); omega = omgadf; double xmp = xmdf; if (!i_use_simple_model_) { const double delomg = i_omgcof_ * tsince; const double delm = i_xmcof_ * (pow(1.0 + i_eta_ * cos(xmdf), 3.0) - i_delmo_); const double temp = delomg + delm; xmp += temp; omega -= temp; const double tcube = tsq * tsince; const double tfour = tsince * tcube; tempa -= i_d2_ * tsq - i_d3_ * tcube - i_d4_ * tfour; tempe += BStar() * i_c5_ * (sin(xmp) - i_sinmo_); templ += i_t3cof_ * tcube + tfour * (i_t4cof_ + tsince * i_t5cof_); } a = RecoveredSemiMajorAxis() * pow(tempa, 2.0); e = Eccentricity() - tempe; xl = xmp + omega + xnode + RecoveredMeanMotion() * templ; /* * using calculated values, find position and velocity * we can pass in constants from Initialize() as these dont change */ CalculateFinalPositionVelocity(eci, tsince, e, a, omega, xl, xnode, xincl, i_xlcof_, i_aycof_, i_x3thm1_, i_x1mth2_, i_x7thm1_, i_cosio_, i_sinio_); } void SGDP4::CalculateFinalPositionVelocity(Eci& eci, const double& tsince, const double& e, const double& a, const double& omega, const double& xl, const double& xnode, const double& xincl, const double& xlcof, const double& aycof, const double& x3thm1, const double& x1mth2, const double& x7thm1, const double& cosio, const double& sinio) const { double temp; double temp1; double temp2; double temp3; if (a < 1.0) { throw new SatelliteException("Error: Satellite crashed (a < 1.0)"); } if (e < -1.0e-3) { throw new SatelliteException("Error: Modified eccentricity too low (e < -1.0e-3)"); } const double beta = sqrt(1.0 - e * e); const double xn = constants_.XKE / pow(a, 1.5); /* * long period periodics */ const double axn = e * cos(omega); temp = 1.0 / (a * beta * beta); const double xll = temp * xlcof * axn; const double aynl = temp * aycof; const double xlt = xl + xll; const double ayn = e * sin(omega) + aynl; const double elsq = axn * axn + ayn * ayn; if (elsq >= 1.0) { throw new SatelliteException("Error: sqrt(e) >= 1 (elsq >= 1.0)"); } /* * solve keplers equation * - solve using Newton-Raphson root solving * - here capu is almost the mean anomoly * - initialise the eccentric anomaly term epw * - The fmod saves reduction of angle to +/-2pi in sin/cos() and prevents * convergence problems. */ const double capu = fmod(xlt - xnode, Globals::TWOPI()); double epw = capu; double sinepw = 0.0; double cosepw = 0.0; double ecose = 0.0; double esine = 0.0; /* * sensibility check for N-R correction */ const double max_newton_naphson = 1.25 * fabs(sqrt(elsq)); bool kepler_running = true; for (int i = 0; i < 10 && kepler_running; i++) { sinepw = sin(epw); cosepw = cos(epw); ecose = axn * cosepw + ayn * sinepw; esine = axn * sinepw - ayn * cosepw; double f = capu - epw + esine; if (fabs(f) < 1.0e-12) { kepler_running = false; } else { /* * 1st order Newton-Raphson correction */ const double fdot = 1.0 - ecose; double delta_epw = f / fdot; /* * 2nd order Newton-Raphson correction. * f / (fdot - 0.5 * d2f * f/fdot) */ if (i == 0) { if (delta_epw > max_newton_naphson) delta_epw = max_newton_naphson; else if (delta_epw < -max_newton_naphson) delta_epw = -max_newton_naphson; } else { delta_epw = f / (fdot + 0.5 * esine * delta_epw); } /* * Newton-Raphson correction of -F/DF */ epw += delta_epw; } } /* * short period preliminary quantities */ temp = 1.0 - elsq; const double pl = a * temp; const double r = a * (1.0 - ecose); temp1 = 1.0 / r; const double rdot = constants_.XKE * sqrt(a) * esine * temp1; const double rfdot = constants_.XKE * sqrt(pl) * temp1; temp2 = a * temp1; const double betal = sqrt(temp); temp3 = 1.0 / (1.0 + betal); const double cosu = temp2 * (cosepw - axn + ayn * esine * temp3); const double sinu = temp2 * (sinepw - ayn - axn * esine * temp3); const double u = atan2(sinu, cosu); const double sin2u = 2.0 * sinu * cosu; const double cos2u = 2.0 * cosu * cosu - 1.0; temp = 1.0 / pl; temp1 = constants_.CK2 * temp; temp2 = temp1 * temp; /* * update for short periodics */ const double rk = r * (1.0 - 1.5 * temp2 * betal * x3thm1) + 0.5 * temp1 * x1mth2 * cos2u; const double uk = u - 0.25 * temp2 * x7thm1 * sin2u; const double xnodek = xnode + 1.5 * temp2 * cosio * sin2u; const double xinck = xincl + 1.5 * temp2 * cosio * sinio * cos2u; const double rdotk = rdot - xn * temp1 * x1mth2 * sin2u; const double rfdotk = rfdot + xn * temp1 * (x1mth2 * cos2u + 1.5 * x3thm1); if (rk < 0.0) { throw new SatelliteException("Error: satellite decayed (rk < 0.0)"); } /* * orientation vectors */ const double sinuk = sin(uk); const double cosuk = cos(uk); const double sinik = sin(xinck); const double cosik = cos(xinck); const double sinnok = sin(xnodek); const double cosnok = cos(xnodek); const double xmx = -sinnok * cosik; const double xmy = cosnok * cosik; const double ux = xmx * sinuk + cosnok * cosuk; const double uy = xmy * sinuk + sinnok * cosuk; const double uz = sinik * sinuk; const double vx = xmx * cosuk - cosnok * sinuk; const double vy = xmy * cosuk - sinnok * sinuk; const double vz = sinik * cosuk; /* * position and velocity */ const double x = rk * ux * constants_.XKMPER; const double y = rk * uy * constants_.XKMPER; const double z = rk * uz * constants_.XKMPER; Vector position(x, y, z); const double xdot = (rdotk * ux + rfdotk * vx) * constants_.XKMPER / 60.0; const double ydot = (rdotk * uy + rfdotk * vy) * constants_.XKMPER / 60.0; const double zdot = (rdotk * uz + rfdotk * vz) * constants_.XKMPER / 60.0; Vector velocity(xdot, ydot, zdot); Julian julian = Epoch(); julian.AddMin(tsince); eci = Eci(julian, position, velocity); } /* * deep space initialization */ void SGDP4::DeepSpaceInitialize(const double& eosq, const double& sinio, const double& cosio, const double& betao, const double& theta2, const double& sing, const double& cosg, const double& betao2, const double& xmdot, const double& omgdot, const double& xnodot) { double se = 0.0; double si = 0.0; double sl = 0.0; double sgh = 0.0; double shdq = 0.0; double bfact = 0.0; static const double ZNS = 1.19459E-5; static const double C1SS = 2.9864797E-6; static const double ZES = 0.01675; static const double ZNL = 1.5835218E-4; static const double C1L = 4.7968065E-7; static const double ZEL = 0.05490; static const double ZCOSIS = 0.91744867; static const double ZSINI = 0.39785416; static const double ZSINGS = -0.98088458; static const double ZCOSGS = 0.1945905; static const double Q22 = 1.7891679E-6; static const double Q31 = 2.1460748E-6; static const double Q33 = 2.2123015E-7; static const double ROOT22 = 1.7891679E-6; static const double ROOT32 = 3.7393792E-7; static const double ROOT44 = 7.3636953E-9; static const double ROOT52 = 1.1428639E-7; static const double ROOT54 = 2.1765803E-9; static const double THDT = 4.3752691E-3; const double aqnv = 1.0 / RecoveredSemiMajorAxis(); const double xpidot = omgdot + xnodot; const double sinq = sin(AscendingNode()); const double cosq = cos(AscendingNode()); /* * initialize lunar / solar terms */ const double d_day_ = Epoch().FromJan1_12h_1900(); const double xnodce = fmod(4.5236020 - 9.2422029e-4 * d_day_, Globals::TWOPI()); const double stem = sin(xnodce); const double ctem = cos(xnodce); const double zcosil = 0.91375164 - 0.03568096 * ctem; const double zsinil = sqrt(1.0 - zcosil * zcosil); const double zsinhl = 0.089683511 * stem / zsinil; const double zcoshl = sqrt(1.0 - zsinhl * zsinhl); const double c = 4.7199672 + 0.22997150 * d_day_; const double gam = 5.8351514 + 0.0019443680 * d_day_; d_zmol_ = Globals::Fmod2p(c - gam); double zx = 0.39785416 * stem / zsinil; double zy = zcoshl * ctem + 0.91744867 * zsinhl * stem; /* * todo: check */ zx = atan2(zx, zy); zx = fmod(gam + zx - xnodce, Globals::TWOPI()); const double zcosgl = cos(zx); const double zsingl = sin(zx); d_zmos_ = 6.2565837 + 0.017201977 * d_day_; d_zmos_ = Globals::Fmod2p(d_zmos_); /* * do solar terms */ double zcosg = ZCOSGS; double zsing = ZSINGS; double zcosi = ZCOSIS; double zsini = ZSINI; double zcosh = cosq; double zsinh = sinq; double cc = C1SS; double zn = ZNS; double ze = ZES; double zmo = d_zmos_; const double xnoi = 1.0 / RecoveredMeanMotion(); for (int cnt = 0; cnt < 2; cnt++) { /* * solar terms are done a second time after lunar terms are done */ const double a1 = zcosg * zcosh + zsing * zcosi * zsinh; const double a3 = -zsing * zcosh + zcosg * zcosi * zsinh; const double a7 = -zcosg * zsinh + zsing * zcosi * zcosh; const double a8 = zsing * zsini; const double a9 = zsing * zsinh + zcosg * zcosi*zcosh; const double a10 = zcosg * zsini; const double a2 = cosio * a7 + sinio * a8; const double a4 = cosio * a9 + sinio * a10; const double a5 = -sinio * a7 + cosio * a8; const double a6 = -sinio * a9 + cosio * a10; const double x1 = a1 * cosg + a2 * sing; const double x2 = a3 * cosg + a4 * sing; const double x3 = -a1 * sing + a2 * cosg; const double x4 = -a3 * sing + a4 * cosg; const double x5 = a5 * sing; const double x6 = a6 * sing; const double x7 = a5 * cosg; const double x8 = a6 * cosg; const double z31 = 12.0 * x1 * x1 - 3. * x3 * x3; const double z32 = 24.0 * x1 * x2 - 6. * x3 * x4; const double z33 = 12.0 * x2 * x2 - 3. * x4 * x4; double z1 = 3.0 * (a1 * a1 + a2 * a2) + z31 * eosq; double z2 = 6.0 * (a1 * a3 + a2 * a4) + z32 * eosq; double z3 = 3.0 * (a3 * a3 + a4 * a4) + z33 * eosq; const double z11 = -6.0 * a1 * a5 + eosq * (-24. * x1 * x7 - 6. * x3 * x5); const double z12 = -6.0 * (a1 * a6 + a3 * a5) + eosq * (-24. * (x2 * x7 + x1 * x8) - 6. * (x3 * x6 + x4 * x5)); const double z13 = -6.0 * a3 * a6 + eosq * (-24. * x2 * x8 - 6. * x4 * x6); const double z21 = 6.0 * a2 * a5 + eosq * (24. * x1 * x5 - 6. * x3 * x7); const double z22 = 6.0 * (a4 * a5 + a2 * a6) + eosq * (24. * (x2 * x5 + x1 * x6) - 6. * (x4 * x7 + x3 * x8)); const double z23 = 6.0 * a4 * a6 + eosq * (24. * x2 * x6 - 6. * x4 * x8); z1 = z1 + z1 + betao2 * z31; z2 = z2 + z2 + betao2 * z32; z3 = z3 + z3 + betao2 * z33; const double s3 = cc * xnoi; const double s2 = -0.5 * s3 / betao; const double s4 = s3 * betao; const double s1 = -15.0 * Eccentricity() * s4; const double s5 = x1 * x3 + x2 * x4; const double s6 = x2 * x3 + x1 * x4; const double s7 = x2 * x4 - x1 * x3; const double se = s1 * zn * s5; const double si = s2 * zn * (z11 + z13); const double sl = -zn * s3 * (z1 + z3 - 14.0 - 6.0 * eosq); const double sgh = s4 * zn * (z31 + z33 - 6.0); /* * replaced * sh = -zn * s2 * (z21 + z23 * with * shdq = (-zn * s2 * (z21 + z23)) / sinio */ if (Inclination() < 5.2359877e-2 || Inclination() > Globals::PI() - 5.2359877e-2) { shdq = 0.0; } else { shdq = (-zn * s2 * (z21 + z23)) / sinio; } d_ee2_ = 2.0 * s1 * s6; d_e3_ = 2.0 * s1 * s7; d_xi2_ = 2.0 * s2 * z12; d_xi3_ = 2.0 * s2 * (z13 - z11); d_xl2_ = -2.0 * s3 * z2; d_xl3_ = -2.0 * s3 * (z3 - z1); d_xl4_ = -2.0 * s3 * (-21.0 - 9.0 * eosq) * ze; d_xgh2_ = 2.0 * s4 * z32; d_xgh3_ = 2.0 * s4 * (z33 - z31); d_xgh4_ = -18.0 * s4 * ze; d_xh2_ = -2.0 * s2 * z22; d_xh3_ = -2.0 * s2 * (z23 - z21); if (cnt == 1) break; /* * do lunar terms */ d_sse_ = se; d_ssi_ = si; d_ssl_ = sl; d_ssh_ = shdq; d_ssg_ = sgh - cosio * d_ssh_; d_se2_ = d_ee2_; d_si2_ = d_xi2_; d_sl2_ = d_xl2_; d_sgh2_ = d_xgh2_; d_sh2_ = d_xh2_; d_se3_ = d_e3_; d_si3_ = d_xi3_; d_sl3_ = d_xl3_; d_sgh3_ = d_xgh3_; d_sh3_ = d_xh3_; d_sl4_ = d_xl4_; d_sgh4_ = d_xgh4_; zcosg = zcosgl; zsing = zsingl; zcosi = zcosil; zsini = zsinil; zcosh = zcoshl * cosq + zsinhl * sinq; zsinh = sinq * zcoshl - cosq * zsinhl; zn = ZNL; cc = C1L; ze = ZEL; zmo = d_zmol_; } d_sse_ += se; d_ssi_ += si; d_ssl_ += sl; d_ssg_ += sgh - cosio * shdq; d_ssh_ += shdq; /* * geopotential resonance initialization for 12 hour orbits */ d_resonance_flag_ = false; d_synchronous_flag_ = false; bool initialize_integrator = false; if (RecoveredMeanMotion() < 0.0052359877 && RecoveredMeanMotion() > 0.0034906585) { /* * 24h synchronous resonance terms initialization */ d_resonance_flag_ = true; d_synchronous_flag_ = true; const double g200 = 1.0 + eosq * (-2.5 + 0.8125 * eosq); const double g310 = 1.0 + 2.0 * eosq; const double g300 = 1.0 + eosq * (-6.0 + 6.60937 * eosq); const double f220 = 0.75 * (1.0 + cosio) * (1.0 + cosio); const double f311 = 0.9375 * sinio * sinio * (1.0 + 3.0 * cosio) - 0.75 * (1.0 + cosio); double f330 = 1.0 + cosio; f330 = 1.875 * f330 * f330 * f330; d_del1_ = 3.0 * RecoveredMeanMotion() * RecoveredMeanMotion() * aqnv * aqnv; d_del2_ = 2.0 * d_del1_ * f220 * g200 * Q22; d_del3_ = 3.0 * d_del1_ * f330 * g300 * Q33 * aqnv; d_del1_ = d_del1_ * f311 * g310 * Q31 * aqnv; d_fasx2_ = 0.13130908; d_fasx4_ = 2.8843198; d_fasx6_ = 0.37448087; d_xlamo_ = MeanAnomoly() + AscendingNode() + ArgumentPerigee() - i_gsto_; bfact = xmdot + xpidot - THDT; bfact += d_ssl_ + d_ssg_ + d_ssh_; } else if (RecoveredMeanMotion() < 8.26e-3 || RecoveredMeanMotion() > 9.24e-3 || Eccentricity() < 0.5) { initialize_integrator = false; } else { /* * geopotential resonance initialization for 12 hour orbits */ d_resonance_flag_ = true; const double eoc = Eccentricity() * eosq; double g211; double g310; double g322; double g410; double g422; double g520; double g201 = -0.306 - (Eccentricity() - 0.64) * 0.440; if (Eccentricity() <= 0.65) { g211 = 3.616 - 13.247 * Eccentricity() + 16.290 * eosq; g310 = -19.302 + 117.390 * Eccentricity() - 228.419 * eosq + 156.591 * eoc; g322 = -18.9068 + 109.7927 * Eccentricity() - 214.6334 * eosq + 146.5816 * eoc; g410 = -41.122 + 242.694 * Eccentricity() - 471.094 * eosq + 313.953 * eoc; g422 = -146.407 + 841.880 * Eccentricity() - 1629.014 * eosq + 1083.435 * eoc; g520 = -532.114 + 3017.977 * Eccentricity() - 5740 * eosq + 3708.276 * eoc; } else { g211 = -72.099 + 331.819 * Eccentricity() - 508.738 * eosq + 266.724 * eoc; g310 = -346.844 + 1582.851 * Eccentricity() - 2415.925 * eosq + 1246.113 * eoc; g322 = -342.585 + 1554.908 * Eccentricity() - 2366.899 * eosq + 1215.972 * eoc; g410 = -1052.797 + 4758.686 * Eccentricity() - 7193.992 * eosq + 3651.957 * eoc; g422 = -3581.69 + 16178.11 * Eccentricity() - 24462.77 * eosq + 12422.52 * eoc; if (Eccentricity() <= 0.715) { g520 = 1464.74 - 4664.75 * Eccentricity() + 3763.64 * eosq; } else { g520 = -5149.66 + 29936.92 * Eccentricity() - 54087.36 * eosq + 31324.56 * eoc; } } double g533; double g521; double g532; if (Eccentricity() < 0.7) { g533 = -919.2277 + 4988.61 * Eccentricity() - 9064.77 * eosq + 5542.21 * eoc; g521 = -822.71072 + 4568.6173 * Eccentricity() - 8491.4146 * eosq + 5337.524 * eoc; g532 = -853.666 + 4690.25 * Eccentricity() - 8624.77 * eosq + 5341.4 * eoc; } else { g533 = -37995.78 + 161616.52 * Eccentricity() - 229838.2 * eosq + 109377.94 * eoc; g521 = -51752.104 + 218913.95 * Eccentricity() - 309468.16 * eosq + 146349.42 * eoc; g532 = -40023.88 + 170470.89 * Eccentricity() - 242699.48 * eosq + 115605.82 * eoc; } const double sini2 = sinio * sinio; const double f220 = 0.75 * (1.0 + 2.0 * cosio + theta2); const double f221 = 1.5 * sini2; const double f321 = 1.875 * sinio * (1.0 - 2.0 * cosio - 3.0 * theta2); const double f322 = -1.875 * sinio * (1.0 + 2.0 * cosio - 3.0 * theta2); const double f441 = 35.0 * sini2 * f220; const double f442 = 39.3750 * sini2 * sini2; const double f522 = 9.84375 * sinio * (sini2 * (1.0 - 2.0 * cosio - 5.0 * theta2) + 0.33333333 * (-2.0 + 4.0 * cosio + 6.0 * theta2)); const double f523 = sinio * (4.92187512 * sini2 * (-2.0 - 4.0 * cosio + 10.0 * theta2) + 6.56250012 * (1.0 + 2.0 * cosio - 3.0 * theta2)); const double f542 = 29.53125 * sinio * (2.0 - 8.0 * cosio + theta2 * (-12.0 + 8.0 * cosio + 10.0 * theta2)); const double f543 = 29.53125 * sinio * (-2.0 - 8.0 * cosio + theta2 * (12.0 + 8.0 * cosio - 10.0 * theta2)); const double xno2 = RecoveredMeanMotion() * RecoveredMeanMotion(); const double ainv2 = aqnv * aqnv; double temp1 = 3.0 * xno2 * ainv2; double temp = temp1 * ROOT22; d_d2201_ = temp * f220 * g201; d_d2211_ = temp * f221 * g211; temp1 = temp1 * aqnv; temp = temp1 * ROOT32; d_d3210_ = temp * f321 * g310; d_d3222_ = temp * f322 * g322; temp1 = temp1 * aqnv; temp = 2.0 * temp1 * ROOT44; d_d4410_ = temp * f441 * g410; d_d4422_ = temp * f442 * g422; temp1 = temp1 * aqnv; temp = temp1 * ROOT52; d_d5220_ = temp * f522 * g520; d_d5232_ = temp * f523 * g532; temp = 2.0 * temp1 * ROOT54; d_d5421_ = temp * f542 * g521; d_d5433_ = temp * f543 * g533; d_xlamo_ = MeanAnomoly() + AscendingNode() + AscendingNode() - i_gsto_ - i_gsto_; bfact = xmdot + xnodot + xnodot - THDT - THDT; bfact = bfact + d_ssl_ + d_ssh_ + d_ssh_; } if (initialize_integrator) { d_xfact_ = bfact - RecoveredMeanMotion(); /* * initialize integrator */ d_atime_ = 0.0; d_xni_ = RecoveredMeanMotion(); d_xli_ = d_xlamo_; } } void SGDP4::DeepSpaceCalculateLunarSolarTerms(const double t, double& pe, double& pinc, double& pl, double& pgh, double& ph) const { static const double ZES = 0.01675; static const double ZNS = 1.19459E-5; static const double ZNL = 1.5835218E-4; static const double ZEL = 0.05490; /* * update solar terms */ double zm = d_zmos_ + ZNS * t; if (first_run_) zm = d_zmos_; double zf = zm + 2.0 * ZES * sin(zm); double sinzf = sin(zf); double f2 = 0.5 * sinzf * sinzf - 0.25; double f3 = -0.5 * sinzf * cos(zf); const double ses = d_se2_ * f2 + d_se3_ * f3; const double sis = d_si2_ * f2 + d_si3_ * f3; const double sls = d_sl2_ * f2 + d_sl3_ * f3 + d_sl4_ * sinzf; const double sghs = d_sgh2_ * f2 + d_sgh3_ * f3 + d_sgh4_ * sinzf; const double shs = d_sh2_ * f2 + d_sh3_ * f3; /* * update lunar terms */ zm = d_zmol_ + ZNL * t; if (first_run_) zm = d_zmol_; zf = zm + 2.0 * ZEL * sin(zm); sinzf = sin(zf); f2 = 0.5 * sinzf * sinzf - 0.25; f3 = -0.5 * sinzf * cos(zf); const double sel = d_ee2_ * f2 + d_e3_ * f3; const double sil = d_xi2_ * f2 + d_xi3_ * f3; const double sll = d_xl2_ * f2 + d_xl3_ * f3 + d_xl4_ * sinzf; const double sghl = d_xgh2_ * f2 + d_xgh3_ * f3 + d_xgh4_ * sinzf; const double shl = d_xh2_ * f2 + d_xh3_ * f3; /* * merge computed values */ pe = ses + sel; pinc = sis + sil; pl = sls + sll; pgh = sghs + sghl; ph = shs + shl; } /* * calculate lunar / solar periodics and apply */ void SGDP4::DeepSpacePeriodics(const double& t, double& em, double& xinc, double& omgasm, double& xnodes, double& xll) { /* * storage for lunar / solar terms set by DeepSpaceCalculateLunarSolarTerms() */ double pe = 0.0; double pinc = 0.0; double pl = 0.0; double pgh = 0.0; double ph = 0.0; /* * calculate lunar / solar terms for current time */ DeepSpaceCalculateLunarSolarTerms(t, pe, pinc, pl, pgh, ph); if (!first_run_) { xinc += pinc; em += pe; /* Spacetrack report #3 has sin/cos from before perturbations * added to xinc (oldxinc), but apparently report # 6 has then * from after they are added. * (moved from start of function) */ const double sinis = sin(xinc); const double cosis = cos(xinc); if (Inclination() >= 0.2) { /* * apply periodics directly */ const double tmp_ph = ph / sinis; omgasm += pgh - cosis * tmp_ph; xnodes += tmp_ph; xll += pl; } else { /* * apply periodics with lyddane modification */ const double sinok = sin(xnodes); const double cosok = cos(xnodes); double alfdp = sinis * sinok; double betdp = sinis * cosok; const double dalf = ph * cosok + pinc * cosis * sinok; const double dbet = -ph * sinok + pinc * cosis * cosok; alfdp += dalf; betdp += dbet; double xls = xll + omgasm + cosis * xnodes; double dls = pl + pgh - pinc * xnodes * sinis; xls += dls; /* * save old xnodes value */ const double oldxnodes = xnodes; xnodes = atan2(alfdp, betdp); /* * Get perturbed xnodes in to same quadrant as original. */ if (fabs(oldxnodes - xnodes) > Globals::PI()) { if (xnodes < oldxnodes) xnodes += Globals::TWOPI(); else xnodes -= Globals::TWOPI(); } xll += pl; omgasm = xls - xll - cosis * xnodes; } } } /* * deep space secular effects */ void SGDP4::DeepSpaceSecular(const double& t, double& xll, double& omgasm, double& xnodes, double& em, double& xinc, double& xn) const { static const double THDT = 4.37526908801129966e-3; static const double STEP2 = 259200.0; static const double STEP = 720.0; double xldot = 0.0; double xndot = 0.0; double xnddt = 0.0; xll += d_ssl_ * t; omgasm += d_ssg_ * t; xnodes += d_ssh_ * t; em += d_sse_ * t; xinc += d_ssi_ * t; if (!d_resonance_flag_) return; /* * 1st condition (if d_atime_ is less than one time step from epoch) * 2nd condition (if d_atime_ and t are of opposite signs, so zero crossing required) * 3rd condition (if t is closer to zero than d_atime_) */ if (fabs(d_atime_) < STEP || t * d_atime_ <= 0.0 || fabs(t) < fabs(d_atime_)) { /* * restart from epoch */ d_atime_ = 0.0; d_xni_ = RecoveredMeanMotion(); d_xli_ = d_xlamo_; } double ft = t - d_atime_; /* * if time difference (ft) is greater than the time step (720.0) * loop around until d_atime_ is within one time step of t */ if (fabs(ft) >= STEP) { /* * calculate step direction to allow d_atime_ * to catch up with t */ double delt = -STEP; if (ft >= 0.0) delt = STEP; do { DeepSpaceCalcIntegrator(delt, STEP2, xndot, xnddt, xldot); ft = t - d_atime_; } while (fabs(ft) >= STEP); } /* * calculate dot terms */ DeepSpaceCalcDotTerms(xndot, xnddt, xldot); /* * integrator */ xn = d_xni_ + xndot * ft + xnddt * ft * ft * 0.5; const double xl = d_xli_ + xldot * ft + xndot * ft * ft * 0.5; const double temp = -xnodes + i_gsto_ + t * THDT; if (!d_synchronous_flag_) xll = xl + temp + temp; else xll = xl - omgasm + temp; } /* * calculate dot terms */ void SGDP4::DeepSpaceCalcDotTerms(double& xndot, double& xnddt, double& xldot) const { static const double G22 = 5.7686396; static const double G32 = 0.95240898; static const double G44 = 1.8014998; static const double G52 = 1.0508330; static const double G54 = 4.4108898; if (d_synchronous_flag_) { xndot = d_del1_ * sin(d_xli_ - d_fasx2_) + d_del2_ * sin(2.0 * (d_xli_ - d_fasx4_)) + d_del3_ * sin(3.0 * (d_xli_ - d_fasx6_)); xnddt = d_del1_ * cos(d_xli_ - d_fasx2_) + 2.0 * d_del2_ * cos(2.0 * (d_xli_ - d_fasx4_)) + 3.0 * d_del3_ * cos(3.0 * (d_xli_ - d_fasx6_)); } else { /* * TODO: check ArgumentPerigee() and i_omgdot_ * are correct to use */ const double xomi = ArgumentPerigee() + i_omgdot_ * d_atime_; const double x2omi = xomi + xomi; const double x2li = d_xli_ + d_xli_; xndot = d_d2201_ * sin(x2omi + d_xli_ - G22) + d_d2211_ * sin(d_xli_ - G22) + d_d3210_ * sin(xomi + d_xli_ - G32) + d_d3222_ * sin(-xomi + d_xli_ - G32) + d_d4410_ * sin(x2omi + x2li - G44) + d_d4422_ * sin(x2li - G44) + d_d5220_ * sin(xomi + d_xli_ - G52) + d_d5232_ * sin(-xomi + d_xli_ - G52) + d_d5421_ * sin(xomi + x2li - G54) + d_d5433_ * sin(-xomi + x2li - G54); xnddt = d_d2201_ * cos(x2omi + d_xli_ - G22) + d_d2211_ * cos(d_xli_ - G22) + d_d3210_ * cos(xomi + d_xli_ - G32) + d_d3222_ * cos(-xomi + d_xli_ - G32) + d_d5220_ * cos(xomi + d_xli_ - G52) + d_d5232_ * cos(-xomi + d_xli_ - G52) + 2.0 * (d_d4410_ * cos(x2omi + x2li - G44) + d_d4422_ * cos(x2li - G44) + d_d5421_ * cos(xomi + x2li - G54) + d_d5433_ * cos(-xomi + x2li - G54)); } xldot = d_xni_ + d_xfact_; xnddt = xnddt * xldot; } /* * deep space integrator for time period of delt */ void SGDP4::DeepSpaceCalcIntegrator(const double& delt, const double& step2, double& xndot, double& xnddt, double& xldot) const { /* * calculate dot terms */ DeepSpaceCalcDotTerms(xndot, xnddt, xldot); /* * integrator */ d_xli_ += xldot * delt + xndot * step2; d_xni_ += xndot * delt + xnddt * step2; /* * increment integrator time */ d_atime_ += delt; } Bug: accidently redeclared some variables #include "SGDP4.h" #include "Vector.h" #include "SatelliteException.h" #include <cmath> #include <iomanip> SGDP4::SGDP4(void) { first_run_ = true; SetConstants(CONSTANTS_WGS72); } SGDP4::~SGDP4(void) { } void SGDP4::SetConstants(EnumConstants constants) { constants_.AE = 1.0; constants_.TWOTHRD = 2.0 / 3.0; switch (constants) { case CONSTANTS_WGS72_OLD: constants_.MU = 0.0; constants_.XKMPER = 6378.135; constants_.XKE = 0.0743669161; constants_.XJ2 = 0.001082616; constants_.XJ3 = -0.00000253881; constants_.XJ4 = -0.00000165597; constants_.J3OJ2 = constants_.XJ3 / constants_.XJ2; break; case CONSTANTS_WGS72: constants_.MU = 398600.8; constants_.XKMPER = 6378.135; constants_.XKE = 60.0 / sqrt(constants_.XKMPER * constants_.XKMPER * constants_.XKMPER / constants_.MU); constants_.XJ2 = 0.001082616; constants_.XJ3 = -0.00000253881; constants_.XJ4 = -0.00000165597; constants_.J3OJ2 = constants_.XJ3 / constants_.XJ2; break; case CONSTANTS_WGS84: constants_.MU = 398600.5; constants_.XKMPER = 6378.137; constants_.XKE = 60.0 / sqrt(constants_.XKMPER * constants_.XKMPER * constants_.XKMPER / constants_.MU); constants_.XJ2 = 0.00108262998905; constants_.XJ3 = -0.00000253215306; constants_.XJ4 = -0.00000161098761; constants_.J3OJ2 = constants_.XJ3 / constants_.XJ2; break; default: throw new SatelliteException("Unrecognised constant value"); break; } constants_.S = constants_.AE + 78.0 / constants_.XKMPER; constants_.CK2 = 0.5 * constants_.XJ2 * constants_.AE * constants_.AE; constants_.CK4 = -0.375 * constants_.XJ4 * constants_.AE * constants_.AE * constants_.AE * constants_.AE; constants_.QOMS2T = pow((120.0 - 78.0) * constants_.AE / constants_.XKMPER, 4.0); } void SGDP4::SetTle(const Tle& tle) { /* * extract and format tle data */ mean_anomoly_ = tle.GetField(Tle::FLD_M, Tle::U_RAD); ascending_node_ = tle.GetField(Tle::FLD_RAAN, Tle::U_RAD); argument_perigee_ = tle.GetField(Tle::FLD_ARGPER, Tle::U_RAD); eccentricity_ = tle.GetField(Tle::FLD_E); inclination_ = tle.GetField(Tle::FLD_I, Tle::U_RAD); mean_motion_ = tle.GetField(Tle::FLD_MMOTION) * Globals::TWOPI() / Globals::MIN_PER_DAY(); bstar_ = tle.GetField(Tle::FLD_BSTAR); epoch_ = tle.GetEpoch(); /* * error checks */ if (eccentricity_ < 0.0 || eccentricity_ > 1.0 - 1.0e-3) { throw new SatelliteException("Eccentricity out of range"); } if (inclination_ < 0.0 || eccentricity_ > Globals::PI()) { throw new SatelliteException("Inclination out of range"); } /* * recover original mean motion (xnodp) and semimajor axis (aodp) * from input elements */ double a1 = pow(constants_.XKE / MeanMotion(), constants_.TWOTHRD); i_cosio_ = cos(Inclination()); i_sinio_ = sin(Inclination()); double theta2 = i_cosio_ * i_cosio_; i_x3thm1_ = 3.0 * theta2 - 1.0; double eosq = Eccentricity() * Eccentricity(); double betao2 = 1.0 - eosq; double betao = sqrt(betao2); double temp = (1.5 * constants_.CK2) * i_x3thm1_ / (betao * betao2); double del1 = temp / (a1 * a1); double a0 = a1 * (1.0 - del1 * (1.0 / 3.0 + del1 * (1.0 + del1 * 134.0 / 81.0))); double del0 = temp / (a0 * a0); recovered_mean_motion_ = MeanMotion() / (1.0 + del0); recovered_semi_major_axis_ = a0 / (1.0 - del0); /* * find perigee and period */ perigee_ = (RecoveredSemiMajorAxis() * (1.0 - Eccentricity()) - constants_.AE) * constants_.XKMPER; period_ = Globals::TWOPI() / RecoveredMeanMotion(); Initialize(theta2, betao2, betao, eosq); } void SGDP4::Initialize(const double& theta2, const double& betao2, const double& betao, const double& eosq) { if (Period() >= 225.0) { i_use_deep_space_ = true; } else { i_use_deep_space_ = false; i_use_simple_model_ = false; /* * for perigee less than 220 kilometers, the simple_model flag is set and * the equations are truncated to linear variation in sqrt a and * quadratic variation in mean anomly. also, the c3 term, the * delta omega term and the delta m term are dropped */ if (Perigee() < 220.0) { i_use_simple_model_ = true; } } /* * for perigee below 156km, the values of * s4 and qoms2t are altered */ double s4 = constants_.S; double qoms24 = constants_.QOMS2T; if (Perigee() < 156.0) { s4 = Perigee() - 78.0; if (Perigee() < 98.0) { s4 = 20.0; } qoms24 = pow((120.0 - s4) * constants_.AE / constants_.XKMPER, 4.0); s4 = s4 / constants_.XKMPER + constants_.AE; } /* * generate constants */ double pinvsq = 1.0 / (RecoveredSemiMajorAxis() * RecoveredSemiMajorAxis() * betao2 * betao2); double tsi = 1.0 / (RecoveredSemiMajorAxis() - s4); i_eta_ = RecoveredSemiMajorAxis() * Eccentricity() * tsi; double etasq = i_eta_ * i_eta_; double eeta = Eccentricity() * i_eta_; double psisq = fabs(1.0 - etasq); double coef = qoms24 * pow(tsi, 4.0); double coef1 = coef / pow(psisq, 3.5); double c2 = coef1 * RecoveredMeanMotion() * (RecoveredSemiMajorAxis() * (1.0 + 1.5 * etasq + eeta * (4.0 + etasq)) + 0.75 * constants_.CK2 * tsi / psisq * i_x3thm1_ * (8.0 + 3.0 * etasq * (8.0 + etasq))); i_c1_ = BStar() * c2; i_a3ovk2_ = -constants_.XJ3 / constants_.CK2 * pow(constants_.AE, 3.0); i_x1mth2_ = 1.0 - theta2; i_c4_ = 2.0 * RecoveredMeanMotion() * coef1 * RecoveredSemiMajorAxis() * betao2 * (i_eta_ * (2.0 + 0.5 * etasq) + Eccentricity() * (0.5 + 2.0 * etasq) - 2.0 * constants_.CK2 * tsi / (RecoveredSemiMajorAxis() * psisq) * (-3.0 * i_x3thm1_ * (1.0 - 2.0 * eeta + etasq * (1.5 - 0.5 * eeta)) + 0.75 * i_x1mth2_ * (2.0 * etasq - eeta * (1.0 + etasq)) * cos(2.0 * ArgumentPerigee()))); double theta4 = theta2 * theta2; double temp1 = 3.0 * constants_.CK2 * pinvsq * RecoveredMeanMotion(); double temp2 = temp1 * constants_.CK2 * pinvsq; double temp3 = 1.25 * constants_.CK4 * pinvsq * pinvsq * RecoveredMeanMotion(); i_xmdot_ = RecoveredMeanMotion() + 0.5 * temp1 * betao * i_x3thm1_ + 0.0625 * temp2 * betao * (13.0 - 78.0 * theta2 + 137.0 * theta4); double x1m5th = 1.0 - 5.0 * theta2; i_omgdot_ = -0.5 * temp1 * x1m5th + 0.0625 * temp2 * (7.0 - 114.0 * theta2 + 395.0 * theta4) + temp3 * (3.0 - 36.0 * theta2 + 49.0 * theta4); double xhdot1_ = -temp1 * i_cosio_; i_xnodot_ = xhdot1_ + (0.5 * temp2 * (4.0 - 19.0 * theta2) + 2.0 * temp3 * (3.0 - 7.0 * theta2)) * i_cosio_; i_xnodcf_ = 3.5 * betao2 * xhdot1_ * i_c1_; i_t2cof_ = 1.5 * i_c1_; if (fabs(i_cosio_ + 1.0) > 1.5e-12) i_xlcof_ = 0.125 * i_a3ovk2_ * i_sinio_ * (3.0 + 5.0 * i_cosio_) / (1.0 + i_cosio_); else i_xlcof_ = 0.125 * i_a3ovk2_ * i_sinio_ * (3.0 + 5.0 * i_cosio_) / 1.5e-12; i_aycof_ = 0.25 * i_a3ovk2_ * i_sinio_; i_x7thm1_ = 7.0 * theta2 - 1.0; if (i_use_deep_space_) { const double sing = sin(ArgumentPerigee()); const double cosg = cos(ArgumentPerigee()); i_gsto_ = Epoch().ToGMST(); DeepSpaceInitialize(eosq, i_sinio_, i_cosio_, betao, theta2, sing, cosg, betao2, i_xmdot_, i_omgdot_, i_xnodot_); } else { double c3 = 0.0; if (Eccentricity() > 1.0e-4) { c3 = coef * tsi * i_a3ovk2_ * RecoveredMeanMotion() * constants_.AE * i_sinio_ / Eccentricity(); } i_c5_ = 2.0 * coef1 * RecoveredSemiMajorAxis() * betao2 * (1.0 + 2.75 * (etasq + eeta) + eeta * etasq); i_omgcof_ = BStar() * c3 * cos(ArgumentPerigee()); i_xmcof_ = 0.0; if (Eccentricity() > 1.0e-4) i_xmcof_ = -constants_.TWOTHRD * coef * BStar() * constants_.AE / eeta; i_delmo_ = pow(1.0 + i_eta_ * (cos(MeanAnomoly())), 3.0); i_sinmo_ = sin(MeanAnomoly()); if (!i_use_simple_model_) { double c1sq = i_c1_ * i_c1_; i_d2_ = 4.0 * RecoveredSemiMajorAxis() * tsi * c1sq; double temp = i_d2_ * tsi * i_c1_ / 3.0; i_d3_ = (17.0 * RecoveredSemiMajorAxis() + s4) * temp; i_d4_ = 0.5 * temp * RecoveredSemiMajorAxis() * tsi * (221.0 * RecoveredSemiMajorAxis() + 31.0 * s4) * i_c1_; i_t3cof_ = i_d2_ + 2.0 * c1sq; i_t4cof_ = 0.25 * (3.0 * i_d3_ + i_c1_ * (12.0 * i_d2_ + 10.0 * c1sq)); i_t5cof_ = 0.2 * (3.0 * i_d4_ + 12.0 * i_c1_ * i_d3_ + 6.0 * i_d2_ * i_d2_ + 15.0 * c1sq * (2.0 * i_d2_ + c1sq)); } } Eci eci; FindPosition(eci, 0.0); first_run_ = false; } void SGDP4::FindPosition(Eci& eci, double tsince) { if (i_use_deep_space_) FindPositionSDP4(eci, tsince); else FindPositionSGP4(eci, tsince); } void SGDP4::FindPositionSDP4(Eci& eci, double tsince) { /* * the final values */ double e = Eccentricity(); double a; double omega; double xl; double xnode; double xincl = Inclination(); /* * update for secular gravity and atmospheric drag */ double xmdf = MeanAnomoly() + i_xmdot_ * tsince; double omgadf = ArgumentPerigee() + i_omgdot_ * tsince; const double xnoddf = AscendingNode() + i_xnodot_ * tsince; omega = omgadf; const double tsq = tsince * tsince; xnode = xnoddf + i_xnodcf_ * tsq; double tempa = 1.0 - i_c1_ * tsince; double tempe = BStar() * i_c4_ * tsince; double templ = i_t2cof_ * tsq; double xn = RecoveredMeanMotion(); /* t, xll, omgasm, xnodes, em, xinc, xn */ DeepSpaceSecular(tsince, xmdf, omega, xnode, e, xincl, xn); if (xn <= 0.0) { throw new SatelliteException("Error: 2 (xn <= 0.0)"); } a = pow(constants_.XKE / xn, constants_.TWOTHRD) * pow(tempa, 2.0); e -= tempe; /* * fix tolerance for error recognition */ if (e >= 1.0 || e < -0.001) { throw new SatelliteException("Error: 1 (e >= 1.0 || e < -0.001)"); } /* * fix tolerance to avoid a divide by zero */ if (e < 1.0e-6) e = 1.0e-6; xmdf += RecoveredMeanMotion() * templ; double xlm = xmdf + omega + xnode; xnode = fmod(xnode, Globals::TWOPI()); omega = fmod(omega, Globals::TWOPI()); xlm = fmod(xlm, Globals::TWOPI()); double xmam = fmod(xlm - omega - xnode, Globals::TWOPI()); DeepSpacePeriodics(tsince, e, xincl, omega, xnode, xmam); if (xincl < 0.0) { xincl = -xincl; xnode += Globals::PI(); omega -= Globals::PI(); } xl = xmam + omega + xnode; if (e < 0.0 || e > 1.0) { throw new SatelliteException("Error: 3 (e < 0.0 || e > 1.0)"); } /* * re-compute the perturbed values */ const double perturbed_sinio = sin(xincl); const double perturbed_cosio = cos(xincl); const double perturbed_theta2 = perturbed_cosio * perturbed_cosio; const double perturbed_x3thm1 = 3.0 * perturbed_theta2 - 1.0; const double perturbed_x1mth2 = 1.0 - perturbed_theta2; const double perturbed_x7thm1 = 7.0 * perturbed_theta2 - 1.0; double perturbed_xlcof; if (fabs(perturbed_cosio + 1.0) > 1.5e-12) perturbed_xlcof = 0.125 * i_a3ovk2_ * perturbed_sinio * (3.0 + 5.0 * perturbed_cosio) / (1.0 + perturbed_cosio); else perturbed_xlcof = 0.125 * i_a3ovk2_ * perturbed_sinio * (3.0 + 5.0 * perturbed_cosio) / 1.5e-12; const double perturbed_aycof = 0.25 * i_a3ovk2_ * perturbed_sinio; /* * using calculated values, find position and velocity */ CalculateFinalPositionVelocity(eci, tsince, e, a, omega, xl, xnode, xincl, perturbed_xlcof, perturbed_aycof, perturbed_x3thm1, perturbed_x1mth2, perturbed_x7thm1, perturbed_cosio, perturbed_sinio); } void SGDP4::FindPositionSGP4(Eci& eci, double tsince) const { /* * the final values */ double e; double a; double omega; double xl; double xnode; double xincl; /* * update for secular gravity and atmospheric drag */ const double xmdf = MeanAnomoly() + i_xmdot_ * tsince; const double omgadf = ArgumentPerigee() + i_omgdot_ * tsince; const double xnoddf = AscendingNode() + i_xnodot_ * tsince; const double tsq = tsince * tsince; xnode = xnoddf + i_xnodcf_ * tsq; double tempa = 1.0 - i_c1_ * tsince; double tempe = BStar() * i_c4_ * tsince; double templ = i_t2cof_ * tsq; xincl = Inclination(); omega = omgadf; double xmp = xmdf; if (!i_use_simple_model_) { const double delomg = i_omgcof_ * tsince; const double delm = i_xmcof_ * (pow(1.0 + i_eta_ * cos(xmdf), 3.0) - i_delmo_); const double temp = delomg + delm; xmp += temp; omega -= temp; const double tcube = tsq * tsince; const double tfour = tsince * tcube; tempa -= i_d2_ * tsq - i_d3_ * tcube - i_d4_ * tfour; tempe += BStar() * i_c5_ * (sin(xmp) - i_sinmo_); templ += i_t3cof_ * tcube + tfour * (i_t4cof_ + tsince * i_t5cof_); } a = RecoveredSemiMajorAxis() * pow(tempa, 2.0); e = Eccentricity() - tempe; xl = xmp + omega + xnode + RecoveredMeanMotion() * templ; /* * using calculated values, find position and velocity * we can pass in constants from Initialize() as these dont change */ CalculateFinalPositionVelocity(eci, tsince, e, a, omega, xl, xnode, xincl, i_xlcof_, i_aycof_, i_x3thm1_, i_x1mth2_, i_x7thm1_, i_cosio_, i_sinio_); } void SGDP4::CalculateFinalPositionVelocity(Eci& eci, const double& tsince, const double& e, const double& a, const double& omega, const double& xl, const double& xnode, const double& xincl, const double& xlcof, const double& aycof, const double& x3thm1, const double& x1mth2, const double& x7thm1, const double& cosio, const double& sinio) const { double temp; double temp1; double temp2; double temp3; if (a < 1.0) { throw new SatelliteException("Error: Satellite crashed (a < 1.0)"); } if (e < -1.0e-3) { throw new SatelliteException("Error: Modified eccentricity too low (e < -1.0e-3)"); } const double beta = sqrt(1.0 - e * e); const double xn = constants_.XKE / pow(a, 1.5); /* * long period periodics */ const double axn = e * cos(omega); temp = 1.0 / (a * beta * beta); const double xll = temp * xlcof * axn; const double aynl = temp * aycof; const double xlt = xl + xll; const double ayn = e * sin(omega) + aynl; const double elsq = axn * axn + ayn * ayn; if (elsq >= 1.0) { throw new SatelliteException("Error: sqrt(e) >= 1 (elsq >= 1.0)"); } /* * solve keplers equation * - solve using Newton-Raphson root solving * - here capu is almost the mean anomoly * - initialise the eccentric anomaly term epw * - The fmod saves reduction of angle to +/-2pi in sin/cos() and prevents * convergence problems. */ const double capu = fmod(xlt - xnode, Globals::TWOPI()); double epw = capu; double sinepw = 0.0; double cosepw = 0.0; double ecose = 0.0; double esine = 0.0; /* * sensibility check for N-R correction */ const double max_newton_naphson = 1.25 * fabs(sqrt(elsq)); bool kepler_running = true; for (int i = 0; i < 10 && kepler_running; i++) { sinepw = sin(epw); cosepw = cos(epw); ecose = axn * cosepw + ayn * sinepw; esine = axn * sinepw - ayn * cosepw; double f = capu - epw + esine; if (fabs(f) < 1.0e-12) { kepler_running = false; } else { /* * 1st order Newton-Raphson correction */ const double fdot = 1.0 - ecose; double delta_epw = f / fdot; /* * 2nd order Newton-Raphson correction. * f / (fdot - 0.5 * d2f * f/fdot) */ if (i == 0) { if (delta_epw > max_newton_naphson) delta_epw = max_newton_naphson; else if (delta_epw < -max_newton_naphson) delta_epw = -max_newton_naphson; } else { delta_epw = f / (fdot + 0.5 * esine * delta_epw); } /* * Newton-Raphson correction of -F/DF */ epw += delta_epw; } } /* * short period preliminary quantities */ temp = 1.0 - elsq; const double pl = a * temp; const double r = a * (1.0 - ecose); temp1 = 1.0 / r; const double rdot = constants_.XKE * sqrt(a) * esine * temp1; const double rfdot = constants_.XKE * sqrt(pl) * temp1; temp2 = a * temp1; const double betal = sqrt(temp); temp3 = 1.0 / (1.0 + betal); const double cosu = temp2 * (cosepw - axn + ayn * esine * temp3); const double sinu = temp2 * (sinepw - ayn - axn * esine * temp3); const double u = atan2(sinu, cosu); const double sin2u = 2.0 * sinu * cosu; const double cos2u = 2.0 * cosu * cosu - 1.0; temp = 1.0 / pl; temp1 = constants_.CK2 * temp; temp2 = temp1 * temp; /* * update for short periodics */ const double rk = r * (1.0 - 1.5 * temp2 * betal * x3thm1) + 0.5 * temp1 * x1mth2 * cos2u; const double uk = u - 0.25 * temp2 * x7thm1 * sin2u; const double xnodek = xnode + 1.5 * temp2 * cosio * sin2u; const double xinck = xincl + 1.5 * temp2 * cosio * sinio * cos2u; const double rdotk = rdot - xn * temp1 * x1mth2 * sin2u; const double rfdotk = rfdot + xn * temp1 * (x1mth2 * cos2u + 1.5 * x3thm1); if (rk < 0.0) { throw new SatelliteException("Error: satellite decayed (rk < 0.0)"); } /* * orientation vectors */ const double sinuk = sin(uk); const double cosuk = cos(uk); const double sinik = sin(xinck); const double cosik = cos(xinck); const double sinnok = sin(xnodek); const double cosnok = cos(xnodek); const double xmx = -sinnok * cosik; const double xmy = cosnok * cosik; const double ux = xmx * sinuk + cosnok * cosuk; const double uy = xmy * sinuk + sinnok * cosuk; const double uz = sinik * sinuk; const double vx = xmx * cosuk - cosnok * sinuk; const double vy = xmy * cosuk - sinnok * sinuk; const double vz = sinik * cosuk; /* * position and velocity */ const double x = rk * ux * constants_.XKMPER; const double y = rk * uy * constants_.XKMPER; const double z = rk * uz * constants_.XKMPER; Vector position(x, y, z); const double xdot = (rdotk * ux + rfdotk * vx) * constants_.XKMPER / 60.0; const double ydot = (rdotk * uy + rfdotk * vy) * constants_.XKMPER / 60.0; const double zdot = (rdotk * uz + rfdotk * vz) * constants_.XKMPER / 60.0; Vector velocity(xdot, ydot, zdot); Julian julian = Epoch(); julian.AddMin(tsince); eci = Eci(julian, position, velocity); } /* * deep space initialization */ void SGDP4::DeepSpaceInitialize(const double& eosq, const double& sinio, const double& cosio, const double& betao, const double& theta2, const double& sing, const double& cosg, const double& betao2, const double& xmdot, const double& omgdot, const double& xnodot) { double se = 0.0; double si = 0.0; double sl = 0.0; double sgh = 0.0; double shdq = 0.0; double bfact = 0.0; static const double ZNS = 1.19459E-5; static const double C1SS = 2.9864797E-6; static const double ZES = 0.01675; static const double ZNL = 1.5835218E-4; static const double C1L = 4.7968065E-7; static const double ZEL = 0.05490; static const double ZCOSIS = 0.91744867; static const double ZSINI = 0.39785416; static const double ZSINGS = -0.98088458; static const double ZCOSGS = 0.1945905; static const double Q22 = 1.7891679E-6; static const double Q31 = 2.1460748E-6; static const double Q33 = 2.2123015E-7; static const double ROOT22 = 1.7891679E-6; static const double ROOT32 = 3.7393792E-7; static const double ROOT44 = 7.3636953E-9; static const double ROOT52 = 1.1428639E-7; static const double ROOT54 = 2.1765803E-9; static const double THDT = 4.3752691E-3; const double aqnv = 1.0 / RecoveredSemiMajorAxis(); const double xpidot = omgdot + xnodot; const double sinq = sin(AscendingNode()); const double cosq = cos(AscendingNode()); /* * initialize lunar / solar terms */ const double d_day_ = Epoch().FromJan1_12h_1900(); const double xnodce = fmod(4.5236020 - 9.2422029e-4 * d_day_, Globals::TWOPI()); const double stem = sin(xnodce); const double ctem = cos(xnodce); const double zcosil = 0.91375164 - 0.03568096 * ctem; const double zsinil = sqrt(1.0 - zcosil * zcosil); const double zsinhl = 0.089683511 * stem / zsinil; const double zcoshl = sqrt(1.0 - zsinhl * zsinhl); const double c = 4.7199672 + 0.22997150 * d_day_; const double gam = 5.8351514 + 0.0019443680 * d_day_; d_zmol_ = Globals::Fmod2p(c - gam); double zx = 0.39785416 * stem / zsinil; double zy = zcoshl * ctem + 0.91744867 * zsinhl * stem; /* * todo: check */ zx = atan2(zx, zy); zx = fmod(gam + zx - xnodce, Globals::TWOPI()); const double zcosgl = cos(zx); const double zsingl = sin(zx); d_zmos_ = 6.2565837 + 0.017201977 * d_day_; d_zmos_ = Globals::Fmod2p(d_zmos_); /* * do solar terms */ double zcosg = ZCOSGS; double zsing = ZSINGS; double zcosi = ZCOSIS; double zsini = ZSINI; double zcosh = cosq; double zsinh = sinq; double cc = C1SS; double zn = ZNS; double ze = ZES; double zmo = d_zmos_; const double xnoi = 1.0 / RecoveredMeanMotion(); for (int cnt = 0; cnt < 2; cnt++) { /* * solar terms are done a second time after lunar terms are done */ const double a1 = zcosg * zcosh + zsing * zcosi * zsinh; const double a3 = -zsing * zcosh + zcosg * zcosi * zsinh; const double a7 = -zcosg * zsinh + zsing * zcosi * zcosh; const double a8 = zsing * zsini; const double a9 = zsing * zsinh + zcosg * zcosi*zcosh; const double a10 = zcosg * zsini; const double a2 = cosio * a7 + sinio * a8; const double a4 = cosio * a9 + sinio * a10; const double a5 = -sinio * a7 + cosio * a8; const double a6 = -sinio * a9 + cosio * a10; const double x1 = a1 * cosg + a2 * sing; const double x2 = a3 * cosg + a4 * sing; const double x3 = -a1 * sing + a2 * cosg; const double x4 = -a3 * sing + a4 * cosg; const double x5 = a5 * sing; const double x6 = a6 * sing; const double x7 = a5 * cosg; const double x8 = a6 * cosg; const double z31 = 12.0 * x1 * x1 - 3. * x3 * x3; const double z32 = 24.0 * x1 * x2 - 6. * x3 * x4; const double z33 = 12.0 * x2 * x2 - 3. * x4 * x4; double z1 = 3.0 * (a1 * a1 + a2 * a2) + z31 * eosq; double z2 = 6.0 * (a1 * a3 + a2 * a4) + z32 * eosq; double z3 = 3.0 * (a3 * a3 + a4 * a4) + z33 * eosq; const double z11 = -6.0 * a1 * a5 + eosq * (-24. * x1 * x7 - 6. * x3 * x5); const double z12 = -6.0 * (a1 * a6 + a3 * a5) + eosq * (-24. * (x2 * x7 + x1 * x8) - 6. * (x3 * x6 + x4 * x5)); const double z13 = -6.0 * a3 * a6 + eosq * (-24. * x2 * x8 - 6. * x4 * x6); const double z21 = 6.0 * a2 * a5 + eosq * (24. * x1 * x5 - 6. * x3 * x7); const double z22 = 6.0 * (a4 * a5 + a2 * a6) + eosq * (24. * (x2 * x5 + x1 * x6) - 6. * (x4 * x7 + x3 * x8)); const double z23 = 6.0 * a4 * a6 + eosq * (24. * x2 * x6 - 6. * x4 * x8); z1 = z1 + z1 + betao2 * z31; z2 = z2 + z2 + betao2 * z32; z3 = z3 + z3 + betao2 * z33; const double s3 = cc * xnoi; const double s2 = -0.5 * s3 / betao; const double s4 = s3 * betao; const double s1 = -15.0 * Eccentricity() * s4; const double s5 = x1 * x3 + x2 * x4; const double s6 = x2 * x3 + x1 * x4; const double s7 = x2 * x4 - x1 * x3; se = s1 * zn * s5; si = s2 * zn * (z11 + z13); sl = -zn * s3 * (z1 + z3 - 14.0 - 6.0 * eosq); sgh = s4 * zn * (z31 + z33 - 6.0); /* * replaced * sh = -zn * s2 * (z21 + z23 * with * shdq = (-zn * s2 * (z21 + z23)) / sinio */ if (Inclination() < 5.2359877e-2 || Inclination() > Globals::PI() - 5.2359877e-2) { shdq = 0.0; } else { shdq = (-zn * s2 * (z21 + z23)) / sinio; } d_ee2_ = 2.0 * s1 * s6; d_e3_ = 2.0 * s1 * s7; d_xi2_ = 2.0 * s2 * z12; d_xi3_ = 2.0 * s2 * (z13 - z11); d_xl2_ = -2.0 * s3 * z2; d_xl3_ = -2.0 * s3 * (z3 - z1); d_xl4_ = -2.0 * s3 * (-21.0 - 9.0 * eosq) * ze; d_xgh2_ = 2.0 * s4 * z32; d_xgh3_ = 2.0 * s4 * (z33 - z31); d_xgh4_ = -18.0 * s4 * ze; d_xh2_ = -2.0 * s2 * z22; d_xh3_ = -2.0 * s2 * (z23 - z21); if (cnt == 1) break; /* * do lunar terms */ d_sse_ = se; d_ssi_ = si; d_ssl_ = sl; d_ssh_ = shdq; d_ssg_ = sgh - cosio * d_ssh_; d_se2_ = d_ee2_; d_si2_ = d_xi2_; d_sl2_ = d_xl2_; d_sgh2_ = d_xgh2_; d_sh2_ = d_xh2_; d_se3_ = d_e3_; d_si3_ = d_xi3_; d_sl3_ = d_xl3_; d_sgh3_ = d_xgh3_; d_sh3_ = d_xh3_; d_sl4_ = d_xl4_; d_sgh4_ = d_xgh4_; zcosg = zcosgl; zsing = zsingl; zcosi = zcosil; zsini = zsinil; zcosh = zcoshl * cosq + zsinhl * sinq; zsinh = sinq * zcoshl - cosq * zsinhl; zn = ZNL; cc = C1L; ze = ZEL; zmo = d_zmol_; } d_sse_ += se; d_ssi_ += si; d_ssl_ += sl; d_ssg_ += sgh - cosio * shdq; d_ssh_ += shdq; /* * geopotential resonance initialization for 12 hour orbits */ d_resonance_flag_ = false; d_synchronous_flag_ = false; bool initialize_integrator = false; if (RecoveredMeanMotion() < 0.0052359877 && RecoveredMeanMotion() > 0.0034906585) { /* * 24h synchronous resonance terms initialization */ d_resonance_flag_ = true; d_synchronous_flag_ = true; const double g200 = 1.0 + eosq * (-2.5 + 0.8125 * eosq); const double g310 = 1.0 + 2.0 * eosq; const double g300 = 1.0 + eosq * (-6.0 + 6.60937 * eosq); const double f220 = 0.75 * (1.0 + cosio) * (1.0 + cosio); const double f311 = 0.9375 * sinio * sinio * (1.0 + 3.0 * cosio) - 0.75 * (1.0 + cosio); double f330 = 1.0 + cosio; f330 = 1.875 * f330 * f330 * f330; d_del1_ = 3.0 * RecoveredMeanMotion() * RecoveredMeanMotion() * aqnv * aqnv; d_del2_ = 2.0 * d_del1_ * f220 * g200 * Q22; d_del3_ = 3.0 * d_del1_ * f330 * g300 * Q33 * aqnv; d_del1_ = d_del1_ * f311 * g310 * Q31 * aqnv; d_fasx2_ = 0.13130908; d_fasx4_ = 2.8843198; d_fasx6_ = 0.37448087; d_xlamo_ = MeanAnomoly() + AscendingNode() + ArgumentPerigee() - i_gsto_; bfact = xmdot + xpidot - THDT; bfact += d_ssl_ + d_ssg_ + d_ssh_; } else if (RecoveredMeanMotion() < 8.26e-3 || RecoveredMeanMotion() > 9.24e-3 || Eccentricity() < 0.5) { initialize_integrator = false; } else { /* * geopotential resonance initialization for 12 hour orbits */ d_resonance_flag_ = true; const double eoc = Eccentricity() * eosq; double g211; double g310; double g322; double g410; double g422; double g520; double g201 = -0.306 - (Eccentricity() - 0.64) * 0.440; if (Eccentricity() <= 0.65) { g211 = 3.616 - 13.247 * Eccentricity() + 16.290 * eosq; g310 = -19.302 + 117.390 * Eccentricity() - 228.419 * eosq + 156.591 * eoc; g322 = -18.9068 + 109.7927 * Eccentricity() - 214.6334 * eosq + 146.5816 * eoc; g410 = -41.122 + 242.694 * Eccentricity() - 471.094 * eosq + 313.953 * eoc; g422 = -146.407 + 841.880 * Eccentricity() - 1629.014 * eosq + 1083.435 * eoc; g520 = -532.114 + 3017.977 * Eccentricity() - 5740 * eosq + 3708.276 * eoc; } else { g211 = -72.099 + 331.819 * Eccentricity() - 508.738 * eosq + 266.724 * eoc; g310 = -346.844 + 1582.851 * Eccentricity() - 2415.925 * eosq + 1246.113 * eoc; g322 = -342.585 + 1554.908 * Eccentricity() - 2366.899 * eosq + 1215.972 * eoc; g410 = -1052.797 + 4758.686 * Eccentricity() - 7193.992 * eosq + 3651.957 * eoc; g422 = -3581.69 + 16178.11 * Eccentricity() - 24462.77 * eosq + 12422.52 * eoc; if (Eccentricity() <= 0.715) { g520 = 1464.74 - 4664.75 * Eccentricity() + 3763.64 * eosq; } else { g520 = -5149.66 + 29936.92 * Eccentricity() - 54087.36 * eosq + 31324.56 * eoc; } } double g533; double g521; double g532; if (Eccentricity() < 0.7) { g533 = -919.2277 + 4988.61 * Eccentricity() - 9064.77 * eosq + 5542.21 * eoc; g521 = -822.71072 + 4568.6173 * Eccentricity() - 8491.4146 * eosq + 5337.524 * eoc; g532 = -853.666 + 4690.25 * Eccentricity() - 8624.77 * eosq + 5341.4 * eoc; } else { g533 = -37995.78 + 161616.52 * Eccentricity() - 229838.2 * eosq + 109377.94 * eoc; g521 = -51752.104 + 218913.95 * Eccentricity() - 309468.16 * eosq + 146349.42 * eoc; g532 = -40023.88 + 170470.89 * Eccentricity() - 242699.48 * eosq + 115605.82 * eoc; } const double sini2 = sinio * sinio; const double f220 = 0.75 * (1.0 + 2.0 * cosio + theta2); const double f221 = 1.5 * sini2; const double f321 = 1.875 * sinio * (1.0 - 2.0 * cosio - 3.0 * theta2); const double f322 = -1.875 * sinio * (1.0 + 2.0 * cosio - 3.0 * theta2); const double f441 = 35.0 * sini2 * f220; const double f442 = 39.3750 * sini2 * sini2; const double f522 = 9.84375 * sinio * (sini2 * (1.0 - 2.0 * cosio - 5.0 * theta2) + 0.33333333 * (-2.0 + 4.0 * cosio + 6.0 * theta2)); const double f523 = sinio * (4.92187512 * sini2 * (-2.0 - 4.0 * cosio + 10.0 * theta2) + 6.56250012 * (1.0 + 2.0 * cosio - 3.0 * theta2)); const double f542 = 29.53125 * sinio * (2.0 - 8.0 * cosio + theta2 * (-12.0 + 8.0 * cosio + 10.0 * theta2)); const double f543 = 29.53125 * sinio * (-2.0 - 8.0 * cosio + theta2 * (12.0 + 8.0 * cosio - 10.0 * theta2)); const double xno2 = RecoveredMeanMotion() * RecoveredMeanMotion(); const double ainv2 = aqnv * aqnv; double temp1 = 3.0 * xno2 * ainv2; double temp = temp1 * ROOT22; d_d2201_ = temp * f220 * g201; d_d2211_ = temp * f221 * g211; temp1 = temp1 * aqnv; temp = temp1 * ROOT32; d_d3210_ = temp * f321 * g310; d_d3222_ = temp * f322 * g322; temp1 = temp1 * aqnv; temp = 2.0 * temp1 * ROOT44; d_d4410_ = temp * f441 * g410; d_d4422_ = temp * f442 * g422; temp1 = temp1 * aqnv; temp = temp1 * ROOT52; d_d5220_ = temp * f522 * g520; d_d5232_ = temp * f523 * g532; temp = 2.0 * temp1 * ROOT54; d_d5421_ = temp * f542 * g521; d_d5433_ = temp * f543 * g533; d_xlamo_ = MeanAnomoly() + AscendingNode() + AscendingNode() - i_gsto_ - i_gsto_; bfact = xmdot + xnodot + xnodot - THDT - THDT; bfact = bfact + d_ssl_ + d_ssh_ + d_ssh_; } if (initialize_integrator) { d_xfact_ = bfact - RecoveredMeanMotion(); /* * initialize integrator */ d_atime_ = 0.0; d_xni_ = RecoveredMeanMotion(); d_xli_ = d_xlamo_; } } void SGDP4::DeepSpaceCalculateLunarSolarTerms(const double t, double& pe, double& pinc, double& pl, double& pgh, double& ph) const { static const double ZES = 0.01675; static const double ZNS = 1.19459E-5; static const double ZNL = 1.5835218E-4; static const double ZEL = 0.05490; /* * update solar terms */ double zm = d_zmos_ + ZNS * t; if (first_run_) zm = d_zmos_; double zf = zm + 2.0 * ZES * sin(zm); double sinzf = sin(zf); double f2 = 0.5 * sinzf * sinzf - 0.25; double f3 = -0.5 * sinzf * cos(zf); const double ses = d_se2_ * f2 + d_se3_ * f3; const double sis = d_si2_ * f2 + d_si3_ * f3; const double sls = d_sl2_ * f2 + d_sl3_ * f3 + d_sl4_ * sinzf; const double sghs = d_sgh2_ * f2 + d_sgh3_ * f3 + d_sgh4_ * sinzf; const double shs = d_sh2_ * f2 + d_sh3_ * f3; /* * update lunar terms */ zm = d_zmol_ + ZNL * t; if (first_run_) zm = d_zmol_; zf = zm + 2.0 * ZEL * sin(zm); sinzf = sin(zf); f2 = 0.5 * sinzf * sinzf - 0.25; f3 = -0.5 * sinzf * cos(zf); const double sel = d_ee2_ * f2 + d_e3_ * f3; const double sil = d_xi2_ * f2 + d_xi3_ * f3; const double sll = d_xl2_ * f2 + d_xl3_ * f3 + d_xl4_ * sinzf; const double sghl = d_xgh2_ * f2 + d_xgh3_ * f3 + d_xgh4_ * sinzf; const double shl = d_xh2_ * f2 + d_xh3_ * f3; /* * merge computed values */ pe = ses + sel; pinc = sis + sil; pl = sls + sll; pgh = sghs + sghl; ph = shs + shl; } /* * calculate lunar / solar periodics and apply */ void SGDP4::DeepSpacePeriodics(const double& t, double& em, double& xinc, double& omgasm, double& xnodes, double& xll) { /* * storage for lunar / solar terms set by DeepSpaceCalculateLunarSolarTerms() */ double pe = 0.0; double pinc = 0.0; double pl = 0.0; double pgh = 0.0; double ph = 0.0; /* * calculate lunar / solar terms for current time */ DeepSpaceCalculateLunarSolarTerms(t, pe, pinc, pl, pgh, ph); if (!first_run_) { xinc += pinc; em += pe; /* Spacetrack report #3 has sin/cos from before perturbations * added to xinc (oldxinc), but apparently report # 6 has then * from after they are added. * (moved from start of function) */ const double sinis = sin(xinc); const double cosis = cos(xinc); if (Inclination() >= 0.2) { /* * apply periodics directly */ const double tmp_ph = ph / sinis; omgasm += pgh - cosis * tmp_ph; xnodes += tmp_ph; xll += pl; } else { /* * apply periodics with lyddane modification */ const double sinok = sin(xnodes); const double cosok = cos(xnodes); double alfdp = sinis * sinok; double betdp = sinis * cosok; const double dalf = ph * cosok + pinc * cosis * sinok; const double dbet = -ph * sinok + pinc * cosis * cosok; alfdp += dalf; betdp += dbet; double xls = xll + omgasm + cosis * xnodes; double dls = pl + pgh - pinc * xnodes * sinis; xls += dls; /* * save old xnodes value */ const double oldxnodes = xnodes; xnodes = atan2(alfdp, betdp); /* * Get perturbed xnodes in to same quadrant as original. */ if (fabs(oldxnodes - xnodes) > Globals::PI()) { if (xnodes < oldxnodes) xnodes += Globals::TWOPI(); else xnodes -= Globals::TWOPI(); } xll += pl; omgasm = xls - xll - cosis * xnodes; } } } /* * deep space secular effects */ void SGDP4::DeepSpaceSecular(const double& t, double& xll, double& omgasm, double& xnodes, double& em, double& xinc, double& xn) const { static const double THDT = 4.37526908801129966e-3; static const double STEP2 = 259200.0; static const double STEP = 720.0; double xldot = 0.0; double xndot = 0.0; double xnddt = 0.0; xll += d_ssl_ * t; omgasm += d_ssg_ * t; xnodes += d_ssh_ * t; em += d_sse_ * t; xinc += d_ssi_ * t; if (!d_resonance_flag_) return; /* * 1st condition (if d_atime_ is less than one time step from epoch) * 2nd condition (if d_atime_ and t are of opposite signs, so zero crossing required) * 3rd condition (if t is closer to zero than d_atime_) */ if (fabs(d_atime_) < STEP || t * d_atime_ <= 0.0 || fabs(t) < fabs(d_atime_)) { /* * restart from epoch */ d_atime_ = 0.0; d_xni_ = RecoveredMeanMotion(); d_xli_ = d_xlamo_; } double ft = t - d_atime_; /* * if time difference (ft) is greater than the time step (720.0) * loop around until d_atime_ is within one time step of t */ if (fabs(ft) >= STEP) { /* * calculate step direction to allow d_atime_ * to catch up with t */ double delt = -STEP; if (ft >= 0.0) delt = STEP; do { DeepSpaceCalcIntegrator(delt, STEP2, xndot, xnddt, xldot); ft = t - d_atime_; } while (fabs(ft) >= STEP); } /* * calculate dot terms */ DeepSpaceCalcDotTerms(xndot, xnddt, xldot); /* * integrator */ xn = d_xni_ + xndot * ft + xnddt * ft * ft * 0.5; const double xl = d_xli_ + xldot * ft + xndot * ft * ft * 0.5; const double temp = -xnodes + i_gsto_ + t * THDT; if (!d_synchronous_flag_) xll = xl + temp + temp; else xll = xl - omgasm + temp; } /* * calculate dot terms */ void SGDP4::DeepSpaceCalcDotTerms(double& xndot, double& xnddt, double& xldot) const { static const double G22 = 5.7686396; static const double G32 = 0.95240898; static const double G44 = 1.8014998; static const double G52 = 1.0508330; static const double G54 = 4.4108898; if (d_synchronous_flag_) { xndot = d_del1_ * sin(d_xli_ - d_fasx2_) + d_del2_ * sin(2.0 * (d_xli_ - d_fasx4_)) + d_del3_ * sin(3.0 * (d_xli_ - d_fasx6_)); xnddt = d_del1_ * cos(d_xli_ - d_fasx2_) + 2.0 * d_del2_ * cos(2.0 * (d_xli_ - d_fasx4_)) + 3.0 * d_del3_ * cos(3.0 * (d_xli_ - d_fasx6_)); } else { /* * TODO: check ArgumentPerigee() and i_omgdot_ * are correct to use */ const double xomi = ArgumentPerigee() + i_omgdot_ * d_atime_; const double x2omi = xomi + xomi; const double x2li = d_xli_ + d_xli_; xndot = d_d2201_ * sin(x2omi + d_xli_ - G22) + d_d2211_ * sin(d_xli_ - G22) + d_d3210_ * sin(xomi + d_xli_ - G32) + d_d3222_ * sin(-xomi + d_xli_ - G32) + d_d4410_ * sin(x2omi + x2li - G44) + d_d4422_ * sin(x2li - G44) + d_d5220_ * sin(xomi + d_xli_ - G52) + d_d5232_ * sin(-xomi + d_xli_ - G52) + d_d5421_ * sin(xomi + x2li - G54) + d_d5433_ * sin(-xomi + x2li - G54); xnddt = d_d2201_ * cos(x2omi + d_xli_ - G22) + d_d2211_ * cos(d_xli_ - G22) + d_d3210_ * cos(xomi + d_xli_ - G32) + d_d3222_ * cos(-xomi + d_xli_ - G32) + d_d5220_ * cos(xomi + d_xli_ - G52) + d_d5232_ * cos(-xomi + d_xli_ - G52) + 2.0 * (d_d4410_ * cos(x2omi + x2li - G44) + d_d4422_ * cos(x2li - G44) + d_d5421_ * cos(xomi + x2li - G54) + d_d5433_ * cos(-xomi + x2li - G54)); } xldot = d_xni_ + d_xfact_; xnddt = xnddt * xldot; } /* * deep space integrator for time period of delt */ void SGDP4::DeepSpaceCalcIntegrator(const double& delt, const double& step2, double& xndot, double& xnddt, double& xldot) const { /* * calculate dot terms */ DeepSpaceCalcDotTerms(xndot, xnddt, xldot); /* * integrator */ d_xli_ += xldot * delt + xndot * step2; d_xni_ += xndot * delt + xnddt * step2; /* * increment integrator time */ d_atime_ += delt; }
// $Id: exodusII_io.C,v 1.7 2005-02-22 22:17:39 jwpeterson Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <fstream> // Local includes #include "exodusII_io.h" #include "mesh_base.h" #include "enum_elem_type.h" #include "elem.h" // Wrap all the helper classes in an #ifdef to avoid excessive compilation // time in the case of no ExodusII support #ifdef HAVE_EXODUS_API namespace exII { extern "C" { #include "exodusII.h" // defines MAX_LINE_LENGTH, MAX_STR_LENGTH used later } } //----------------------------------------------------------------------------- // Exodus class - private helper class defined in an anonymous namespace namespace { /** * This is the \p ExodusII class. * This class hides the implementation * details of interfacing with * the Exodus binary format. * * @author Johw W. Peterson, 2002. */ class ExodusII { public: /** * Constructor. Automatically * initializes all the private * members of the class. Also * allows you to set the verbosity * level to v=1 (on) or v=0 (off). */ ExodusII(const bool v=false) : verbose(v), comp_ws(sizeof(double)), io_ws(0), ex_id(0), ex_err(0), num_dim(0), num_nodes(0), num_elem(0), num_elem_blk(0), num_node_sets(0), num_side_sets(0), num_elem_this_blk(0), num_nodes_per_elem(0), num_attr(0), req_info(0), ret_int(0), num_elem_all_sidesets(0), ex_version(0.0), ret_float(0.0), ret_char(0), title(new char[MAX_LINE_LENGTH]), elem_type(new char[MAX_STR_LENGTH]) {} /** * Destructor. The only memory * allocated is for \p title and * \p elem_type. This memory * is freed in the destructor. */ ~ExodusII(); /** * @returns the \p ExodusII * mesh dimension. */ int get_num_dim() const { return num_dim; } /** * @returns the total number of * nodes in the \p ExodusII mesh. */ int get_num_nodes() const { return num_nodes; } /** * @returns the total number of * elements in the \p ExodusII mesh. */ int get_num_elem() const { return num_elem; } /** * @returns the total number * of element blocks in * the \p ExodusII mesh. */ int get_num_elem_blk() const { return num_elem_blk; } /** * For a given block, * returns the total number * of elements. */ int get_num_elem_this_blk() const { return num_elem_this_blk; } /** * @returns the number of * nodes per element in * a given block. e.g. * for HEX27 it returns 27. */ int get_num_nodes_per_elem() const { return num_nodes_per_elem; } /** * @returns the total number * of sidesets in the \p ExodusII * mesh. Each sideset contains * only one type of element. */ int get_num_side_sets() const { return num_side_sets; } // /** // * @returns the number of // * elements in all the sidesets. // * Effectively returns the // * total number of elements // * on the \p ExodusII mesh boundary. // */ // int get_num_elem_all_sidesets() const { return num_elem_all_sidesets; } /** * @returns the \f$ i^{th} \f$ * node number in the * element connectivity * list for a given element. */ int get_connect(int i) const { return connect[i]; } /** * For a single sideset, * returns the total number of * elements in the sideset. */ int get_num_sides_per_set(int i) const { return num_sides_per_set[i]; } // /** // * @returns the \f$ i^{th} \f$ entry // * in the element list. // * The element list contains // * the numbers of all elements // * on the boundary. // */ // int get_elem_list(int i) const { return elem_list[i]; } /** * @return a constant reference to the \p elem_list. */ const std::vector<int>& get_elem_list() const { return elem_list; } // /** // * @returns the \f$ i^{th} \f$ entry in // * the side list. This is // * effectively the "side" // * (face in 3D or edge in // * 2D) number which lies // * on the boundary. // */ // int get_side_list(int i) const { return side_list[i]; } /** * @return a constant reference to the \p side_list. */ const std::vector<int>& get_side_list() const { return side_list; } // /** // * @returns the \f$ i^{th} \f$ entry in // * the id list. This is the id // * for the ith face on the boundary. // */ // int get_id_list(int i) const { return id_list[i]; } /** * @return a constant reference to the \p id_list. */ const std::vector<int>& get_id_list() const { return id_list; } /** * @returns the current * element type. Note: * the default behavior * is for this value * to be in all capital * letters, e.g. \p HEX27. */ char* get_elem_type() const { return elem_type; } /** * @returns the \f$ i^{th} \f$ * node's x-coordinate. */ double get_x(int i) const { return x[i]; } /** * @returns the \f$ i^{th} \f$ * node's y-coordinate. */ double get_y(int i) const { return y[i]; } /** * @returns the \f$ i^{th} \f$ * node's z-coordinate. */ double get_z(int i) const { return z[i]; } /** * Opens an \p ExodusII mesh * file named \p filename * for reading. */ void open(const char* filename); /** * Reads an \p ExodusII mesh * file header. */ void read_header(); /** * Prints the \p ExodusII * mesh file header, * which includes the * mesh title, the number * of nodes, number of * elements, mesh dimension, * and number of sidesets. */ void print_header(); /** * Reads the nodal data * (x,y,z coordinates) * from the \p ExodusII mesh * file. */ void read_nodes(); /** * Prints the nodal information * to \p std::cout. */ void print_nodes(); /** * Reads information for * all of the blocks in * the \p ExodusII mesh file. */ void read_block_info(); /** * Reads all of the element * connectivity for * block \p block in the * \p ExodusII mesh file. */ void read_elem_in_block(int block); /** * Reads information about * all of the sidesets in * the \p ExodusII mesh file. */ void read_sideset_info(); /** * Reads information about * sideset \p id and * inserts it into the global * sideset array at the * position \p offset. */ void read_sideset(int id, int offset); /** * Prints information * about all the sidesets. */ void print_sideset_info(); /** * Closes the \p ExodusII * mesh file. */ void close(); //------------------------------------------------------------------------- /** * This is the \p ExodusII * Conversion class. * * It provides a * data structure * which contains * \p ExodusII node/edge maps * and name conversions. */ class Conversion { public: /** * Constructor. Initializes the const private member * variables. */ Conversion(const int* nm, const int* sm, const ElemType ct) : node_map(nm), // Node map for this element side_map(sm), canonical_type(ct) // Element type name in this code {} /** * Returns the ith component of the node map for this * element. The node map maps the exodusII node numbering * format to this library's format. */ int get_node_map(int i) const { return node_map[i]; } /** * Returns the ith component of the side map for this * element. The side map maps the exodusII side numbering * format to this library's format. */ int get_side_map(int i) const { return side_map[i]; } /** * Returns the canonical element type for this * element. The canonical element type is the standard * element type understood by this library. */ ElemType get_canonical_type() const { return canonical_type; } private: /** * Pointer to the node map for this element. */ const int* node_map; /** * Pointer to the side map for this element. */ const int* side_map; /** * The canonical (i.e. standard for this library) * element type. */ const ElemType canonical_type; }; //------------------------------------------------------------------------- /** * This is the \p ExodusII * ElementMap class. * * It contains constant * maps between the \p ExodusII * naming/numbering schemes * and the canonical schemes * used in this code. */ class ElementMaps { public: /** * Constructor. */ ElementMaps() {} /** * 2D node maps. These define * mappings from ExodusII-formatted * element numberings. */ /** * The Quad4 node map. * Use this map for bi-linear * quadrilateral elements in 2D. */ static const int quad4_node_map[4]; /** * The Quad8 node map. * Use this map for serendipity * quadrilateral elements in 2D. */ static const int quad8_node_map[8]; /** * The Quad9 node map. * Use this map for bi-quadratic * quadrilateral elements in 2D. */ static const int quad9_node_map[9]; /** * The Tri3 node map. * Use this map for linear * triangles in 2D. */ static const int tri3_node_map[3]; /** * The Tri6 node map. * Use this map for quadratic * triangular elements in 2D. */ static const int tri6_node_map[6]; /** * 2D edge maps */ /** * Maps the Exodus edge numbering for triangles. * Useful for reading sideset information. */ static const int tri_edge_map[3]; /** * Maps the Exodus edge numbering for quadrilaterals. * Useful for reading sideset information. */ static const int quad_edge_map[4]; /** * 3D maps. These define * mappings from ExodusII-formatted * element numberings. */ /** * The Hex8 node map. * Use this map for bi-linear * hexahedral elements in 3D. */ static const int hex8_node_map[8]; /** * The Hex20 node map. * Use this map for serendipity * hexahedral elements in 3D. */ static const int hex20_node_map[20]; /** * The Hex27 node map. * Use this map for bi-quadratic * hexahedral elements in 3D. */ static const int hex27_node_map[27]; /** * The Tet4 node map. * Use this map for linear * tetrahedral elements in 3D. */ static const int tet4_node_map[4]; /** * The Tet10 node map. * Use this map for quadratic * tetrahedral elements in 3D. */ static const int tet10_node_map[10]; /** * 3D face maps */ /** * Maps the Exodus face numbering for general hexahedrals. * Useful for reading sideset information. */ static const int hex_face_map[6]; /** * Maps the Exodus face numbering for 27-noded hexahedrals. * Useful for reading sideset information. */ static const int hex27_face_map[6]; /** * Maps the Exodus face numbering for general tetrahedrals. * Useful for reading sideset information. */ static const int tet_face_map[4]; /** * @returns a conversion object given an element type name. */ const Conversion assign_conversion(const std::string type); /** * @returns a conversion object given an element type. */ const Conversion assign_conversion(const ElemType type); }; private: /** * All of the \p ExodusII * API functions return * an \p int error value. * This function checks * to see if the error has * been set, and if it has, * prints the error message * contained in \p msg. */ void check_err(const int error, const std::string msg); /** * Prints the message defined * in \p msg to \p std::cout. * Can be turned off if * verbosity is set to 0. */ void message(const std::string msg); /** * Prints the message defined * in \p msg to \p std::cout * and appends the number * \p i to the end of the * message. Useful for * printing messages in loops. * Can be turned off if * verbosity is set to 0. */ void message(const std::string msg, int i); const bool verbose; // On/Off message flag int comp_ws; // ? int io_ws; // ? int ex_id; // File identification flag int ex_err; // General error flag int num_dim; // Number of dimensions in the mesh int num_nodes; // Total number of nodes in the mesh int num_elem; // Total number of elements in the mesh int num_elem_blk; // Total number of element blocks int num_node_sets; // Total number of node sets int num_side_sets; // Total number of element sets int num_elem_this_blk; // Number of elements in this block int num_nodes_per_elem; // Number of nodes in each element int num_attr; // Number of attributes for a given block int req_info; // Generic required info tag int ret_int; // Generic int returned by ex_inquire int num_elem_all_sidesets; // Total number of elements in all side sets std::vector<int> block_ids; // Vector of the block identification numbers std::vector<int> connect; // Vector of nodes in an element std::vector<int> ss_ids; // Vector of the sideset IDs std::vector<int> num_sides_per_set; // Number of sides (edges/faces) in current set std::vector<int> num_df_per_set; // Number of distribution factors per set std::vector<int> elem_list; // List of element numbers in all sidesets std::vector<int> side_list; // Side (face/edge) number actually on the boundary std::vector<int> id_list; // Side (face/edge) id number float ex_version; // Version of Exodus you are using float ret_float; // Generic float returned by ex_inquire std::vector<double> x; // x locations of node points std::vector<double> y; // y locations of node points std::vector<double> z; // z locations of node points char ret_char; // Generic char returned by ex_inquire char* title; // Problem title char* elem_type; // Type of element in a given block }; // ------------------------------------------------------------ // ExodusII::ElementMaps static data // 2D node map definitions const int ExodusII::ElementMaps::quad4_node_map[4] = {0, 1, 2, 3}; const int ExodusII::ElementMaps::quad8_node_map[8] = {0, 1, 2, 3, 4, 5, 6, 7}; const int ExodusII::ElementMaps::quad9_node_map[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; const int ExodusII::ElementMaps::tri3_node_map[3] = {0, 1, 2}; const int ExodusII::ElementMaps::tri6_node_map[6] = {0, 1, 2, 3, 4, 5}; // 2D edge map definitions const int ExodusII::ElementMaps::tri_edge_map[3] = {0, 1, 2}; const int ExodusII::ElementMaps::quad_edge_map[4] = {0, 1, 2, 3}; // 3D node map definitions const int ExodusII::ElementMaps::hex8_node_map[8] = {0, 1, 2, 3, 4, 5, 6, 7}; const int ExodusII::ElementMaps::hex20_node_map[20] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; const int ExodusII::ElementMaps::hex27_node_map[27] = { 1, 5, 6, 2, 0, 4, 7, 3, 13, 17, 14, 9, 8, 16, 18, 10, 12, 19, 15, 11, 24, 25, 22, 26, 21, 23, 20}; const int ExodusII::ElementMaps::tet4_node_map[4] = {0, 1, 2, 3}; const int ExodusII::ElementMaps::tet10_node_map[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // 3D face map definitions const int ExodusII::ElementMaps::tet_face_map[4] = {1, 2, 3, 0}; const int ExodusII::ElementMaps::hex_face_map[6] = {1, 2, 3, 4, 0, 5}; const int ExodusII::ElementMaps::hex27_face_map[6] = {1, 0, 3, 5, 4, 2}; // ------------------------------------------------------------ // ExodusII class members ExodusII::~ExodusII() { delete [] title; delete [] elem_type; } void ExodusII::check_err(const int err, const std::string msg) { if (err < 0) { std::cout << msg << std::endl; error(); } } void ExodusII::message(const std::string msg) { if (verbose) std::cout << msg << std::endl; } void ExodusII::message(const std::string msg, int i) { if (verbose) std::cout << msg << i << "." << std::endl; } void ExodusII::open(const char* filename) { ex_id = exII::ex_open(filename, EX_READ, &comp_ws, &io_ws, &ex_version); check_err(ex_id, "Error opening ExodusII mesh file."); if (verbose) std::cout << "File opened successfully." << std::endl; } void ExodusII::read_header() { ex_err = exII::ex_get_init(ex_id, title, &num_dim, &num_nodes, &num_elem, &num_elem_blk, &num_node_sets, &num_side_sets); check_err(ex_err, "Error retrieving header info."); message("Exodus header info retrieved successfully."); } void ExodusII::print_header() { if (verbose) std::cout << "Title: \t" << title << std::endl << "Mesh Dimension: \t" << num_dim << std::endl << "Number of Nodes: \t" << num_nodes << std::endl << "Number of elements: \t" << num_elem << std::endl << "Number of elt blocks: \t" << num_elem_blk << std::endl << "Number of node sets: \t" << num_node_sets << std::endl << "Number of side sets: \t" << num_side_sets << std::endl; } void ExodusII::read_nodes() { x.resize(num_nodes); y.resize(num_nodes); z.resize(num_nodes); ex_err = exII::ex_get_coord(ex_id, static_cast<void*>(&x[0]), static_cast<void*>(&y[0]), static_cast<void*>(&z[0])); check_err(ex_err, "Error retrieving nodal data."); message("Nodal data retrieved successfully."); } void ExodusII::print_nodes() { for (int i=0; i<num_nodes; i++) { std::cout << "(" << x[i] << ", " << y[i] << ", " << z[i] << ")" << std::endl; } } void ExodusII::read_block_info() { block_ids.resize(num_elem_blk); ex_err = exII::ex_get_elem_blk_ids(ex_id, &block_ids[0]); // Get all element block IDs. // Usually, there is only one // block since there is only // one type of element. // However, there could be more. check_err(ex_err, "Error getting block IDs."); message("All block IDs retrieved successfully."); } void ExodusII::read_elem_in_block(int block) { ex_err = exII::ex_get_elem_block(ex_id, block_ids[block], elem_type, &num_elem_this_blk, &num_nodes_per_elem, &num_attr); check_err(ex_err, "Error getting block info."); message("Info retrieved successfully for block: ", block); // Read in the connectivity of the elements of this block connect.resize(num_nodes_per_elem*num_elem_this_blk); ex_err = exII::ex_get_elem_conn(ex_id, block_ids[block], &connect[0]); check_err(ex_err, "Error reading block connectivity."); message("Connectivity retrieved successfully for block: ", block); } void ExodusII::read_sideset_info() { ss_ids.resize(num_side_sets); ex_err = exII::ex_get_side_set_ids(ex_id, &ss_ids[0]); check_err(ex_err, "Error retrieving sideset information."); message("All sideset information retrieved successfully."); // Resize appropriate data structures -- only do this once outside the loop num_sides_per_set.resize(num_side_sets); num_df_per_set.resize(num_side_sets); req_info = EX_INQ_SS_ELEM_LEN; // Inquire about the length of the // concatenated side sets element list ex_err = exII::ex_inquire(ex_id, req_info, &ret_int, &ret_float, &ret_char); check_err(ex_err, "Error inquiring about side set element list length."); //std::cout << "Value returned by ex_inquire was: " << ret_int << std::endl; num_elem_all_sidesets = ret_int; elem_list.resize (num_elem_all_sidesets); side_list.resize (num_elem_all_sidesets); id_list.resize (num_elem_all_sidesets); } void ExodusII::read_sideset(int id, int offset) { ex_err = exII::ex_get_side_set_param(ex_id, ss_ids[id], &num_sides_per_set[id], &num_df_per_set[id]); check_err(ex_err, "Error retrieving sideset parameters."); message("Parameters retrieved successfully for sideset: ", id); ex_err = exII::ex_get_side_set(ex_id, ss_ids[id], &elem_list[offset], &side_list[offset]); check_err(ex_err, "Error retrieving sideset data."); message("Data retrieved successfully for sideset: ", id); for (int i=0; i<num_sides_per_set[id]; i++) id_list[i+offset] = ss_ids[id]; } void ExodusII::print_sideset_info() { for (int i=0; i<num_elem_all_sidesets; i++) { std::cout << elem_list[i] << " " << side_list[i] << std::endl; } } void ExodusII::close() { ex_err = exII::ex_close(ex_id); check_err(ex_err, "Error closing Exodus file."); message("Exodus file closed successfully."); } // ------------------------------------------------------------ // ExodusII::Conversion class members const ExodusII::Conversion ExodusII::ElementMaps::assign_conversion(const std::string type) { if (type == "QUAD4") return assign_conversion(QUAD4); else if (type == "QUAD8") return assign_conversion(QUAD8); else if (type == "QUAD9") return assign_conversion(QUAD9); else if (type == "TRI3") return assign_conversion(TRI3); else if (type == "TRI6") return assign_conversion(TRI6); else if (type == "HEX8") return assign_conversion(HEX8); else if (type == "HEX20") return assign_conversion(HEX20); else if (type == "HEX27") return assign_conversion(HEX27); else if (type == "TETRA4") return assign_conversion(TET4); else if (type == "TETRA10") return assign_conversion(TET10); else { std::cerr << "ERROR! Unrecognized element type: " << type << std::endl; error(); } error(); const Conversion conv(tri3_node_map, tri_edge_map, TRI3); // dummy return conv; } const ExodusII::Conversion ExodusII::ElementMaps::assign_conversion(const ElemType type) { switch (type) { case QUAD4: { const Conversion conv(quad4_node_map, quad_edge_map, QUAD4); return conv; } case QUAD8: { const Conversion conv(quad8_node_map, quad_edge_map, QUAD8); return conv; } case QUAD9: { const Conversion conv(quad9_node_map, quad_edge_map, QUAD9); return conv; } case TRI3: { const Conversion conv(tri3_node_map, tri_edge_map, TRI3); return conv; } case TRI6: { const Conversion conv(tri6_node_map, tri_edge_map, TRI6); return conv; } case HEX8: { const Conversion conv(hex8_node_map, hex_face_map, HEX8); return conv; } case HEX20: { const Conversion conv(hex20_node_map, hex_face_map, HEX20); return conv; } case HEX27: { const Conversion conv(hex27_node_map, hex27_face_map, HEX27); return conv; } case TET4: { const Conversion conv(tet4_node_map, tet_face_map, TET4); return conv; } case TET10: { const Conversion conv(tet10_node_map, tet_face_map, TET10); return conv; } default: error(); } error(); const Conversion conv(tri3_node_map, tri_edge_map, TRI3); // dummy return conv; } } // end anonymous namespace #endif // #ifdef HAVE_EXODUS_API // ------------------------------------------------------------ // ExodusII_IO class members void ExodusII_IO::read (const std::string& fname) { #ifndef HAVE_EXODUS_API std::cerr << "ERROR, ExodusII API is not defined.\n" << "Input file " << fname << " cannot be read" << std::endl; error(); #else // Get a reference to the mesh we are reading MeshBase& mesh = MeshInput<MeshBase>::mesh(); // Clear any existing mesh data mesh.clear(); assert(mesh.mesh_dimension() != 1); // No support for 1D ExodusII meshes #ifdef DEBUG this->verbose() = true; #endif ExodusII ex(this->verbose()); // Instantiate ExodusII interface ExodusII::ElementMaps em; // Instantiate the ElementMaps interface ex.open(fname.c_str()); // Open the exodus file, if possible ex.read_header(); // Get header information from exodus file ex.print_header(); // Print header information assert(static_cast<unsigned int>(ex.get_num_dim()) == mesh.mesh_dimension()); // Be sure number of dimensions // is equal to the number of // dimensions in the mesh supplied. ex.read_nodes(); // Read nodes from the exodus file mesh.reserve_nodes(ex.get_num_nodes()); // Reserve space for the nodes. // Loop over the nodes, create Nodes. for (int i=0; i<ex.get_num_nodes(); i++) mesh.add_point (Point(ex.get_x(i), ex.get_y(i), ex.get_z(i))); assert (static_cast<unsigned int>(ex.get_num_nodes()) == mesh.n_nodes()); ex.read_block_info(); // Get information about all the blocks mesh.reserve_elem(ex.get_num_elem()); // Reserve space for the elements // Read in the element connectivity for each block. int nelem_last_block = 0; // Loop over all the blocks for (int i=0; i<ex.get_num_elem_blk(); i++) { // Read the information for block i ex.read_elem_in_block (i); // Set any relevant node/edge maps for this element const std::string type (ex.get_elem_type()); const ExodusII::Conversion conv = em.assign_conversion(type); // Loop over all the faces in this block int jmax = nelem_last_block+ex.get_num_elem_this_blk(); for (int j=nelem_last_block; j<jmax; j++) { Elem* elem = mesh.add_elem (Elem::build (conv.get_canonical_type()).release()); assert (elem != NULL); // Set all the nodes for this element for (int k=0; k<ex.get_num_nodes_per_elem(); k++) { int gi = (j-nelem_last_block)*ex.get_num_nodes_per_elem() + conv.get_node_map(k); // global index int node_number = ex.get_connect(gi); // Global node number (1-based) elem->set_node(k) = mesh.node_ptr((node_number-1)); // Set node number // Subtract 1 since // exodus is internally 1-based } } // running sum of # of elements per block, // (should equal total number of elements in the end) nelem_last_block += ex.get_num_elem_this_blk(); } assert (static_cast<unsigned int>(nelem_last_block) == mesh.n_elem()); // Read in sideset information -- this is useful for applying boundary conditions { ex.read_sideset_info(); // Get basic information about ALL sidesets int offset=0; for (int i=0; i<ex.get_num_side_sets(); i++) { offset += (i > 0 ? ex.get_num_sides_per_set(i-1) : 0); // Compute new offset ex.read_sideset (i, offset); } const std::vector<int>& elem_list = ex.get_elem_list(); const std::vector<int>& side_list = ex.get_side_list(); const std::vector<int>& id_list = ex.get_id_list(); for (unsigned int e=0; e<elem_list.size(); e++) { // Set any relevant node/edge maps for this element const ExodusII::Conversion conv = em.assign_conversion(mesh.elem(elem_list[e]-1)->type()); mesh.boundary_info.add_side (elem_list[e]-1, conv.get_side_map(side_list[e]-1), id_list[e]); } } ex.close(); // Close the exodus file, if possible #endif } initial support for the pseudo-ExodusII files written by gridgen git-svn-id: e88a1e38e13faf406e05cc89eca8dd613216f6c4@1032 434f946d-2f3d-0410-ba4c-cb9f52fb0dbf // $Id: exodusII_io.C,v 1.8 2005-04-20 13:34:41 benkirk Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <fstream> // Local includes #include "exodusII_io.h" #include "mesh_base.h" #include "enum_elem_type.h" #include "elem.h" // Wrap all the helper classes in an #ifdef to avoid excessive compilation // time in the case of no ExodusII support #ifdef HAVE_EXODUS_API namespace exII { extern "C" { #include "exodusII.h" // defines MAX_LINE_LENGTH, MAX_STR_LENGTH used later } } //----------------------------------------------------------------------------- // Exodus class - private helper class defined in an anonymous namespace namespace { /** * This is the \p ExodusII class. * This class hides the implementation * details of interfacing with * the Exodus binary format. * * @author Johw W. Peterson, 2002. */ class ExodusII { public: /** * Constructor. Automatically * initializes all the private * members of the class. Also * allows you to set the verbosity * level to v=1 (on) or v=0 (off). */ ExodusII(const bool v=false) : verbose(v), comp_ws(sizeof(double)), io_ws(0), ex_id(0), ex_err(0), num_dim(0), num_nodes(0), num_elem(0), num_elem_blk(0), num_node_sets(0), num_side_sets(0), num_elem_this_blk(0), num_nodes_per_elem(0), num_attr(0), req_info(0), ret_int(0), num_elem_all_sidesets(0), ex_version(0.0), ret_float(0.0), ret_char(0), title(new char[MAX_LINE_LENGTH]), elem_type(new char[MAX_STR_LENGTH]) {} /** * Destructor. The only memory * allocated is for \p title and * \p elem_type. This memory * is freed in the destructor. */ ~ExodusII(); /** * @returns the \p ExodusII * mesh dimension. */ int get_num_dim() const { return num_dim; } /** * @returns the total number of * nodes in the \p ExodusII mesh. */ int get_num_nodes() const { return num_nodes; } /** * @returns the total number of * elements in the \p ExodusII mesh. */ int get_num_elem() const { return num_elem; } /** * @returns the total number * of element blocks in * the \p ExodusII mesh. */ int get_num_elem_blk() const { return num_elem_blk; } /** * For a given block, * returns the total number * of elements. */ int get_num_elem_this_blk() const { return num_elem_this_blk; } /** * @returns the number of * nodes per element in * a given block. e.g. * for HEX27 it returns 27. */ int get_num_nodes_per_elem() const { return num_nodes_per_elem; } /** * @returns the total number * of sidesets in the \p ExodusII * mesh. Each sideset contains * only one type of element. */ int get_num_side_sets() const { return num_side_sets; } // /** // * @returns the number of // * elements in all the sidesets. // * Effectively returns the // * total number of elements // * on the \p ExodusII mesh boundary. // */ // int get_num_elem_all_sidesets() const { return num_elem_all_sidesets; } /** * @returns the \f$ i^{th} \f$ * node number in the * element connectivity * list for a given element. */ int get_connect(int i) const { return connect[i]; } /** * For a single sideset, * returns the total number of * elements in the sideset. */ int get_num_sides_per_set(int i) const { return num_sides_per_set[i]; } // /** // * @returns the \f$ i^{th} \f$ entry // * in the element list. // * The element list contains // * the numbers of all elements // * on the boundary. // */ // int get_elem_list(int i) const { return elem_list[i]; } /** * @return a constant reference to the \p elem_list. */ const std::vector<int>& get_elem_list() const { return elem_list; } // /** // * @returns the \f$ i^{th} \f$ entry in // * the side list. This is // * effectively the "side" // * (face in 3D or edge in // * 2D) number which lies // * on the boundary. // */ // int get_side_list(int i) const { return side_list[i]; } /** * @return a constant reference to the \p side_list. */ const std::vector<int>& get_side_list() const { return side_list; } // /** // * @returns the \f$ i^{th} \f$ entry in // * the id list. This is the id // * for the ith face on the boundary. // */ // int get_id_list(int i) const { return id_list[i]; } /** * @return a constant reference to the \p id_list. */ const std::vector<int>& get_id_list() const { return id_list; } /** * @returns the current * element type. Note: * the default behavior * is for this value * to be in all capital * letters, e.g. \p HEX27. */ char* get_elem_type() const { return elem_type; } /** * @returns the \f$ i^{th} \f$ * node's x-coordinate. */ double get_x(int i) const { return x[i]; } /** * @returns the \f$ i^{th} \f$ * node's y-coordinate. */ double get_y(int i) const { return y[i]; } /** * @returns the \f$ i^{th} \f$ * node's z-coordinate. */ double get_z(int i) const { return z[i]; } /** * Opens an \p ExodusII mesh * file named \p filename * for reading. */ void open(const char* filename); /** * Reads an \p ExodusII mesh * file header. */ void read_header(); /** * Prints the \p ExodusII * mesh file header, * which includes the * mesh title, the number * of nodes, number of * elements, mesh dimension, * and number of sidesets. */ void print_header(); /** * Reads the nodal data * (x,y,z coordinates) * from the \p ExodusII mesh * file. */ void read_nodes(); /** * Prints the nodal information * to \p std::cout. */ void print_nodes(); /** * Reads information for * all of the blocks in * the \p ExodusII mesh file. */ void read_block_info(); /** * Reads all of the element * connectivity for * block \p block in the * \p ExodusII mesh file. */ void read_elem_in_block(int block); /** * Reads information about * all of the sidesets in * the \p ExodusII mesh file. */ void read_sideset_info(); /** * Reads information about * sideset \p id and * inserts it into the global * sideset array at the * position \p offset. */ void read_sideset(int id, int offset); /** * Prints information * about all the sidesets. */ void print_sideset_info(); /** * Closes the \p ExodusII * mesh file. */ void close(); //------------------------------------------------------------------------- /** * This is the \p ExodusII * Conversion class. * * It provides a * data structure * which contains * \p ExodusII node/edge maps * and name conversions. */ class Conversion { public: /** * Constructor. Initializes the const private member * variables. */ Conversion(const int* nm, const int* sm, const ElemType ct) : node_map(nm), // Node map for this element side_map(sm), canonical_type(ct) // Element type name in this code {} /** * Returns the ith component of the node map for this * element. The node map maps the exodusII node numbering * format to this library's format. */ int get_node_map(int i) const { return node_map[i]; } /** * Returns the ith component of the side map for this * element. The side map maps the exodusII side numbering * format to this library's format. */ int get_side_map(int i) const { return side_map[i]; } /** * Returns the canonical element type for this * element. The canonical element type is the standard * element type understood by this library. */ ElemType get_canonical_type() const { return canonical_type; } private: /** * Pointer to the node map for this element. */ const int* node_map; /** * Pointer to the side map for this element. */ const int* side_map; /** * The canonical (i.e. standard for this library) * element type. */ const ElemType canonical_type; }; //------------------------------------------------------------------------- /** * This is the \p ExodusII * ElementMap class. * * It contains constant * maps between the \p ExodusII * naming/numbering schemes * and the canonical schemes * used in this code. */ class ElementMaps { public: /** * Constructor. */ ElementMaps() {} /** * 2D node maps. These define * mappings from ExodusII-formatted * element numberings. */ /** * The Quad4 node map. * Use this map for bi-linear * quadrilateral elements in 2D. */ static const int quad4_node_map[4]; /** * The Quad8 node map. * Use this map for serendipity * quadrilateral elements in 2D. */ static const int quad8_node_map[8]; /** * The Quad9 node map. * Use this map for bi-quadratic * quadrilateral elements in 2D. */ static const int quad9_node_map[9]; /** * The Tri3 node map. * Use this map for linear * triangles in 2D. */ static const int tri3_node_map[3]; /** * The Tri6 node map. * Use this map for quadratic * triangular elements in 2D. */ static const int tri6_node_map[6]; /** * 2D edge maps */ /** * Maps the Exodus edge numbering for triangles. * Useful for reading sideset information. */ static const int tri_edge_map[3]; /** * Maps the Exodus edge numbering for quadrilaterals. * Useful for reading sideset information. */ static const int quad_edge_map[4]; /** * 3D maps. These define * mappings from ExodusII-formatted * element numberings. */ /** * The Hex8 node map. * Use this map for bi-linear * hexahedral elements in 3D. */ static const int hex8_node_map[8]; /** * The Hex20 node map. * Use this map for serendipity * hexahedral elements in 3D. */ static const int hex20_node_map[20]; /** * The Hex27 node map. * Use this map for bi-quadratic * hexahedral elements in 3D. */ static const int hex27_node_map[27]; /** * The Tet4 node map. * Use this map for linear * tetrahedral elements in 3D. */ static const int tet4_node_map[4]; /** * The Tet10 node map. * Use this map for quadratic * tetrahedral elements in 3D. */ static const int tet10_node_map[10]; /** * The Prism6 node map. * Use this map for quadratic * tetrahedral elements in 3D. */ static const int prism6_node_map[6]; /** * 3D face maps */ /** * Maps the Exodus face numbering for general hexahedrals. * Useful for reading sideset information. */ static const int hex_face_map[6]; /** * Maps the Exodus face numbering for 27-noded hexahedrals. * Useful for reading sideset information. */ static const int hex27_face_map[6]; /** * Maps the Exodus face numbering for general tetrahedrals. * Useful for reading sideset information. */ static const int tet_face_map[4]; /** * Maps the Exodus face numbering for general prisms. * Useful for reading sideset information. */ static const int prism_face_map[5]; /** * @returns a conversion object given an element type name. */ const Conversion assign_conversion(const std::string type); /** * @returns a conversion object given an element type. */ const Conversion assign_conversion(const ElemType type); }; private: /** * All of the \p ExodusII * API functions return * an \p int error value. * This function checks * to see if the error has * been set, and if it has, * prints the error message * contained in \p msg. */ void check_err(const int error, const std::string msg); /** * Prints the message defined * in \p msg to \p std::cout. * Can be turned off if * verbosity is set to 0. */ void message(const std::string msg); /** * Prints the message defined * in \p msg to \p std::cout * and appends the number * \p i to the end of the * message. Useful for * printing messages in loops. * Can be turned off if * verbosity is set to 0. */ void message(const std::string msg, int i); const bool verbose; // On/Off message flag int comp_ws; // ? int io_ws; // ? int ex_id; // File identification flag int ex_err; // General error flag int num_dim; // Number of dimensions in the mesh int num_nodes; // Total number of nodes in the mesh int num_elem; // Total number of elements in the mesh int num_elem_blk; // Total number of element blocks int num_node_sets; // Total number of node sets int num_side_sets; // Total number of element sets int num_elem_this_blk; // Number of elements in this block int num_nodes_per_elem; // Number of nodes in each element int num_attr; // Number of attributes for a given block int req_info; // Generic required info tag int ret_int; // Generic int returned by ex_inquire int num_elem_all_sidesets; // Total number of elements in all side sets std::vector<int> block_ids; // Vector of the block identification numbers std::vector<int> connect; // Vector of nodes in an element std::vector<int> ss_ids; // Vector of the sideset IDs std::vector<int> num_sides_per_set; // Number of sides (edges/faces) in current set std::vector<int> num_df_per_set; // Number of distribution factors per set std::vector<int> elem_list; // List of element numbers in all sidesets std::vector<int> side_list; // Side (face/edge) number actually on the boundary std::vector<int> id_list; // Side (face/edge) id number float ex_version; // Version of Exodus you are using float ret_float; // Generic float returned by ex_inquire std::vector<double> x; // x locations of node points std::vector<double> y; // y locations of node points std::vector<double> z; // z locations of node points char ret_char; // Generic char returned by ex_inquire char* title; // Problem title char* elem_type; // Type of element in a given block }; // ------------------------------------------------------------ // ExodusII::ElementMaps static data // 2D node map definitions const int ExodusII::ElementMaps::quad4_node_map[4] = {0, 1, 2, 3}; const int ExodusII::ElementMaps::quad8_node_map[8] = {0, 1, 2, 3, 4, 5, 6, 7}; const int ExodusII::ElementMaps::quad9_node_map[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; const int ExodusII::ElementMaps::tri3_node_map[3] = {0, 1, 2}; const int ExodusII::ElementMaps::tri6_node_map[6] = {0, 1, 2, 3, 4, 5}; // 2D edge map definitions const int ExodusII::ElementMaps::tri_edge_map[3] = {0, 1, 2}; const int ExodusII::ElementMaps::quad_edge_map[4] = {0, 1, 2, 3}; // 3D node map definitions const int ExodusII::ElementMaps::hex8_node_map[8] = {0, 1, 2, 3, 4, 5, 6, 7}; const int ExodusII::ElementMaps::hex20_node_map[20] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; const int ExodusII::ElementMaps::hex27_node_map[27] = { 1, 5, 6, 2, 0, 4, 7, 3, 13, 17, 14, 9, 8, 16, 18, 10, 12, 19, 15, 11, 24, 25, 22, 26, 21, 23, 20}; const int ExodusII::ElementMaps::tet4_node_map[4] = {0, 1, 2, 3}; const int ExodusII::ElementMaps::tet10_node_map[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; const int ExodusII::ElementMaps::prism6_node_map[6] = {0, 1, 2, 3, 4, 5}; // 3D face map definitions const int ExodusII::ElementMaps::tet_face_map[4] = {1, 2, 3, 0}; const int ExodusII::ElementMaps::hex_face_map[6] = {1, 2, 3, 4, 0, 5}; const int ExodusII::ElementMaps::hex27_face_map[6] = {1, 0, 3, 5, 4, 2}; const int ExodusII::ElementMaps::prism_face_map[5] = {-1,-1,-1,-1,-1}; // Not Implemented! // ------------------------------------------------------------ // ExodusII class members ExodusII::~ExodusII() { delete [] title; delete [] elem_type; } void ExodusII::check_err(const int err, const std::string msg) { if (err < 0) { std::cout << msg << std::endl; error(); } } void ExodusII::message(const std::string msg) { if (verbose) std::cout << msg << std::endl; } void ExodusII::message(const std::string msg, int i) { if (verbose) std::cout << msg << i << "." << std::endl; } void ExodusII::open(const char* filename) { ex_id = exII::ex_open(filename, EX_READ, &comp_ws, &io_ws, &ex_version); check_err(ex_id, "Error opening ExodusII mesh file."); if (verbose) std::cout << "File opened successfully." << std::endl; } void ExodusII::read_header() { ex_err = exII::ex_get_init(ex_id, title, &num_dim, &num_nodes, &num_elem, &num_elem_blk, &num_node_sets, &num_side_sets); check_err(ex_err, "Error retrieving header info."); message("Exodus header info retrieved successfully."); } void ExodusII::print_header() { if (verbose) std::cout << "Title: \t" << title << std::endl << "Mesh Dimension: \t" << num_dim << std::endl << "Number of Nodes: \t" << num_nodes << std::endl << "Number of elements: \t" << num_elem << std::endl << "Number of elt blocks: \t" << num_elem_blk << std::endl << "Number of node sets: \t" << num_node_sets << std::endl << "Number of side sets: \t" << num_side_sets << std::endl; } void ExodusII::read_nodes() { x.resize(num_nodes); y.resize(num_nodes); z.resize(num_nodes); ex_err = exII::ex_get_coord(ex_id, static_cast<void*>(&x[0]), static_cast<void*>(&y[0]), static_cast<void*>(&z[0])); check_err(ex_err, "Error retrieving nodal data."); message("Nodal data retrieved successfully."); } void ExodusII::print_nodes() { for (int i=0; i<num_nodes; i++) { std::cout << "(" << x[i] << ", " << y[i] << ", " << z[i] << ")" << std::endl; } } void ExodusII::read_block_info() { block_ids.resize(num_elem_blk); ex_err = exII::ex_get_elem_blk_ids(ex_id, &block_ids[0]); // Get all element block IDs. // Usually, there is only one // block since there is only // one type of element. // However, there could be more. check_err(ex_err, "Error getting block IDs."); message("All block IDs retrieved successfully."); } void ExodusII::read_elem_in_block(int block) { ex_err = exII::ex_get_elem_block(ex_id, block_ids[block], elem_type, &num_elem_this_blk, &num_nodes_per_elem, &num_attr); check_err(ex_err, "Error getting block info."); message("Info retrieved successfully for block: ", block); // Read in the connectivity of the elements of this block connect.resize(num_nodes_per_elem*num_elem_this_blk); ex_err = exII::ex_get_elem_conn(ex_id, block_ids[block], &connect[0]); check_err(ex_err, "Error reading block connectivity."); message("Connectivity retrieved successfully for block: ", block); } void ExodusII::read_sideset_info() { ss_ids.resize(num_side_sets); ex_err = exII::ex_get_side_set_ids(ex_id, &ss_ids[0]); check_err(ex_err, "Error retrieving sideset information."); message("All sideset information retrieved successfully."); // Resize appropriate data structures -- only do this once outside the loop num_sides_per_set.resize(num_side_sets); num_df_per_set.resize(num_side_sets); req_info = EX_INQ_SS_ELEM_LEN; // Inquire about the length of the // concatenated side sets element list ex_err = exII::ex_inquire(ex_id, req_info, &ret_int, &ret_float, &ret_char); check_err(ex_err, "Error inquiring about side set element list length."); //std::cout << "Value returned by ex_inquire was: " << ret_int << std::endl; num_elem_all_sidesets = ret_int; elem_list.resize (num_elem_all_sidesets); side_list.resize (num_elem_all_sidesets); id_list.resize (num_elem_all_sidesets); } void ExodusII::read_sideset(int id, int offset) { ex_err = exII::ex_get_side_set_param(ex_id, ss_ids[id], &num_sides_per_set[id], &num_df_per_set[id]); check_err(ex_err, "Error retrieving sideset parameters."); message("Parameters retrieved successfully for sideset: ", id); ex_err = exII::ex_get_side_set(ex_id, ss_ids[id], &elem_list[offset], &side_list[offset]); check_err(ex_err, "Error retrieving sideset data."); message("Data retrieved successfully for sideset: ", id); for (int i=0; i<num_sides_per_set[id]; i++) id_list[i+offset] = ss_ids[id]; } void ExodusII::print_sideset_info() { for (int i=0; i<num_elem_all_sidesets; i++) { std::cout << elem_list[i] << " " << side_list[i] << std::endl; } } void ExodusII::close() { ex_err = exII::ex_close(ex_id); check_err(ex_err, "Error closing Exodus file."); message("Exodus file closed successfully."); } // ------------------------------------------------------------ // ExodusII::Conversion class members const ExodusII::Conversion ExodusII::ElementMaps::assign_conversion(const std::string type) { if (type == "QUAD4") return assign_conversion(QUAD4); else if (type == "QUAD8") return assign_conversion(QUAD8); else if (type == "QUAD9") return assign_conversion(QUAD9); else if (type == "TRI3") return assign_conversion(TRI3); else if (type == "TRI6") return assign_conversion(TRI6); else if ((type == "HEX8") || (type == "HEX")) return assign_conversion(HEX8); else if (type == "HEX20") return assign_conversion(HEX20); else if (type == "HEX27") return assign_conversion(HEX27); else if (type == "TETRA4") return assign_conversion(TET4); else if (type == "TETRA10") return assign_conversion(TET10); else if (type == "WEDGE") return assign_conversion(PRISM6); else { std::cerr << "ERROR! Unrecognized element type: " << type << std::endl; error(); } error(); const Conversion conv(tri3_node_map, tri_edge_map, TRI3); // dummy return conv; } const ExodusII::Conversion ExodusII::ElementMaps::assign_conversion(const ElemType type) { switch (type) { case QUAD4: { const Conversion conv(quad4_node_map, quad_edge_map, QUAD4); return conv; } case QUAD8: { const Conversion conv(quad8_node_map, quad_edge_map, QUAD8); return conv; } case QUAD9: { const Conversion conv(quad9_node_map, quad_edge_map, QUAD9); return conv; } case TRI3: { const Conversion conv(tri3_node_map, tri_edge_map, TRI3); return conv; } case TRI6: { const Conversion conv(tri6_node_map, tri_edge_map, TRI6); return conv; } case HEX8: { const Conversion conv(hex8_node_map, hex_face_map, HEX8); return conv; } case HEX20: { const Conversion conv(hex20_node_map, hex_face_map, HEX20); return conv; } case HEX27: { const Conversion conv(hex27_node_map, hex27_face_map, HEX27); return conv; } case TET4: { const Conversion conv(tet4_node_map, tet_face_map, TET4); return conv; } case TET10: { const Conversion conv(tet10_node_map, tet_face_map, TET10); return conv; } case PRISM6: { const Conversion conv(prism6_node_map, prism_face_map, PRISM6); return conv; } default: error(); } error(); const Conversion conv(tri3_node_map, tri_edge_map, TRI3); // dummy return conv; } } // end anonymous namespace #endif // #ifdef HAVE_EXODUS_API // ------------------------------------------------------------ // ExodusII_IO class members void ExodusII_IO::read (const std::string& fname) { #ifndef HAVE_EXODUS_API std::cerr << "ERROR, ExodusII API is not defined.\n" << "Input file " << fname << " cannot be read" << std::endl; error(); #else // Get a reference to the mesh we are reading MeshBase& mesh = MeshInput<MeshBase>::mesh(); // Clear any existing mesh data mesh.clear(); assert(mesh.mesh_dimension() != 1); // No support for 1D ExodusII meshes #ifdef DEBUG this->verbose() = true; #endif ExodusII ex(this->verbose()); // Instantiate ExodusII interface ExodusII::ElementMaps em; // Instantiate the ElementMaps interface ex.open(fname.c_str()); // Open the exodus file, if possible ex.read_header(); // Get header information from exodus file ex.print_header(); // Print header information assert(static_cast<unsigned int>(ex.get_num_dim()) == mesh.mesh_dimension()); // Be sure number of dimensions // is equal to the number of // dimensions in the mesh supplied. ex.read_nodes(); // Read nodes from the exodus file mesh.reserve_nodes(ex.get_num_nodes()); // Reserve space for the nodes. // Loop over the nodes, create Nodes. for (int i=0; i<ex.get_num_nodes(); i++) mesh.add_point (Point(ex.get_x(i), ex.get_y(i), ex.get_z(i))); assert (static_cast<unsigned int>(ex.get_num_nodes()) == mesh.n_nodes()); ex.read_block_info(); // Get information about all the blocks mesh.reserve_elem(ex.get_num_elem()); // Reserve space for the elements // Read in the element connectivity for each block. int nelem_last_block = 0; // Loop over all the blocks for (int i=0; i<ex.get_num_elem_blk(); i++) { // Read the information for block i ex.read_elem_in_block (i); // Set any relevant node/edge maps for this element const std::string type (ex.get_elem_type()); const ExodusII::Conversion conv = em.assign_conversion(type); // Loop over all the faces in this block int jmax = nelem_last_block+ex.get_num_elem_this_blk(); for (int j=nelem_last_block; j<jmax; j++) { Elem* elem = mesh.add_elem (Elem::build (conv.get_canonical_type()).release()); assert (elem != NULL); // Set all the nodes for this element for (int k=0; k<ex.get_num_nodes_per_elem(); k++) { int gi = (j-nelem_last_block)*ex.get_num_nodes_per_elem() + conv.get_node_map(k); // global index int node_number = ex.get_connect(gi); // Global node number (1-based) elem->set_node(k) = mesh.node_ptr((node_number-1)); // Set node number // Subtract 1 since // exodus is internally 1-based } } // running sum of # of elements per block, // (should equal total number of elements in the end) nelem_last_block += ex.get_num_elem_this_blk(); } assert (static_cast<unsigned int>(nelem_last_block) == mesh.n_elem()); // Read in sideset information -- this is useful for applying boundary conditions { ex.read_sideset_info(); // Get basic information about ALL sidesets int offset=0; for (int i=0; i<ex.get_num_side_sets(); i++) { offset += (i > 0 ? ex.get_num_sides_per_set(i-1) : 0); // Compute new offset ex.read_sideset (i, offset); } const std::vector<int>& elem_list = ex.get_elem_list(); const std::vector<int>& side_list = ex.get_side_list(); const std::vector<int>& id_list = ex.get_id_list(); for (unsigned int e=0; e<elem_list.size(); e++) { // Set any relevant node/edge maps for this element const ExodusII::Conversion conv = em.assign_conversion(mesh.elem(elem_list[e]-1)->type()); mesh.boundary_info.add_side (elem_list[e]-1, conv.get_side_map(side_list[e]-1), id_list[e]); } } ex.close(); // Close the exodus file, if possible #endif }
/*************************************************************************/ /* project_manager.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "project_manager.h" #include "core/io/config_file.h" #include "core/io/resource_saver.h" #include "core/io/stream_peer_ssl.h" #include "core/io/zip_io.h" #include "core/os/dir_access.h" #include "core/os/file_access.h" #include "core/os/keyboard.h" #include "core/os/os.h" #include "core/translation.h" #include "core/version.h" #include "core/version_hash.gen.h" #include "editor_scale.h" #include "editor_settings.h" #include "editor_themes.h" #include "scene/gui/center_container.h" #include "scene/gui/line_edit.h" #include "scene/gui/margin_container.h" #include "scene/gui/panel_container.h" #include "scene/gui/separator.h" #include "scene/gui/texture_rect.h" #include "scene/gui/tool_button.h" static inline String get_project_key_from_path(const String &dir) { return dir.replace("/", "::"); } class ProjectDialog : public ConfirmationDialog { GDCLASS(ProjectDialog, ConfirmationDialog); public: enum Mode { MODE_NEW, MODE_IMPORT, MODE_INSTALL, MODE_RENAME }; private: enum MessageType { MESSAGE_ERROR, MESSAGE_WARNING, MESSAGE_SUCCESS }; enum InputType { PROJECT_PATH, INSTALL_PATH }; Mode mode; Button *browse; Button *install_browse; Button *create_dir; Container *name_container; Container *path_container; Container *install_path_container; Container *rasterizer_container; Ref<ButtonGroup> rasterizer_button_group; Label *msg; LineEdit *project_path; LineEdit *project_name; LineEdit *install_path; TextureRect *status_rect; TextureRect *install_status_rect; FileDialog *fdialog; FileDialog *fdialog_install; String zip_path; String zip_title; AcceptDialog *dialog_error; String fav_dir; String created_folder_path; void set_message(const String &p_msg, MessageType p_type = MESSAGE_SUCCESS, InputType input_type = PROJECT_PATH) { msg->set_text(p_msg); Ref<Texture2D> current_path_icon = status_rect->get_texture(); Ref<Texture2D> current_install_icon = install_status_rect->get_texture(); Ref<Texture2D> new_icon; switch (p_type) { case MESSAGE_ERROR: { msg->add_color_override("font_color", get_color("error_color", "Editor")); msg->set_modulate(Color(1, 1, 1, 1)); new_icon = get_icon("StatusError", "EditorIcons"); } break; case MESSAGE_WARNING: { msg->add_color_override("font_color", get_color("warning_color", "Editor")); msg->set_modulate(Color(1, 1, 1, 1)); new_icon = get_icon("StatusWarning", "EditorIcons"); } break; case MESSAGE_SUCCESS: { msg->set_modulate(Color(1, 1, 1, 0)); new_icon = get_icon("StatusSuccess", "EditorIcons"); } break; } if (current_path_icon != new_icon && input_type == PROJECT_PATH) { status_rect->set_texture(new_icon); } else if (current_install_icon != new_icon && input_type == INSTALL_PATH) { install_status_rect->set_texture(new_icon); } set_size(Size2(500, 0) * EDSCALE); } String _test_path() { DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); String valid_path, valid_install_path; if (d->change_dir(project_path->get_text()) == OK) { valid_path = project_path->get_text(); } else if (d->change_dir(project_path->get_text().strip_edges()) == OK) { valid_path = project_path->get_text().strip_edges(); } else if (project_path->get_text().ends_with(".zip")) { if (d->file_exists(project_path->get_text())) { valid_path = project_path->get_text(); } } else if (project_path->get_text().strip_edges().ends_with(".zip")) { if (d->file_exists(project_path->get_text().strip_edges())) { valid_path = project_path->get_text().strip_edges(); } } if (valid_path == "") { set_message(TTR("The path specified doesn't exist."), MESSAGE_ERROR); memdelete(d); get_ok()->set_disabled(true); return ""; } if (mode == MODE_IMPORT && valid_path.ends_with(".zip")) { if (d->change_dir(install_path->get_text()) == OK) { valid_install_path = install_path->get_text(); } else if (d->change_dir(install_path->get_text().strip_edges()) == OK) { valid_install_path = install_path->get_text().strip_edges(); } if (valid_install_path == "") { set_message(TTR("The path specified doesn't exist."), MESSAGE_ERROR, INSTALL_PATH); memdelete(d); get_ok()->set_disabled(true); return ""; } } if (mode == MODE_IMPORT || mode == MODE_RENAME) { if (valid_path != "" && !d->file_exists("project.godot")) { if (valid_path.ends_with(".zip")) { FileAccess *src_f = NULL; zlib_filefunc_def io = zipio_create_io_from_file(&src_f); unzFile pkg = unzOpen2(valid_path.utf8().get_data(), &io); if (!pkg) { set_message(TTR("Error opening package file (it's not in ZIP format)."), MESSAGE_ERROR); memdelete(d); get_ok()->set_disabled(true); unzClose(pkg); return ""; } int ret = unzGoToFirstFile(pkg); while (ret == UNZ_OK) { unz_file_info info; char fname[16384]; ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0); if (String(fname).ends_with("project.godot")) { break; } ret = unzGoToNextFile(pkg); } if (ret == UNZ_END_OF_LIST_OF_FILE) { set_message(TTR("Invalid \".zip\" project file; it doesn't contain a \"project.godot\" file."), MESSAGE_ERROR); memdelete(d); get_ok()->set_disabled(true); unzClose(pkg); return ""; } unzClose(pkg); // check if the specified install folder is empty, even though this is not an error, it is good to check here d->list_dir_begin(); bool is_empty = true; String n = d->get_next(); while (n != String()) { if (!n.begins_with(".")) { // Allow `.`, `..` (reserved current/parent folder names) // and hidden files/folders to be present. // For instance, this lets users initialize a Git repository // and still be able to create a project in the directory afterwards. is_empty = false; break; } n = d->get_next(); } d->list_dir_end(); if (!is_empty) { set_message(TTR("Please choose an empty folder."), MESSAGE_WARNING, INSTALL_PATH); memdelete(d); get_ok()->set_disabled(true); return ""; } } else { set_message(TTR("Please choose a \"project.godot\" or \".zip\" file."), MESSAGE_ERROR); memdelete(d); install_path_container->hide(); get_ok()->set_disabled(true); return ""; } } else if (valid_path.ends_with("zip")) { set_message(TTR("This directory already contains a Godot project."), MESSAGE_ERROR, INSTALL_PATH); memdelete(d); get_ok()->set_disabled(true); return ""; } } else { // check if the specified folder is empty, even though this is not an error, it is good to check here d->list_dir_begin(); bool is_empty = true; String n = d->get_next(); while (n != String()) { if (!n.begins_with(".")) { // Allow `.`, `..` (reserved current/parent folder names) // and hidden files/folders to be present. // For instance, this lets users initialize a Git repository // and still be able to create a project in the directory afterwards. is_empty = false; break; } n = d->get_next(); } d->list_dir_end(); if (!is_empty) { set_message(TTR("Please choose an empty folder."), MESSAGE_ERROR); memdelete(d); get_ok()->set_disabled(true); return ""; } } set_message(""); set_message("", MESSAGE_SUCCESS, INSTALL_PATH); memdelete(d); get_ok()->set_disabled(false); return valid_path; } void _path_text_changed(const String &p_path) { String sp = _test_path(); if (sp != "") { // If the project name is empty or default, infer the project name from the selected folder name if (project_name->get_text() == "" || project_name->get_text() == TTR("New Game Project")) { sp = sp.replace("\\", "/"); int lidx = sp.find_last("/"); if (lidx != -1) { sp = sp.substr(lidx + 1, sp.length()).capitalize(); } if (sp == "" && mode == MODE_IMPORT) sp = TTR("Imported Project"); project_name->set_text(sp); _text_changed(sp); } } if (created_folder_path != "" && created_folder_path != p_path) { _remove_created_folder(); } } void _file_selected(const String &p_path) { String p = p_path; if (mode == MODE_IMPORT) { if (p.ends_with("project.godot")) { p = p.get_base_dir(); install_path_container->hide(); get_ok()->set_disabled(false); } else if (p.ends_with(".zip")) { install_path->set_text(p.get_base_dir()); install_path_container->show(); get_ok()->set_disabled(false); } else { set_message(TTR("Please choose a \"project.godot\" or \".zip\" file."), MESSAGE_ERROR); get_ok()->set_disabled(true); return; } } String sp = p.simplify_path(); project_path->set_text(sp); _path_text_changed(sp); if (p.ends_with(".zip")) { install_path->call_deferred("grab_focus"); } else { get_ok()->call_deferred("grab_focus"); } } void _path_selected(const String &p_path) { String sp = p_path.simplify_path(); project_path->set_text(sp); _path_text_changed(sp); get_ok()->call_deferred("grab_focus"); } void _install_path_selected(const String &p_path) { String sp = p_path.simplify_path(); install_path->set_text(sp); _path_text_changed(sp); get_ok()->call_deferred("grab_focus"); } void _browse_path() { fdialog->set_current_dir(project_path->get_text()); if (mode == MODE_IMPORT) { fdialog->set_mode(FileDialog::MODE_OPEN_FILE); fdialog->clear_filters(); fdialog->add_filter(vformat("project.godot ; %s %s", VERSION_NAME, TTR("Project"))); fdialog->add_filter("*.zip ; " + TTR("ZIP File")); } else { fdialog->set_mode(FileDialog::MODE_OPEN_DIR); } fdialog->popup_centered_ratio(); } void _browse_install_path() { fdialog_install->set_current_dir(install_path->get_text()); fdialog_install->set_mode(FileDialog::MODE_OPEN_DIR); fdialog_install->popup_centered_ratio(); } void _create_folder() { if (project_name->get_text() == "" || created_folder_path != "" || project_name->get_text().ends_with(".") || project_name->get_text().ends_with(" ")) { set_message(TTR("Invalid Project Name."), MESSAGE_WARNING); return; } DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); if (d->change_dir(project_path->get_text()) == OK) { if (!d->dir_exists(project_name->get_text())) { if (d->make_dir(project_name->get_text()) == OK) { d->change_dir(project_name->get_text()); String dir_str = d->get_current_dir(); project_path->set_text(dir_str); _path_text_changed(dir_str); created_folder_path = d->get_current_dir(); create_dir->set_disabled(true); } else { dialog_error->set_text(TTR("Couldn't create folder.")); dialog_error->popup_centered_minsize(); } } else { dialog_error->set_text(TTR("There is already a folder in this path with the specified name.")); dialog_error->popup_centered_minsize(); } } memdelete(d); } void _text_changed(const String &p_text) { if (mode != MODE_NEW) return; _test_path(); if (p_text == "") set_message(TTR("It would be a good idea to name your project."), MESSAGE_WARNING); } void ok_pressed() { String dir = project_path->get_text(); if (mode == MODE_RENAME) { String dir2 = _test_path(); if (dir2 == "") { set_message(TTR("Invalid project path (changed anything?)."), MESSAGE_ERROR); return; } ProjectSettings *current = memnew(ProjectSettings); int err = current->setup(dir2, ""); if (err != OK) { set_message(vformat(TTR("Couldn't load project.godot in project path (error %d). It may be missing or corrupted."), err), MESSAGE_ERROR); } else { ProjectSettings::CustomMap edited_settings; edited_settings["application/config/name"] = project_name->get_text(); if (current->save_custom(dir2.plus_file("project.godot"), edited_settings, Vector<String>(), true) != OK) { set_message(TTR("Couldn't edit project.godot in project path."), MESSAGE_ERROR); } } hide(); emit_signal("projects_updated"); } else { if (mode == MODE_IMPORT) { if (project_path->get_text().ends_with(".zip")) { mode = MODE_INSTALL; ok_pressed(); return; } } else { if (mode == MODE_NEW) { ProjectSettings::CustomMap initial_settings; if (rasterizer_button_group->get_pressed_button()->get_meta("driver_name") == "GLES3") { initial_settings["rendering/quality/driver/driver_name"] = "GLES3"; } else { initial_settings["rendering/quality/driver/driver_name"] = "GLES2"; initial_settings["rendering/vram_compression/import_etc2"] = false; initial_settings["rendering/vram_compression/import_etc"] = true; } initial_settings["application/config/name"] = project_name->get_text(); initial_settings["application/config/icon"] = "res://icon.png"; initial_settings["rendering/environment/default_environment"] = "res://default_env.tres"; if (ProjectSettings::get_singleton()->save_custom(dir.plus_file("project.godot"), initial_settings, Vector<String>(), false) != OK) { set_message(TTR("Couldn't create project.godot in project path."), MESSAGE_ERROR); } else { ResourceSaver::save(dir.plus_file("icon.png"), get_icon("DefaultProjectIcon", "EditorIcons")); FileAccess *f = FileAccess::open(dir.plus_file("default_env.tres"), FileAccess::WRITE); if (!f) { set_message(TTR("Couldn't create project.godot in project path."), MESSAGE_ERROR); } else { f->store_line("[gd_resource type=\"Environment\" load_steps=2 format=2]"); f->store_line("[sub_resource type=\"ProceduralSky\" id=1]"); f->store_line("[resource]"); f->store_line("background_mode = 2"); f->store_line("background_sky = SubResource( 1 )"); memdelete(f); } } } else if (mode == MODE_INSTALL) { if (project_path->get_text().ends_with(".zip")) { dir = install_path->get_text(); zip_path = project_path->get_text(); } FileAccess *src_f = NULL; zlib_filefunc_def io = zipio_create_io_from_file(&src_f); unzFile pkg = unzOpen2(zip_path.utf8().get_data(), &io); if (!pkg) { dialog_error->set_text(TTR("Error opening package file, not in ZIP format.")); dialog_error->popup_centered_minsize(); return; } int ret = unzGoToFirstFile(pkg); Vector<String> failed_files; int idx = 0; while (ret == UNZ_OK) { //get filename unz_file_info info; char fname[16384]; ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0); String path = fname; int depth = 1; //stuff from github comes with tag bool skip = false; while (depth > 0) { int pp = path.find("/"); if (pp == -1) { skip = true; break; } path = path.substr(pp + 1, path.length()); depth--; } if (skip || path == String()) { // } else if (path.ends_with("/")) { // a dir path = path.substr(0, path.length() - 1); DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); da->make_dir(dir.plus_file(path)); memdelete(da); } else { Vector<uint8_t> data; data.resize(info.uncompressed_size); //read unzOpenCurrentFile(pkg); unzReadCurrentFile(pkg, data.ptrw(), data.size()); unzCloseCurrentFile(pkg); FileAccess *f = FileAccess::open(dir.plus_file(path), FileAccess::WRITE); if (f) { f->store_buffer(data.ptr(), data.size()); memdelete(f); } else { failed_files.push_back(path); } } idx++; ret = unzGoToNextFile(pkg); } unzClose(pkg); if (failed_files.size()) { String msg = TTR("The following files failed extraction from package:") + "\n\n"; for (int i = 0; i < failed_files.size(); i++) { if (i > 15) { msg += "\nAnd " + itos(failed_files.size() - i) + " more files."; break; } msg += failed_files[i] + "\n"; } dialog_error->set_text(msg); dialog_error->popup_centered_minsize(); } else if (!project_path->get_text().ends_with(".zip")) { dialog_error->set_text(TTR("Package installed successfully!")); dialog_error->popup_centered_minsize(); } } } dir = dir.replace("\\", "/"); if (dir.ends_with("/")) dir = dir.substr(0, dir.length() - 1); String proj = get_project_key_from_path(dir); EditorSettings::get_singleton()->set("projects/" + proj, dir); EditorSettings::get_singleton()->save(); hide(); emit_signal("project_created", dir); } } void _remove_created_folder() { if (created_folder_path != "") { DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); d->remove(created_folder_path); memdelete(d); create_dir->set_disabled(false); created_folder_path = ""; } } void cancel_pressed() { _remove_created_folder(); project_path->clear(); _path_text_changed(""); project_name->clear(); _text_changed(""); if (status_rect->get_texture() == get_icon("StatusError", "EditorIcons")) msg->show(); if (install_status_rect->get_texture() == get_icon("StatusError", "EditorIcons")) msg->show(); } void _notification(int p_what) { if (p_what == MainLoop::NOTIFICATION_WM_QUIT_REQUEST) _remove_created_folder(); } protected: static void _bind_methods() { ClassDB::bind_method("_browse_path", &ProjectDialog::_browse_path); ClassDB::bind_method("_create_folder", &ProjectDialog::_create_folder); ClassDB::bind_method("_text_changed", &ProjectDialog::_text_changed); ClassDB::bind_method("_path_text_changed", &ProjectDialog::_path_text_changed); ClassDB::bind_method("_path_selected", &ProjectDialog::_path_selected); ClassDB::bind_method("_file_selected", &ProjectDialog::_file_selected); ClassDB::bind_method("_install_path_selected", &ProjectDialog::_install_path_selected); ClassDB::bind_method("_browse_install_path", &ProjectDialog::_browse_install_path); ADD_SIGNAL(MethodInfo("project_created")); ADD_SIGNAL(MethodInfo("projects_updated")); } public: void set_zip_path(const String &p_path) { zip_path = p_path; } void set_zip_title(const String &p_title) { zip_title = p_title; } void set_mode(Mode p_mode) { mode = p_mode; } void set_project_path(const String &p_path) { project_path->set_text(p_path); } void show_dialog() { if (mode == MODE_RENAME) { project_path->set_editable(false); browse->hide(); install_browse->hide(); set_title(TTR("Rename Project")); get_ok()->set_text(TTR("Rename")); name_container->show(); status_rect->hide(); msg->hide(); install_path_container->hide(); install_status_rect->hide(); rasterizer_container->hide(); get_ok()->set_disabled(false); ProjectSettings *current = memnew(ProjectSettings); int err = current->setup(project_path->get_text(), ""); if (err != OK) { set_message(vformat(TTR("Couldn't load project.godot in project path (error %d). It may be missing or corrupted."), err), MESSAGE_ERROR); status_rect->show(); msg->show(); get_ok()->set_disabled(true); } else if (current->has_setting("application/config/name")) { String proj = current->get("application/config/name"); project_name->set_text(proj); _text_changed(proj); } project_name->call_deferred("grab_focus"); create_dir->hide(); } else { fav_dir = EditorSettings::get_singleton()->get("filesystem/directories/default_project_path"); if (fav_dir != "") { project_path->set_text(fav_dir); fdialog->set_current_dir(fav_dir); } else { DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); project_path->set_text(d->get_current_dir()); fdialog->set_current_dir(d->get_current_dir()); memdelete(d); } String proj = TTR("New Game Project"); project_name->set_text(proj); _text_changed(proj); project_path->set_editable(true); browse->set_disabled(false); browse->show(); install_browse->set_disabled(false); install_browse->show(); create_dir->show(); status_rect->show(); install_status_rect->show(); msg->show(); if (mode == MODE_IMPORT) { set_title(TTR("Import Existing Project")); get_ok()->set_text(TTR("Import & Edit")); name_container->hide(); install_path_container->hide(); rasterizer_container->hide(); project_path->grab_focus(); } else if (mode == MODE_NEW) { set_title(TTR("Create New Project")); get_ok()->set_text(TTR("Create & Edit")); name_container->show(); install_path_container->hide(); rasterizer_container->show(); project_name->call_deferred("grab_focus"); project_name->call_deferred("select_all"); } else if (mode == MODE_INSTALL) { set_title(TTR("Install Project:") + " " + zip_title); get_ok()->set_text(TTR("Install & Edit")); project_name->set_text(zip_title); name_container->show(); install_path_container->hide(); rasterizer_container->hide(); project_path->grab_focus(); } _test_path(); } popup_centered_minsize(Size2(500, 0) * EDSCALE); } ProjectDialog() { VBoxContainer *vb = memnew(VBoxContainer); add_child(vb); name_container = memnew(VBoxContainer); vb->add_child(name_container); Label *l = memnew(Label); l->set_text(TTR("Project Name:")); name_container->add_child(l); HBoxContainer *pnhb = memnew(HBoxContainer); name_container->add_child(pnhb); project_name = memnew(LineEdit); project_name->set_h_size_flags(SIZE_EXPAND_FILL); pnhb->add_child(project_name); create_dir = memnew(Button); pnhb->add_child(create_dir); create_dir->set_text(TTR("Create Folder")); create_dir->connect("pressed", this, "_create_folder"); path_container = memnew(VBoxContainer); vb->add_child(path_container); l = memnew(Label); l->set_text(TTR("Project Path:")); path_container->add_child(l); HBoxContainer *pphb = memnew(HBoxContainer); path_container->add_child(pphb); project_path = memnew(LineEdit); project_path->set_h_size_flags(SIZE_EXPAND_FILL); pphb->add_child(project_path); install_path_container = memnew(VBoxContainer); vb->add_child(install_path_container); l = memnew(Label); l->set_text(TTR("Project Installation Path:")); install_path_container->add_child(l); HBoxContainer *iphb = memnew(HBoxContainer); install_path_container->add_child(iphb); install_path = memnew(LineEdit); install_path->set_h_size_flags(SIZE_EXPAND_FILL); iphb->add_child(install_path); // status icon status_rect = memnew(TextureRect); status_rect->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED); pphb->add_child(status_rect); browse = memnew(Button); browse->set_text(TTR("Browse")); browse->connect("pressed", this, "_browse_path"); pphb->add_child(browse); // install status icon install_status_rect = memnew(TextureRect); install_status_rect->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED); iphb->add_child(install_status_rect); install_browse = memnew(Button); install_browse->set_text(TTR("Browse")); install_browse->connect("pressed", this, "_browse_install_path"); iphb->add_child(install_browse); msg = memnew(Label); msg->set_align(Label::ALIGN_CENTER); vb->add_child(msg); // rasterizer selection rasterizer_container = memnew(VBoxContainer); vb->add_child(rasterizer_container); l = memnew(Label); l->set_text(TTR("Renderer:")); rasterizer_container->add_child(l); Container *rshb = memnew(HBoxContainer); rasterizer_container->add_child(rshb); rasterizer_button_group.instance(); Container *rvb = memnew(VBoxContainer); rvb->set_h_size_flags(SIZE_EXPAND_FILL); rshb->add_child(rvb); Button *rs_button = memnew(CheckBox); rs_button->set_button_group(rasterizer_button_group); rs_button->set_text(TTR("Vulkan")); rs_button->set_meta("driver_name", "GLES3"); rs_button->set_pressed(true); rvb->add_child(rs_button); l = memnew(Label); l->set_text(TTR("- Higher visual quality\n- More accurate API, which produces very fast code\n- Some features not implemented yet — work in progress\n- Incompatible with older hardware\n- Not recommended for web and mobile games")); l->set_modulate(Color(1, 1, 1, 0.7)); rvb->add_child(l); rshb->add_child(memnew(VSeparator)); rvb = memnew(VBoxContainer); rvb->set_h_size_flags(SIZE_EXPAND_FILL); rshb->add_child(rvb); rs_button = memnew(CheckBox); rs_button->set_button_group(rasterizer_button_group); rs_button->set_text(TTR("OpenGL ES 2.0")); rs_button->set_meta("driver_name", "GLES2"); rvb->add_child(rs_button); l = memnew(Label); l->set_text(TTR("- Lower visual quality\n- Some features not available\n- Works on most hardware\n- Recommended for web and mobile games")); l->set_modulate(Color(1, 1, 1, 0.7)); rvb->add_child(l); l = memnew(Label); l->set_text(TTR("The renderer can be changed later, but scenes may need to be adjusted.")); // Add some extra spacing to separate it from the list above and the buttons below. l->set_custom_minimum_size(Size2(0, 40) * EDSCALE); l->set_align(Label::ALIGN_CENTER); l->set_valign(Label::VALIGN_CENTER); l->set_modulate(Color(1, 1, 1, 0.7)); rasterizer_container->add_child(l); fdialog = memnew(FileDialog); fdialog->set_access(FileDialog::ACCESS_FILESYSTEM); fdialog_install = memnew(FileDialog); fdialog_install->set_access(FileDialog::ACCESS_FILESYSTEM); add_child(fdialog); add_child(fdialog_install); project_name->connect("text_changed", this, "_text_changed"); project_path->connect("text_changed", this, "_path_text_changed"); install_path->connect("text_changed", this, "_path_text_changed"); fdialog->connect("dir_selected", this, "_path_selected"); fdialog->connect("file_selected", this, "_file_selected"); fdialog_install->connect("dir_selected", this, "_install_path_selected"); fdialog_install->connect("file_selected", this, "_install_path_selected"); set_hide_on_ok(false); mode = MODE_NEW; dialog_error = memnew(AcceptDialog); add_child(dialog_error); } }; class ProjectListItemControl : public HBoxContainer { GDCLASS(ProjectListItemControl, HBoxContainer) public: TextureButton *favorite_button; TextureRect *icon; bool icon_needs_reload; bool hover; ProjectListItemControl() { favorite_button = NULL; icon = NULL; icon_needs_reload = true; hover = false; } void set_is_favorite(bool fav) { favorite_button->set_modulate(fav ? Color(1, 1, 1, 1) : Color(1, 1, 1, 0.2)); } void _notification(int p_what) { switch (p_what) { case NOTIFICATION_MOUSE_ENTER: { hover = true; update(); } break; case NOTIFICATION_MOUSE_EXIT: { hover = false; update(); } break; case NOTIFICATION_DRAW: { if (hover) { draw_style_box(get_stylebox("hover", "Tree"), Rect2(Point2(), get_size() - Size2(10, 0) * EDSCALE)); } } break; } } }; class ProjectList : public ScrollContainer { GDCLASS(ProjectList, ScrollContainer) public: static const char *SIGNAL_SELECTION_CHANGED; static const char *SIGNAL_PROJECT_ASK_OPEN; enum MenuOptions { GLOBAL_NEW_WINDOW, GLOBAL_OPEN_PROJECT }; // Can often be passed by copy struct Item { String project_key; String project_name; String description; String path; String icon; String main_scene; uint64_t last_modified; bool favorite; bool grayed; bool missing; int version; ProjectListItemControl *control; Item() {} Item(const String &p_project, const String &p_name, const String &p_description, const String &p_path, const String &p_icon, const String &p_main_scene, uint64_t p_last_modified, bool p_favorite, bool p_grayed, bool p_missing, int p_version) { project_key = p_project; project_name = p_name; description = p_description; path = p_path; icon = p_icon; main_scene = p_main_scene; last_modified = p_last_modified; favorite = p_favorite; grayed = p_grayed; missing = p_missing; version = p_version; control = NULL; } _FORCE_INLINE_ bool operator==(const Item &l) const { return project_key == l.project_key; } }; ProjectList(); ~ProjectList(); void update_dock_menu(); void load_projects(); void set_search_term(String p_search_term); void set_order_option(ProjectListFilter::FilterOption p_option); void sort_projects(); int get_project_count() const; void select_project(int p_index); void select_first_visible_project(); void erase_selected_projects(); Vector<Item> get_selected_projects() const; const Set<String> &get_selected_project_keys() const; void ensure_project_visible(int p_index); int get_single_selected_index() const; bool is_any_project_missing() const; void erase_missing_projects(); int refresh_project(const String &dir_path); private: static void _bind_methods(); void _notification(int p_what); void _panel_draw(Node *p_hb); void _panel_input(const Ref<InputEvent> &p_ev, Node *p_hb); void _favorite_pressed(Node *p_hb); void _show_project(const String &p_path); void select_range(int p_begin, int p_end); void toggle_select(int p_index); void create_project_item_control(int p_index); void remove_project(int p_index, bool p_update_settings); void update_icons_async(); void load_project_icon(int p_index); static void load_project_data(const String &p_property_key, Item &p_item, bool p_favorite); String _search_term; ProjectListFilter::FilterOption _order_option; Set<String> _selected_project_keys; String _last_clicked; // Project key VBoxContainer *_scroll_children; int _icon_load_index; Vector<Item> _projects; }; struct ProjectListComparator { ProjectListFilter::FilterOption order_option; // operator< _FORCE_INLINE_ bool operator()(const ProjectList::Item &a, const ProjectList::Item &b) const { if (a.favorite && !b.favorite) { return true; } if (b.favorite && !a.favorite) { return false; } switch (order_option) { case ProjectListFilter::FILTER_PATH: return a.project_key < b.project_key; case ProjectListFilter::FILTER_MODIFIED: return a.last_modified > b.last_modified; default: return a.project_name < b.project_name; } } }; ProjectList::ProjectList() { _order_option = ProjectListFilter::FILTER_MODIFIED; _scroll_children = memnew(VBoxContainer); _scroll_children->set_h_size_flags(SIZE_EXPAND_FILL); add_child(_scroll_children); _icon_load_index = 0; } ProjectList::~ProjectList() { } void ProjectList::update_icons_async() { _icon_load_index = 0; set_process(true); } void ProjectList::_notification(int p_what) { if (p_what == NOTIFICATION_PROCESS) { // Load icons as a coroutine to speed up launch when you have hundreds of projects if (_icon_load_index < _projects.size()) { Item &item = _projects.write[_icon_load_index]; if (item.control->icon_needs_reload) { load_project_icon(_icon_load_index); } _icon_load_index++; } else { set_process(false); } } } void ProjectList::load_project_icon(int p_index) { Item &item = _projects.write[p_index]; Ref<Texture2D> default_icon = get_icon("DefaultProjectIcon", "EditorIcons"); Ref<Texture2D> icon; if (item.icon != "") { Ref<Image> img; img.instance(); Error err = img->load(item.icon.replace_first("res://", item.path + "/")); if (err == OK) { img->resize(default_icon->get_width(), default_icon->get_height(), Image::INTERPOLATE_LANCZOS); Ref<ImageTexture> it = memnew(ImageTexture); it->create_from_image(img); icon = it; } } if (icon.is_null()) { icon = default_icon; } item.control->icon->set_texture(icon); item.control->icon_needs_reload = false; } void ProjectList::load_project_data(const String &p_property_key, Item &p_item, bool p_favorite) { String path = EditorSettings::get_singleton()->get(p_property_key); String conf = path.plus_file("project.godot"); bool grayed = false; bool missing = false; Ref<ConfigFile> cf = memnew(ConfigFile); Error cf_err = cf->load(conf); int config_version = 0; String project_name = TTR("Unnamed Project"); if (cf_err == OK) { String cf_project_name = static_cast<String>(cf->get_value("application", "config/name", "")); if (cf_project_name != "") project_name = cf_project_name.xml_unescape(); config_version = (int)cf->get_value("", "config_version", 0); } if (config_version > ProjectSettings::CONFIG_VERSION) { // Comes from an incompatible (more recent) Godot version, grey it out grayed = true; } String description = cf->get_value("application", "config/description", ""); String icon = cf->get_value("application", "config/icon", ""); String main_scene = cf->get_value("application", "run/main_scene", ""); uint64_t last_modified = 0; if (FileAccess::exists(conf)) { last_modified = FileAccess::get_modified_time(conf); String fscache = path.plus_file(".fscache"); if (FileAccess::exists(fscache)) { uint64_t cache_modified = FileAccess::get_modified_time(fscache); if (cache_modified > last_modified) last_modified = cache_modified; } } else { grayed = true; missing = true; print_line("Project is missing: " + conf); } String project_key = p_property_key.get_slice("/", 1); p_item = Item(project_key, project_name, description, path, icon, main_scene, last_modified, p_favorite, grayed, missing, config_version); } void ProjectList::load_projects() { // This is a full, hard reload of the list. Don't call this unless really required, it's expensive. // If you have 150 projects, it may read through 150 files on your disk at once + load 150 icons. // Clear whole list for (int i = 0; i < _projects.size(); ++i) { Item &project = _projects.write[i]; CRASH_COND(project.control == NULL); memdelete(project.control); // Why not queue_free()? } _projects.clear(); _last_clicked = ""; _selected_project_keys.clear(); // Load data // TODO Would be nice to change how projects and favourites are stored... it complicates things a bit. // Use a dictionary associating project path to metadata (like is_favorite). List<PropertyInfo> properties; EditorSettings::get_singleton()->get_property_list(&properties); Set<String> favorites; // Find favourites... for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { String property_key = E->get().name; if (property_key.begins_with("favorite_projects/")) { favorites.insert(property_key); } } for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { // This is actually something like "projects/C:::Documents::Godot::Projects::MyGame" String property_key = E->get().name; if (!property_key.begins_with("projects/")) continue; String project_key = property_key.get_slice("/", 1); bool favorite = favorites.has("favorite_projects/" + project_key); Item item; load_project_data(property_key, item, favorite); _projects.push_back(item); } // Create controls for (int i = 0; i < _projects.size(); ++i) { create_project_item_control(i); } sort_projects(); set_v_scroll(0); update_icons_async(); update_dock_menu(); } void ProjectList::update_dock_menu() { OS::get_singleton()->global_menu_clear("_dock"); int favs_added = 0; int total_added = 0; for (int i = 0; i < _projects.size(); ++i) { if (!_projects[i].grayed && !_projects[i].missing) { if (_projects[i].favorite) { favs_added++; } else { if (favs_added != 0) { OS::get_singleton()->global_menu_add_separator("_dock"); } favs_added = 0; } OS::get_singleton()->global_menu_add_item("_dock", _projects[i].project_name + " ( " + _projects[i].path + " )", GLOBAL_OPEN_PROJECT, Variant(_projects[i].path.plus_file("project.godot"))); total_added++; } } if (total_added != 0) { OS::get_singleton()->global_menu_add_separator("_dock"); } OS::get_singleton()->global_menu_add_item("_dock", TTR("New Window"), GLOBAL_NEW_WINDOW, Variant()); } void ProjectList::create_project_item_control(int p_index) { // Will be added last in the list, so make sure indexes match ERR_FAIL_COND(p_index != _scroll_children->get_child_count()); Item &item = _projects.write[p_index]; ERR_FAIL_COND(item.control != NULL); // Already created Ref<Texture2D> favorite_icon = get_icon("Favorites", "EditorIcons"); Color font_color = get_color("font_color", "Tree"); ProjectListItemControl *hb = memnew(ProjectListItemControl); hb->connect("draw", this, "_panel_draw", varray(hb)); hb->connect("gui_input", this, "_panel_input", varray(hb)); hb->add_constant_override("separation", 10 * EDSCALE); hb->set_tooltip(item.description); VBoxContainer *favorite_box = memnew(VBoxContainer); favorite_box->set_name("FavoriteBox"); TextureButton *favorite = memnew(TextureButton); favorite->set_name("FavoriteButton"); favorite->set_normal_texture(favorite_icon); // This makes the project's "hover" style display correctly when hovering the favorite icon favorite->set_mouse_filter(MOUSE_FILTER_PASS); favorite->connect("pressed", this, "_favorite_pressed", varray(hb)); favorite_box->add_child(favorite); favorite_box->set_alignment(BoxContainer::ALIGN_CENTER); hb->add_child(favorite_box); hb->favorite_button = favorite; hb->set_is_favorite(item.favorite); TextureRect *tf = memnew(TextureRect); // The project icon may not be loaded by the time the control is displayed, // so use a loading placeholder. tf->set_texture(get_icon("ProjectIconLoading", "EditorIcons")); tf->set_v_size_flags(SIZE_SHRINK_CENTER); if (item.missing) { tf->set_modulate(Color(1, 1, 1, 0.5)); } hb->add_child(tf); hb->icon = tf; VBoxContainer *vb = memnew(VBoxContainer); if (item.grayed) vb->set_modulate(Color(1, 1, 1, 0.5)); vb->set_h_size_flags(SIZE_EXPAND_FILL); hb->add_child(vb); Control *ec = memnew(Control); ec->set_custom_minimum_size(Size2(0, 1)); ec->set_mouse_filter(MOUSE_FILTER_PASS); vb->add_child(ec); Label *title = memnew(Label(!item.missing ? item.project_name : TTR("Missing Project"))); title->add_font_override("font", get_font("title", "EditorFonts")); title->add_color_override("font_color", font_color); title->set_clip_text(true); vb->add_child(title); HBoxContainer *path_hb = memnew(HBoxContainer); path_hb->set_h_size_flags(SIZE_EXPAND_FILL); vb->add_child(path_hb); Button *show = memnew(Button); // Display a folder icon if the project directory can be opened, or a "broken file" icon if it can't show->set_icon(get_icon(!item.missing ? "Load" : "FileBroken", "EditorIcons")); show->set_flat(true); if (!item.grayed) { // Don't make the icon less prominent if the parent is already grayed out show->set_modulate(Color(1, 1, 1, 0.5)); } path_hb->add_child(show); if (!item.missing) { show->connect("pressed", this, "_show_project", varray(item.path)); show->set_tooltip(TTR("Show in File Manager")); } else { show->set_tooltip(TTR("Error: Project is missing on the filesystem.")); } Label *fpath = memnew(Label(item.path)); path_hb->add_child(fpath); fpath->set_h_size_flags(SIZE_EXPAND_FILL); fpath->set_modulate(Color(1, 1, 1, 0.5)); fpath->add_color_override("font_color", font_color); fpath->set_clip_text(true); _scroll_children->add_child(hb); item.control = hb; } void ProjectList::set_search_term(String p_search_term) { _search_term = p_search_term; } void ProjectList::set_order_option(ProjectListFilter::FilterOption p_option) { if (_order_option != p_option) { _order_option = p_option; EditorSettings::get_singleton()->set("project_manager/sorting_order", (int)_order_option); EditorSettings::get_singleton()->save(); } } void ProjectList::sort_projects() { SortArray<Item, ProjectListComparator> sorter; sorter.compare.order_option = _order_option; sorter.sort(_projects.ptrw(), _projects.size()); for (int i = 0; i < _projects.size(); ++i) { Item &item = _projects.write[i]; bool visible = true; if (_search_term != "") { String search_path; if (_search_term.find("/") != -1) { // Search path will match the whole path search_path = item.path; } else { // Search path will only match the last path component to make searching more strict search_path = item.path.get_file(); } // When searching, display projects whose name or path contain the search term visible = item.project_name.findn(_search_term) != -1 || search_path.findn(_search_term) != -1; } item.control->set_visible(visible); } for (int i = 0; i < _projects.size(); ++i) { Item &item = _projects.write[i]; item.control->get_parent()->move_child(item.control, i); } // Rewind the coroutine because order of projects changed update_icons_async(); update_dock_menu(); } const Set<String> &ProjectList::get_selected_project_keys() const { // Faster if that's all you need return _selected_project_keys; } Vector<ProjectList::Item> ProjectList::get_selected_projects() const { Vector<Item> items; if (_selected_project_keys.size() == 0) { return items; } items.resize(_selected_project_keys.size()); int j = 0; for (int i = 0; i < _projects.size(); ++i) { const Item &item = _projects[i]; if (_selected_project_keys.has(item.project_key)) { items.write[j++] = item; } } ERR_FAIL_COND_V(j != items.size(), items); return items; } void ProjectList::ensure_project_visible(int p_index) { const Item &item = _projects[p_index]; int item_top = item.control->get_position().y; int item_bottom = item.control->get_position().y + item.control->get_size().y; if (item_top < get_v_scroll()) { set_v_scroll(item_top); } else if (item_bottom > get_v_scroll() + get_size().y) { set_v_scroll(item_bottom - get_size().y); } } int ProjectList::get_single_selected_index() const { if (_selected_project_keys.size() == 0) { // Default selection return 0; } String key; if (_selected_project_keys.size() == 1) { // Only one selected key = _selected_project_keys.front()->get(); } else { // Multiple selected, consider the last clicked one as "main" key = _last_clicked; } for (int i = 0; i < _projects.size(); ++i) { if (_projects[i].project_key == key) { return i; } } return 0; } void ProjectList::remove_project(int p_index, bool p_update_settings) { const Item item = _projects[p_index]; // Take a copy _selected_project_keys.erase(item.project_key); if (_last_clicked == item.project_key) { _last_clicked = ""; } memdelete(item.control); _projects.remove(p_index); if (p_update_settings) { EditorSettings::get_singleton()->erase("projects/" + item.project_key); EditorSettings::get_singleton()->erase("favorite_projects/" + item.project_key); // Not actually saving the file, in case you are doing more changes to settings } update_dock_menu(); } bool ProjectList::is_any_project_missing() const { for (int i = 0; i < _projects.size(); ++i) { if (_projects[i].missing) { return true; } } return false; } void ProjectList::erase_missing_projects() { if (_projects.empty()) { return; } int deleted_count = 0; int remaining_count = 0; for (int i = 0; i < _projects.size(); ++i) { const Item &item = _projects[i]; if (item.missing) { remove_project(i, true); --i; ++deleted_count; } else { ++remaining_count; } } print_line("Removed " + itos(deleted_count) + " projects from the list, remaining " + itos(remaining_count) + " projects"); EditorSettings::get_singleton()->save(); } int ProjectList::refresh_project(const String &dir_path) { // Reads editor settings and reloads information about a specific project. // If it wasn't loaded and should be in the list, it is added (i.e new project). // If it isn't in the list anymore, it is removed. // If it is in the list but doesn't exist anymore, it is marked as missing. String project_key = get_project_key_from_path(dir_path); // Read project manager settings bool is_favourite = false; bool should_be_in_list = false; String property_key = "projects/" + project_key; { List<PropertyInfo> properties; EditorSettings::get_singleton()->get_property_list(&properties); String favorite_property_key = "favorite_projects/" + project_key; bool found = false; for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { String prop = E->get().name; if (!found && prop == property_key) { found = true; } else if (!is_favourite && prop == favorite_property_key) { is_favourite = true; } } should_be_in_list = found; } bool was_selected = _selected_project_keys.has(project_key); // Remove item in any case for (int i = 0; i < _projects.size(); ++i) { const Item &existing_item = _projects[i]; if (existing_item.path == dir_path) { remove_project(i, false); break; } } int index = -1; if (should_be_in_list) { // Recreate it with updated info Item item; load_project_data(property_key, item, is_favourite); _projects.push_back(item); create_project_item_control(_projects.size() - 1); sort_projects(); for (int i = 0; i < _projects.size(); ++i) { if (_projects[i].project_key == project_key) { if (was_selected) { select_project(i); ensure_project_visible(i); } load_project_icon(i); index = i; break; } } } return index; } int ProjectList::get_project_count() const { return _projects.size(); } void ProjectList::select_project(int p_index) { Vector<Item> previous_selected_items = get_selected_projects(); _selected_project_keys.clear(); for (int i = 0; i < previous_selected_items.size(); ++i) { previous_selected_items[i].control->update(); } toggle_select(p_index); } void ProjectList::select_first_visible_project() { bool found = false; for (int i = 0; i < _projects.size(); i++) { if (_projects[i].control->is_visible()) { select_project(i); found = true; break; } } if (!found) { // Deselect all projects if there are no visible projects in the list. _selected_project_keys.clear(); } } inline void sort(int &a, int &b) { if (a > b) { int temp = a; a = b; b = temp; } } void ProjectList::select_range(int p_begin, int p_end) { sort(p_begin, p_end); select_project(p_begin); for (int i = p_begin + 1; i <= p_end; ++i) { toggle_select(i); } } void ProjectList::toggle_select(int p_index) { Item &item = _projects.write[p_index]; if (_selected_project_keys.has(item.project_key)) { _selected_project_keys.erase(item.project_key); } else { _selected_project_keys.insert(item.project_key); } item.control->update(); } void ProjectList::erase_selected_projects() { if (_selected_project_keys.size() == 0) { return; } for (int i = 0; i < _projects.size(); ++i) { Item &item = _projects.write[i]; if (_selected_project_keys.has(item.project_key) && item.control->is_visible()) { EditorSettings::get_singleton()->erase("projects/" + item.project_key); EditorSettings::get_singleton()->erase("favorite_projects/" + item.project_key); memdelete(item.control); _projects.remove(i); --i; } } EditorSettings::get_singleton()->save(); _selected_project_keys.clear(); _last_clicked = ""; update_dock_menu(); } // Draws selected project highlight void ProjectList::_panel_draw(Node *p_hb) { Control *hb = Object::cast_to<Control>(p_hb); hb->draw_line(Point2(0, hb->get_size().y + 1), Point2(hb->get_size().x - 10, hb->get_size().y + 1), get_color("guide_color", "Tree")); String key = _projects[p_hb->get_index()].project_key; if (_selected_project_keys.has(key)) { hb->draw_style_box(get_stylebox("selected", "Tree"), Rect2(Point2(), hb->get_size() - Size2(10, 0) * EDSCALE)); } } // Input for each item in the list void ProjectList::_panel_input(const Ref<InputEvent> &p_ev, Node *p_hb) { Ref<InputEventMouseButton> mb = p_ev; int clicked_index = p_hb->get_index(); const Item &clicked_project = _projects[clicked_index]; if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) { if (mb->get_shift() && _selected_project_keys.size() > 0 && _last_clicked != "" && clicked_project.project_key != _last_clicked) { int anchor_index = -1; for (int i = 0; i < _projects.size(); ++i) { const Item &p = _projects[i]; if (p.project_key == _last_clicked) { anchor_index = p.control->get_index(); break; } } CRASH_COND(anchor_index == -1); select_range(anchor_index, clicked_index); } else if (mb->get_control()) { toggle_select(clicked_index); } else { _last_clicked = clicked_project.project_key; select_project(clicked_index); } emit_signal(SIGNAL_SELECTION_CHANGED); if (!mb->get_control() && mb->is_doubleclick()) { emit_signal(SIGNAL_PROJECT_ASK_OPEN); } } } void ProjectList::_favorite_pressed(Node *p_hb) { ProjectListItemControl *control = Object::cast_to<ProjectListItemControl>(p_hb); int index = control->get_index(); Item item = _projects.write[index]; // Take copy item.favorite = !item.favorite; if (item.favorite) { EditorSettings::get_singleton()->set("favorite_projects/" + item.project_key, item.path); } else { EditorSettings::get_singleton()->erase("favorite_projects/" + item.project_key); } EditorSettings::get_singleton()->save(); _projects.write[index] = item; control->set_is_favorite(item.favorite); sort_projects(); if (item.favorite) { for (int i = 0; i < _projects.size(); ++i) { if (_projects[i].project_key == item.project_key) { ensure_project_visible(i); break; } } } update_dock_menu(); } void ProjectList::_show_project(const String &p_path) { OS::get_singleton()->shell_open(String("file://") + p_path); } const char *ProjectList::SIGNAL_SELECTION_CHANGED = "selection_changed"; const char *ProjectList::SIGNAL_PROJECT_ASK_OPEN = "project_ask_open"; void ProjectList::_bind_methods() { ClassDB::bind_method("_panel_draw", &ProjectList::_panel_draw); ClassDB::bind_method("_panel_input", &ProjectList::_panel_input); ClassDB::bind_method("_favorite_pressed", &ProjectList::_favorite_pressed); ClassDB::bind_method("_show_project", &ProjectList::_show_project); ADD_SIGNAL(MethodInfo(SIGNAL_SELECTION_CHANGED)); ADD_SIGNAL(MethodInfo(SIGNAL_PROJECT_ASK_OPEN)); } void ProjectManager::_notification(int p_what) { switch (p_what) { case NOTIFICATION_ENTER_TREE: { Engine::get_singleton()->set_editor_hint(false); } break; case NOTIFICATION_RESIZED: { if (open_templates->is_visible()) { open_templates->popup_centered_minsize(); } } break; case NOTIFICATION_READY: { if (_project_list->get_project_count() == 0 && StreamPeerSSL::is_available()) open_templates->popup_centered_minsize(); if (_project_list->get_project_count() >= 1) { // Focus on the search box immediately to allow the user // to search without having to reach for their mouse project_filter->search_box->grab_focus(); } } break; case NOTIFICATION_VISIBILITY_CHANGED: { set_process_unhandled_input(is_visible_in_tree()); } break; case NOTIFICATION_WM_QUIT_REQUEST: { _dim_window(); } break; } } void ProjectManager::_dim_window() { // This method must be called before calling `get_tree()->quit()`. // Otherwise, its effect won't be visible // Dim the project manager window while it's quitting to make it clearer that it's busy. // No transition is applied, as the effect needs to be visible immediately float c = 0.5f; Color dim_color = Color(c, c, c); gui_base->set_modulate(dim_color); } void ProjectManager::_update_project_buttons() { Vector<ProjectList::Item> selected_projects = _project_list->get_selected_projects(); bool empty_selection = selected_projects.empty(); bool is_missing_project_selected = false; for (int i = 0; i < selected_projects.size(); ++i) { if (selected_projects[i].missing) { is_missing_project_selected = true; break; } } erase_btn->set_disabled(empty_selection); open_btn->set_disabled(empty_selection || is_missing_project_selected); rename_btn->set_disabled(empty_selection || is_missing_project_selected); run_btn->set_disabled(empty_selection || is_missing_project_selected); erase_missing_btn->set_visible(_project_list->is_any_project_missing()); } void ProjectManager::_unhandled_input(const Ref<InputEvent> &p_ev) { Ref<InputEventKey> k = p_ev; if (k.is_valid()) { if (!k->is_pressed()) { return; } // Pressing Command + Q quits the Project Manager // This is handled by the platform implementation on macOS, // so only define the shortcut on other platforms #ifndef OSX_ENABLED if (k->get_scancode_with_modifiers() == (KEY_MASK_CMD | KEY_Q)) { _dim_window(); get_tree()->quit(); } #endif if (tabs->get_current_tab() != 0) return; bool scancode_handled = true; switch (k->get_scancode()) { case KEY_ENTER: { _open_selected_projects_ask(); } break; case KEY_DELETE: { _erase_project(); } break; case KEY_HOME: { if (_project_list->get_project_count() > 0) { _project_list->select_project(0); _update_project_buttons(); } } break; case KEY_END: { if (_project_list->get_project_count() > 0) { _project_list->select_project(_project_list->get_project_count() - 1); _update_project_buttons(); } } break; case KEY_UP: { if (k->get_shift()) break; int index = _project_list->get_single_selected_index(); if (index > 0) { _project_list->select_project(index - 1); _project_list->ensure_project_visible(index - 1); _update_project_buttons(); } break; } case KEY_DOWN: { if (k->get_shift()) break; int index = _project_list->get_single_selected_index(); if (index + 1 < _project_list->get_project_count()) { _project_list->select_project(index + 1); _project_list->ensure_project_visible(index + 1); _update_project_buttons(); } } break; case KEY_F: { if (k->get_command()) this->project_filter->search_box->grab_focus(); else scancode_handled = false; } break; default: { scancode_handled = false; } break; } if (scancode_handled) { accept_event(); } } } void ProjectManager::_load_recent_projects() { _project_list->set_order_option(project_order_filter->get_filter_option()); _project_list->set_search_term(project_filter->get_search_term()); _project_list->load_projects(); _update_project_buttons(); tabs->set_current_tab(0); } void ProjectManager::_on_projects_updated() { Vector<ProjectList::Item> selected_projects = _project_list->get_selected_projects(); int index = 0; for (int i = 0; i < selected_projects.size(); ++i) { index = _project_list->refresh_project(selected_projects[i].path); } if (index != -1) { _project_list->ensure_project_visible(index); } _project_list->update_dock_menu(); } void ProjectManager::_on_project_created(const String &dir) { project_filter->clear(); int i = _project_list->refresh_project(dir); _project_list->select_project(i); _project_list->ensure_project_visible(i); _open_selected_projects_ask(); _project_list->update_dock_menu(); } void ProjectManager::_confirm_update_settings() { _open_selected_projects(); } void ProjectManager::_global_menu_action(const Variant &p_id, const Variant &p_meta) { int id = (int)p_id; if (id == ProjectList::GLOBAL_NEW_WINDOW) { List<String> args; args.push_back("-p"); String exec = OS::get_singleton()->get_executable_path(); OS::ProcessID pid = 0; OS::get_singleton()->execute(exec, args, false, &pid); } else if (id == ProjectList::GLOBAL_OPEN_PROJECT) { String conf = (String)p_meta; if (conf != String()) { List<String> args; args.push_back(conf); String exec = OS::get_singleton()->get_executable_path(); OS::ProcessID pid = 0; OS::get_singleton()->execute(exec, args, false, &pid); } } } void ProjectManager::_open_selected_projects() { const Set<String> &selected_list = _project_list->get_selected_project_keys(); for (const Set<String>::Element *E = selected_list.front(); E; E = E->next()) { const String &selected = E->get(); String path = EditorSettings::get_singleton()->get("projects/" + selected); String conf = path.plus_file("project.godot"); if (!FileAccess::exists(conf)) { dialog_error->set_text(vformat(TTR("Can't open project at '%s'."), path)); dialog_error->popup_centered_minsize(); return; } print_line("Editing project: " + path + " (" + selected + ")"); List<String> args; args.push_back("--path"); args.push_back(path); args.push_back("--editor"); if (OS::get_singleton()->is_disable_crash_handler()) { args.push_back("--disable-crash-handler"); } String exec = OS::get_singleton()->get_executable_path(); OS::ProcessID pid = 0; Error err = OS::get_singleton()->execute(exec, args, false, &pid); ERR_FAIL_COND(err); } _dim_window(); get_tree()->quit(); } void ProjectManager::_open_selected_projects_ask() { const Set<String> &selected_list = _project_list->get_selected_project_keys(); if (selected_list.size() < 1) { return; } if (selected_list.size() > 1) { multi_open_ask->set_text(TTR("Are you sure to open more than one project?")); multi_open_ask->popup_centered_minsize(); return; } ProjectList::Item project = _project_list->get_selected_projects()[0]; if (project.missing) { return; } // Update the project settings or don't open String conf = project.path.plus_file("project.godot"); int config_version = project.version; // Check if the config_version property was empty or 0 if (config_version == 0) { ask_update_settings->set_text(vformat(TTR("The following project settings file does not specify the version of Godot through which it was created.\n\n%s\n\nIf you proceed with opening it, it will be converted to Godot's current configuration file format.\nWarning: You won't be able to open the project with previous versions of the engine anymore."), conf)); ask_update_settings->popup_centered_minsize(); return; } // Check if we need to convert project settings from an earlier engine version if (config_version < ProjectSettings::CONFIG_VERSION) { ask_update_settings->set_text(vformat(TTR("The following project settings file was generated by an older engine version, and needs to be converted for this version:\n\n%s\n\nDo you want to convert it?\nWarning: You won't be able to open the project with previous versions of the engine anymore."), conf)); ask_update_settings->popup_centered_minsize(); return; } // Check if the file was generated by a newer, incompatible engine version if (config_version > ProjectSettings::CONFIG_VERSION) { dialog_error->set_text(vformat(TTR("Can't open project at '%s'.") + "\n" + TTR("The project settings were created by a newer engine version, whose settings are not compatible with this version."), project.path)); dialog_error->popup_centered_minsize(); return; } // Open if the project is up-to-date _open_selected_projects(); } void ProjectManager::_run_project_confirm() { Vector<ProjectList::Item> selected_list = _project_list->get_selected_projects(); for (int i = 0; i < selected_list.size(); ++i) { const String &selected_main = selected_list[i].main_scene; if (selected_main == "") { run_error_diag->set_text(TTR("Can't run project: no main scene defined.\nPlease edit the project and set the main scene in the Project Settings under the \"Application\" category.")); run_error_diag->popup_centered(); return; } const String &selected = selected_list[i].project_key; String path = EditorSettings::get_singleton()->get("projects/" + selected); if (!DirAccess::exists(path + "/.import")) { run_error_diag->set_text(TTR("Can't run project: Assets need to be imported.\nPlease edit the project to trigger the initial import.")); run_error_diag->popup_centered(); return; } print_line("Running project: " + path + " (" + selected + ")"); List<String> args; args.push_back("--path"); args.push_back(path); if (OS::get_singleton()->is_disable_crash_handler()) { args.push_back("--disable-crash-handler"); } String exec = OS::get_singleton()->get_executable_path(); OS::ProcessID pid = 0; Error err = OS::get_singleton()->execute(exec, args, false, &pid); ERR_FAIL_COND(err); } } // When you press the "Run" button void ProjectManager::_run_project() { const Set<String> &selected_list = _project_list->get_selected_project_keys(); if (selected_list.size() < 1) { return; } if (selected_list.size() > 1) { multi_run_ask->set_text(vformat(TTR("Are you sure to run %d projects at once?"), selected_list.size())); multi_run_ask->popup_centered_minsize(); } else { _run_project_confirm(); } } void ProjectManager::_scan_dir(const String &path, List<String> *r_projects) { DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); da->change_dir(path); da->list_dir_begin(); String n = da->get_next(); while (n != String()) { if (da->current_is_dir() && !n.begins_with(".")) { _scan_dir(da->get_current_dir().plus_file(n), r_projects); } else if (n == "project.godot") { r_projects->push_back(da->get_current_dir()); } n = da->get_next(); } da->list_dir_end(); memdelete(da); } void ProjectManager::_scan_begin(const String &p_base) { print_line("Scanning projects at: " + p_base); List<String> projects; _scan_dir(p_base, &projects); print_line("Found " + itos(projects.size()) + " projects."); for (List<String>::Element *E = projects.front(); E; E = E->next()) { String proj = get_project_key_from_path(E->get()); EditorSettings::get_singleton()->set("projects/" + proj, E->get()); } EditorSettings::get_singleton()->save(); _load_recent_projects(); } void ProjectManager::_scan_projects() { scan_dir->popup_centered_ratio(); } void ProjectManager::_new_project() { npdialog->set_mode(ProjectDialog::MODE_NEW); npdialog->show_dialog(); } void ProjectManager::_import_project() { npdialog->set_mode(ProjectDialog::MODE_IMPORT); npdialog->show_dialog(); } void ProjectManager::_rename_project() { const Set<String> &selected_list = _project_list->get_selected_project_keys(); if (selected_list.size() == 0) { return; } for (Set<String>::Element *E = selected_list.front(); E; E = E->next()) { const String &selected = E->get(); String path = EditorSettings::get_singleton()->get("projects/" + selected); npdialog->set_project_path(path); npdialog->set_mode(ProjectDialog::MODE_RENAME); npdialog->show_dialog(); } } void ProjectManager::_erase_project_confirm() { _project_list->erase_selected_projects(); _update_project_buttons(); } void ProjectManager::_erase_missing_projects_confirm() { _project_list->erase_missing_projects(); _update_project_buttons(); } void ProjectManager::_erase_project() { const Set<String> &selected_list = _project_list->get_selected_project_keys(); if (selected_list.size() == 0) return; String confirm_message; if (selected_list.size() >= 2) { confirm_message = vformat(TTR("Remove %d projects from the list?\nThe project folders' contents won't be modified."), selected_list.size()); } else { confirm_message = TTR("Remove this project from the list?\nThe project folder's contents won't be modified."); } erase_ask->set_text(confirm_message); erase_ask->popup_centered_minsize(); } void ProjectManager::_erase_missing_projects() { erase_missing_ask->set_text(TTR("Remove all missing projects from the list?\nThe project folders' contents won't be modified.")); erase_missing_ask->popup_centered_minsize(); } void ProjectManager::_language_selected(int p_id) { String lang = language_btn->get_item_metadata(p_id); EditorSettings::get_singleton()->set("interface/editor/editor_language", lang); language_btn->set_text(lang); language_btn->set_icon(get_icon("Environment", "EditorIcons")); language_restart_ask->set_text(TTR("Language changed.\nThe interface will update after restarting the editor or project manager.")); language_restart_ask->popup_centered(); } void ProjectManager::_restart_confirm() { List<String> args = OS::get_singleton()->get_cmdline_args(); String exec = OS::get_singleton()->get_executable_path(); OS::ProcessID pid = 0; Error err = OS::get_singleton()->execute(exec, args, false, &pid); ERR_FAIL_COND(err); _dim_window(); get_tree()->quit(); } void ProjectManager::_exit_dialog() { _dim_window(); get_tree()->quit(); } void ProjectManager::_install_project(const String &p_zip_path, const String &p_title) { npdialog->set_mode(ProjectDialog::MODE_INSTALL); npdialog->set_zip_path(p_zip_path); npdialog->set_zip_title(p_title); npdialog->show_dialog(); } void ProjectManager::_files_dropped(PoolStringArray p_files, int p_screen) { Set<String> folders_set; DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); for (int i = 0; i < p_files.size(); i++) { String file = p_files[i]; folders_set.insert(da->dir_exists(file) ? file : file.get_base_dir()); } memdelete(da); if (folders_set.size() > 0) { PoolStringArray folders; for (Set<String>::Element *E = folders_set.front(); E; E = E->next()) { folders.append(E->get()); } bool confirm = true; if (folders.size() == 1) { DirAccess *dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); if (dir->change_dir(folders[0]) == OK) { dir->list_dir_begin(); String file = dir->get_next(); while (confirm && file != String()) { if (!dir->current_is_dir() && file.ends_with("project.godot")) { confirm = false; } file = dir->get_next(); } dir->list_dir_end(); } memdelete(dir); } if (confirm) { multi_scan_ask->get_ok()->disconnect("pressed", this, "_scan_multiple_folders"); multi_scan_ask->get_ok()->connect("pressed", this, "_scan_multiple_folders", varray(folders)); multi_scan_ask->set_text( vformat(TTR("Are you sure to scan %s folders for existing Godot projects?\nThis could take a while."), folders.size())); multi_scan_ask->popup_centered_minsize(); } else { _scan_multiple_folders(folders); } } } void ProjectManager::_scan_multiple_folders(PoolStringArray p_files) { for (int i = 0; i < p_files.size(); i++) { _scan_begin(p_files.get(i)); } } void ProjectManager::_on_order_option_changed() { _project_list->set_order_option(project_order_filter->get_filter_option()); _project_list->sort_projects(); } void ProjectManager::_on_filter_option_changed() { _project_list->set_search_term(project_filter->get_search_term()); _project_list->sort_projects(); // Select the first visible project in the list. // This makes it possible to open a project without ever touching the mouse, // as the search field is automatically focused on startup. _project_list->select_first_visible_project(); _update_project_buttons(); } void ProjectManager::_bind_methods() { ClassDB::bind_method("_open_selected_projects_ask", &ProjectManager::_open_selected_projects_ask); ClassDB::bind_method("_open_selected_projects", &ProjectManager::_open_selected_projects); ClassDB::bind_method(D_METHOD("_global_menu_action"), &ProjectManager::_global_menu_action, DEFVAL(Variant())); ClassDB::bind_method("_run_project", &ProjectManager::_run_project); ClassDB::bind_method("_run_project_confirm", &ProjectManager::_run_project_confirm); ClassDB::bind_method("_scan_projects", &ProjectManager::_scan_projects); ClassDB::bind_method("_scan_begin", &ProjectManager::_scan_begin); ClassDB::bind_method("_import_project", &ProjectManager::_import_project); ClassDB::bind_method("_new_project", &ProjectManager::_new_project); ClassDB::bind_method("_rename_project", &ProjectManager::_rename_project); ClassDB::bind_method("_erase_project", &ProjectManager::_erase_project); ClassDB::bind_method("_erase_missing_projects", &ProjectManager::_erase_missing_projects); ClassDB::bind_method("_erase_project_confirm", &ProjectManager::_erase_project_confirm); ClassDB::bind_method("_erase_missing_projects_confirm", &ProjectManager::_erase_missing_projects_confirm); ClassDB::bind_method("_language_selected", &ProjectManager::_language_selected); ClassDB::bind_method("_restart_confirm", &ProjectManager::_restart_confirm); ClassDB::bind_method("_exit_dialog", &ProjectManager::_exit_dialog); ClassDB::bind_method("_on_order_option_changed", &ProjectManager::_on_order_option_changed); ClassDB::bind_method("_on_filter_option_changed", &ProjectManager::_on_filter_option_changed); ClassDB::bind_method("_on_projects_updated", &ProjectManager::_on_projects_updated); ClassDB::bind_method("_on_project_created", &ProjectManager::_on_project_created); ClassDB::bind_method("_unhandled_input", &ProjectManager::_unhandled_input); ClassDB::bind_method("_install_project", &ProjectManager::_install_project); ClassDB::bind_method("_files_dropped", &ProjectManager::_files_dropped); ClassDB::bind_method("_open_asset_library", &ProjectManager::_open_asset_library); ClassDB::bind_method("_confirm_update_settings", &ProjectManager::_confirm_update_settings); ClassDB::bind_method("_update_project_buttons", &ProjectManager::_update_project_buttons); ClassDB::bind_method(D_METHOD("_scan_multiple_folders", "files"), &ProjectManager::_scan_multiple_folders); } void ProjectManager::_open_asset_library() { asset_library->disable_community_support(); tabs->set_current_tab(1); } ProjectManager::ProjectManager() { // load settings if (!EditorSettings::get_singleton()) EditorSettings::create(); EditorSettings::get_singleton()->set_optimize_save(false); //just write settings as they came { int display_scale = EditorSettings::get_singleton()->get("interface/editor/display_scale"); float custom_display_scale = EditorSettings::get_singleton()->get("interface/editor/custom_display_scale"); switch (display_scale) { case 0: { // Try applying a suitable display scale automatically const int screen = OS::get_singleton()->get_current_screen(); editor_set_scale(OS::get_singleton()->get_screen_dpi(screen) >= 192 && OS::get_singleton()->get_screen_size(screen).x > 2000 ? 2.0 : 1.0); } break; case 1: editor_set_scale(0.75); break; case 2: editor_set_scale(1.0); break; case 3: editor_set_scale(1.25); break; case 4: editor_set_scale(1.5); break; case 5: editor_set_scale(1.75); break; case 6: editor_set_scale(2.0); break; default: { editor_set_scale(custom_display_scale); } break; } // Define a minimum window size to prevent UI elements from overlapping or being cut off OS::get_singleton()->set_min_window_size(Size2(750, 420) * EDSCALE); #ifndef OSX_ENABLED // The macOS platform implementation uses its own hiDPI window resizing code // TODO: Resize windows on hiDPI displays on Windows and Linux and remove the line below OS::get_singleton()->set_window_size(OS::get_singleton()->get_window_size() * MAX(1, EDSCALE)); #endif } FileDialog::set_default_show_hidden_files(EditorSettings::get_singleton()->get("filesystem/file_dialog/show_hidden_files")); set_anchors_and_margins_preset(Control::PRESET_WIDE); set_theme(create_custom_theme()); gui_base = memnew(Control); add_child(gui_base); gui_base->set_anchors_and_margins_preset(Control::PRESET_WIDE); Panel *panel = memnew(Panel); gui_base->add_child(panel); panel->set_anchors_and_margins_preset(Control::PRESET_WIDE); panel->add_style_override("panel", gui_base->get_stylebox("Background", "EditorStyles")); VBoxContainer *vb = memnew(VBoxContainer); panel->add_child(vb); vb->set_anchors_and_margins_preset(Control::PRESET_WIDE, Control::PRESET_MODE_MINSIZE, 8 * EDSCALE); String cp; cp += 0xA9; OS::get_singleton()->set_window_title(VERSION_NAME + String(" - ") + TTR("Project Manager") + " - " + cp + " 2007-2020 Juan Linietsky, Ariel Manzur & Godot Contributors"); Control *center_box = memnew(Control); center_box->set_v_size_flags(SIZE_EXPAND_FILL); vb->add_child(center_box); tabs = memnew(TabContainer); center_box->add_child(tabs); tabs->set_anchors_and_margins_preset(Control::PRESET_WIDE); tabs->set_tab_align(TabContainer::ALIGN_LEFT); HBoxContainer *tree_hb = memnew(HBoxContainer); projects_hb = tree_hb; projects_hb->set_name(TTR("Projects")); tabs->add_child(tree_hb); VBoxContainer *search_tree_vb = memnew(VBoxContainer); tree_hb->add_child(search_tree_vb); search_tree_vb->set_h_size_flags(SIZE_EXPAND_FILL); HBoxContainer *sort_filters = memnew(HBoxContainer); Label *sort_label = memnew(Label); sort_label->set_text(TTR("Sort:")); sort_filters->add_child(sort_label); Vector<String> sort_filter_titles; sort_filter_titles.push_back(TTR("Name")); sort_filter_titles.push_back(TTR("Path")); sort_filter_titles.push_back(TTR("Last Modified")); project_order_filter = memnew(ProjectListFilter); project_order_filter->add_filter_option(); project_order_filter->_setup_filters(sort_filter_titles); project_order_filter->set_filter_size(150); sort_filters->add_child(project_order_filter); project_order_filter->connect("filter_changed", this, "_on_order_option_changed"); project_order_filter->set_custom_minimum_size(Size2(180, 10) * EDSCALE); int projects_sorting_order = (int)EditorSettings::get_singleton()->get("project_manager/sorting_order"); project_order_filter->set_filter_option((ProjectListFilter::FilterOption)projects_sorting_order); sort_filters->add_spacer(true); project_filter = memnew(ProjectListFilter); project_filter->add_search_box(); project_filter->connect("filter_changed", this, "_on_filter_option_changed"); project_filter->set_custom_minimum_size(Size2(280, 10) * EDSCALE); sort_filters->add_child(project_filter); search_tree_vb->add_child(sort_filters); PanelContainer *pc = memnew(PanelContainer); pc->add_style_override("panel", gui_base->get_stylebox("bg", "Tree")); search_tree_vb->add_child(pc); pc->set_v_size_flags(SIZE_EXPAND_FILL); _project_list = memnew(ProjectList); _project_list->connect(ProjectList::SIGNAL_SELECTION_CHANGED, this, "_update_project_buttons"); _project_list->connect(ProjectList::SIGNAL_PROJECT_ASK_OPEN, this, "_open_selected_projects_ask"); pc->add_child(_project_list); _project_list->set_enable_h_scroll(false); VBoxContainer *tree_vb = memnew(VBoxContainer); tree_hb->add_child(tree_vb); Button *open = memnew(Button); open->set_text(TTR("Edit")); tree_vb->add_child(open); open->connect("pressed", this, "_open_selected_projects_ask"); open_btn = open; Button *run = memnew(Button); run->set_text(TTR("Run")); tree_vb->add_child(run); run->connect("pressed", this, "_run_project"); run_btn = run; tree_vb->add_child(memnew(HSeparator)); Button *scan = memnew(Button); scan->set_text(TTR("Scan")); tree_vb->add_child(scan); scan->connect("pressed", this, "_scan_projects"); tree_vb->add_child(memnew(HSeparator)); scan_dir = memnew(FileDialog); scan_dir->set_access(FileDialog::ACCESS_FILESYSTEM); scan_dir->set_mode(FileDialog::MODE_OPEN_DIR); scan_dir->set_title(TTR("Select a Folder to Scan")); // must be after mode or it's overridden scan_dir->set_current_dir(EditorSettings::get_singleton()->get("filesystem/directories/default_project_path")); gui_base->add_child(scan_dir); scan_dir->connect("dir_selected", this, "_scan_begin"); Button *create = memnew(Button); create->set_text(TTR("New Project")); tree_vb->add_child(create); create->connect("pressed", this, "_new_project"); Button *import = memnew(Button); import->set_text(TTR("Import")); tree_vb->add_child(import); import->connect("pressed", this, "_import_project"); Button *rename = memnew(Button); rename->set_text(TTR("Rename")); tree_vb->add_child(rename); rename->connect("pressed", this, "_rename_project"); rename_btn = rename; Button *erase = memnew(Button); erase->set_text(TTR("Remove")); tree_vb->add_child(erase); erase->connect("pressed", this, "_erase_project"); erase_btn = erase; Button *erase_missing = memnew(Button); erase_missing->set_text(TTR("Remove Missing")); tree_vb->add_child(erase_missing); erase_missing->connect("pressed", this, "_erase_missing_projects"); erase_missing_btn = erase_missing; tree_vb->add_spacer(); if (StreamPeerSSL::is_available()) { asset_library = memnew(EditorAssetLibrary(true)); asset_library->set_name(TTR("Templates")); tabs->add_child(asset_library); asset_library->connect("install_asset", this, "_install_project"); } else { WARN_PRINT("Asset Library not available, as it requires SSL to work."); } HBoxContainer *settings_hb = memnew(HBoxContainer); settings_hb->set_alignment(BoxContainer::ALIGN_END); settings_hb->set_h_grow_direction(Control::GROW_DIRECTION_BEGIN); Label *version_label = memnew(Label); String hash = String(VERSION_HASH); if (hash.length() != 0) { hash = "." + hash.left(9); } version_label->set_text("v" VERSION_FULL_BUILD "" + hash); // Fade out the version label to be less prominent, but still readable version_label->set_self_modulate(Color(1, 1, 1, 0.6)); version_label->set_align(Label::ALIGN_CENTER); settings_hb->add_child(version_label); language_btn = memnew(OptionButton); language_btn->set_flat(true); language_btn->set_focus_mode(Control::FOCUS_NONE); Vector<String> editor_languages; List<PropertyInfo> editor_settings_properties; EditorSettings::get_singleton()->get_property_list(&editor_settings_properties); for (List<PropertyInfo>::Element *E = editor_settings_properties.front(); E; E = E->next()) { PropertyInfo &pi = E->get(); if (pi.name == "interface/editor/editor_language") { editor_languages = pi.hint_string.split(","); } } String current_lang = EditorSettings::get_singleton()->get("interface/editor/editor_language"); for (int i = 0; i < editor_languages.size(); i++) { String lang = editor_languages[i]; String lang_name = TranslationServer::get_singleton()->get_locale_name(lang); language_btn->add_item(lang_name + " [" + lang + "]", i); language_btn->set_item_metadata(i, lang); if (current_lang == lang) { language_btn->select(i); language_btn->set_text(lang); } } language_btn->set_icon(get_icon("Environment", "EditorIcons")); settings_hb->add_child(language_btn); language_btn->connect("item_selected", this, "_language_selected"); center_box->add_child(settings_hb); settings_hb->set_anchors_and_margins_preset(Control::PRESET_TOP_RIGHT); ////////////////////////////////////////////////////////////// language_restart_ask = memnew(ConfirmationDialog); language_restart_ask->get_ok()->set_text(TTR("Restart Now")); language_restart_ask->get_ok()->connect("pressed", this, "_restart_confirm"); language_restart_ask->get_cancel()->set_text(TTR("Continue")); gui_base->add_child(language_restart_ask); erase_missing_ask = memnew(ConfirmationDialog); erase_missing_ask->get_ok()->set_text(TTR("Remove All")); erase_missing_ask->get_ok()->connect("pressed", this, "_erase_missing_projects_confirm"); gui_base->add_child(erase_missing_ask); erase_ask = memnew(ConfirmationDialog); erase_ask->get_ok()->set_text(TTR("Remove")); erase_ask->get_ok()->connect("pressed", this, "_erase_project_confirm"); gui_base->add_child(erase_ask); multi_open_ask = memnew(ConfirmationDialog); multi_open_ask->get_ok()->set_text(TTR("Edit")); multi_open_ask->get_ok()->connect("pressed", this, "_open_selected_projects"); gui_base->add_child(multi_open_ask); multi_run_ask = memnew(ConfirmationDialog); multi_run_ask->get_ok()->set_text(TTR("Run")); multi_run_ask->get_ok()->connect("pressed", this, "_run_project_confirm"); gui_base->add_child(multi_run_ask); multi_scan_ask = memnew(ConfirmationDialog); multi_scan_ask->get_ok()->set_text(TTR("Scan")); gui_base->add_child(multi_scan_ask); ask_update_settings = memnew(ConfirmationDialog); ask_update_settings->get_ok()->connect("pressed", this, "_confirm_update_settings"); gui_base->add_child(ask_update_settings); OS::get_singleton()->set_low_processor_usage_mode(true); npdialog = memnew(ProjectDialog); gui_base->add_child(npdialog); npdialog->connect("projects_updated", this, "_on_projects_updated"); npdialog->connect("project_created", this, "_on_project_created"); _load_recent_projects(); if (EditorSettings::get_singleton()->get("filesystem/directories/autoscan_project_path")) { _scan_begin(EditorSettings::get_singleton()->get("filesystem/directories/autoscan_project_path")); } SceneTree::get_singleton()->connect("files_dropped", this, "_files_dropped"); SceneTree::get_singleton()->connect("global_menu_action", this, "_global_menu_action"); run_error_diag = memnew(AcceptDialog); gui_base->add_child(run_error_diag); run_error_diag->set_title(TTR("Can't run project")); dialog_error = memnew(AcceptDialog); gui_base->add_child(dialog_error); open_templates = memnew(ConfirmationDialog); open_templates->set_text(TTR("You currently don't have any projects.\nWould you like to explore official example projects in the Asset Library?")); open_templates->get_ok()->set_text(TTR("Open Asset Library")); open_templates->connect("confirmed", this, "_open_asset_library"); add_child(open_templates); } ProjectManager::~ProjectManager() { if (EditorSettings::get_singleton()) EditorSettings::destroy(); } void ProjectListFilter::_setup_filters(Vector<String> options) { filter_option->clear(); for (int i = 0; i < options.size(); i++) filter_option->add_item(options[i]); } void ProjectListFilter::_search_text_changed(const String &p_newtext) { emit_signal("filter_changed"); } String ProjectListFilter::get_search_term() { return search_box->get_text().strip_edges(); } ProjectListFilter::FilterOption ProjectListFilter::get_filter_option() { return _current_filter; } void ProjectListFilter::set_filter_option(FilterOption option) { filter_option->select((int)option); _filter_option_selected(0); } void ProjectListFilter::_filter_option_selected(int p_idx) { FilterOption selected = (FilterOption)(filter_option->get_selected()); if (_current_filter != selected) { _current_filter = selected; emit_signal("filter_changed"); } } void ProjectListFilter::_notification(int p_what) { if (p_what == NOTIFICATION_ENTER_TREE && has_search_box) { search_box->set_right_icon(get_icon("Search", "EditorIcons")); search_box->set_clear_button_enabled(true); } } void ProjectListFilter::_bind_methods() { ClassDB::bind_method(D_METHOD("_search_text_changed"), &ProjectListFilter::_search_text_changed); ClassDB::bind_method(D_METHOD("_filter_option_selected"), &ProjectListFilter::_filter_option_selected); ADD_SIGNAL(MethodInfo("filter_changed")); } void ProjectListFilter::add_filter_option() { filter_option = memnew(OptionButton); filter_option->set_clip_text(true); filter_option->connect("item_selected", this, "_filter_option_selected"); add_child(filter_option); } void ProjectListFilter::add_search_box() { search_box = memnew(LineEdit); search_box->set_placeholder(TTR("Search")); search_box->connect("text_changed", this, "_search_text_changed"); search_box->set_h_size_flags(SIZE_EXPAND_FILL); add_child(search_box); has_search_box = true; } void ProjectListFilter::set_filter_size(int h_size) { filter_option->set_custom_minimum_size(Size2(h_size * EDSCALE, 10 * EDSCALE)); } ProjectListFilter::ProjectListFilter() { _current_filter = FILTER_NAME; has_search_box = false; } void ProjectListFilter::clear() { if (has_search_box) { search_box->clear(); } } Disable the GLES2 renderer option in the Project Manager It will be re-enabled once the GLES2 renderer is refactored to work in Godot 4.0. /*************************************************************************/ /* project_manager.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "project_manager.h" #include "core/io/config_file.h" #include "core/io/resource_saver.h" #include "core/io/stream_peer_ssl.h" #include "core/io/zip_io.h" #include "core/os/dir_access.h" #include "core/os/file_access.h" #include "core/os/keyboard.h" #include "core/os/os.h" #include "core/translation.h" #include "core/version.h" #include "core/version_hash.gen.h" #include "editor_scale.h" #include "editor_settings.h" #include "editor_themes.h" #include "scene/gui/center_container.h" #include "scene/gui/line_edit.h" #include "scene/gui/margin_container.h" #include "scene/gui/panel_container.h" #include "scene/gui/separator.h" #include "scene/gui/texture_rect.h" #include "scene/gui/tool_button.h" static inline String get_project_key_from_path(const String &dir) { return dir.replace("/", "::"); } class ProjectDialog : public ConfirmationDialog { GDCLASS(ProjectDialog, ConfirmationDialog); public: enum Mode { MODE_NEW, MODE_IMPORT, MODE_INSTALL, MODE_RENAME }; private: enum MessageType { MESSAGE_ERROR, MESSAGE_WARNING, MESSAGE_SUCCESS }; enum InputType { PROJECT_PATH, INSTALL_PATH }; Mode mode; Button *browse; Button *install_browse; Button *create_dir; Container *name_container; Container *path_container; Container *install_path_container; Container *rasterizer_container; Ref<ButtonGroup> rasterizer_button_group; Label *msg; LineEdit *project_path; LineEdit *project_name; LineEdit *install_path; TextureRect *status_rect; TextureRect *install_status_rect; FileDialog *fdialog; FileDialog *fdialog_install; String zip_path; String zip_title; AcceptDialog *dialog_error; String fav_dir; String created_folder_path; void set_message(const String &p_msg, MessageType p_type = MESSAGE_SUCCESS, InputType input_type = PROJECT_PATH) { msg->set_text(p_msg); Ref<Texture2D> current_path_icon = status_rect->get_texture(); Ref<Texture2D> current_install_icon = install_status_rect->get_texture(); Ref<Texture2D> new_icon; switch (p_type) { case MESSAGE_ERROR: { msg->add_color_override("font_color", get_color("error_color", "Editor")); msg->set_modulate(Color(1, 1, 1, 1)); new_icon = get_icon("StatusError", "EditorIcons"); } break; case MESSAGE_WARNING: { msg->add_color_override("font_color", get_color("warning_color", "Editor")); msg->set_modulate(Color(1, 1, 1, 1)); new_icon = get_icon("StatusWarning", "EditorIcons"); } break; case MESSAGE_SUCCESS: { msg->set_modulate(Color(1, 1, 1, 0)); new_icon = get_icon("StatusSuccess", "EditorIcons"); } break; } if (current_path_icon != new_icon && input_type == PROJECT_PATH) { status_rect->set_texture(new_icon); } else if (current_install_icon != new_icon && input_type == INSTALL_PATH) { install_status_rect->set_texture(new_icon); } set_size(Size2(500, 0) * EDSCALE); } String _test_path() { DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); String valid_path, valid_install_path; if (d->change_dir(project_path->get_text()) == OK) { valid_path = project_path->get_text(); } else if (d->change_dir(project_path->get_text().strip_edges()) == OK) { valid_path = project_path->get_text().strip_edges(); } else if (project_path->get_text().ends_with(".zip")) { if (d->file_exists(project_path->get_text())) { valid_path = project_path->get_text(); } } else if (project_path->get_text().strip_edges().ends_with(".zip")) { if (d->file_exists(project_path->get_text().strip_edges())) { valid_path = project_path->get_text().strip_edges(); } } if (valid_path == "") { set_message(TTR("The path specified doesn't exist."), MESSAGE_ERROR); memdelete(d); get_ok()->set_disabled(true); return ""; } if (mode == MODE_IMPORT && valid_path.ends_with(".zip")) { if (d->change_dir(install_path->get_text()) == OK) { valid_install_path = install_path->get_text(); } else if (d->change_dir(install_path->get_text().strip_edges()) == OK) { valid_install_path = install_path->get_text().strip_edges(); } if (valid_install_path == "") { set_message(TTR("The path specified doesn't exist."), MESSAGE_ERROR, INSTALL_PATH); memdelete(d); get_ok()->set_disabled(true); return ""; } } if (mode == MODE_IMPORT || mode == MODE_RENAME) { if (valid_path != "" && !d->file_exists("project.godot")) { if (valid_path.ends_with(".zip")) { FileAccess *src_f = NULL; zlib_filefunc_def io = zipio_create_io_from_file(&src_f); unzFile pkg = unzOpen2(valid_path.utf8().get_data(), &io); if (!pkg) { set_message(TTR("Error opening package file (it's not in ZIP format)."), MESSAGE_ERROR); memdelete(d); get_ok()->set_disabled(true); unzClose(pkg); return ""; } int ret = unzGoToFirstFile(pkg); while (ret == UNZ_OK) { unz_file_info info; char fname[16384]; ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0); if (String(fname).ends_with("project.godot")) { break; } ret = unzGoToNextFile(pkg); } if (ret == UNZ_END_OF_LIST_OF_FILE) { set_message(TTR("Invalid \".zip\" project file; it doesn't contain a \"project.godot\" file."), MESSAGE_ERROR); memdelete(d); get_ok()->set_disabled(true); unzClose(pkg); return ""; } unzClose(pkg); // check if the specified install folder is empty, even though this is not an error, it is good to check here d->list_dir_begin(); bool is_empty = true; String n = d->get_next(); while (n != String()) { if (!n.begins_with(".")) { // Allow `.`, `..` (reserved current/parent folder names) // and hidden files/folders to be present. // For instance, this lets users initialize a Git repository // and still be able to create a project in the directory afterwards. is_empty = false; break; } n = d->get_next(); } d->list_dir_end(); if (!is_empty) { set_message(TTR("Please choose an empty folder."), MESSAGE_WARNING, INSTALL_PATH); memdelete(d); get_ok()->set_disabled(true); return ""; } } else { set_message(TTR("Please choose a \"project.godot\" or \".zip\" file."), MESSAGE_ERROR); memdelete(d); install_path_container->hide(); get_ok()->set_disabled(true); return ""; } } else if (valid_path.ends_with("zip")) { set_message(TTR("This directory already contains a Godot project."), MESSAGE_ERROR, INSTALL_PATH); memdelete(d); get_ok()->set_disabled(true); return ""; } } else { // check if the specified folder is empty, even though this is not an error, it is good to check here d->list_dir_begin(); bool is_empty = true; String n = d->get_next(); while (n != String()) { if (!n.begins_with(".")) { // Allow `.`, `..` (reserved current/parent folder names) // and hidden files/folders to be present. // For instance, this lets users initialize a Git repository // and still be able to create a project in the directory afterwards. is_empty = false; break; } n = d->get_next(); } d->list_dir_end(); if (!is_empty) { set_message(TTR("Please choose an empty folder."), MESSAGE_ERROR); memdelete(d); get_ok()->set_disabled(true); return ""; } } set_message(""); set_message("", MESSAGE_SUCCESS, INSTALL_PATH); memdelete(d); get_ok()->set_disabled(false); return valid_path; } void _path_text_changed(const String &p_path) { String sp = _test_path(); if (sp != "") { // If the project name is empty or default, infer the project name from the selected folder name if (project_name->get_text() == "" || project_name->get_text() == TTR("New Game Project")) { sp = sp.replace("\\", "/"); int lidx = sp.find_last("/"); if (lidx != -1) { sp = sp.substr(lidx + 1, sp.length()).capitalize(); } if (sp == "" && mode == MODE_IMPORT) sp = TTR("Imported Project"); project_name->set_text(sp); _text_changed(sp); } } if (created_folder_path != "" && created_folder_path != p_path) { _remove_created_folder(); } } void _file_selected(const String &p_path) { String p = p_path; if (mode == MODE_IMPORT) { if (p.ends_with("project.godot")) { p = p.get_base_dir(); install_path_container->hide(); get_ok()->set_disabled(false); } else if (p.ends_with(".zip")) { install_path->set_text(p.get_base_dir()); install_path_container->show(); get_ok()->set_disabled(false); } else { set_message(TTR("Please choose a \"project.godot\" or \".zip\" file."), MESSAGE_ERROR); get_ok()->set_disabled(true); return; } } String sp = p.simplify_path(); project_path->set_text(sp); _path_text_changed(sp); if (p.ends_with(".zip")) { install_path->call_deferred("grab_focus"); } else { get_ok()->call_deferred("grab_focus"); } } void _path_selected(const String &p_path) { String sp = p_path.simplify_path(); project_path->set_text(sp); _path_text_changed(sp); get_ok()->call_deferred("grab_focus"); } void _install_path_selected(const String &p_path) { String sp = p_path.simplify_path(); install_path->set_text(sp); _path_text_changed(sp); get_ok()->call_deferred("grab_focus"); } void _browse_path() { fdialog->set_current_dir(project_path->get_text()); if (mode == MODE_IMPORT) { fdialog->set_mode(FileDialog::MODE_OPEN_FILE); fdialog->clear_filters(); fdialog->add_filter(vformat("project.godot ; %s %s", VERSION_NAME, TTR("Project"))); fdialog->add_filter("*.zip ; " + TTR("ZIP File")); } else { fdialog->set_mode(FileDialog::MODE_OPEN_DIR); } fdialog->popup_centered_ratio(); } void _browse_install_path() { fdialog_install->set_current_dir(install_path->get_text()); fdialog_install->set_mode(FileDialog::MODE_OPEN_DIR); fdialog_install->popup_centered_ratio(); } void _create_folder() { if (project_name->get_text() == "" || created_folder_path != "" || project_name->get_text().ends_with(".") || project_name->get_text().ends_with(" ")) { set_message(TTR("Invalid Project Name."), MESSAGE_WARNING); return; } DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); if (d->change_dir(project_path->get_text()) == OK) { if (!d->dir_exists(project_name->get_text())) { if (d->make_dir(project_name->get_text()) == OK) { d->change_dir(project_name->get_text()); String dir_str = d->get_current_dir(); project_path->set_text(dir_str); _path_text_changed(dir_str); created_folder_path = d->get_current_dir(); create_dir->set_disabled(true); } else { dialog_error->set_text(TTR("Couldn't create folder.")); dialog_error->popup_centered_minsize(); } } else { dialog_error->set_text(TTR("There is already a folder in this path with the specified name.")); dialog_error->popup_centered_minsize(); } } memdelete(d); } void _text_changed(const String &p_text) { if (mode != MODE_NEW) return; _test_path(); if (p_text == "") set_message(TTR("It would be a good idea to name your project."), MESSAGE_WARNING); } void ok_pressed() { String dir = project_path->get_text(); if (mode == MODE_RENAME) { String dir2 = _test_path(); if (dir2 == "") { set_message(TTR("Invalid project path (changed anything?)."), MESSAGE_ERROR); return; } ProjectSettings *current = memnew(ProjectSettings); int err = current->setup(dir2, ""); if (err != OK) { set_message(vformat(TTR("Couldn't load project.godot in project path (error %d). It may be missing or corrupted."), err), MESSAGE_ERROR); } else { ProjectSettings::CustomMap edited_settings; edited_settings["application/config/name"] = project_name->get_text(); if (current->save_custom(dir2.plus_file("project.godot"), edited_settings, Vector<String>(), true) != OK) { set_message(TTR("Couldn't edit project.godot in project path."), MESSAGE_ERROR); } } hide(); emit_signal("projects_updated"); } else { if (mode == MODE_IMPORT) { if (project_path->get_text().ends_with(".zip")) { mode = MODE_INSTALL; ok_pressed(); return; } } else { if (mode == MODE_NEW) { ProjectSettings::CustomMap initial_settings; if (rasterizer_button_group->get_pressed_button()->get_meta("driver_name") == "GLES3") { initial_settings["rendering/quality/driver/driver_name"] = "GLES3"; } else { initial_settings["rendering/quality/driver/driver_name"] = "GLES2"; initial_settings["rendering/vram_compression/import_etc2"] = false; initial_settings["rendering/vram_compression/import_etc"] = true; } initial_settings["application/config/name"] = project_name->get_text(); initial_settings["application/config/icon"] = "res://icon.png"; initial_settings["rendering/environment/default_environment"] = "res://default_env.tres"; if (ProjectSettings::get_singleton()->save_custom(dir.plus_file("project.godot"), initial_settings, Vector<String>(), false) != OK) { set_message(TTR("Couldn't create project.godot in project path."), MESSAGE_ERROR); } else { ResourceSaver::save(dir.plus_file("icon.png"), get_icon("DefaultProjectIcon", "EditorIcons")); FileAccess *f = FileAccess::open(dir.plus_file("default_env.tres"), FileAccess::WRITE); if (!f) { set_message(TTR("Couldn't create project.godot in project path."), MESSAGE_ERROR); } else { f->store_line("[gd_resource type=\"Environment\" load_steps=2 format=2]"); f->store_line("[sub_resource type=\"ProceduralSky\" id=1]"); f->store_line("[resource]"); f->store_line("background_mode = 2"); f->store_line("background_sky = SubResource( 1 )"); memdelete(f); } } } else if (mode == MODE_INSTALL) { if (project_path->get_text().ends_with(".zip")) { dir = install_path->get_text(); zip_path = project_path->get_text(); } FileAccess *src_f = NULL; zlib_filefunc_def io = zipio_create_io_from_file(&src_f); unzFile pkg = unzOpen2(zip_path.utf8().get_data(), &io); if (!pkg) { dialog_error->set_text(TTR("Error opening package file, not in ZIP format.")); dialog_error->popup_centered_minsize(); return; } int ret = unzGoToFirstFile(pkg); Vector<String> failed_files; int idx = 0; while (ret == UNZ_OK) { //get filename unz_file_info info; char fname[16384]; ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0); String path = fname; int depth = 1; //stuff from github comes with tag bool skip = false; while (depth > 0) { int pp = path.find("/"); if (pp == -1) { skip = true; break; } path = path.substr(pp + 1, path.length()); depth--; } if (skip || path == String()) { // } else if (path.ends_with("/")) { // a dir path = path.substr(0, path.length() - 1); DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); da->make_dir(dir.plus_file(path)); memdelete(da); } else { Vector<uint8_t> data; data.resize(info.uncompressed_size); //read unzOpenCurrentFile(pkg); unzReadCurrentFile(pkg, data.ptrw(), data.size()); unzCloseCurrentFile(pkg); FileAccess *f = FileAccess::open(dir.plus_file(path), FileAccess::WRITE); if (f) { f->store_buffer(data.ptr(), data.size()); memdelete(f); } else { failed_files.push_back(path); } } idx++; ret = unzGoToNextFile(pkg); } unzClose(pkg); if (failed_files.size()) { String msg = TTR("The following files failed extraction from package:") + "\n\n"; for (int i = 0; i < failed_files.size(); i++) { if (i > 15) { msg += "\nAnd " + itos(failed_files.size() - i) + " more files."; break; } msg += failed_files[i] + "\n"; } dialog_error->set_text(msg); dialog_error->popup_centered_minsize(); } else if (!project_path->get_text().ends_with(".zip")) { dialog_error->set_text(TTR("Package installed successfully!")); dialog_error->popup_centered_minsize(); } } } dir = dir.replace("\\", "/"); if (dir.ends_with("/")) dir = dir.substr(0, dir.length() - 1); String proj = get_project_key_from_path(dir); EditorSettings::get_singleton()->set("projects/" + proj, dir); EditorSettings::get_singleton()->save(); hide(); emit_signal("project_created", dir); } } void _remove_created_folder() { if (created_folder_path != "") { DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); d->remove(created_folder_path); memdelete(d); create_dir->set_disabled(false); created_folder_path = ""; } } void cancel_pressed() { _remove_created_folder(); project_path->clear(); _path_text_changed(""); project_name->clear(); _text_changed(""); if (status_rect->get_texture() == get_icon("StatusError", "EditorIcons")) msg->show(); if (install_status_rect->get_texture() == get_icon("StatusError", "EditorIcons")) msg->show(); } void _notification(int p_what) { if (p_what == MainLoop::NOTIFICATION_WM_QUIT_REQUEST) _remove_created_folder(); } protected: static void _bind_methods() { ClassDB::bind_method("_browse_path", &ProjectDialog::_browse_path); ClassDB::bind_method("_create_folder", &ProjectDialog::_create_folder); ClassDB::bind_method("_text_changed", &ProjectDialog::_text_changed); ClassDB::bind_method("_path_text_changed", &ProjectDialog::_path_text_changed); ClassDB::bind_method("_path_selected", &ProjectDialog::_path_selected); ClassDB::bind_method("_file_selected", &ProjectDialog::_file_selected); ClassDB::bind_method("_install_path_selected", &ProjectDialog::_install_path_selected); ClassDB::bind_method("_browse_install_path", &ProjectDialog::_browse_install_path); ADD_SIGNAL(MethodInfo("project_created")); ADD_SIGNAL(MethodInfo("projects_updated")); } public: void set_zip_path(const String &p_path) { zip_path = p_path; } void set_zip_title(const String &p_title) { zip_title = p_title; } void set_mode(Mode p_mode) { mode = p_mode; } void set_project_path(const String &p_path) { project_path->set_text(p_path); } void show_dialog() { if (mode == MODE_RENAME) { project_path->set_editable(false); browse->hide(); install_browse->hide(); set_title(TTR("Rename Project")); get_ok()->set_text(TTR("Rename")); name_container->show(); status_rect->hide(); msg->hide(); install_path_container->hide(); install_status_rect->hide(); rasterizer_container->hide(); get_ok()->set_disabled(false); ProjectSettings *current = memnew(ProjectSettings); int err = current->setup(project_path->get_text(), ""); if (err != OK) { set_message(vformat(TTR("Couldn't load project.godot in project path (error %d). It may be missing or corrupted."), err), MESSAGE_ERROR); status_rect->show(); msg->show(); get_ok()->set_disabled(true); } else if (current->has_setting("application/config/name")) { String proj = current->get("application/config/name"); project_name->set_text(proj); _text_changed(proj); } project_name->call_deferred("grab_focus"); create_dir->hide(); } else { fav_dir = EditorSettings::get_singleton()->get("filesystem/directories/default_project_path"); if (fav_dir != "") { project_path->set_text(fav_dir); fdialog->set_current_dir(fav_dir); } else { DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); project_path->set_text(d->get_current_dir()); fdialog->set_current_dir(d->get_current_dir()); memdelete(d); } String proj = TTR("New Game Project"); project_name->set_text(proj); _text_changed(proj); project_path->set_editable(true); browse->set_disabled(false); browse->show(); install_browse->set_disabled(false); install_browse->show(); create_dir->show(); status_rect->show(); install_status_rect->show(); msg->show(); if (mode == MODE_IMPORT) { set_title(TTR("Import Existing Project")); get_ok()->set_text(TTR("Import & Edit")); name_container->hide(); install_path_container->hide(); rasterizer_container->hide(); project_path->grab_focus(); } else if (mode == MODE_NEW) { set_title(TTR("Create New Project")); get_ok()->set_text(TTR("Create & Edit")); name_container->show(); install_path_container->hide(); rasterizer_container->show(); project_name->call_deferred("grab_focus"); project_name->call_deferred("select_all"); } else if (mode == MODE_INSTALL) { set_title(TTR("Install Project:") + " " + zip_title); get_ok()->set_text(TTR("Install & Edit")); project_name->set_text(zip_title); name_container->show(); install_path_container->hide(); rasterizer_container->hide(); project_path->grab_focus(); } _test_path(); } popup_centered_minsize(Size2(500, 0) * EDSCALE); } ProjectDialog() { VBoxContainer *vb = memnew(VBoxContainer); add_child(vb); name_container = memnew(VBoxContainer); vb->add_child(name_container); Label *l = memnew(Label); l->set_text(TTR("Project Name:")); name_container->add_child(l); HBoxContainer *pnhb = memnew(HBoxContainer); name_container->add_child(pnhb); project_name = memnew(LineEdit); project_name->set_h_size_flags(SIZE_EXPAND_FILL); pnhb->add_child(project_name); create_dir = memnew(Button); pnhb->add_child(create_dir); create_dir->set_text(TTR("Create Folder")); create_dir->connect("pressed", this, "_create_folder"); path_container = memnew(VBoxContainer); vb->add_child(path_container); l = memnew(Label); l->set_text(TTR("Project Path:")); path_container->add_child(l); HBoxContainer *pphb = memnew(HBoxContainer); path_container->add_child(pphb); project_path = memnew(LineEdit); project_path->set_h_size_flags(SIZE_EXPAND_FILL); pphb->add_child(project_path); install_path_container = memnew(VBoxContainer); vb->add_child(install_path_container); l = memnew(Label); l->set_text(TTR("Project Installation Path:")); install_path_container->add_child(l); HBoxContainer *iphb = memnew(HBoxContainer); install_path_container->add_child(iphb); install_path = memnew(LineEdit); install_path->set_h_size_flags(SIZE_EXPAND_FILL); iphb->add_child(install_path); // status icon status_rect = memnew(TextureRect); status_rect->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED); pphb->add_child(status_rect); browse = memnew(Button); browse->set_text(TTR("Browse")); browse->connect("pressed", this, "_browse_path"); pphb->add_child(browse); // install status icon install_status_rect = memnew(TextureRect); install_status_rect->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED); iphb->add_child(install_status_rect); install_browse = memnew(Button); install_browse->set_text(TTR("Browse")); install_browse->connect("pressed", this, "_browse_install_path"); iphb->add_child(install_browse); msg = memnew(Label); msg->set_align(Label::ALIGN_CENTER); vb->add_child(msg); // rasterizer selection rasterizer_container = memnew(VBoxContainer); vb->add_child(rasterizer_container); l = memnew(Label); l->set_text(TTR("Renderer:")); rasterizer_container->add_child(l); Container *rshb = memnew(HBoxContainer); rasterizer_container->add_child(rshb); rasterizer_button_group.instance(); Container *rvb = memnew(VBoxContainer); rvb->set_h_size_flags(SIZE_EXPAND_FILL); rshb->add_child(rvb); Button *rs_button = memnew(CheckBox); rs_button->set_button_group(rasterizer_button_group); rs_button->set_text(TTR("Vulkan")); rs_button->set_meta("driver_name", "GLES3"); rs_button->set_pressed(true); rvb->add_child(rs_button); l = memnew(Label); l->set_text(TTR("- Higher visual quality\n- More accurate API, which produces very fast code\n- Some features not implemented yet — work in progress\n- Incompatible with older hardware\n- Not recommended for web and mobile games")); l->set_modulate(Color(1, 1, 1, 0.7)); rvb->add_child(l); rshb->add_child(memnew(VSeparator)); const String gles2_unsupported_tooltip = TTR("The GLES2 renderer is currently unavailable, as it needs to be reworked for Godot 4.0.\nUse Godot 3.2 if you need GLES2 support."); rvb = memnew(VBoxContainer); rvb->set_h_size_flags(SIZE_EXPAND_FILL); rshb->add_child(rvb); rs_button = memnew(CheckBox); rs_button->set_button_group(rasterizer_button_group); rs_button->set_text(TTR("OpenGL ES 2.0 (currently unavailable)")); rs_button->set_meta("driver_name", "GLES2"); rs_button->set_disabled(true); rs_button->set_tooltip(gles2_unsupported_tooltip); rvb->add_child(rs_button); l = memnew(Label); l->set_text(TTR("- Lower visual quality\n- Some features not available\n- Works on most hardware\n- Recommended for web and mobile games")); l->set_modulate(Color(1, 1, 1, 0.7)); // Also set the tooltip on the label so it appears when hovering either the checkbox or label. l->set_tooltip(gles2_unsupported_tooltip); // Required for the tooltip to show. l->set_mouse_filter(MOUSE_FILTER_STOP); rvb->add_child(l); l = memnew(Label); l->set_text(TTR("The renderer can be changed later, but scenes may need to be adjusted.")); // Add some extra spacing to separate it from the list above and the buttons below. l->set_custom_minimum_size(Size2(0, 40) * EDSCALE); l->set_align(Label::ALIGN_CENTER); l->set_valign(Label::VALIGN_CENTER); l->set_modulate(Color(1, 1, 1, 0.7)); rasterizer_container->add_child(l); fdialog = memnew(FileDialog); fdialog->set_access(FileDialog::ACCESS_FILESYSTEM); fdialog_install = memnew(FileDialog); fdialog_install->set_access(FileDialog::ACCESS_FILESYSTEM); add_child(fdialog); add_child(fdialog_install); project_name->connect("text_changed", this, "_text_changed"); project_path->connect("text_changed", this, "_path_text_changed"); install_path->connect("text_changed", this, "_path_text_changed"); fdialog->connect("dir_selected", this, "_path_selected"); fdialog->connect("file_selected", this, "_file_selected"); fdialog_install->connect("dir_selected", this, "_install_path_selected"); fdialog_install->connect("file_selected", this, "_install_path_selected"); set_hide_on_ok(false); mode = MODE_NEW; dialog_error = memnew(AcceptDialog); add_child(dialog_error); } }; class ProjectListItemControl : public HBoxContainer { GDCLASS(ProjectListItemControl, HBoxContainer) public: TextureButton *favorite_button; TextureRect *icon; bool icon_needs_reload; bool hover; ProjectListItemControl() { favorite_button = NULL; icon = NULL; icon_needs_reload = true; hover = false; } void set_is_favorite(bool fav) { favorite_button->set_modulate(fav ? Color(1, 1, 1, 1) : Color(1, 1, 1, 0.2)); } void _notification(int p_what) { switch (p_what) { case NOTIFICATION_MOUSE_ENTER: { hover = true; update(); } break; case NOTIFICATION_MOUSE_EXIT: { hover = false; update(); } break; case NOTIFICATION_DRAW: { if (hover) { draw_style_box(get_stylebox("hover", "Tree"), Rect2(Point2(), get_size() - Size2(10, 0) * EDSCALE)); } } break; } } }; class ProjectList : public ScrollContainer { GDCLASS(ProjectList, ScrollContainer) public: static const char *SIGNAL_SELECTION_CHANGED; static const char *SIGNAL_PROJECT_ASK_OPEN; enum MenuOptions { GLOBAL_NEW_WINDOW, GLOBAL_OPEN_PROJECT }; // Can often be passed by copy struct Item { String project_key; String project_name; String description; String path; String icon; String main_scene; uint64_t last_modified; bool favorite; bool grayed; bool missing; int version; ProjectListItemControl *control; Item() {} Item(const String &p_project, const String &p_name, const String &p_description, const String &p_path, const String &p_icon, const String &p_main_scene, uint64_t p_last_modified, bool p_favorite, bool p_grayed, bool p_missing, int p_version) { project_key = p_project; project_name = p_name; description = p_description; path = p_path; icon = p_icon; main_scene = p_main_scene; last_modified = p_last_modified; favorite = p_favorite; grayed = p_grayed; missing = p_missing; version = p_version; control = NULL; } _FORCE_INLINE_ bool operator==(const Item &l) const { return project_key == l.project_key; } }; ProjectList(); ~ProjectList(); void update_dock_menu(); void load_projects(); void set_search_term(String p_search_term); void set_order_option(ProjectListFilter::FilterOption p_option); void sort_projects(); int get_project_count() const; void select_project(int p_index); void select_first_visible_project(); void erase_selected_projects(); Vector<Item> get_selected_projects() const; const Set<String> &get_selected_project_keys() const; void ensure_project_visible(int p_index); int get_single_selected_index() const; bool is_any_project_missing() const; void erase_missing_projects(); int refresh_project(const String &dir_path); private: static void _bind_methods(); void _notification(int p_what); void _panel_draw(Node *p_hb); void _panel_input(const Ref<InputEvent> &p_ev, Node *p_hb); void _favorite_pressed(Node *p_hb); void _show_project(const String &p_path); void select_range(int p_begin, int p_end); void toggle_select(int p_index); void create_project_item_control(int p_index); void remove_project(int p_index, bool p_update_settings); void update_icons_async(); void load_project_icon(int p_index); static void load_project_data(const String &p_property_key, Item &p_item, bool p_favorite); String _search_term; ProjectListFilter::FilterOption _order_option; Set<String> _selected_project_keys; String _last_clicked; // Project key VBoxContainer *_scroll_children; int _icon_load_index; Vector<Item> _projects; }; struct ProjectListComparator { ProjectListFilter::FilterOption order_option; // operator< _FORCE_INLINE_ bool operator()(const ProjectList::Item &a, const ProjectList::Item &b) const { if (a.favorite && !b.favorite) { return true; } if (b.favorite && !a.favorite) { return false; } switch (order_option) { case ProjectListFilter::FILTER_PATH: return a.project_key < b.project_key; case ProjectListFilter::FILTER_MODIFIED: return a.last_modified > b.last_modified; default: return a.project_name < b.project_name; } } }; ProjectList::ProjectList() { _order_option = ProjectListFilter::FILTER_MODIFIED; _scroll_children = memnew(VBoxContainer); _scroll_children->set_h_size_flags(SIZE_EXPAND_FILL); add_child(_scroll_children); _icon_load_index = 0; } ProjectList::~ProjectList() { } void ProjectList::update_icons_async() { _icon_load_index = 0; set_process(true); } void ProjectList::_notification(int p_what) { if (p_what == NOTIFICATION_PROCESS) { // Load icons as a coroutine to speed up launch when you have hundreds of projects if (_icon_load_index < _projects.size()) { Item &item = _projects.write[_icon_load_index]; if (item.control->icon_needs_reload) { load_project_icon(_icon_load_index); } _icon_load_index++; } else { set_process(false); } } } void ProjectList::load_project_icon(int p_index) { Item &item = _projects.write[p_index]; Ref<Texture2D> default_icon = get_icon("DefaultProjectIcon", "EditorIcons"); Ref<Texture2D> icon; if (item.icon != "") { Ref<Image> img; img.instance(); Error err = img->load(item.icon.replace_first("res://", item.path + "/")); if (err == OK) { img->resize(default_icon->get_width(), default_icon->get_height(), Image::INTERPOLATE_LANCZOS); Ref<ImageTexture> it = memnew(ImageTexture); it->create_from_image(img); icon = it; } } if (icon.is_null()) { icon = default_icon; } item.control->icon->set_texture(icon); item.control->icon_needs_reload = false; } void ProjectList::load_project_data(const String &p_property_key, Item &p_item, bool p_favorite) { String path = EditorSettings::get_singleton()->get(p_property_key); String conf = path.plus_file("project.godot"); bool grayed = false; bool missing = false; Ref<ConfigFile> cf = memnew(ConfigFile); Error cf_err = cf->load(conf); int config_version = 0; String project_name = TTR("Unnamed Project"); if (cf_err == OK) { String cf_project_name = static_cast<String>(cf->get_value("application", "config/name", "")); if (cf_project_name != "") project_name = cf_project_name.xml_unescape(); config_version = (int)cf->get_value("", "config_version", 0); } if (config_version > ProjectSettings::CONFIG_VERSION) { // Comes from an incompatible (more recent) Godot version, grey it out grayed = true; } String description = cf->get_value("application", "config/description", ""); String icon = cf->get_value("application", "config/icon", ""); String main_scene = cf->get_value("application", "run/main_scene", ""); uint64_t last_modified = 0; if (FileAccess::exists(conf)) { last_modified = FileAccess::get_modified_time(conf); String fscache = path.plus_file(".fscache"); if (FileAccess::exists(fscache)) { uint64_t cache_modified = FileAccess::get_modified_time(fscache); if (cache_modified > last_modified) last_modified = cache_modified; } } else { grayed = true; missing = true; print_line("Project is missing: " + conf); } String project_key = p_property_key.get_slice("/", 1); p_item = Item(project_key, project_name, description, path, icon, main_scene, last_modified, p_favorite, grayed, missing, config_version); } void ProjectList::load_projects() { // This is a full, hard reload of the list. Don't call this unless really required, it's expensive. // If you have 150 projects, it may read through 150 files on your disk at once + load 150 icons. // Clear whole list for (int i = 0; i < _projects.size(); ++i) { Item &project = _projects.write[i]; CRASH_COND(project.control == NULL); memdelete(project.control); // Why not queue_free()? } _projects.clear(); _last_clicked = ""; _selected_project_keys.clear(); // Load data // TODO Would be nice to change how projects and favourites are stored... it complicates things a bit. // Use a dictionary associating project path to metadata (like is_favorite). List<PropertyInfo> properties; EditorSettings::get_singleton()->get_property_list(&properties); Set<String> favorites; // Find favourites... for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { String property_key = E->get().name; if (property_key.begins_with("favorite_projects/")) { favorites.insert(property_key); } } for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { // This is actually something like "projects/C:::Documents::Godot::Projects::MyGame" String property_key = E->get().name; if (!property_key.begins_with("projects/")) continue; String project_key = property_key.get_slice("/", 1); bool favorite = favorites.has("favorite_projects/" + project_key); Item item; load_project_data(property_key, item, favorite); _projects.push_back(item); } // Create controls for (int i = 0; i < _projects.size(); ++i) { create_project_item_control(i); } sort_projects(); set_v_scroll(0); update_icons_async(); update_dock_menu(); } void ProjectList::update_dock_menu() { OS::get_singleton()->global_menu_clear("_dock"); int favs_added = 0; int total_added = 0; for (int i = 0; i < _projects.size(); ++i) { if (!_projects[i].grayed && !_projects[i].missing) { if (_projects[i].favorite) { favs_added++; } else { if (favs_added != 0) { OS::get_singleton()->global_menu_add_separator("_dock"); } favs_added = 0; } OS::get_singleton()->global_menu_add_item("_dock", _projects[i].project_name + " ( " + _projects[i].path + " )", GLOBAL_OPEN_PROJECT, Variant(_projects[i].path.plus_file("project.godot"))); total_added++; } } if (total_added != 0) { OS::get_singleton()->global_menu_add_separator("_dock"); } OS::get_singleton()->global_menu_add_item("_dock", TTR("New Window"), GLOBAL_NEW_WINDOW, Variant()); } void ProjectList::create_project_item_control(int p_index) { // Will be added last in the list, so make sure indexes match ERR_FAIL_COND(p_index != _scroll_children->get_child_count()); Item &item = _projects.write[p_index]; ERR_FAIL_COND(item.control != NULL); // Already created Ref<Texture2D> favorite_icon = get_icon("Favorites", "EditorIcons"); Color font_color = get_color("font_color", "Tree"); ProjectListItemControl *hb = memnew(ProjectListItemControl); hb->connect("draw", this, "_panel_draw", varray(hb)); hb->connect("gui_input", this, "_panel_input", varray(hb)); hb->add_constant_override("separation", 10 * EDSCALE); hb->set_tooltip(item.description); VBoxContainer *favorite_box = memnew(VBoxContainer); favorite_box->set_name("FavoriteBox"); TextureButton *favorite = memnew(TextureButton); favorite->set_name("FavoriteButton"); favorite->set_normal_texture(favorite_icon); // This makes the project's "hover" style display correctly when hovering the favorite icon favorite->set_mouse_filter(MOUSE_FILTER_PASS); favorite->connect("pressed", this, "_favorite_pressed", varray(hb)); favorite_box->add_child(favorite); favorite_box->set_alignment(BoxContainer::ALIGN_CENTER); hb->add_child(favorite_box); hb->favorite_button = favorite; hb->set_is_favorite(item.favorite); TextureRect *tf = memnew(TextureRect); // The project icon may not be loaded by the time the control is displayed, // so use a loading placeholder. tf->set_texture(get_icon("ProjectIconLoading", "EditorIcons")); tf->set_v_size_flags(SIZE_SHRINK_CENTER); if (item.missing) { tf->set_modulate(Color(1, 1, 1, 0.5)); } hb->add_child(tf); hb->icon = tf; VBoxContainer *vb = memnew(VBoxContainer); if (item.grayed) vb->set_modulate(Color(1, 1, 1, 0.5)); vb->set_h_size_flags(SIZE_EXPAND_FILL); hb->add_child(vb); Control *ec = memnew(Control); ec->set_custom_minimum_size(Size2(0, 1)); ec->set_mouse_filter(MOUSE_FILTER_PASS); vb->add_child(ec); Label *title = memnew(Label(!item.missing ? item.project_name : TTR("Missing Project"))); title->add_font_override("font", get_font("title", "EditorFonts")); title->add_color_override("font_color", font_color); title->set_clip_text(true); vb->add_child(title); HBoxContainer *path_hb = memnew(HBoxContainer); path_hb->set_h_size_flags(SIZE_EXPAND_FILL); vb->add_child(path_hb); Button *show = memnew(Button); // Display a folder icon if the project directory can be opened, or a "broken file" icon if it can't show->set_icon(get_icon(!item.missing ? "Load" : "FileBroken", "EditorIcons")); show->set_flat(true); if (!item.grayed) { // Don't make the icon less prominent if the parent is already grayed out show->set_modulate(Color(1, 1, 1, 0.5)); } path_hb->add_child(show); if (!item.missing) { show->connect("pressed", this, "_show_project", varray(item.path)); show->set_tooltip(TTR("Show in File Manager")); } else { show->set_tooltip(TTR("Error: Project is missing on the filesystem.")); } Label *fpath = memnew(Label(item.path)); path_hb->add_child(fpath); fpath->set_h_size_flags(SIZE_EXPAND_FILL); fpath->set_modulate(Color(1, 1, 1, 0.5)); fpath->add_color_override("font_color", font_color); fpath->set_clip_text(true); _scroll_children->add_child(hb); item.control = hb; } void ProjectList::set_search_term(String p_search_term) { _search_term = p_search_term; } void ProjectList::set_order_option(ProjectListFilter::FilterOption p_option) { if (_order_option != p_option) { _order_option = p_option; EditorSettings::get_singleton()->set("project_manager/sorting_order", (int)_order_option); EditorSettings::get_singleton()->save(); } } void ProjectList::sort_projects() { SortArray<Item, ProjectListComparator> sorter; sorter.compare.order_option = _order_option; sorter.sort(_projects.ptrw(), _projects.size()); for (int i = 0; i < _projects.size(); ++i) { Item &item = _projects.write[i]; bool visible = true; if (_search_term != "") { String search_path; if (_search_term.find("/") != -1) { // Search path will match the whole path search_path = item.path; } else { // Search path will only match the last path component to make searching more strict search_path = item.path.get_file(); } // When searching, display projects whose name or path contain the search term visible = item.project_name.findn(_search_term) != -1 || search_path.findn(_search_term) != -1; } item.control->set_visible(visible); } for (int i = 0; i < _projects.size(); ++i) { Item &item = _projects.write[i]; item.control->get_parent()->move_child(item.control, i); } // Rewind the coroutine because order of projects changed update_icons_async(); update_dock_menu(); } const Set<String> &ProjectList::get_selected_project_keys() const { // Faster if that's all you need return _selected_project_keys; } Vector<ProjectList::Item> ProjectList::get_selected_projects() const { Vector<Item> items; if (_selected_project_keys.size() == 0) { return items; } items.resize(_selected_project_keys.size()); int j = 0; for (int i = 0; i < _projects.size(); ++i) { const Item &item = _projects[i]; if (_selected_project_keys.has(item.project_key)) { items.write[j++] = item; } } ERR_FAIL_COND_V(j != items.size(), items); return items; } void ProjectList::ensure_project_visible(int p_index) { const Item &item = _projects[p_index]; int item_top = item.control->get_position().y; int item_bottom = item.control->get_position().y + item.control->get_size().y; if (item_top < get_v_scroll()) { set_v_scroll(item_top); } else if (item_bottom > get_v_scroll() + get_size().y) { set_v_scroll(item_bottom - get_size().y); } } int ProjectList::get_single_selected_index() const { if (_selected_project_keys.size() == 0) { // Default selection return 0; } String key; if (_selected_project_keys.size() == 1) { // Only one selected key = _selected_project_keys.front()->get(); } else { // Multiple selected, consider the last clicked one as "main" key = _last_clicked; } for (int i = 0; i < _projects.size(); ++i) { if (_projects[i].project_key == key) { return i; } } return 0; } void ProjectList::remove_project(int p_index, bool p_update_settings) { const Item item = _projects[p_index]; // Take a copy _selected_project_keys.erase(item.project_key); if (_last_clicked == item.project_key) { _last_clicked = ""; } memdelete(item.control); _projects.remove(p_index); if (p_update_settings) { EditorSettings::get_singleton()->erase("projects/" + item.project_key); EditorSettings::get_singleton()->erase("favorite_projects/" + item.project_key); // Not actually saving the file, in case you are doing more changes to settings } update_dock_menu(); } bool ProjectList::is_any_project_missing() const { for (int i = 0; i < _projects.size(); ++i) { if (_projects[i].missing) { return true; } } return false; } void ProjectList::erase_missing_projects() { if (_projects.empty()) { return; } int deleted_count = 0; int remaining_count = 0; for (int i = 0; i < _projects.size(); ++i) { const Item &item = _projects[i]; if (item.missing) { remove_project(i, true); --i; ++deleted_count; } else { ++remaining_count; } } print_line("Removed " + itos(deleted_count) + " projects from the list, remaining " + itos(remaining_count) + " projects"); EditorSettings::get_singleton()->save(); } int ProjectList::refresh_project(const String &dir_path) { // Reads editor settings and reloads information about a specific project. // If it wasn't loaded and should be in the list, it is added (i.e new project). // If it isn't in the list anymore, it is removed. // If it is in the list but doesn't exist anymore, it is marked as missing. String project_key = get_project_key_from_path(dir_path); // Read project manager settings bool is_favourite = false; bool should_be_in_list = false; String property_key = "projects/" + project_key; { List<PropertyInfo> properties; EditorSettings::get_singleton()->get_property_list(&properties); String favorite_property_key = "favorite_projects/" + project_key; bool found = false; for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { String prop = E->get().name; if (!found && prop == property_key) { found = true; } else if (!is_favourite && prop == favorite_property_key) { is_favourite = true; } } should_be_in_list = found; } bool was_selected = _selected_project_keys.has(project_key); // Remove item in any case for (int i = 0; i < _projects.size(); ++i) { const Item &existing_item = _projects[i]; if (existing_item.path == dir_path) { remove_project(i, false); break; } } int index = -1; if (should_be_in_list) { // Recreate it with updated info Item item; load_project_data(property_key, item, is_favourite); _projects.push_back(item); create_project_item_control(_projects.size() - 1); sort_projects(); for (int i = 0; i < _projects.size(); ++i) { if (_projects[i].project_key == project_key) { if (was_selected) { select_project(i); ensure_project_visible(i); } load_project_icon(i); index = i; break; } } } return index; } int ProjectList::get_project_count() const { return _projects.size(); } void ProjectList::select_project(int p_index) { Vector<Item> previous_selected_items = get_selected_projects(); _selected_project_keys.clear(); for (int i = 0; i < previous_selected_items.size(); ++i) { previous_selected_items[i].control->update(); } toggle_select(p_index); } void ProjectList::select_first_visible_project() { bool found = false; for (int i = 0; i < _projects.size(); i++) { if (_projects[i].control->is_visible()) { select_project(i); found = true; break; } } if (!found) { // Deselect all projects if there are no visible projects in the list. _selected_project_keys.clear(); } } inline void sort(int &a, int &b) { if (a > b) { int temp = a; a = b; b = temp; } } void ProjectList::select_range(int p_begin, int p_end) { sort(p_begin, p_end); select_project(p_begin); for (int i = p_begin + 1; i <= p_end; ++i) { toggle_select(i); } } void ProjectList::toggle_select(int p_index) { Item &item = _projects.write[p_index]; if (_selected_project_keys.has(item.project_key)) { _selected_project_keys.erase(item.project_key); } else { _selected_project_keys.insert(item.project_key); } item.control->update(); } void ProjectList::erase_selected_projects() { if (_selected_project_keys.size() == 0) { return; } for (int i = 0; i < _projects.size(); ++i) { Item &item = _projects.write[i]; if (_selected_project_keys.has(item.project_key) && item.control->is_visible()) { EditorSettings::get_singleton()->erase("projects/" + item.project_key); EditorSettings::get_singleton()->erase("favorite_projects/" + item.project_key); memdelete(item.control); _projects.remove(i); --i; } } EditorSettings::get_singleton()->save(); _selected_project_keys.clear(); _last_clicked = ""; update_dock_menu(); } // Draws selected project highlight void ProjectList::_panel_draw(Node *p_hb) { Control *hb = Object::cast_to<Control>(p_hb); hb->draw_line(Point2(0, hb->get_size().y + 1), Point2(hb->get_size().x - 10, hb->get_size().y + 1), get_color("guide_color", "Tree")); String key = _projects[p_hb->get_index()].project_key; if (_selected_project_keys.has(key)) { hb->draw_style_box(get_stylebox("selected", "Tree"), Rect2(Point2(), hb->get_size() - Size2(10, 0) * EDSCALE)); } } // Input for each item in the list void ProjectList::_panel_input(const Ref<InputEvent> &p_ev, Node *p_hb) { Ref<InputEventMouseButton> mb = p_ev; int clicked_index = p_hb->get_index(); const Item &clicked_project = _projects[clicked_index]; if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) { if (mb->get_shift() && _selected_project_keys.size() > 0 && _last_clicked != "" && clicked_project.project_key != _last_clicked) { int anchor_index = -1; for (int i = 0; i < _projects.size(); ++i) { const Item &p = _projects[i]; if (p.project_key == _last_clicked) { anchor_index = p.control->get_index(); break; } } CRASH_COND(anchor_index == -1); select_range(anchor_index, clicked_index); } else if (mb->get_control()) { toggle_select(clicked_index); } else { _last_clicked = clicked_project.project_key; select_project(clicked_index); } emit_signal(SIGNAL_SELECTION_CHANGED); if (!mb->get_control() && mb->is_doubleclick()) { emit_signal(SIGNAL_PROJECT_ASK_OPEN); } } } void ProjectList::_favorite_pressed(Node *p_hb) { ProjectListItemControl *control = Object::cast_to<ProjectListItemControl>(p_hb); int index = control->get_index(); Item item = _projects.write[index]; // Take copy item.favorite = !item.favorite; if (item.favorite) { EditorSettings::get_singleton()->set("favorite_projects/" + item.project_key, item.path); } else { EditorSettings::get_singleton()->erase("favorite_projects/" + item.project_key); } EditorSettings::get_singleton()->save(); _projects.write[index] = item; control->set_is_favorite(item.favorite); sort_projects(); if (item.favorite) { for (int i = 0; i < _projects.size(); ++i) { if (_projects[i].project_key == item.project_key) { ensure_project_visible(i); break; } } } update_dock_menu(); } void ProjectList::_show_project(const String &p_path) { OS::get_singleton()->shell_open(String("file://") + p_path); } const char *ProjectList::SIGNAL_SELECTION_CHANGED = "selection_changed"; const char *ProjectList::SIGNAL_PROJECT_ASK_OPEN = "project_ask_open"; void ProjectList::_bind_methods() { ClassDB::bind_method("_panel_draw", &ProjectList::_panel_draw); ClassDB::bind_method("_panel_input", &ProjectList::_panel_input); ClassDB::bind_method("_favorite_pressed", &ProjectList::_favorite_pressed); ClassDB::bind_method("_show_project", &ProjectList::_show_project); ADD_SIGNAL(MethodInfo(SIGNAL_SELECTION_CHANGED)); ADD_SIGNAL(MethodInfo(SIGNAL_PROJECT_ASK_OPEN)); } void ProjectManager::_notification(int p_what) { switch (p_what) { case NOTIFICATION_ENTER_TREE: { Engine::get_singleton()->set_editor_hint(false); } break; case NOTIFICATION_RESIZED: { if (open_templates->is_visible()) { open_templates->popup_centered_minsize(); } } break; case NOTIFICATION_READY: { if (_project_list->get_project_count() == 0 && StreamPeerSSL::is_available()) open_templates->popup_centered_minsize(); if (_project_list->get_project_count() >= 1) { // Focus on the search box immediately to allow the user // to search without having to reach for their mouse project_filter->search_box->grab_focus(); } } break; case NOTIFICATION_VISIBILITY_CHANGED: { set_process_unhandled_input(is_visible_in_tree()); } break; case NOTIFICATION_WM_QUIT_REQUEST: { _dim_window(); } break; } } void ProjectManager::_dim_window() { // This method must be called before calling `get_tree()->quit()`. // Otherwise, its effect won't be visible // Dim the project manager window while it's quitting to make it clearer that it's busy. // No transition is applied, as the effect needs to be visible immediately float c = 0.5f; Color dim_color = Color(c, c, c); gui_base->set_modulate(dim_color); } void ProjectManager::_update_project_buttons() { Vector<ProjectList::Item> selected_projects = _project_list->get_selected_projects(); bool empty_selection = selected_projects.empty(); bool is_missing_project_selected = false; for (int i = 0; i < selected_projects.size(); ++i) { if (selected_projects[i].missing) { is_missing_project_selected = true; break; } } erase_btn->set_disabled(empty_selection); open_btn->set_disabled(empty_selection || is_missing_project_selected); rename_btn->set_disabled(empty_selection || is_missing_project_selected); run_btn->set_disabled(empty_selection || is_missing_project_selected); erase_missing_btn->set_visible(_project_list->is_any_project_missing()); } void ProjectManager::_unhandled_input(const Ref<InputEvent> &p_ev) { Ref<InputEventKey> k = p_ev; if (k.is_valid()) { if (!k->is_pressed()) { return; } // Pressing Command + Q quits the Project Manager // This is handled by the platform implementation on macOS, // so only define the shortcut on other platforms #ifndef OSX_ENABLED if (k->get_scancode_with_modifiers() == (KEY_MASK_CMD | KEY_Q)) { _dim_window(); get_tree()->quit(); } #endif if (tabs->get_current_tab() != 0) return; bool scancode_handled = true; switch (k->get_scancode()) { case KEY_ENTER: { _open_selected_projects_ask(); } break; case KEY_DELETE: { _erase_project(); } break; case KEY_HOME: { if (_project_list->get_project_count() > 0) { _project_list->select_project(0); _update_project_buttons(); } } break; case KEY_END: { if (_project_list->get_project_count() > 0) { _project_list->select_project(_project_list->get_project_count() - 1); _update_project_buttons(); } } break; case KEY_UP: { if (k->get_shift()) break; int index = _project_list->get_single_selected_index(); if (index > 0) { _project_list->select_project(index - 1); _project_list->ensure_project_visible(index - 1); _update_project_buttons(); } break; } case KEY_DOWN: { if (k->get_shift()) break; int index = _project_list->get_single_selected_index(); if (index + 1 < _project_list->get_project_count()) { _project_list->select_project(index + 1); _project_list->ensure_project_visible(index + 1); _update_project_buttons(); } } break; case KEY_F: { if (k->get_command()) this->project_filter->search_box->grab_focus(); else scancode_handled = false; } break; default: { scancode_handled = false; } break; } if (scancode_handled) { accept_event(); } } } void ProjectManager::_load_recent_projects() { _project_list->set_order_option(project_order_filter->get_filter_option()); _project_list->set_search_term(project_filter->get_search_term()); _project_list->load_projects(); _update_project_buttons(); tabs->set_current_tab(0); } void ProjectManager::_on_projects_updated() { Vector<ProjectList::Item> selected_projects = _project_list->get_selected_projects(); int index = 0; for (int i = 0; i < selected_projects.size(); ++i) { index = _project_list->refresh_project(selected_projects[i].path); } if (index != -1) { _project_list->ensure_project_visible(index); } _project_list->update_dock_menu(); } void ProjectManager::_on_project_created(const String &dir) { project_filter->clear(); int i = _project_list->refresh_project(dir); _project_list->select_project(i); _project_list->ensure_project_visible(i); _open_selected_projects_ask(); _project_list->update_dock_menu(); } void ProjectManager::_confirm_update_settings() { _open_selected_projects(); } void ProjectManager::_global_menu_action(const Variant &p_id, const Variant &p_meta) { int id = (int)p_id; if (id == ProjectList::GLOBAL_NEW_WINDOW) { List<String> args; args.push_back("-p"); String exec = OS::get_singleton()->get_executable_path(); OS::ProcessID pid = 0; OS::get_singleton()->execute(exec, args, false, &pid); } else if (id == ProjectList::GLOBAL_OPEN_PROJECT) { String conf = (String)p_meta; if (conf != String()) { List<String> args; args.push_back(conf); String exec = OS::get_singleton()->get_executable_path(); OS::ProcessID pid = 0; OS::get_singleton()->execute(exec, args, false, &pid); } } } void ProjectManager::_open_selected_projects() { const Set<String> &selected_list = _project_list->get_selected_project_keys(); for (const Set<String>::Element *E = selected_list.front(); E; E = E->next()) { const String &selected = E->get(); String path = EditorSettings::get_singleton()->get("projects/" + selected); String conf = path.plus_file("project.godot"); if (!FileAccess::exists(conf)) { dialog_error->set_text(vformat(TTR("Can't open project at '%s'."), path)); dialog_error->popup_centered_minsize(); return; } print_line("Editing project: " + path + " (" + selected + ")"); List<String> args; args.push_back("--path"); args.push_back(path); args.push_back("--editor"); if (OS::get_singleton()->is_disable_crash_handler()) { args.push_back("--disable-crash-handler"); } String exec = OS::get_singleton()->get_executable_path(); OS::ProcessID pid = 0; Error err = OS::get_singleton()->execute(exec, args, false, &pid); ERR_FAIL_COND(err); } _dim_window(); get_tree()->quit(); } void ProjectManager::_open_selected_projects_ask() { const Set<String> &selected_list = _project_list->get_selected_project_keys(); if (selected_list.size() < 1) { return; } if (selected_list.size() > 1) { multi_open_ask->set_text(TTR("Are you sure to open more than one project?")); multi_open_ask->popup_centered_minsize(); return; } ProjectList::Item project = _project_list->get_selected_projects()[0]; if (project.missing) { return; } // Update the project settings or don't open String conf = project.path.plus_file("project.godot"); int config_version = project.version; // Check if the config_version property was empty or 0 if (config_version == 0) { ask_update_settings->set_text(vformat(TTR("The following project settings file does not specify the version of Godot through which it was created.\n\n%s\n\nIf you proceed with opening it, it will be converted to Godot's current configuration file format.\nWarning: You won't be able to open the project with previous versions of the engine anymore."), conf)); ask_update_settings->popup_centered_minsize(); return; } // Check if we need to convert project settings from an earlier engine version if (config_version < ProjectSettings::CONFIG_VERSION) { ask_update_settings->set_text(vformat(TTR("The following project settings file was generated by an older engine version, and needs to be converted for this version:\n\n%s\n\nDo you want to convert it?\nWarning: You won't be able to open the project with previous versions of the engine anymore."), conf)); ask_update_settings->popup_centered_minsize(); return; } // Check if the file was generated by a newer, incompatible engine version if (config_version > ProjectSettings::CONFIG_VERSION) { dialog_error->set_text(vformat(TTR("Can't open project at '%s'.") + "\n" + TTR("The project settings were created by a newer engine version, whose settings are not compatible with this version."), project.path)); dialog_error->popup_centered_minsize(); return; } // Open if the project is up-to-date _open_selected_projects(); } void ProjectManager::_run_project_confirm() { Vector<ProjectList::Item> selected_list = _project_list->get_selected_projects(); for (int i = 0; i < selected_list.size(); ++i) { const String &selected_main = selected_list[i].main_scene; if (selected_main == "") { run_error_diag->set_text(TTR("Can't run project: no main scene defined.\nPlease edit the project and set the main scene in the Project Settings under the \"Application\" category.")); run_error_diag->popup_centered(); return; } const String &selected = selected_list[i].project_key; String path = EditorSettings::get_singleton()->get("projects/" + selected); if (!DirAccess::exists(path + "/.import")) { run_error_diag->set_text(TTR("Can't run project: Assets need to be imported.\nPlease edit the project to trigger the initial import.")); run_error_diag->popup_centered(); return; } print_line("Running project: " + path + " (" + selected + ")"); List<String> args; args.push_back("--path"); args.push_back(path); if (OS::get_singleton()->is_disable_crash_handler()) { args.push_back("--disable-crash-handler"); } String exec = OS::get_singleton()->get_executable_path(); OS::ProcessID pid = 0; Error err = OS::get_singleton()->execute(exec, args, false, &pid); ERR_FAIL_COND(err); } } // When you press the "Run" button void ProjectManager::_run_project() { const Set<String> &selected_list = _project_list->get_selected_project_keys(); if (selected_list.size() < 1) { return; } if (selected_list.size() > 1) { multi_run_ask->set_text(vformat(TTR("Are you sure to run %d projects at once?"), selected_list.size())); multi_run_ask->popup_centered_minsize(); } else { _run_project_confirm(); } } void ProjectManager::_scan_dir(const String &path, List<String> *r_projects) { DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); da->change_dir(path); da->list_dir_begin(); String n = da->get_next(); while (n != String()) { if (da->current_is_dir() && !n.begins_with(".")) { _scan_dir(da->get_current_dir().plus_file(n), r_projects); } else if (n == "project.godot") { r_projects->push_back(da->get_current_dir()); } n = da->get_next(); } da->list_dir_end(); memdelete(da); } void ProjectManager::_scan_begin(const String &p_base) { print_line("Scanning projects at: " + p_base); List<String> projects; _scan_dir(p_base, &projects); print_line("Found " + itos(projects.size()) + " projects."); for (List<String>::Element *E = projects.front(); E; E = E->next()) { String proj = get_project_key_from_path(E->get()); EditorSettings::get_singleton()->set("projects/" + proj, E->get()); } EditorSettings::get_singleton()->save(); _load_recent_projects(); } void ProjectManager::_scan_projects() { scan_dir->popup_centered_ratio(); } void ProjectManager::_new_project() { npdialog->set_mode(ProjectDialog::MODE_NEW); npdialog->show_dialog(); } void ProjectManager::_import_project() { npdialog->set_mode(ProjectDialog::MODE_IMPORT); npdialog->show_dialog(); } void ProjectManager::_rename_project() { const Set<String> &selected_list = _project_list->get_selected_project_keys(); if (selected_list.size() == 0) { return; } for (Set<String>::Element *E = selected_list.front(); E; E = E->next()) { const String &selected = E->get(); String path = EditorSettings::get_singleton()->get("projects/" + selected); npdialog->set_project_path(path); npdialog->set_mode(ProjectDialog::MODE_RENAME); npdialog->show_dialog(); } } void ProjectManager::_erase_project_confirm() { _project_list->erase_selected_projects(); _update_project_buttons(); } void ProjectManager::_erase_missing_projects_confirm() { _project_list->erase_missing_projects(); _update_project_buttons(); } void ProjectManager::_erase_project() { const Set<String> &selected_list = _project_list->get_selected_project_keys(); if (selected_list.size() == 0) return; String confirm_message; if (selected_list.size() >= 2) { confirm_message = vformat(TTR("Remove %d projects from the list?\nThe project folders' contents won't be modified."), selected_list.size()); } else { confirm_message = TTR("Remove this project from the list?\nThe project folder's contents won't be modified."); } erase_ask->set_text(confirm_message); erase_ask->popup_centered_minsize(); } void ProjectManager::_erase_missing_projects() { erase_missing_ask->set_text(TTR("Remove all missing projects from the list?\nThe project folders' contents won't be modified.")); erase_missing_ask->popup_centered_minsize(); } void ProjectManager::_language_selected(int p_id) { String lang = language_btn->get_item_metadata(p_id); EditorSettings::get_singleton()->set("interface/editor/editor_language", lang); language_btn->set_text(lang); language_btn->set_icon(get_icon("Environment", "EditorIcons")); language_restart_ask->set_text(TTR("Language changed.\nThe interface will update after restarting the editor or project manager.")); language_restart_ask->popup_centered(); } void ProjectManager::_restart_confirm() { List<String> args = OS::get_singleton()->get_cmdline_args(); String exec = OS::get_singleton()->get_executable_path(); OS::ProcessID pid = 0; Error err = OS::get_singleton()->execute(exec, args, false, &pid); ERR_FAIL_COND(err); _dim_window(); get_tree()->quit(); } void ProjectManager::_exit_dialog() { _dim_window(); get_tree()->quit(); } void ProjectManager::_install_project(const String &p_zip_path, const String &p_title) { npdialog->set_mode(ProjectDialog::MODE_INSTALL); npdialog->set_zip_path(p_zip_path); npdialog->set_zip_title(p_title); npdialog->show_dialog(); } void ProjectManager::_files_dropped(PoolStringArray p_files, int p_screen) { Set<String> folders_set; DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); for (int i = 0; i < p_files.size(); i++) { String file = p_files[i]; folders_set.insert(da->dir_exists(file) ? file : file.get_base_dir()); } memdelete(da); if (folders_set.size() > 0) { PoolStringArray folders; for (Set<String>::Element *E = folders_set.front(); E; E = E->next()) { folders.append(E->get()); } bool confirm = true; if (folders.size() == 1) { DirAccess *dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); if (dir->change_dir(folders[0]) == OK) { dir->list_dir_begin(); String file = dir->get_next(); while (confirm && file != String()) { if (!dir->current_is_dir() && file.ends_with("project.godot")) { confirm = false; } file = dir->get_next(); } dir->list_dir_end(); } memdelete(dir); } if (confirm) { multi_scan_ask->get_ok()->disconnect("pressed", this, "_scan_multiple_folders"); multi_scan_ask->get_ok()->connect("pressed", this, "_scan_multiple_folders", varray(folders)); multi_scan_ask->set_text( vformat(TTR("Are you sure to scan %s folders for existing Godot projects?\nThis could take a while."), folders.size())); multi_scan_ask->popup_centered_minsize(); } else { _scan_multiple_folders(folders); } } } void ProjectManager::_scan_multiple_folders(PoolStringArray p_files) { for (int i = 0; i < p_files.size(); i++) { _scan_begin(p_files.get(i)); } } void ProjectManager::_on_order_option_changed() { _project_list->set_order_option(project_order_filter->get_filter_option()); _project_list->sort_projects(); } void ProjectManager::_on_filter_option_changed() { _project_list->set_search_term(project_filter->get_search_term()); _project_list->sort_projects(); // Select the first visible project in the list. // This makes it possible to open a project without ever touching the mouse, // as the search field is automatically focused on startup. _project_list->select_first_visible_project(); _update_project_buttons(); } void ProjectManager::_bind_methods() { ClassDB::bind_method("_open_selected_projects_ask", &ProjectManager::_open_selected_projects_ask); ClassDB::bind_method("_open_selected_projects", &ProjectManager::_open_selected_projects); ClassDB::bind_method(D_METHOD("_global_menu_action"), &ProjectManager::_global_menu_action, DEFVAL(Variant())); ClassDB::bind_method("_run_project", &ProjectManager::_run_project); ClassDB::bind_method("_run_project_confirm", &ProjectManager::_run_project_confirm); ClassDB::bind_method("_scan_projects", &ProjectManager::_scan_projects); ClassDB::bind_method("_scan_begin", &ProjectManager::_scan_begin); ClassDB::bind_method("_import_project", &ProjectManager::_import_project); ClassDB::bind_method("_new_project", &ProjectManager::_new_project); ClassDB::bind_method("_rename_project", &ProjectManager::_rename_project); ClassDB::bind_method("_erase_project", &ProjectManager::_erase_project); ClassDB::bind_method("_erase_missing_projects", &ProjectManager::_erase_missing_projects); ClassDB::bind_method("_erase_project_confirm", &ProjectManager::_erase_project_confirm); ClassDB::bind_method("_erase_missing_projects_confirm", &ProjectManager::_erase_missing_projects_confirm); ClassDB::bind_method("_language_selected", &ProjectManager::_language_selected); ClassDB::bind_method("_restart_confirm", &ProjectManager::_restart_confirm); ClassDB::bind_method("_exit_dialog", &ProjectManager::_exit_dialog); ClassDB::bind_method("_on_order_option_changed", &ProjectManager::_on_order_option_changed); ClassDB::bind_method("_on_filter_option_changed", &ProjectManager::_on_filter_option_changed); ClassDB::bind_method("_on_projects_updated", &ProjectManager::_on_projects_updated); ClassDB::bind_method("_on_project_created", &ProjectManager::_on_project_created); ClassDB::bind_method("_unhandled_input", &ProjectManager::_unhandled_input); ClassDB::bind_method("_install_project", &ProjectManager::_install_project); ClassDB::bind_method("_files_dropped", &ProjectManager::_files_dropped); ClassDB::bind_method("_open_asset_library", &ProjectManager::_open_asset_library); ClassDB::bind_method("_confirm_update_settings", &ProjectManager::_confirm_update_settings); ClassDB::bind_method("_update_project_buttons", &ProjectManager::_update_project_buttons); ClassDB::bind_method(D_METHOD("_scan_multiple_folders", "files"), &ProjectManager::_scan_multiple_folders); } void ProjectManager::_open_asset_library() { asset_library->disable_community_support(); tabs->set_current_tab(1); } ProjectManager::ProjectManager() { // load settings if (!EditorSettings::get_singleton()) EditorSettings::create(); EditorSettings::get_singleton()->set_optimize_save(false); //just write settings as they came { int display_scale = EditorSettings::get_singleton()->get("interface/editor/display_scale"); float custom_display_scale = EditorSettings::get_singleton()->get("interface/editor/custom_display_scale"); switch (display_scale) { case 0: { // Try applying a suitable display scale automatically const int screen = OS::get_singleton()->get_current_screen(); editor_set_scale(OS::get_singleton()->get_screen_dpi(screen) >= 192 && OS::get_singleton()->get_screen_size(screen).x > 2000 ? 2.0 : 1.0); } break; case 1: editor_set_scale(0.75); break; case 2: editor_set_scale(1.0); break; case 3: editor_set_scale(1.25); break; case 4: editor_set_scale(1.5); break; case 5: editor_set_scale(1.75); break; case 6: editor_set_scale(2.0); break; default: { editor_set_scale(custom_display_scale); } break; } // Define a minimum window size to prevent UI elements from overlapping or being cut off OS::get_singleton()->set_min_window_size(Size2(750, 420) * EDSCALE); #ifndef OSX_ENABLED // The macOS platform implementation uses its own hiDPI window resizing code // TODO: Resize windows on hiDPI displays on Windows and Linux and remove the line below OS::get_singleton()->set_window_size(OS::get_singleton()->get_window_size() * MAX(1, EDSCALE)); #endif } FileDialog::set_default_show_hidden_files(EditorSettings::get_singleton()->get("filesystem/file_dialog/show_hidden_files")); set_anchors_and_margins_preset(Control::PRESET_WIDE); set_theme(create_custom_theme()); gui_base = memnew(Control); add_child(gui_base); gui_base->set_anchors_and_margins_preset(Control::PRESET_WIDE); Panel *panel = memnew(Panel); gui_base->add_child(panel); panel->set_anchors_and_margins_preset(Control::PRESET_WIDE); panel->add_style_override("panel", gui_base->get_stylebox("Background", "EditorStyles")); VBoxContainer *vb = memnew(VBoxContainer); panel->add_child(vb); vb->set_anchors_and_margins_preset(Control::PRESET_WIDE, Control::PRESET_MODE_MINSIZE, 8 * EDSCALE); String cp; cp += 0xA9; OS::get_singleton()->set_window_title(VERSION_NAME + String(" - ") + TTR("Project Manager") + " - " + cp + " 2007-2020 Juan Linietsky, Ariel Manzur & Godot Contributors"); Control *center_box = memnew(Control); center_box->set_v_size_flags(SIZE_EXPAND_FILL); vb->add_child(center_box); tabs = memnew(TabContainer); center_box->add_child(tabs); tabs->set_anchors_and_margins_preset(Control::PRESET_WIDE); tabs->set_tab_align(TabContainer::ALIGN_LEFT); HBoxContainer *tree_hb = memnew(HBoxContainer); projects_hb = tree_hb; projects_hb->set_name(TTR("Projects")); tabs->add_child(tree_hb); VBoxContainer *search_tree_vb = memnew(VBoxContainer); tree_hb->add_child(search_tree_vb); search_tree_vb->set_h_size_flags(SIZE_EXPAND_FILL); HBoxContainer *sort_filters = memnew(HBoxContainer); Label *sort_label = memnew(Label); sort_label->set_text(TTR("Sort:")); sort_filters->add_child(sort_label); Vector<String> sort_filter_titles; sort_filter_titles.push_back(TTR("Name")); sort_filter_titles.push_back(TTR("Path")); sort_filter_titles.push_back(TTR("Last Modified")); project_order_filter = memnew(ProjectListFilter); project_order_filter->add_filter_option(); project_order_filter->_setup_filters(sort_filter_titles); project_order_filter->set_filter_size(150); sort_filters->add_child(project_order_filter); project_order_filter->connect("filter_changed", this, "_on_order_option_changed"); project_order_filter->set_custom_minimum_size(Size2(180, 10) * EDSCALE); int projects_sorting_order = (int)EditorSettings::get_singleton()->get("project_manager/sorting_order"); project_order_filter->set_filter_option((ProjectListFilter::FilterOption)projects_sorting_order); sort_filters->add_spacer(true); project_filter = memnew(ProjectListFilter); project_filter->add_search_box(); project_filter->connect("filter_changed", this, "_on_filter_option_changed"); project_filter->set_custom_minimum_size(Size2(280, 10) * EDSCALE); sort_filters->add_child(project_filter); search_tree_vb->add_child(sort_filters); PanelContainer *pc = memnew(PanelContainer); pc->add_style_override("panel", gui_base->get_stylebox("bg", "Tree")); search_tree_vb->add_child(pc); pc->set_v_size_flags(SIZE_EXPAND_FILL); _project_list = memnew(ProjectList); _project_list->connect(ProjectList::SIGNAL_SELECTION_CHANGED, this, "_update_project_buttons"); _project_list->connect(ProjectList::SIGNAL_PROJECT_ASK_OPEN, this, "_open_selected_projects_ask"); pc->add_child(_project_list); _project_list->set_enable_h_scroll(false); VBoxContainer *tree_vb = memnew(VBoxContainer); tree_hb->add_child(tree_vb); Button *open = memnew(Button); open->set_text(TTR("Edit")); tree_vb->add_child(open); open->connect("pressed", this, "_open_selected_projects_ask"); open_btn = open; Button *run = memnew(Button); run->set_text(TTR("Run")); tree_vb->add_child(run); run->connect("pressed", this, "_run_project"); run_btn = run; tree_vb->add_child(memnew(HSeparator)); Button *scan = memnew(Button); scan->set_text(TTR("Scan")); tree_vb->add_child(scan); scan->connect("pressed", this, "_scan_projects"); tree_vb->add_child(memnew(HSeparator)); scan_dir = memnew(FileDialog); scan_dir->set_access(FileDialog::ACCESS_FILESYSTEM); scan_dir->set_mode(FileDialog::MODE_OPEN_DIR); scan_dir->set_title(TTR("Select a Folder to Scan")); // must be after mode or it's overridden scan_dir->set_current_dir(EditorSettings::get_singleton()->get("filesystem/directories/default_project_path")); gui_base->add_child(scan_dir); scan_dir->connect("dir_selected", this, "_scan_begin"); Button *create = memnew(Button); create->set_text(TTR("New Project")); tree_vb->add_child(create); create->connect("pressed", this, "_new_project"); Button *import = memnew(Button); import->set_text(TTR("Import")); tree_vb->add_child(import); import->connect("pressed", this, "_import_project"); Button *rename = memnew(Button); rename->set_text(TTR("Rename")); tree_vb->add_child(rename); rename->connect("pressed", this, "_rename_project"); rename_btn = rename; Button *erase = memnew(Button); erase->set_text(TTR("Remove")); tree_vb->add_child(erase); erase->connect("pressed", this, "_erase_project"); erase_btn = erase; Button *erase_missing = memnew(Button); erase_missing->set_text(TTR("Remove Missing")); tree_vb->add_child(erase_missing); erase_missing->connect("pressed", this, "_erase_missing_projects"); erase_missing_btn = erase_missing; tree_vb->add_spacer(); if (StreamPeerSSL::is_available()) { asset_library = memnew(EditorAssetLibrary(true)); asset_library->set_name(TTR("Templates")); tabs->add_child(asset_library); asset_library->connect("install_asset", this, "_install_project"); } else { WARN_PRINT("Asset Library not available, as it requires SSL to work."); } HBoxContainer *settings_hb = memnew(HBoxContainer); settings_hb->set_alignment(BoxContainer::ALIGN_END); settings_hb->set_h_grow_direction(Control::GROW_DIRECTION_BEGIN); Label *version_label = memnew(Label); String hash = String(VERSION_HASH); if (hash.length() != 0) { hash = "." + hash.left(9); } version_label->set_text("v" VERSION_FULL_BUILD "" + hash); // Fade out the version label to be less prominent, but still readable version_label->set_self_modulate(Color(1, 1, 1, 0.6)); version_label->set_align(Label::ALIGN_CENTER); settings_hb->add_child(version_label); language_btn = memnew(OptionButton); language_btn->set_flat(true); language_btn->set_focus_mode(Control::FOCUS_NONE); Vector<String> editor_languages; List<PropertyInfo> editor_settings_properties; EditorSettings::get_singleton()->get_property_list(&editor_settings_properties); for (List<PropertyInfo>::Element *E = editor_settings_properties.front(); E; E = E->next()) { PropertyInfo &pi = E->get(); if (pi.name == "interface/editor/editor_language") { editor_languages = pi.hint_string.split(","); } } String current_lang = EditorSettings::get_singleton()->get("interface/editor/editor_language"); for (int i = 0; i < editor_languages.size(); i++) { String lang = editor_languages[i]; String lang_name = TranslationServer::get_singleton()->get_locale_name(lang); language_btn->add_item(lang_name + " [" + lang + "]", i); language_btn->set_item_metadata(i, lang); if (current_lang == lang) { language_btn->select(i); language_btn->set_text(lang); } } language_btn->set_icon(get_icon("Environment", "EditorIcons")); settings_hb->add_child(language_btn); language_btn->connect("item_selected", this, "_language_selected"); center_box->add_child(settings_hb); settings_hb->set_anchors_and_margins_preset(Control::PRESET_TOP_RIGHT); ////////////////////////////////////////////////////////////// language_restart_ask = memnew(ConfirmationDialog); language_restart_ask->get_ok()->set_text(TTR("Restart Now")); language_restart_ask->get_ok()->connect("pressed", this, "_restart_confirm"); language_restart_ask->get_cancel()->set_text(TTR("Continue")); gui_base->add_child(language_restart_ask); erase_missing_ask = memnew(ConfirmationDialog); erase_missing_ask->get_ok()->set_text(TTR("Remove All")); erase_missing_ask->get_ok()->connect("pressed", this, "_erase_missing_projects_confirm"); gui_base->add_child(erase_missing_ask); erase_ask = memnew(ConfirmationDialog); erase_ask->get_ok()->set_text(TTR("Remove")); erase_ask->get_ok()->connect("pressed", this, "_erase_project_confirm"); gui_base->add_child(erase_ask); multi_open_ask = memnew(ConfirmationDialog); multi_open_ask->get_ok()->set_text(TTR("Edit")); multi_open_ask->get_ok()->connect("pressed", this, "_open_selected_projects"); gui_base->add_child(multi_open_ask); multi_run_ask = memnew(ConfirmationDialog); multi_run_ask->get_ok()->set_text(TTR("Run")); multi_run_ask->get_ok()->connect("pressed", this, "_run_project_confirm"); gui_base->add_child(multi_run_ask); multi_scan_ask = memnew(ConfirmationDialog); multi_scan_ask->get_ok()->set_text(TTR("Scan")); gui_base->add_child(multi_scan_ask); ask_update_settings = memnew(ConfirmationDialog); ask_update_settings->get_ok()->connect("pressed", this, "_confirm_update_settings"); gui_base->add_child(ask_update_settings); OS::get_singleton()->set_low_processor_usage_mode(true); npdialog = memnew(ProjectDialog); gui_base->add_child(npdialog); npdialog->connect("projects_updated", this, "_on_projects_updated"); npdialog->connect("project_created", this, "_on_project_created"); _load_recent_projects(); if (EditorSettings::get_singleton()->get("filesystem/directories/autoscan_project_path")) { _scan_begin(EditorSettings::get_singleton()->get("filesystem/directories/autoscan_project_path")); } SceneTree::get_singleton()->connect("files_dropped", this, "_files_dropped"); SceneTree::get_singleton()->connect("global_menu_action", this, "_global_menu_action"); run_error_diag = memnew(AcceptDialog); gui_base->add_child(run_error_diag); run_error_diag->set_title(TTR("Can't run project")); dialog_error = memnew(AcceptDialog); gui_base->add_child(dialog_error); open_templates = memnew(ConfirmationDialog); open_templates->set_text(TTR("You currently don't have any projects.\nWould you like to explore official example projects in the Asset Library?")); open_templates->get_ok()->set_text(TTR("Open Asset Library")); open_templates->connect("confirmed", this, "_open_asset_library"); add_child(open_templates); } ProjectManager::~ProjectManager() { if (EditorSettings::get_singleton()) EditorSettings::destroy(); } void ProjectListFilter::_setup_filters(Vector<String> options) { filter_option->clear(); for (int i = 0; i < options.size(); i++) filter_option->add_item(options[i]); } void ProjectListFilter::_search_text_changed(const String &p_newtext) { emit_signal("filter_changed"); } String ProjectListFilter::get_search_term() { return search_box->get_text().strip_edges(); } ProjectListFilter::FilterOption ProjectListFilter::get_filter_option() { return _current_filter; } void ProjectListFilter::set_filter_option(FilterOption option) { filter_option->select((int)option); _filter_option_selected(0); } void ProjectListFilter::_filter_option_selected(int p_idx) { FilterOption selected = (FilterOption)(filter_option->get_selected()); if (_current_filter != selected) { _current_filter = selected; emit_signal("filter_changed"); } } void ProjectListFilter::_notification(int p_what) { if (p_what == NOTIFICATION_ENTER_TREE && has_search_box) { search_box->set_right_icon(get_icon("Search", "EditorIcons")); search_box->set_clear_button_enabled(true); } } void ProjectListFilter::_bind_methods() { ClassDB::bind_method(D_METHOD("_search_text_changed"), &ProjectListFilter::_search_text_changed); ClassDB::bind_method(D_METHOD("_filter_option_selected"), &ProjectListFilter::_filter_option_selected); ADD_SIGNAL(MethodInfo("filter_changed")); } void ProjectListFilter::add_filter_option() { filter_option = memnew(OptionButton); filter_option->set_clip_text(true); filter_option->connect("item_selected", this, "_filter_option_selected"); add_child(filter_option); } void ProjectListFilter::add_search_box() { search_box = memnew(LineEdit); search_box->set_placeholder(TTR("Search")); search_box->connect("text_changed", this, "_search_text_changed"); search_box->set_h_size_flags(SIZE_EXPAND_FILL); add_child(search_box); has_search_box = true; } void ProjectListFilter::set_filter_size(int h_size) { filter_option->set_custom_minimum_size(Size2(h_size * EDSCALE, 10 * EDSCALE)); } ProjectListFilter::ProjectListFilter() { _current_filter = FILTER_NAME; has_search_box = false; } void ProjectListFilter::clear() { if (has_search_box) { search_box->clear(); } }
/* The MIT License (MIT) Copyright (c) 2013 winlin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <srs_core_protocol.hpp> #include <srs_core_log.hpp> #include <srs_core_amf0.hpp> #include <srs_core_error.hpp> #include <srs_core_socket.hpp> #include <srs_core_buffer.hpp> #include <srs_core_stream.hpp> #include <srs_core_auto_free.hpp> /**************************************************************************** ***************************************************************************** ****************************************************************************/ /** 5. Protocol Control Messages RTMP reserves message type IDs 1-7 for protocol control messages. These messages contain information needed by the RTM Chunk Stream protocol or RTMP itself. Protocol messages with IDs 1 & 2 are reserved for usage with RTM Chunk Stream protocol. Protocol messages with IDs 3-6 are reserved for usage of RTMP. Protocol message with ID 7 is used between edge server and origin server. */ #define RTMP_MSG_SetChunkSize 0x01 #define RTMP_MSG_AbortMessage 0x02 #define RTMP_MSG_Acknowledgement 0x03 #define RTMP_MSG_UserControlMessage 0x04 #define RTMP_MSG_WindowAcknowledgementSize 0x05 #define RTMP_MSG_SetPeerBandwidth 0x06 #define RTMP_MSG_EdgeAndOriginServerCommand 0x07 /** 3. Types of messages The server and the client send messages over the network to communicate with each other. The messages can be of any type which includes audio messages, video messages, command messages, shared object messages, data messages, and user control messages. 3.1. Command message Command messages carry the AMF-encoded commands between the client and the server. These messages have been assigned message type value of 20 for AMF0 encoding and message type value of 17 for AMF3 encoding. These messages are sent to perform some operations like connect, createStream, publish, play, pause on the peer. Command messages like onstatus, result etc. are used to inform the sender about the status of the requested commands. A command message consists of command name, transaction ID, and command object that contains related parameters. A client or a server can request Remote Procedure Calls (RPC) over streams that are communicated using the command messages to the peer. */ #define RTMP_MSG_AMF3CommandMessage 17 // 0x11 #define RTMP_MSG_AMF0CommandMessage 20 // 0x14 /** 3.2. Data message The client or the server sends this message to send Metadata or any user data to the peer. Metadata includes details about the data(audio, video etc.) like creation time, duration, theme and so on. These messages have been assigned message type value of 18 for AMF0 and message type value of 15 for AMF3. */ #define RTMP_MSG_AMF0DataMessage 18 // 0x12 #define RTMP_MSG_AMF3DataMessage 15 // 0x0F /** 3.3. Shared object message A shared object is a Flash object (a collection of name value pairs) that are in synchronization across multiple clients, instances, and so on. The message types kMsgContainer=19 for AMF0 and kMsgContainerEx=16 for AMF3 are reserved for shared object events. Each message can contain multiple events. */ #define RTMP_MSG_AMF3SharedObject 16 // 0x10 #define RTMP_MSG_AMF0SharedObject 19 // 0x13 /** 3.4. Audio message The client or the server sends this message to send audio data to the peer. The message type value of 8 is reserved for audio messages. */ #define RTMP_MSG_AudioMessage 8 // 0x08 /* * 3.5. Video message The client or the server sends this message to send video data to the peer. The message type value of 9 is reserved for video messages. These messages are large and can delay the sending of other type of messages. To avoid such a situation, the video message is assigned the lowest priority. */ #define RTMP_MSG_VideoMessage 9 // 0x09 /** 3.6. Aggregate message An aggregate message is a single message that contains a list of submessages. The message type value of 22 is reserved for aggregate messages. */ #define RTMP_MSG_AggregateMessage 22 // 0x16 /**************************************************************************** ***************************************************************************** ****************************************************************************/ /** * 6.1.2. Chunk Message Header * There are four different formats for the chunk message header, * selected by the "fmt" field in the chunk basic header. */ // 6.1.2.1. Type 0 // Chunks of Type 0 are 11 bytes long. This type MUST be used at the // start of a chunk stream, and whenever the stream timestamp goes // backward (e.g., because of a backward seek). #define RTMP_FMT_TYPE0 0 // 6.1.2.2. Type 1 // Chunks of Type 1 are 7 bytes long. The message stream ID is not // included; this chunk takes the same stream ID as the preceding chunk. // Streams with variable-sized messages (for example, many video // formats) SHOULD use this format for the first chunk of each new // message after the first. #define RTMP_FMT_TYPE1 1 // 6.1.2.3. Type 2 // Chunks of Type 2 are 3 bytes long. Neither the stream ID nor the // message length is included; this chunk has the same stream ID and // message length as the preceding chunk. Streams with constant-sized // messages (for example, some audio and data formats) SHOULD use this // format for the first chunk of each message after the first. #define RTMP_FMT_TYPE2 2 // 6.1.2.4. Type 3 // Chunks of Type 3 have no header. Stream ID, message length and // timestamp delta are not present; chunks of this type take values from // the preceding chunk. When a single message is split into chunks, all // chunks of a message except the first one, SHOULD use this type. Refer // to example 2 in section 6.2.2. Stream consisting of messages of // exactly the same size, stream ID and spacing in time SHOULD use this // type for all chunks after chunk of Type 2. Refer to example 1 in // section 6.2.1. If the delta between the first message and the second // message is same as the time stamp of first message, then chunk of // type 3 would immediately follow the chunk of type 0 as there is no // need for a chunk of type 2 to register the delta. If Type 3 chunk // follows a Type 0 chunk, then timestamp delta for this Type 3 chunk is // the same as the timestamp of Type 0 chunk. #define RTMP_FMT_TYPE3 3 /**************************************************************************** ***************************************************************************** ****************************************************************************/ /** * 6. Chunking * The chunk size is configurable. It can be set using a control * message(Set Chunk Size) as described in section 7.1. The maximum * chunk size can be 65536 bytes and minimum 128 bytes. Larger values * reduce CPU usage, but also commit to larger writes that can delay * other content on lower bandwidth connections. Smaller chunks are not * good for high-bit rate streaming. Chunk size is maintained * independently for each direction. */ #define RTMP_DEFAULT_CHUNK_SIZE 128 #define RTMP_MIN_CHUNK_SIZE 2 /** * 6.1. Chunk Format * Extended timestamp: 0 or 4 bytes * This field MUST be sent when the normal timsestamp is set to * 0xffffff, it MUST NOT be sent if the normal timestamp is set to * anything else. So for values less than 0xffffff the normal * timestamp field SHOULD be used in which case the extended timestamp * MUST NOT be present. For values greater than or equal to 0xffffff * the normal timestamp field MUST NOT be used and MUST be set to * 0xffffff and the extended timestamp MUST be sent. */ #define RTMP_EXTENDED_TIMESTAMP 0xFFFFFF /**************************************************************************** ***************************************************************************** ****************************************************************************/ /** * amf0 command message, command name macros */ #define RTMP_AMF0_COMMAND_CONNECT "connect" #define RTMP_AMF0_COMMAND_CREATE_STREAM "createStream" #define RTMP_AMF0_COMMAND_PLAY "play" #define RTMP_AMF0_COMMAND_ON_BW_DONE "onBWDone" #define RTMP_AMF0_COMMAND_ON_STATUS "onStatus" #define RTMP_AMF0_COMMAND_RESULT "_result" #define RTMP_AMF0_COMMAND_RELEASE_STREAM "releaseStream" #define RTMP_AMF0_COMMAND_FC_PUBLISH "FCPublish" #define RTMP_AMF0_COMMAND_UNPUBLISH "FCUnpublish" #define RTMP_AMF0_COMMAND_PUBLISH "publish" #define RTMP_AMF0_DATA_SAMPLE_ACCESS "|RtmpSampleAccess" #define RTMP_AMF0_DATA_SET_DATAFRAME "@setDataFrame" #define RTMP_AMF0_DATA_ON_METADATA "onMetaData" /**************************************************************************** ***************************************************************************** ****************************************************************************/ /** * the chunk stream id used for some under-layer message, * for example, the PC(protocol control) message. */ #define RTMP_CID_ProtocolControl 0x02 /** * the AMF0/AMF3 command message, invoke method and return the result, over NetConnection. * generally use 0x03. */ #define RTMP_CID_OverConnection 0x03 /** * the AMF0/AMF3 command message, invoke method and return the result, over NetConnection, * the midst state(we guess). * rarely used, e.g. onStatus(NetStream.Play.Reset). */ #define RTMP_CID_OverConnection2 0x04 /** * the stream message(amf0/amf3), over NetStream. * generally use 0x05. */ #define RTMP_CID_OverStream 0x05 /** * the stream message(amf0/amf3), over NetStream, the midst state(we guess). * rarely used, e.g. play("mp4:mystram.f4v") */ #define RTMP_CID_OverStream2 0x08 /** * the stream message(video), over NetStream * generally use 0x06. */ #define RTMP_CID_Video 0x06 /** * the stream message(audio), over NetStream. * generally use 0x07. */ #define RTMP_CID_Audio 0x07 /**************************************************************************** ***************************************************************************** ****************************************************************************/ SrsProtocol::SrsProtocol(st_netfd_t client_stfd) { stfd = client_stfd; buffer = new SrsBuffer(); skt = new SrsSocket(stfd); in_chunk_size = out_chunk_size = RTMP_DEFAULT_CHUNK_SIZE; } SrsProtocol::~SrsProtocol() { std::map<int, SrsChunkStream*>::iterator it; for (it = chunk_streams.begin(); it != chunk_streams.end(); ++it) { SrsChunkStream* stream = it->second; srs_freep(stream); } chunk_streams.clear(); srs_freep(buffer); srs_freep(skt); } int SrsProtocol::can_read(int timeout_ms, bool& ready) { return skt->can_read(timeout_ms, ready); } int SrsProtocol::recv_message(SrsCommonMessage** pmsg) { *pmsg = NULL; int ret = ERROR_SUCCESS; while (true) { SrsCommonMessage* msg = NULL; if ((ret = recv_interlaced_message(&msg)) != ERROR_SUCCESS) { srs_error("recv interlaced message failed. ret=%d", ret); return ret; } srs_verbose("entire msg received"); if (!msg) { continue; } if (msg->size <= 0 || msg->header.payload_length <= 0) { srs_trace("ignore empty message(type=%d, size=%d, time=%d, sid=%d).", msg->header.message_type, msg->header.payload_length, msg->header.timestamp, msg->header.stream_id); srs_freep(msg); continue; } if ((ret = on_recv_message(msg)) != ERROR_SUCCESS) { srs_error("hook the received msg failed. ret=%d", ret); srs_freep(msg); return ret; } srs_verbose("get a msg with raw/undecoded payload"); *pmsg = msg; break; } return ret; } int SrsProtocol::send_message(ISrsMessage* msg) { int ret = ERROR_SUCCESS; // free msg whatever return value. SrsAutoFree(ISrsMessage, msg, false); if ((ret = msg->encode_packet()) != ERROR_SUCCESS) { srs_error("encode packet to message payload failed. ret=%d", ret); return ret; } srs_info("encode packet to message payload success"); // p set to current write position, // it's ok when payload is NULL and size is 0. char* p = (char*)msg->payload; // always write the header event payload is empty. do { // generate the header. char* pheader = NULL; int header_size = 0; if (p == (char*)msg->payload) { // write new chunk stream header, fmt is 0 pheader = out_header_fmt0; *pheader++ = 0x00 | (msg->get_perfer_cid() & 0x3F); // chunk message header, 11 bytes // timestamp, 3bytes, big-endian if (msg->header.timestamp >= RTMP_EXTENDED_TIMESTAMP) { *pheader++ = 0xFF; *pheader++ = 0xFF; *pheader++ = 0xFF; } else { pp = (char*)&msg->header.timestamp; *pheader++ = pp[2]; *pheader++ = pp[1]; *pheader++ = pp[0]; } // message_length, 3bytes, big-endian pp = (char*)&msg->header.payload_length; *pheader++ = pp[2]; *pheader++ = pp[1]; *pheader++ = pp[0]; // message_type, 1bytes *pheader++ = msg->header.message_type; // message_length, 3bytes, little-endian pp = (char*)&msg->header.stream_id; *pheader++ = pp[0]; *pheader++ = pp[1]; *pheader++ = pp[2]; *pheader++ = pp[3]; // chunk extended timestamp header, 0 or 4 bytes, big-endian if(msg->header.timestamp >= RTMP_EXTENDED_TIMESTAMP){ pp = (char*)&msg->header.timestamp; *pheader++ = pp[3]; *pheader++ = pp[2]; *pheader++ = pp[1]; *pheader++ = pp[0]; } header_size = pheader - out_header_fmt0; pheader = out_header_fmt0; } else { // write no message header chunk stream, fmt is 3 pheader = out_header_fmt3; *pheader++ = 0xC0 | (msg->get_perfer_cid() & 0x3F); // chunk extended timestamp header, 0 or 4 bytes, big-endian if(msg->header.timestamp >= RTMP_EXTENDED_TIMESTAMP){ pp = (char*)&msg->header.timestamp; *pheader++ = pp[3]; *pheader++ = pp[2]; *pheader++ = pp[1]; *pheader++ = pp[0]; } header_size = pheader - out_header_fmt3; pheader = out_header_fmt3; } // sendout header and payload by writev. // decrease the sys invoke count to get higher performance. int payload_size = msg->size - (p - (char*)msg->payload); payload_size = srs_min(payload_size, out_chunk_size); // send by writev iovec iov[2]; iov[0].iov_base = pheader; iov[0].iov_len = header_size; iov[1].iov_base = p; iov[1].iov_len = payload_size; ssize_t nwrite; if ((ret = skt->writev(iov, 2, &nwrite)) != ERROR_SUCCESS) { srs_error("send with writev failed. ret=%d", ret); return ret; } // consume sendout bytes when not empty packet. if (msg->payload && msg->size > 0) { p += payload_size; } } while (p < (char*)msg->payload + msg->size); if ((ret = on_send_message(msg)) != ERROR_SUCCESS) { srs_error("hook the send message failed. ret=%d", ret); return ret; } return ret; } int SrsProtocol::on_recv_message(SrsCommonMessage* msg) { int ret = ERROR_SUCCESS; srs_assert(msg != NULL); switch (msg->header.message_type) { case RTMP_MSG_SetChunkSize: case RTMP_MSG_WindowAcknowledgementSize: if ((ret = msg->decode_packet()) != ERROR_SUCCESS) { srs_error("decode packet from message payload failed. ret=%d", ret); return ret; } srs_verbose("decode packet from message payload success."); break; } switch (msg->header.message_type) { case RTMP_MSG_WindowAcknowledgementSize: { SrsSetWindowAckSizePacket* pkt = dynamic_cast<SrsSetWindowAckSizePacket*>(msg->get_packet()); srs_assert(pkt != NULL); // TODO: take effect. srs_trace("set ack window size to %d", pkt->ackowledgement_window_size); break; } case RTMP_MSG_SetChunkSize: { SrsSetChunkSizePacket* pkt = dynamic_cast<SrsSetChunkSizePacket*>(msg->get_packet()); srs_assert(pkt != NULL); in_chunk_size = pkt->chunk_size; srs_trace("set input chunk size to %d", pkt->chunk_size); break; } } return ret; } int SrsProtocol::on_send_message(ISrsMessage* msg) { int ret = ERROR_SUCCESS; if (!msg->can_decode()) { srs_verbose("ignore the un-decodable message."); return ret; } SrsCommonMessage* common_msg = dynamic_cast<SrsCommonMessage*>(msg); if (!msg) { srs_verbose("ignore the shared ptr message."); return ret; } srs_assert(common_msg != NULL); switch (common_msg->header.message_type) { case RTMP_MSG_SetChunkSize: { SrsSetChunkSizePacket* pkt = dynamic_cast<SrsSetChunkSizePacket*>(common_msg->get_packet()); srs_assert(pkt != NULL); out_chunk_size = pkt->chunk_size; srs_trace("set output chunk size to %d", pkt->chunk_size); break; } } return ret; } int SrsProtocol::recv_interlaced_message(SrsCommonMessage** pmsg) { int ret = ERROR_SUCCESS; // chunk stream basic header. char fmt = 0; int cid = 0; int bh_size = 0; if ((ret = read_basic_header(fmt, cid, bh_size)) != ERROR_SUCCESS) { srs_error("read basic header failed. ret=%d", ret); return ret; } srs_info("read basic header success. fmt=%d, cid=%d, bh_size=%d", fmt, cid, bh_size); // get the cached chunk stream. SrsChunkStream* chunk = NULL; if (chunk_streams.find(cid) == chunk_streams.end()) { chunk = chunk_streams[cid] = new SrsChunkStream(cid); srs_info("cache new chunk stream: fmt=%d, cid=%d", fmt, cid); } else { chunk = chunk_streams[cid]; srs_info("cached chunk stream: fmt=%d, cid=%d, size=%d, message(type=%d, size=%d, time=%d, sid=%d)", chunk->fmt, chunk->cid, (chunk->msg? chunk->msg->size : 0), chunk->header.message_type, chunk->header.payload_length, chunk->header.timestamp, chunk->header.stream_id); } // chunk stream message header int mh_size = 0; if ((ret = read_message_header(chunk, fmt, bh_size, mh_size)) != ERROR_SUCCESS) { srs_error("read message header failed. ret=%d", ret); return ret; } srs_info("read message header success. " "fmt=%d, mh_size=%d, ext_time=%d, size=%d, message(type=%d, size=%d, time=%d, sid=%d)", fmt, mh_size, chunk->extended_timestamp, (chunk->msg? chunk->msg->size : 0), chunk->header.message_type, chunk->header.payload_length, chunk->header.timestamp, chunk->header.stream_id); // read msg payload from chunk stream. SrsCommonMessage* msg = NULL; int payload_size = 0; if ((ret = read_message_payload(chunk, bh_size, mh_size, payload_size, &msg)) != ERROR_SUCCESS) { srs_error("read message payload failed. ret=%d", ret); return ret; } // not got an entire RTMP message, try next chunk. if (!msg) { srs_info("get partial message success. chunk_payload_size=%d, size=%d, message(type=%d, size=%d, time=%d, sid=%d)", payload_size, (msg? msg->size : (chunk->msg? chunk->msg->size : 0)), chunk->header.message_type, chunk->header.payload_length, chunk->header.timestamp, chunk->header.stream_id); return ret; } *pmsg = msg; srs_info("get entire message success. chunk_payload_size=%d, size=%d, message(type=%d, size=%d, time=%d, sid=%d)", payload_size, (msg? msg->size : (chunk->msg? chunk->msg->size : 0)), chunk->header.message_type, chunk->header.payload_length, chunk->header.timestamp, chunk->header.stream_id); return ret; } int SrsProtocol::read_basic_header(char& fmt, int& cid, int& bh_size) { int ret = ERROR_SUCCESS; int required_size = 1; if ((ret = buffer->ensure_buffer_bytes(skt, required_size)) != ERROR_SUCCESS) { srs_error("read 1bytes basic header failed. required_size=%d, ret=%d", required_size, ret); return ret; } char* p = buffer->bytes(); fmt = (*p >> 6) & 0x03; cid = *p & 0x3f; bh_size = 1; if (cid > 1) { srs_verbose("%dbytes basic header parsed. fmt=%d, cid=%d", bh_size, fmt, cid); return ret; } if (cid == 0) { required_size = 2; if ((ret = buffer->ensure_buffer_bytes(skt, required_size)) != ERROR_SUCCESS) { srs_error("read 2bytes basic header failed. required_size=%d, ret=%d", required_size, ret); return ret; } cid = 64; cid += *(++p); bh_size = 2; srs_verbose("%dbytes basic header parsed. fmt=%d, cid=%d", bh_size, fmt, cid); } else if (cid == 1) { required_size = 3; if ((ret = buffer->ensure_buffer_bytes(skt, 3)) != ERROR_SUCCESS) { srs_error("read 3bytes basic header failed. required_size=%d, ret=%d", required_size, ret); return ret; } cid = 64; cid += *(++p); cid += *(++p) * 256; bh_size = 3; srs_verbose("%dbytes basic header parsed. fmt=%d, cid=%d", bh_size, fmt, cid); } else { srs_error("invalid path, impossible basic header."); srs_assert(false); } return ret; } int SrsProtocol::read_message_header(SrsChunkStream* chunk, char fmt, int bh_size, int& mh_size) { int ret = ERROR_SUCCESS; /** * we should not assert anything about fmt, for the first packet. * (when first packet, the chunk->msg is NULL). * the fmt maybe 0/1/2/3, the FMLE will send a 0xC4 for some audio packet. * the previous packet is: * 04 // fmt=0, cid=4 * 00 00 1a // timestamp=26 * 00 00 9d // payload_length=157 * 08 // message_type=8(audio) * 01 00 00 00 // stream_id=1 * the current packet maybe: * c4 // fmt=3, cid=4 * it's ok, for the packet is audio, and timestamp delta is 26. * the current packet must be parsed as: * fmt=0, cid=4 * timestamp=26+26=52 * payload_length=157 * message_type=8(audio) * stream_id=1 * so we must update the timestamp even fmt=3 for first packet. */ // fresh packet used to update the timestamp even fmt=3 for first packet. bool is_fresh_packet = !chunk->msg; // but, we can ensure that when a chunk stream is fresh, // the fmt must be 0, a new stream. if (chunk->msg_count == 0 && fmt != RTMP_FMT_TYPE0) { ret = ERROR_RTMP_CHUNK_START; srs_error("chunk stream is fresh, " "fmt must be %d, actual is %d. ret=%d", RTMP_FMT_TYPE0, fmt, ret); return ret; } // when exists cache msg, means got an partial message, // the fmt must not be type0 which means new message. if (chunk->msg && fmt == RTMP_FMT_TYPE0) { ret = ERROR_RTMP_CHUNK_START; srs_error("chunk stream exists, " "fmt must not be %d, actual is %d. ret=%d", RTMP_FMT_TYPE0, fmt, ret); return ret; } // create msg when new chunk stream start if (!chunk->msg) { chunk->msg = new SrsCommonMessage(); srs_verbose("create message for new chunk, fmt=%d, cid=%d", fmt, chunk->cid); } // read message header from socket to buffer. static char mh_sizes[] = {11, 7, 3, 0}; mh_size = mh_sizes[(int)fmt]; srs_verbose("calc chunk message header size. fmt=%d, mh_size=%d", fmt, mh_size); int required_size = bh_size + mh_size; if ((ret = buffer->ensure_buffer_bytes(skt, required_size)) != ERROR_SUCCESS) { srs_error("read %dbytes message header failed. required_size=%d, ret=%d", mh_size, required_size, ret); return ret; } char* p = buffer->bytes() + bh_size; // parse the message header. // see also: ngx_rtmp_recv if (fmt <= RTMP_FMT_TYPE2) { char* pp = (char*)&chunk->header.timestamp_delta; pp[2] = *p++; pp[1] = *p++; pp[0] = *p++; pp[3] = 0; if (fmt == RTMP_FMT_TYPE0) { // 6.1.2.1. Type 0 // For a type-0 chunk, the absolute timestamp of the message is sent // here. chunk->header.timestamp = chunk->header.timestamp_delta; } else { // 6.1.2.2. Type 1 // 6.1.2.3. Type 2 // For a type-1 or type-2 chunk, the difference between the previous // chunk's timestamp and the current chunk's timestamp is sent here. chunk->header.timestamp += chunk->header.timestamp_delta; } // fmt: 0 // timestamp: 3 bytes // If the timestamp is greater than or equal to 16777215 // (hexadecimal 0x00ffffff), this value MUST be 16777215, and the // ‘extended timestamp header’ MUST be present. Otherwise, this value // SHOULD be the entire timestamp. // // fmt: 1 or 2 // timestamp delta: 3 bytes // If the delta is greater than or equal to 16777215 (hexadecimal // 0x00ffffff), this value MUST be 16777215, and the ‘extended // timestamp header’ MUST be present. Otherwise, this value SHOULD be // the entire delta. chunk->extended_timestamp = (chunk->header.timestamp_delta >= RTMP_EXTENDED_TIMESTAMP); if (chunk->extended_timestamp) { chunk->header.timestamp = RTMP_EXTENDED_TIMESTAMP; } if (fmt <= RTMP_FMT_TYPE1) { pp = (char*)&chunk->header.payload_length; pp[2] = *p++; pp[1] = *p++; pp[0] = *p++; pp[3] = 0; chunk->header.message_type = *p++; if (fmt == 0) { pp = (char*)&chunk->header.stream_id; pp[0] = *p++; pp[1] = *p++; pp[2] = *p++; pp[3] = *p++; srs_verbose("header read completed. fmt=%d, mh_size=%d, ext_time=%d, time=%d, payload=%d, type=%d, sid=%d", fmt, mh_size, chunk->extended_timestamp, chunk->header.timestamp, chunk->header.payload_length, chunk->header.message_type, chunk->header.stream_id); } else { srs_verbose("header read completed. fmt=%d, mh_size=%d, ext_time=%d, time=%d, payload=%d, type=%d", fmt, mh_size, chunk->extended_timestamp, chunk->header.timestamp, chunk->header.payload_length, chunk->header.message_type); } } else { srs_verbose("header read completed. fmt=%d, mh_size=%d, ext_time=%d, time=%d", fmt, mh_size, chunk->extended_timestamp, chunk->header.timestamp); } } else { // update the timestamp even fmt=3 for first stream if (is_fresh_packet && !chunk->extended_timestamp) { chunk->header.timestamp += chunk->header.timestamp_delta; } srs_verbose("header read completed. fmt=%d, size=%d, ext_time=%d", fmt, mh_size, chunk->extended_timestamp); } if (chunk->extended_timestamp) { mh_size += 4; required_size = bh_size + mh_size; srs_verbose("read header ext time. fmt=%d, ext_time=%d, mh_size=%d", fmt, chunk->extended_timestamp, mh_size); if ((ret = buffer->ensure_buffer_bytes(skt, required_size)) != ERROR_SUCCESS) { srs_error("read %dbytes message header failed. required_size=%d, ret=%d", mh_size, required_size, ret); return ret; } char* pp = (char*)&chunk->header.timestamp; pp[3] = *p++; pp[2] = *p++; pp[1] = *p++; pp[0] = *p++; srs_verbose("header read ext_time completed. time=%d", chunk->header.timestamp); } // valid message if (chunk->header.payload_length < 0) { ret = ERROR_RTMP_MSG_INVLIAD_SIZE; srs_error("RTMP message size must not be negative. size=%d, ret=%d", chunk->header.payload_length, ret); return ret; } // copy header to msg chunk->msg->header = chunk->header; // increase the msg count, the chunk stream can accept fmt=1/2/3 message now. chunk->msg_count++; return ret; } int SrsProtocol::read_message_payload(SrsChunkStream* chunk, int bh_size, int mh_size, int& payload_size, SrsCommonMessage** pmsg) { int ret = ERROR_SUCCESS; // empty message if (chunk->header.payload_length == 0) { // need erase the header in buffer. buffer->erase(bh_size + mh_size); srs_trace("get an empty RTMP " "message(type=%d, size=%d, time=%d, sid=%d)", chunk->header.message_type, chunk->header.payload_length, chunk->header.timestamp, chunk->header.stream_id); *pmsg = chunk->msg; chunk->msg = NULL; return ret; } srs_assert(chunk->header.payload_length > 0); // the chunk payload size. payload_size = chunk->header.payload_length - chunk->msg->size; payload_size = srs_min(payload_size, in_chunk_size); srs_verbose("chunk payload size is %d, message_size=%d, received_size=%d, in_chunk_size=%d", payload_size, chunk->header.payload_length, chunk->msg->size, in_chunk_size); // create msg payload if not initialized if (!chunk->msg->payload) { chunk->msg->payload = new int8_t[chunk->header.payload_length]; memset(chunk->msg->payload, 0, chunk->header.payload_length); srs_verbose("create empty payload for RTMP message. size=%d", chunk->header.payload_length); } // read payload to buffer int required_size = bh_size + mh_size + payload_size; if ((ret = buffer->ensure_buffer_bytes(skt, required_size)) != ERROR_SUCCESS) { srs_error("read payload failed. required_size=%d, ret=%d", required_size, ret); return ret; } memcpy(chunk->msg->payload + chunk->msg->size, buffer->bytes() + bh_size + mh_size, payload_size); buffer->erase(bh_size + mh_size + payload_size); chunk->msg->size += payload_size; srs_verbose("chunk payload read completed. bh_size=%d, mh_size=%d, payload_size=%d", bh_size, mh_size, payload_size); // got entire RTMP message? if (chunk->header.payload_length == chunk->msg->size) { *pmsg = chunk->msg; chunk->msg = NULL; srs_verbose("get entire RTMP message(type=%d, size=%d, time=%d, sid=%d)", chunk->header.message_type, chunk->header.payload_length, chunk->header.timestamp, chunk->header.stream_id); return ret; } srs_verbose("get partial RTMP message(type=%d, size=%d, time=%d, sid=%d), partial size=%d", chunk->header.message_type, chunk->header.payload_length, chunk->header.timestamp, chunk->header.stream_id, chunk->msg->size); return ret; } SrsMessageHeader::SrsMessageHeader() { message_type = 0; payload_length = 0; timestamp_delta = 0; stream_id = 0; timestamp = 0; } SrsMessageHeader::~SrsMessageHeader() { } bool SrsMessageHeader::is_audio() { return message_type == RTMP_MSG_AudioMessage; } bool SrsMessageHeader::is_video() { return message_type == RTMP_MSG_VideoMessage; } bool SrsMessageHeader::is_amf0_command() { return message_type == RTMP_MSG_AMF0CommandMessage; } bool SrsMessageHeader::is_amf0_data() { return message_type == RTMP_MSG_AMF0DataMessage; } bool SrsMessageHeader::is_amf3_command() { return message_type == RTMP_MSG_AMF3CommandMessage; } bool SrsMessageHeader::is_amf3_data() { return message_type == RTMP_MSG_AMF3DataMessage; } bool SrsMessageHeader::is_window_ackledgement_size() { return message_type == RTMP_MSG_WindowAcknowledgementSize; } bool SrsMessageHeader::is_set_chunk_size() { return message_type == RTMP_MSG_SetChunkSize; } SrsChunkStream::SrsChunkStream(int _cid) { fmt = 0; cid = _cid; extended_timestamp = false; msg = NULL; msg_count = 0; } SrsChunkStream::~SrsChunkStream() { srs_freep(msg); } ISrsMessage::ISrsMessage() { payload = NULL; size = 0; } ISrsMessage::~ISrsMessage() { } SrsCommonMessage::SrsCommonMessage() { stream = NULL; packet = NULL; } SrsCommonMessage::~SrsCommonMessage() { // we must directly free the ptrs, // nevery use the virtual functions to delete, // for in the destructor, the virtual functions is disabled. srs_freepa(payload); srs_freep(packet); srs_freep(stream); } bool SrsCommonMessage::can_decode() { return true; } int SrsCommonMessage::decode_packet() { int ret = ERROR_SUCCESS; srs_assert(payload != NULL); srs_assert(size > 0); if (packet) { srs_verbose("msg already decoded"); return ret; } if (!stream) { srs_verbose("create decode stream for message."); stream = new SrsStream(); } // initialize the decode stream for all message, // it's ok for the initialize if fast and without memory copy. if ((ret = stream->initialize((char*)payload, size)) != ERROR_SUCCESS) { srs_error("initialize stream failed. ret=%d", ret); return ret; } srs_verbose("decode stream initialized success"); // decode specified packet type if (header.is_amf0_command() || header.is_amf3_command() || header.is_amf0_data() || header.is_amf3_data()) { srs_verbose("start to decode AMF0/AMF3 command message."); // skip 1bytes to decode the amf3 command. if (header.is_amf3_command() && stream->require(1)) { srs_verbose("skip 1bytes to decode AMF3 command"); stream->skip(1); } // amf0 command message. // need to read the command name. std::string command; if ((ret = srs_amf0_read_string(stream, command)) != ERROR_SUCCESS) { srs_error("decode AMF0/AMF3 command name failed. ret=%d", ret); return ret; } srs_verbose("AMF0/AMF3 command message, command_name=%s", command.c_str()); // reset to zero(amf3 to 1) to restart decode. stream->reset(); if (header.is_amf3_command()) { stream->skip(1); } // decode command object. if (command == RTMP_AMF0_COMMAND_CONNECT) { srs_info("decode the AMF0/AMF3 command(connect vhost/app message)."); packet = new SrsConnectAppPacket(); return packet->decode(stream); } else if(command == RTMP_AMF0_COMMAND_CREATE_STREAM) { srs_info("decode the AMF0/AMF3 command(createStream message)."); packet = new SrsCreateStreamPacket(); return packet->decode(stream); } else if(command == RTMP_AMF0_COMMAND_PLAY) { srs_info("decode the AMF0/AMF3 command(paly message)."); packet = new SrsPlayPacket(); return packet->decode(stream); } else if(command == RTMP_AMF0_COMMAND_RELEASE_STREAM) { srs_info("decode the AMF0/AMF3 command(FMLE releaseStream message)."); packet = new SrsFMLEStartPacket(); return packet->decode(stream); } else if(command == RTMP_AMF0_COMMAND_FC_PUBLISH) { srs_info("decode the AMF0/AMF3 command(FMLE FCPublish message)."); packet = new SrsFMLEStartPacket(); return packet->decode(stream); } else if(command == RTMP_AMF0_COMMAND_PUBLISH) { srs_info("decode the AMF0/AMF3 command(publish message)."); packet = new SrsPublishPacket(); return packet->decode(stream); } else if(command == RTMP_AMF0_COMMAND_UNPUBLISH) { srs_info("decode the AMF0/AMF3 command(unpublish message)."); packet = new SrsFMLEStartPacket(); return packet->decode(stream); } else if(command == RTMP_AMF0_DATA_SET_DATAFRAME || command == RTMP_AMF0_DATA_ON_METADATA) { srs_info("decode the AMF0/AMF3 data(onMetaData message)."); packet = new SrsOnMetaDataPacket(); return packet->decode(stream); } // default packet to drop message. srs_trace("drop the AMF0/AMF3 command message, command_name=%s", command.c_str()); packet = new SrsPacket(); return ret; } else if(header.is_window_ackledgement_size()) { srs_verbose("start to decode set ack window size message."); packet = new SrsSetWindowAckSizePacket(); return packet->decode(stream); } else if(header.is_set_chunk_size()) { srs_verbose("start to decode set chunk size message."); packet = new SrsSetChunkSizePacket(); return packet->decode(stream); } else { // default packet to drop message. srs_trace("drop the unknown message, type=%d", header.message_type); packet = new SrsPacket(); } return ret; } SrsPacket* SrsCommonMessage::get_packet() { if (!packet) { srs_error("the payload is raw/undecoded, invoke decode_packet to decode it."); } srs_assert(packet != NULL); return packet; } int SrsCommonMessage::get_perfer_cid() { if (!packet) { return RTMP_CID_ProtocolControl; } // we donot use the complex basic header, // ensure the basic header is 1bytes. if (packet->get_perfer_cid() < 2) { return packet->get_perfer_cid(); } return packet->get_perfer_cid(); } void SrsCommonMessage::set_packet(SrsPacket* pkt, int stream_id) { srs_freep(packet); packet = pkt; header.message_type = packet->get_message_type(); header.payload_length = packet->get_payload_length(); header.stream_id = stream_id; } int SrsCommonMessage::encode_packet() { int ret = ERROR_SUCCESS; if (packet == NULL) { srs_warn("packet is empty, send out empty message."); return ret; } // realloc the payload. size = 0; srs_freepa(payload); return packet->encode(size, (char*&)payload); } SrsSharedPtrMessage::SrsSharedPtr::SrsSharedPtr() { payload = NULL; size = 0; perfer_cid = 0; shared_count = 0; } SrsSharedPtrMessage::SrsSharedPtr::~SrsSharedPtr() { srs_freepa(payload); } SrsSharedPtrMessage::SrsSharedPtrMessage() { ptr = NULL; } SrsSharedPtrMessage::~SrsSharedPtrMessage() { if (ptr) { if (ptr->shared_count == 0) { srs_freep(ptr); } else { ptr->shared_count--; } } } bool SrsSharedPtrMessage::can_decode() { return false; } int SrsSharedPtrMessage::initialize(ISrsMessage* msg, char* payload, int size) { int ret = ERROR_SUCCESS; srs_assert(msg != NULL); if (ptr) { ret = ERROR_SYSTEM_ASSERT_FAILED; srs_error("should not set the payload twice. ret=%d", ret); srs_assert(false); return ret; } header = msg->header; header.payload_length = size; ptr = new SrsSharedPtr(); ptr->payload = payload; ptr->size = size; ptr->perfer_cid = msg->get_perfer_cid(); super::payload = (int8_t*)ptr->payload; super::size = ptr->size; return ret; } SrsSharedPtrMessage* SrsSharedPtrMessage::copy() { if (!ptr) { srs_error("invoke initialize to initialize the ptr."); srs_assert(false); return NULL; } SrsSharedPtrMessage* copy = new SrsSharedPtrMessage(); copy->header = header; copy->ptr = ptr; ptr->shared_count++; copy->payload = (int8_t*)ptr->payload; copy->size = ptr->size; return copy; } int SrsSharedPtrMessage::get_perfer_cid() { if (!ptr) { return 0; } return ptr->perfer_cid; } int SrsSharedPtrMessage::encode_packet() { srs_verbose("shared message ignore the encode method."); return ERROR_SUCCESS; } SrsPacket::SrsPacket() { } SrsPacket::~SrsPacket() { } int SrsPacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; srs_assert(stream != NULL); ret = ERROR_SYSTEM_PACKET_INVALID; srs_error("current packet is not support to decode. " "paket=%s, ret=%d", get_class_name(), ret); return ret; } int SrsPacket::get_perfer_cid() { return 0; } int SrsPacket::get_message_type() { return 0; } int SrsPacket::get_payload_length() { return get_size(); } int SrsPacket::encode(int& psize, char*& ppayload) { int ret = ERROR_SUCCESS; int size = get_size(); char* payload = NULL; SrsStream stream; if (size > 0) { payload = new char[size]; if ((ret = stream.initialize(payload, size)) != ERROR_SUCCESS) { srs_error("initialize the stream failed. ret=%d", ret); srs_freepa(payload); return ret; } } if ((ret = encode_packet(&stream)) != ERROR_SUCCESS) { srs_error("encode the packet failed. ret=%d", ret); srs_freepa(payload); return ret; } psize = size; ppayload = payload; srs_verbose("encode the packet success. size=%d", size); return ret; } int SrsPacket::get_size() { return 0; } int SrsPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; srs_assert(stream != NULL); ret = ERROR_SYSTEM_PACKET_INVALID; srs_error("current packet is not support to encode. " "paket=%s, ret=%d", get_class_name(), ret); return ret; } SrsConnectAppPacket::SrsConnectAppPacket() { command_name = RTMP_AMF0_COMMAND_CONNECT; transaction_id = 1; command_object = NULL; } SrsConnectAppPacket::~SrsConnectAppPacket() { srs_freep(command_object); } int SrsConnectAppPacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("amf0 decode connect command_name failed. ret=%d", ret); return ret; } if (command_name.empty() || command_name != RTMP_AMF0_COMMAND_CONNECT) { ret = ERROR_RTMP_AMF0_DECODE; srs_error("amf0 decode connect command_name failed. " "command_name=%s, ret=%d", command_name.c_str(), ret); return ret; } if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("amf0 decode connect transaction_id failed. ret=%d", ret); return ret; } if (transaction_id != 1.0) { ret = ERROR_RTMP_AMF0_DECODE; srs_error("amf0 decode connect transaction_id failed. " "required=%.1f, actual=%.1f, ret=%d", 1.0, transaction_id, ret); return ret; } if ((ret = srs_amf0_read_object(stream, command_object)) != ERROR_SUCCESS) { srs_error("amf0 decode connect command_object failed. ret=%d", ret); return ret; } if (command_object == NULL) { ret = ERROR_RTMP_AMF0_DECODE; srs_error("amf0 decode connect command_object failed. ret=%d", ret); return ret; } srs_info("amf0 decode connect packet success"); return ret; } SrsConnectAppResPacket::SrsConnectAppResPacket() { command_name = RTMP_AMF0_COMMAND_RESULT; transaction_id = 1; props = new SrsAmf0Object(); info = new SrsAmf0Object(); } SrsConnectAppResPacket::~SrsConnectAppResPacket() { srs_freep(props); srs_freep(info); } int SrsConnectAppResPacket::get_perfer_cid() { return RTMP_CID_OverConnection; } int SrsConnectAppResPacket::get_message_type() { return RTMP_MSG_AMF0CommandMessage; } int SrsConnectAppResPacket::get_size() { return srs_amf0_get_string_size(command_name) + srs_amf0_get_number_size() + srs_amf0_get_object_size(props)+ srs_amf0_get_object_size(info); } int SrsConnectAppResPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("encode command_name failed. ret=%d", ret); return ret; } srs_verbose("encode command_name success."); if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("encode transaction_id failed. ret=%d", ret); return ret; } srs_verbose("encode transaction_id success."); if ((ret = srs_amf0_write_object(stream, props)) != ERROR_SUCCESS) { srs_error("encode props failed. ret=%d", ret); return ret; } srs_verbose("encode props success."); if ((ret = srs_amf0_write_object(stream, info)) != ERROR_SUCCESS) { srs_error("encode info failed. ret=%d", ret); return ret; } srs_verbose("encode info success."); srs_info("encode connect app response packet success."); return ret; } SrsCreateStreamPacket::SrsCreateStreamPacket() { command_name = RTMP_AMF0_COMMAND_CREATE_STREAM; transaction_id = 2; command_object = new SrsAmf0Null(); } SrsCreateStreamPacket::~SrsCreateStreamPacket() { srs_freep(command_object); } int SrsCreateStreamPacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("amf0 decode createStream command_name failed. ret=%d", ret); return ret; } if (command_name.empty() || command_name != RTMP_AMF0_COMMAND_CREATE_STREAM) { ret = ERROR_RTMP_AMF0_DECODE; srs_error("amf0 decode createStream command_name failed. " "command_name=%s, ret=%d", command_name.c_str(), ret); return ret; } if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("amf0 decode createStream transaction_id failed. ret=%d", ret); return ret; } if ((ret = srs_amf0_read_null(stream)) != ERROR_SUCCESS) { srs_error("amf0 decode createStream command_object failed. ret=%d", ret); return ret; } srs_info("amf0 decode createStream packet success"); return ret; } SrsCreateStreamResPacket::SrsCreateStreamResPacket(double _transaction_id, double _stream_id) { command_name = RTMP_AMF0_COMMAND_RESULT; transaction_id = _transaction_id; command_object = new SrsAmf0Null(); stream_id = _stream_id; } SrsCreateStreamResPacket::~SrsCreateStreamResPacket() { srs_freep(command_object); } int SrsCreateStreamResPacket::get_perfer_cid() { return RTMP_CID_OverConnection; } int SrsCreateStreamResPacket::get_message_type() { return RTMP_MSG_AMF0CommandMessage; } int SrsCreateStreamResPacket::get_size() { return srs_amf0_get_string_size(command_name) + srs_amf0_get_number_size() + srs_amf0_get_null_size() + srs_amf0_get_number_size(); } int SrsCreateStreamResPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("encode command_name failed. ret=%d", ret); return ret; } srs_verbose("encode command_name success."); if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("encode transaction_id failed. ret=%d", ret); return ret; } srs_verbose("encode transaction_id success."); if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) { srs_error("encode command_object failed. ret=%d", ret); return ret; } srs_verbose("encode command_object success."); if ((ret = srs_amf0_write_number(stream, stream_id)) != ERROR_SUCCESS) { srs_error("encode stream_id failed. ret=%d", ret); return ret; } srs_verbose("encode stream_id success."); srs_info("encode createStream response packet success."); return ret; } SrsFMLEStartPacket::SrsFMLEStartPacket() { command_name = RTMP_AMF0_COMMAND_CREATE_STREAM; transaction_id = 0; command_object = new SrsAmf0Null(); } SrsFMLEStartPacket::~SrsFMLEStartPacket() { srs_freep(command_object); } int SrsFMLEStartPacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("amf0 decode FMLE start command_name failed. ret=%d", ret); return ret; } if (command_name.empty() || (command_name != RTMP_AMF0_COMMAND_RELEASE_STREAM && command_name != RTMP_AMF0_COMMAND_FC_PUBLISH && command_name != RTMP_AMF0_COMMAND_UNPUBLISH) ) { ret = ERROR_RTMP_AMF0_DECODE; srs_error("amf0 decode FMLE start command_name failed. " "command_name=%s, ret=%d", command_name.c_str(), ret); return ret; } if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("amf0 decode FMLE start transaction_id failed. ret=%d", ret); return ret; } if ((ret = srs_amf0_read_null(stream)) != ERROR_SUCCESS) { srs_error("amf0 decode FMLE start command_object failed. ret=%d", ret); return ret; } if ((ret = srs_amf0_read_string(stream, stream_name)) != ERROR_SUCCESS) { srs_error("amf0 decode FMLE start stream_name failed. ret=%d", ret); return ret; } srs_info("amf0 decode FMLE start packet success"); return ret; } SrsFMLEStartResPacket::SrsFMLEStartResPacket(double _transaction_id) { command_name = RTMP_AMF0_COMMAND_RESULT; transaction_id = _transaction_id; command_object = new SrsAmf0Null(); args = new SrsAmf0Undefined(); } SrsFMLEStartResPacket::~SrsFMLEStartResPacket() { srs_freep(command_object); srs_freep(args); } int SrsFMLEStartResPacket::get_perfer_cid() { return RTMP_CID_OverConnection; } int SrsFMLEStartResPacket::get_message_type() { return RTMP_MSG_AMF0CommandMessage; } int SrsFMLEStartResPacket::get_size() { return srs_amf0_get_string_size(command_name) + srs_amf0_get_number_size() + srs_amf0_get_null_size() + srs_amf0_get_undefined_size(); } int SrsFMLEStartResPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("encode command_name failed. ret=%d", ret); return ret; } srs_verbose("encode command_name success."); if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("encode transaction_id failed. ret=%d", ret); return ret; } srs_verbose("encode transaction_id success."); if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) { srs_error("encode command_object failed. ret=%d", ret); return ret; } srs_verbose("encode command_object success."); if ((ret = srs_amf0_write_undefined(stream)) != ERROR_SUCCESS) { srs_error("encode args failed. ret=%d", ret); return ret; } srs_verbose("encode args success."); srs_info("encode FMLE start response packet success."); return ret; } SrsPublishPacket::SrsPublishPacket() { command_name = RTMP_AMF0_COMMAND_PUBLISH; transaction_id = 0; command_object = new SrsAmf0Null(); type = "live"; } SrsPublishPacket::~SrsPublishPacket() { srs_freep(command_object); } int SrsPublishPacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("amf0 decode publish command_name failed. ret=%d", ret); return ret; } if (command_name.empty() || command_name != RTMP_AMF0_COMMAND_PUBLISH) { ret = ERROR_RTMP_AMF0_DECODE; srs_error("amf0 decode publish command_name failed. " "command_name=%s, ret=%d", command_name.c_str(), ret); return ret; } if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("amf0 decode publish transaction_id failed. ret=%d", ret); return ret; } if ((ret = srs_amf0_read_null(stream)) != ERROR_SUCCESS) { srs_error("amf0 decode publish command_object failed. ret=%d", ret); return ret; } if ((ret = srs_amf0_read_string(stream, stream_name)) != ERROR_SUCCESS) { srs_error("amf0 decode publish stream_name failed. ret=%d", ret); return ret; } if ((ret = srs_amf0_read_string(stream, type)) != ERROR_SUCCESS) { srs_error("amf0 decode publish type failed. ret=%d", ret); return ret; } srs_info("amf0 decode publish packet success"); return ret; } SrsPlayPacket::SrsPlayPacket() { command_name = RTMP_AMF0_COMMAND_PLAY; transaction_id = 0; command_object = new SrsAmf0Null(); start = -2; duration = -1; reset = true; } SrsPlayPacket::~SrsPlayPacket() { srs_freep(command_object); } int SrsPlayPacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("amf0 decode play command_name failed. ret=%d", ret); return ret; } if (command_name.empty() || command_name != RTMP_AMF0_COMMAND_PLAY) { ret = ERROR_RTMP_AMF0_DECODE; srs_error("amf0 decode play command_name failed. " "command_name=%s, ret=%d", command_name.c_str(), ret); return ret; } if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("amf0 decode play transaction_id failed. ret=%d", ret); return ret; } if ((ret = srs_amf0_read_null(stream)) != ERROR_SUCCESS) { srs_error("amf0 decode play command_object failed. ret=%d", ret); return ret; } if ((ret = srs_amf0_read_string(stream, stream_name)) != ERROR_SUCCESS) { srs_error("amf0 decode play stream_name failed. ret=%d", ret); return ret; } if (!stream->empty() && (ret = srs_amf0_read_number(stream, start)) != ERROR_SUCCESS) { srs_error("amf0 decode play start failed. ret=%d", ret); return ret; } if (!stream->empty() && (ret = srs_amf0_read_number(stream, duration)) != ERROR_SUCCESS) { srs_error("amf0 decode play duration failed. ret=%d", ret); return ret; } if (!stream->empty() && (ret = srs_amf0_read_boolean(stream, reset)) != ERROR_SUCCESS) { srs_error("amf0 decode play reset failed. ret=%d", ret); return ret; } srs_info("amf0 decode play packet success"); return ret; } SrsPlayResPacket::SrsPlayResPacket() { command_name = RTMP_AMF0_COMMAND_RESULT; transaction_id = 0; command_object = new SrsAmf0Null(); desc = new SrsAmf0Object(); } SrsPlayResPacket::~SrsPlayResPacket() { srs_freep(command_object); srs_freep(desc); } int SrsPlayResPacket::get_perfer_cid() { return RTMP_CID_OverStream; } int SrsPlayResPacket::get_message_type() { return RTMP_MSG_AMF0CommandMessage; } int SrsPlayResPacket::get_size() { return srs_amf0_get_string_size(command_name) + srs_amf0_get_number_size() + srs_amf0_get_null_size() + srs_amf0_get_object_size(desc); } int SrsPlayResPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("encode command_name failed. ret=%d", ret); return ret; } srs_verbose("encode command_name success."); if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("encode transaction_id failed. ret=%d", ret); return ret; } srs_verbose("encode transaction_id success."); if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) { srs_error("encode command_object failed. ret=%d", ret); return ret; } srs_verbose("encode command_object success."); if ((ret = srs_amf0_write_object(stream, desc)) != ERROR_SUCCESS) { srs_error("encode desc failed. ret=%d", ret); return ret; } srs_verbose("encode desc success."); srs_info("encode play response packet success."); return ret; } SrsOnBWDonePacket::SrsOnBWDonePacket() { command_name = RTMP_AMF0_COMMAND_ON_BW_DONE; transaction_id = 0; args = new SrsAmf0Null(); } SrsOnBWDonePacket::~SrsOnBWDonePacket() { srs_freep(args); } int SrsOnBWDonePacket::get_perfer_cid() { return RTMP_CID_OverConnection; } int SrsOnBWDonePacket::get_message_type() { return RTMP_MSG_AMF0CommandMessage; } int SrsOnBWDonePacket::get_size() { return srs_amf0_get_string_size(command_name) + srs_amf0_get_number_size() + srs_amf0_get_null_size(); } int SrsOnBWDonePacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("encode command_name failed. ret=%d", ret); return ret; } srs_verbose("encode command_name success."); if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("encode transaction_id failed. ret=%d", ret); return ret; } srs_verbose("encode transaction_id success."); if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) { srs_error("encode args failed. ret=%d", ret); return ret; } srs_verbose("encode args success."); srs_info("encode onBWDone packet success."); return ret; } SrsOnStatusCallPacket::SrsOnStatusCallPacket() { command_name = RTMP_AMF0_COMMAND_ON_STATUS; transaction_id = 0; args = new SrsAmf0Null(); data = new SrsAmf0Object(); } SrsOnStatusCallPacket::~SrsOnStatusCallPacket() { srs_freep(args); srs_freep(data); } int SrsOnStatusCallPacket::get_perfer_cid() { return RTMP_CID_OverStream; } int SrsOnStatusCallPacket::get_message_type() { return RTMP_MSG_AMF0CommandMessage; } int SrsOnStatusCallPacket::get_size() { return srs_amf0_get_string_size(command_name) + srs_amf0_get_number_size() + srs_amf0_get_null_size() + srs_amf0_get_object_size(data); } int SrsOnStatusCallPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("encode command_name failed. ret=%d", ret); return ret; } srs_verbose("encode command_name success."); if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("encode transaction_id failed. ret=%d", ret); return ret; } srs_verbose("encode transaction_id success."); if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) { srs_error("encode args failed. ret=%d", ret); return ret; } srs_verbose("encode args success.");; if ((ret = srs_amf0_write_object(stream, data)) != ERROR_SUCCESS) { srs_error("encode data failed. ret=%d", ret); return ret; } srs_verbose("encode data success."); srs_info("encode onStatus(Call) packet success."); return ret; } SrsOnStatusDataPacket::SrsOnStatusDataPacket() { command_name = RTMP_AMF0_COMMAND_ON_STATUS; data = new SrsAmf0Object(); } SrsOnStatusDataPacket::~SrsOnStatusDataPacket() { srs_freep(data); } int SrsOnStatusDataPacket::get_perfer_cid() { return RTMP_CID_OverStream; } int SrsOnStatusDataPacket::get_message_type() { return RTMP_MSG_AMF0DataMessage; } int SrsOnStatusDataPacket::get_size() { return srs_amf0_get_string_size(command_name) + srs_amf0_get_object_size(data); } int SrsOnStatusDataPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("encode command_name failed. ret=%d", ret); return ret; } srs_verbose("encode command_name success."); if ((ret = srs_amf0_write_object(stream, data)) != ERROR_SUCCESS) { srs_error("encode data failed. ret=%d", ret); return ret; } srs_verbose("encode data success."); srs_info("encode onStatus(Data) packet success."); return ret; } SrsSampleAccessPacket::SrsSampleAccessPacket() { command_name = RTMP_AMF0_DATA_SAMPLE_ACCESS; video_sample_access = false; audio_sample_access = false; } SrsSampleAccessPacket::~SrsSampleAccessPacket() { } int SrsSampleAccessPacket::get_perfer_cid() { return RTMP_CID_OverStream; } int SrsSampleAccessPacket::get_message_type() { return RTMP_MSG_AMF0DataMessage; } int SrsSampleAccessPacket::get_size() { return srs_amf0_get_string_size(command_name) + srs_amf0_get_boolean_size() + srs_amf0_get_boolean_size(); } int SrsSampleAccessPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("encode command_name failed. ret=%d", ret); return ret; } srs_verbose("encode command_name success."); if ((ret = srs_amf0_write_boolean(stream, video_sample_access)) != ERROR_SUCCESS) { srs_error("encode video_sample_access failed. ret=%d", ret); return ret; } srs_verbose("encode video_sample_access success."); if ((ret = srs_amf0_write_boolean(stream, audio_sample_access)) != ERROR_SUCCESS) { srs_error("encode audio_sample_access failed. ret=%d", ret); return ret; } srs_verbose("encode audio_sample_access success.");; srs_info("encode |RtmpSampleAccess packet success."); return ret; } SrsOnMetaDataPacket::SrsOnMetaDataPacket() { name = RTMP_AMF0_DATA_ON_METADATA; metadata = new SrsAmf0Object(); } SrsOnMetaDataPacket::~SrsOnMetaDataPacket() { srs_freep(metadata); } int SrsOnMetaDataPacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_read_string(stream, name)) != ERROR_SUCCESS) { srs_error("decode metadata name failed. ret=%d", ret); return ret; } // ignore the @setDataFrame if (name == RTMP_AMF0_DATA_SET_DATAFRAME) { if ((ret = srs_amf0_read_string(stream, name)) != ERROR_SUCCESS) { srs_error("decode metadata name failed. ret=%d", ret); return ret; } } srs_verbose("decode metadata name success. name=%s", name.c_str()); // the metadata maybe object or ecma array SrsAmf0Any* any = NULL; if ((ret = srs_amf0_read_any(stream, any)) != ERROR_SUCCESS) { srs_error("decode metadata metadata failed. ret=%d", ret); return ret; } if (any->is_object()) { srs_freep(metadata); metadata = srs_amf0_convert<SrsAmf0Object>(any); srs_info("decode metadata object success"); return ret; } SrsASrsAmf0EcmaArray* arr = dynamic_cast<SrsASrsAmf0EcmaArray*>(any); if (!arr) { ret = ERROR_RTMP_AMF0_DECODE; srs_error("decode metadata array failed. ret=%d", ret); srs_freep(any); return ret; } for (int i = 0; i < arr->size(); i++) { metadata->set(arr->key_at(i), arr->value_at(i)); } arr->clear(); srs_info("decode metadata array success"); return ret; } int SrsOnMetaDataPacket::get_perfer_cid() { return RTMP_CID_OverConnection2; } int SrsOnMetaDataPacket::get_message_type() { return RTMP_MSG_AMF0DataMessage; } int SrsOnMetaDataPacket::get_size() { return srs_amf0_get_string_size(name) + srs_amf0_get_object_size(metadata); } int SrsOnMetaDataPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, name)) != ERROR_SUCCESS) { srs_error("encode name failed. ret=%d", ret); return ret; } srs_verbose("encode name success."); if ((ret = srs_amf0_write_object(stream, metadata)) != ERROR_SUCCESS) { srs_error("encode metadata failed. ret=%d", ret); return ret; } srs_verbose("encode metadata success."); srs_info("encode onMetaData packet success."); return ret; } SrsSetWindowAckSizePacket::SrsSetWindowAckSizePacket() { ackowledgement_window_size = 0; } SrsSetWindowAckSizePacket::~SrsSetWindowAckSizePacket() { } int SrsSetWindowAckSizePacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; if (!stream->require(4)) { ret = ERROR_RTMP_MESSAGE_DECODE; srs_error("decode ack window size failed. ret=%d", ret); return ret; } ackowledgement_window_size = stream->read_4bytes(); srs_info("decode ack window size success"); return ret; } int SrsSetWindowAckSizePacket::get_perfer_cid() { return RTMP_CID_ProtocolControl; } int SrsSetWindowAckSizePacket::get_message_type() { return RTMP_MSG_WindowAcknowledgementSize; } int SrsSetWindowAckSizePacket::get_size() { return 4; } int SrsSetWindowAckSizePacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if (!stream->require(4)) { ret = ERROR_RTMP_MESSAGE_ENCODE; srs_error("encode ack size packet failed. ret=%d", ret); return ret; } stream->write_4bytes(ackowledgement_window_size); srs_verbose("encode ack size packet " "success. ack_size=%d", ackowledgement_window_size); return ret; } SrsSetChunkSizePacket::SrsSetChunkSizePacket() { chunk_size = RTMP_DEFAULT_CHUNK_SIZE; } SrsSetChunkSizePacket::~SrsSetChunkSizePacket() { } int SrsSetChunkSizePacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; if (!stream->require(4)) { ret = ERROR_RTMP_MESSAGE_DECODE; srs_error("decode chunk size failed. ret=%d", ret); return ret; } chunk_size = stream->read_4bytes(); srs_info("decode chunk size success. chunk_size=%d", chunk_size); if (chunk_size < RTMP_MIN_CHUNK_SIZE) { ret = ERROR_RTMP_CHUNK_SIZE; srs_error("invalid chunk size. min=%d, actual=%d, ret=%d", ERROR_RTMP_CHUNK_SIZE, chunk_size, ret); return ret; } return ret; } int SrsSetChunkSizePacket::get_perfer_cid() { return RTMP_CID_ProtocolControl; } int SrsSetChunkSizePacket::get_message_type() { return RTMP_MSG_SetChunkSize; } int SrsSetChunkSizePacket::get_size() { return 4; } int SrsSetChunkSizePacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if (!stream->require(4)) { ret = ERROR_RTMP_MESSAGE_ENCODE; srs_error("encode chunk packet failed. ret=%d", ret); return ret; } stream->write_4bytes(chunk_size); srs_verbose("encode chunk packet success. ack_size=%d", chunk_size); return ret; } SrsSetPeerBandwidthPacket::SrsSetPeerBandwidthPacket() { bandwidth = 0; type = 2; } SrsSetPeerBandwidthPacket::~SrsSetPeerBandwidthPacket() { } int SrsSetPeerBandwidthPacket::get_perfer_cid() { return RTMP_CID_ProtocolControl; } int SrsSetPeerBandwidthPacket::get_message_type() { return RTMP_MSG_SetPeerBandwidth; } int SrsSetPeerBandwidthPacket::get_size() { return 5; } int SrsSetPeerBandwidthPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if (!stream->require(5)) { ret = ERROR_RTMP_MESSAGE_ENCODE; srs_error("encode set bandwidth packet failed. ret=%d", ret); return ret; } stream->write_4bytes(bandwidth); stream->write_1bytes(type); srs_verbose("encode set bandwidth packet " "success. bandwidth=%d, type=%d", bandwidth, type); return ret; } SrsPCUC4BytesPacket::SrsPCUC4BytesPacket() { event_type = 0; event_data = 0; } SrsPCUC4BytesPacket::~SrsPCUC4BytesPacket() { } int SrsPCUC4BytesPacket::get_perfer_cid() { return RTMP_CID_ProtocolControl; } int SrsPCUC4BytesPacket::get_message_type() { return RTMP_MSG_UserControlMessage; } int SrsPCUC4BytesPacket::get_size() { return 2 + 4; } int SrsPCUC4BytesPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if (!stream->require(6)) { ret = ERROR_RTMP_MESSAGE_ENCODE; srs_error("encode set bandwidth packet failed. ret=%d", ret); return ret; } stream->write_2bytes(event_type); stream->write_4bytes(event_data); srs_verbose("encode PCUC packet success. " "event_type=%d, event_data=%d", event_type, event_data); return ret; } support FMLE/FFMPEG publish vp6 codec, h264/aac not support yet /* The MIT License (MIT) Copyright (c) 2013 winlin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <srs_core_protocol.hpp> #include <srs_core_log.hpp> #include <srs_core_amf0.hpp> #include <srs_core_error.hpp> #include <srs_core_socket.hpp> #include <srs_core_buffer.hpp> #include <srs_core_stream.hpp> #include <srs_core_auto_free.hpp> /**************************************************************************** ***************************************************************************** ****************************************************************************/ /** 5. Protocol Control Messages RTMP reserves message type IDs 1-7 for protocol control messages. These messages contain information needed by the RTM Chunk Stream protocol or RTMP itself. Protocol messages with IDs 1 & 2 are reserved for usage with RTM Chunk Stream protocol. Protocol messages with IDs 3-6 are reserved for usage of RTMP. Protocol message with ID 7 is used between edge server and origin server. */ #define RTMP_MSG_SetChunkSize 0x01 #define RTMP_MSG_AbortMessage 0x02 #define RTMP_MSG_Acknowledgement 0x03 #define RTMP_MSG_UserControlMessage 0x04 #define RTMP_MSG_WindowAcknowledgementSize 0x05 #define RTMP_MSG_SetPeerBandwidth 0x06 #define RTMP_MSG_EdgeAndOriginServerCommand 0x07 /** 3. Types of messages The server and the client send messages over the network to communicate with each other. The messages can be of any type which includes audio messages, video messages, command messages, shared object messages, data messages, and user control messages. 3.1. Command message Command messages carry the AMF-encoded commands between the client and the server. These messages have been assigned message type value of 20 for AMF0 encoding and message type value of 17 for AMF3 encoding. These messages are sent to perform some operations like connect, createStream, publish, play, pause on the peer. Command messages like onstatus, result etc. are used to inform the sender about the status of the requested commands. A command message consists of command name, transaction ID, and command object that contains related parameters. A client or a server can request Remote Procedure Calls (RPC) over streams that are communicated using the command messages to the peer. */ #define RTMP_MSG_AMF3CommandMessage 17 // 0x11 #define RTMP_MSG_AMF0CommandMessage 20 // 0x14 /** 3.2. Data message The client or the server sends this message to send Metadata or any user data to the peer. Metadata includes details about the data(audio, video etc.) like creation time, duration, theme and so on. These messages have been assigned message type value of 18 for AMF0 and message type value of 15 for AMF3. */ #define RTMP_MSG_AMF0DataMessage 18 // 0x12 #define RTMP_MSG_AMF3DataMessage 15 // 0x0F /** 3.3. Shared object message A shared object is a Flash object (a collection of name value pairs) that are in synchronization across multiple clients, instances, and so on. The message types kMsgContainer=19 for AMF0 and kMsgContainerEx=16 for AMF3 are reserved for shared object events. Each message can contain multiple events. */ #define RTMP_MSG_AMF3SharedObject 16 // 0x10 #define RTMP_MSG_AMF0SharedObject 19 // 0x13 /** 3.4. Audio message The client or the server sends this message to send audio data to the peer. The message type value of 8 is reserved for audio messages. */ #define RTMP_MSG_AudioMessage 8 // 0x08 /* * 3.5. Video message The client or the server sends this message to send video data to the peer. The message type value of 9 is reserved for video messages. These messages are large and can delay the sending of other type of messages. To avoid such a situation, the video message is assigned the lowest priority. */ #define RTMP_MSG_VideoMessage 9 // 0x09 /** 3.6. Aggregate message An aggregate message is a single message that contains a list of submessages. The message type value of 22 is reserved for aggregate messages. */ #define RTMP_MSG_AggregateMessage 22 // 0x16 /**************************************************************************** ***************************************************************************** ****************************************************************************/ /** * 6.1.2. Chunk Message Header * There are four different formats for the chunk message header, * selected by the "fmt" field in the chunk basic header. */ // 6.1.2.1. Type 0 // Chunks of Type 0 are 11 bytes long. This type MUST be used at the // start of a chunk stream, and whenever the stream timestamp goes // backward (e.g., because of a backward seek). #define RTMP_FMT_TYPE0 0 // 6.1.2.2. Type 1 // Chunks of Type 1 are 7 bytes long. The message stream ID is not // included; this chunk takes the same stream ID as the preceding chunk. // Streams with variable-sized messages (for example, many video // formats) SHOULD use this format for the first chunk of each new // message after the first. #define RTMP_FMT_TYPE1 1 // 6.1.2.3. Type 2 // Chunks of Type 2 are 3 bytes long. Neither the stream ID nor the // message length is included; this chunk has the same stream ID and // message length as the preceding chunk. Streams with constant-sized // messages (for example, some audio and data formats) SHOULD use this // format for the first chunk of each message after the first. #define RTMP_FMT_TYPE2 2 // 6.1.2.4. Type 3 // Chunks of Type 3 have no header. Stream ID, message length and // timestamp delta are not present; chunks of this type take values from // the preceding chunk. When a single message is split into chunks, all // chunks of a message except the first one, SHOULD use this type. Refer // to example 2 in section 6.2.2. Stream consisting of messages of // exactly the same size, stream ID and spacing in time SHOULD use this // type for all chunks after chunk of Type 2. Refer to example 1 in // section 6.2.1. If the delta between the first message and the second // message is same as the time stamp of first message, then chunk of // type 3 would immediately follow the chunk of type 0 as there is no // need for a chunk of type 2 to register the delta. If Type 3 chunk // follows a Type 0 chunk, then timestamp delta for this Type 3 chunk is // the same as the timestamp of Type 0 chunk. #define RTMP_FMT_TYPE3 3 /**************************************************************************** ***************************************************************************** ****************************************************************************/ /** * 6. Chunking * The chunk size is configurable. It can be set using a control * message(Set Chunk Size) as described in section 7.1. The maximum * chunk size can be 65536 bytes and minimum 128 bytes. Larger values * reduce CPU usage, but also commit to larger writes that can delay * other content on lower bandwidth connections. Smaller chunks are not * good for high-bit rate streaming. Chunk size is maintained * independently for each direction. */ #define RTMP_DEFAULT_CHUNK_SIZE 128 #define RTMP_MIN_CHUNK_SIZE 2 /** * 6.1. Chunk Format * Extended timestamp: 0 or 4 bytes * This field MUST be sent when the normal timsestamp is set to * 0xffffff, it MUST NOT be sent if the normal timestamp is set to * anything else. So for values less than 0xffffff the normal * timestamp field SHOULD be used in which case the extended timestamp * MUST NOT be present. For values greater than or equal to 0xffffff * the normal timestamp field MUST NOT be used and MUST be set to * 0xffffff and the extended timestamp MUST be sent. */ #define RTMP_EXTENDED_TIMESTAMP 0xFFFFFF /**************************************************************************** ***************************************************************************** ****************************************************************************/ /** * amf0 command message, command name macros */ #define RTMP_AMF0_COMMAND_CONNECT "connect" #define RTMP_AMF0_COMMAND_CREATE_STREAM "createStream" #define RTMP_AMF0_COMMAND_PLAY "play" #define RTMP_AMF0_COMMAND_ON_BW_DONE "onBWDone" #define RTMP_AMF0_COMMAND_ON_STATUS "onStatus" #define RTMP_AMF0_COMMAND_RESULT "_result" #define RTMP_AMF0_COMMAND_RELEASE_STREAM "releaseStream" #define RTMP_AMF0_COMMAND_FC_PUBLISH "FCPublish" #define RTMP_AMF0_COMMAND_UNPUBLISH "FCUnpublish" #define RTMP_AMF0_COMMAND_PUBLISH "publish" #define RTMP_AMF0_DATA_SAMPLE_ACCESS "|RtmpSampleAccess" #define RTMP_AMF0_DATA_SET_DATAFRAME "@setDataFrame" #define RTMP_AMF0_DATA_ON_METADATA "onMetaData" /**************************************************************************** ***************************************************************************** ****************************************************************************/ /** * the chunk stream id used for some under-layer message, * for example, the PC(protocol control) message. */ #define RTMP_CID_ProtocolControl 0x02 /** * the AMF0/AMF3 command message, invoke method and return the result, over NetConnection. * generally use 0x03. */ #define RTMP_CID_OverConnection 0x03 /** * the AMF0/AMF3 command message, invoke method and return the result, over NetConnection, * the midst state(we guess). * rarely used, e.g. onStatus(NetStream.Play.Reset). */ #define RTMP_CID_OverConnection2 0x04 /** * the stream message(amf0/amf3), over NetStream. * generally use 0x05. */ #define RTMP_CID_OverStream 0x05 /** * the stream message(amf0/amf3), over NetStream, the midst state(we guess). * rarely used, e.g. play("mp4:mystram.f4v") */ #define RTMP_CID_OverStream2 0x08 /** * the stream message(video), over NetStream * generally use 0x06. */ #define RTMP_CID_Video 0x06 /** * the stream message(audio), over NetStream. * generally use 0x07. */ #define RTMP_CID_Audio 0x07 /**************************************************************************** ***************************************************************************** ****************************************************************************/ SrsProtocol::SrsProtocol(st_netfd_t client_stfd) { stfd = client_stfd; buffer = new SrsBuffer(); skt = new SrsSocket(stfd); in_chunk_size = out_chunk_size = RTMP_DEFAULT_CHUNK_SIZE; } SrsProtocol::~SrsProtocol() { std::map<int, SrsChunkStream*>::iterator it; for (it = chunk_streams.begin(); it != chunk_streams.end(); ++it) { SrsChunkStream* stream = it->second; srs_freep(stream); } chunk_streams.clear(); srs_freep(buffer); srs_freep(skt); } int SrsProtocol::can_read(int timeout_ms, bool& ready) { return skt->can_read(timeout_ms, ready); } int SrsProtocol::recv_message(SrsCommonMessage** pmsg) { *pmsg = NULL; int ret = ERROR_SUCCESS; while (true) { SrsCommonMessage* msg = NULL; if ((ret = recv_interlaced_message(&msg)) != ERROR_SUCCESS) { srs_error("recv interlaced message failed. ret=%d", ret); return ret; } srs_verbose("entire msg received"); if (!msg) { continue; } if (msg->size <= 0 || msg->header.payload_length <= 0) { srs_trace("ignore empty message(type=%d, size=%d, time=%d, sid=%d).", msg->header.message_type, msg->header.payload_length, msg->header.timestamp, msg->header.stream_id); srs_freep(msg); continue; } if ((ret = on_recv_message(msg)) != ERROR_SUCCESS) { srs_error("hook the received msg failed. ret=%d", ret); srs_freep(msg); return ret; } srs_verbose("get a msg with raw/undecoded payload"); *pmsg = msg; break; } return ret; } int SrsProtocol::send_message(ISrsMessage* msg) { int ret = ERROR_SUCCESS; // free msg whatever return value. SrsAutoFree(ISrsMessage, msg, false); if ((ret = msg->encode_packet()) != ERROR_SUCCESS) { srs_error("encode packet to message payload failed. ret=%d", ret); return ret; } srs_info("encode packet to message payload success"); // p set to current write position, // it's ok when payload is NULL and size is 0. char* p = (char*)msg->payload; // always write the header event payload is empty. do { // generate the header. char* pheader = NULL; int header_size = 0; if (p == (char*)msg->payload) { // write new chunk stream header, fmt is 0 pheader = out_header_fmt0; *pheader++ = 0x00 | (msg->get_perfer_cid() & 0x3F); // chunk message header, 11 bytes // timestamp, 3bytes, big-endian if (msg->header.timestamp >= RTMP_EXTENDED_TIMESTAMP) { *pheader++ = 0xFF; *pheader++ = 0xFF; *pheader++ = 0xFF; } else { pp = (char*)&msg->header.timestamp; *pheader++ = pp[2]; *pheader++ = pp[1]; *pheader++ = pp[0]; } // message_length, 3bytes, big-endian pp = (char*)&msg->header.payload_length; *pheader++ = pp[2]; *pheader++ = pp[1]; *pheader++ = pp[0]; // message_type, 1bytes *pheader++ = msg->header.message_type; // message_length, 3bytes, little-endian pp = (char*)&msg->header.stream_id; *pheader++ = pp[0]; *pheader++ = pp[1]; *pheader++ = pp[2]; *pheader++ = pp[3]; // chunk extended timestamp header, 0 or 4 bytes, big-endian if(msg->header.timestamp >= RTMP_EXTENDED_TIMESTAMP){ pp = (char*)&msg->header.timestamp; *pheader++ = pp[3]; *pheader++ = pp[2]; *pheader++ = pp[1]; *pheader++ = pp[0]; } header_size = pheader - out_header_fmt0; pheader = out_header_fmt0; } else { // write no message header chunk stream, fmt is 3 pheader = out_header_fmt3; *pheader++ = 0xC0 | (msg->get_perfer_cid() & 0x3F); // chunk extended timestamp header, 0 or 4 bytes, big-endian if(msg->header.timestamp >= RTMP_EXTENDED_TIMESTAMP){ pp = (char*)&msg->header.timestamp; *pheader++ = pp[3]; *pheader++ = pp[2]; *pheader++ = pp[1]; *pheader++ = pp[0]; } header_size = pheader - out_header_fmt3; pheader = out_header_fmt3; } // sendout header and payload by writev. // decrease the sys invoke count to get higher performance. int payload_size = msg->size - (p - (char*)msg->payload); payload_size = srs_min(payload_size, out_chunk_size); // send by writev iovec iov[2]; iov[0].iov_base = pheader; iov[0].iov_len = header_size; iov[1].iov_base = p; iov[1].iov_len = payload_size; ssize_t nwrite; if ((ret = skt->writev(iov, 2, &nwrite)) != ERROR_SUCCESS) { srs_error("send with writev failed. ret=%d", ret); return ret; } // consume sendout bytes when not empty packet. if (msg->payload && msg->size > 0) { p += payload_size; } } while (p < (char*)msg->payload + msg->size); if ((ret = on_send_message(msg)) != ERROR_SUCCESS) { srs_error("hook the send message failed. ret=%d", ret); return ret; } return ret; } int SrsProtocol::on_recv_message(SrsCommonMessage* msg) { int ret = ERROR_SUCCESS; srs_assert(msg != NULL); switch (msg->header.message_type) { case RTMP_MSG_SetChunkSize: case RTMP_MSG_WindowAcknowledgementSize: if ((ret = msg->decode_packet()) != ERROR_SUCCESS) { srs_error("decode packet from message payload failed. ret=%d", ret); return ret; } srs_verbose("decode packet from message payload success."); break; } switch (msg->header.message_type) { case RTMP_MSG_WindowAcknowledgementSize: { SrsSetWindowAckSizePacket* pkt = dynamic_cast<SrsSetWindowAckSizePacket*>(msg->get_packet()); srs_assert(pkt != NULL); // TODO: take effect. srs_trace("set ack window size to %d", pkt->ackowledgement_window_size); break; } case RTMP_MSG_SetChunkSize: { SrsSetChunkSizePacket* pkt = dynamic_cast<SrsSetChunkSizePacket*>(msg->get_packet()); srs_assert(pkt != NULL); in_chunk_size = pkt->chunk_size; srs_trace("set input chunk size to %d", pkt->chunk_size); break; } } return ret; } int SrsProtocol::on_send_message(ISrsMessage* msg) { int ret = ERROR_SUCCESS; if (!msg->can_decode()) { srs_verbose("ignore the un-decodable message."); return ret; } SrsCommonMessage* common_msg = dynamic_cast<SrsCommonMessage*>(msg); if (!msg) { srs_verbose("ignore the shared ptr message."); return ret; } srs_assert(common_msg != NULL); switch (common_msg->header.message_type) { case RTMP_MSG_SetChunkSize: { SrsSetChunkSizePacket* pkt = dynamic_cast<SrsSetChunkSizePacket*>(common_msg->get_packet()); srs_assert(pkt != NULL); out_chunk_size = pkt->chunk_size; srs_trace("set output chunk size to %d", pkt->chunk_size); break; } } return ret; } int SrsProtocol::recv_interlaced_message(SrsCommonMessage** pmsg) { int ret = ERROR_SUCCESS; // chunk stream basic header. char fmt = 0; int cid = 0; int bh_size = 0; if ((ret = read_basic_header(fmt, cid, bh_size)) != ERROR_SUCCESS) { srs_error("read basic header failed. ret=%d", ret); return ret; } srs_info("read basic header success. fmt=%d, cid=%d, bh_size=%d", fmt, cid, bh_size); // get the cached chunk stream. SrsChunkStream* chunk = NULL; if (chunk_streams.find(cid) == chunk_streams.end()) { chunk = chunk_streams[cid] = new SrsChunkStream(cid); srs_info("cache new chunk stream: fmt=%d, cid=%d", fmt, cid); } else { chunk = chunk_streams[cid]; srs_info("cached chunk stream: fmt=%d, cid=%d, size=%d, message(type=%d, size=%d, time=%d, sid=%d)", chunk->fmt, chunk->cid, (chunk->msg? chunk->msg->size : 0), chunk->header.message_type, chunk->header.payload_length, chunk->header.timestamp, chunk->header.stream_id); } // chunk stream message header int mh_size = 0; if ((ret = read_message_header(chunk, fmt, bh_size, mh_size)) != ERROR_SUCCESS) { srs_error("read message header failed. ret=%d", ret); return ret; } srs_info("read message header success. " "fmt=%d, mh_size=%d, ext_time=%d, size=%d, message(type=%d, size=%d, time=%d, sid=%d)", fmt, mh_size, chunk->extended_timestamp, (chunk->msg? chunk->msg->size : 0), chunk->header.message_type, chunk->header.payload_length, chunk->header.timestamp, chunk->header.stream_id); // read msg payload from chunk stream. SrsCommonMessage* msg = NULL; int payload_size = 0; if ((ret = read_message_payload(chunk, bh_size, mh_size, payload_size, &msg)) != ERROR_SUCCESS) { srs_error("read message payload failed. ret=%d", ret); return ret; } // not got an entire RTMP message, try next chunk. if (!msg) { srs_info("get partial message success. chunk_payload_size=%d, size=%d, message(type=%d, size=%d, time=%d, sid=%d)", payload_size, (msg? msg->size : (chunk->msg? chunk->msg->size : 0)), chunk->header.message_type, chunk->header.payload_length, chunk->header.timestamp, chunk->header.stream_id); return ret; } *pmsg = msg; srs_info("get entire message success. chunk_payload_size=%d, size=%d, message(type=%d, size=%d, time=%d, sid=%d)", payload_size, (msg? msg->size : (chunk->msg? chunk->msg->size : 0)), chunk->header.message_type, chunk->header.payload_length, chunk->header.timestamp, chunk->header.stream_id); return ret; } int SrsProtocol::read_basic_header(char& fmt, int& cid, int& bh_size) { int ret = ERROR_SUCCESS; int required_size = 1; if ((ret = buffer->ensure_buffer_bytes(skt, required_size)) != ERROR_SUCCESS) { srs_error("read 1bytes basic header failed. required_size=%d, ret=%d", required_size, ret); return ret; } char* p = buffer->bytes(); fmt = (*p >> 6) & 0x03; cid = *p & 0x3f; bh_size = 1; if (cid > 1) { srs_verbose("%dbytes basic header parsed. fmt=%d, cid=%d", bh_size, fmt, cid); return ret; } if (cid == 0) { required_size = 2; if ((ret = buffer->ensure_buffer_bytes(skt, required_size)) != ERROR_SUCCESS) { srs_error("read 2bytes basic header failed. required_size=%d, ret=%d", required_size, ret); return ret; } cid = 64; cid += *(++p); bh_size = 2; srs_verbose("%dbytes basic header parsed. fmt=%d, cid=%d", bh_size, fmt, cid); } else if (cid == 1) { required_size = 3; if ((ret = buffer->ensure_buffer_bytes(skt, 3)) != ERROR_SUCCESS) { srs_error("read 3bytes basic header failed. required_size=%d, ret=%d", required_size, ret); return ret; } cid = 64; cid += *(++p); cid += *(++p) * 256; bh_size = 3; srs_verbose("%dbytes basic header parsed. fmt=%d, cid=%d", bh_size, fmt, cid); } else { srs_error("invalid path, impossible basic header."); srs_assert(false); } return ret; } int SrsProtocol::read_message_header(SrsChunkStream* chunk, char fmt, int bh_size, int& mh_size) { int ret = ERROR_SUCCESS; /** * we should not assert anything about fmt, for the first packet. * (when first packet, the chunk->msg is NULL). * the fmt maybe 0/1/2/3, the FMLE will send a 0xC4 for some audio packet. * the previous packet is: * 04 // fmt=0, cid=4 * 00 00 1a // timestamp=26 * 00 00 9d // payload_length=157 * 08 // message_type=8(audio) * 01 00 00 00 // stream_id=1 * the current packet maybe: * c4 // fmt=3, cid=4 * it's ok, for the packet is audio, and timestamp delta is 26. * the current packet must be parsed as: * fmt=0, cid=4 * timestamp=26+26=52 * payload_length=157 * message_type=8(audio) * stream_id=1 * so we must update the timestamp even fmt=3 for first packet. */ // fresh packet used to update the timestamp even fmt=3 for first packet. bool is_fresh_packet = !chunk->msg; // but, we can ensure that when a chunk stream is fresh, // the fmt must be 0, a new stream. if (chunk->msg_count == 0 && fmt != RTMP_FMT_TYPE0) { ret = ERROR_RTMP_CHUNK_START; srs_error("chunk stream is fresh, " "fmt must be %d, actual is %d. ret=%d", RTMP_FMT_TYPE0, fmt, ret); return ret; } // when exists cache msg, means got an partial message, // the fmt must not be type0 which means new message. if (chunk->msg && fmt == RTMP_FMT_TYPE0) { ret = ERROR_RTMP_CHUNK_START; srs_error("chunk stream exists, " "fmt must not be %d, actual is %d. ret=%d", RTMP_FMT_TYPE0, fmt, ret); return ret; } // create msg when new chunk stream start if (!chunk->msg) { chunk->msg = new SrsCommonMessage(); srs_verbose("create message for new chunk, fmt=%d, cid=%d", fmt, chunk->cid); } // read message header from socket to buffer. static char mh_sizes[] = {11, 7, 3, 0}; mh_size = mh_sizes[(int)fmt]; srs_verbose("calc chunk message header size. fmt=%d, mh_size=%d", fmt, mh_size); int required_size = bh_size + mh_size; if ((ret = buffer->ensure_buffer_bytes(skt, required_size)) != ERROR_SUCCESS) { srs_error("read %dbytes message header failed. required_size=%d, ret=%d", mh_size, required_size, ret); return ret; } char* p = buffer->bytes() + bh_size; // parse the message header. // see also: ngx_rtmp_recv if (fmt <= RTMP_FMT_TYPE2) { char* pp = (char*)&chunk->header.timestamp_delta; pp[2] = *p++; pp[1] = *p++; pp[0] = *p++; pp[3] = 0; if (fmt == RTMP_FMT_TYPE0) { // 6.1.2.1. Type 0 // For a type-0 chunk, the absolute timestamp of the message is sent // here. chunk->header.timestamp = chunk->header.timestamp_delta; } else { // 6.1.2.2. Type 1 // 6.1.2.3. Type 2 // For a type-1 or type-2 chunk, the difference between the previous // chunk's timestamp and the current chunk's timestamp is sent here. chunk->header.timestamp += chunk->header.timestamp_delta; } // fmt: 0 // timestamp: 3 bytes // If the timestamp is greater than or equal to 16777215 // (hexadecimal 0x00ffffff), this value MUST be 16777215, and the // ‘extended timestamp header’ MUST be present. Otherwise, this value // SHOULD be the entire timestamp. // // fmt: 1 or 2 // timestamp delta: 3 bytes // If the delta is greater than or equal to 16777215 (hexadecimal // 0x00ffffff), this value MUST be 16777215, and the ‘extended // timestamp header’ MUST be present. Otherwise, this value SHOULD be // the entire delta. chunk->extended_timestamp = (chunk->header.timestamp_delta >= RTMP_EXTENDED_TIMESTAMP); if (chunk->extended_timestamp) { chunk->header.timestamp = RTMP_EXTENDED_TIMESTAMP; } if (fmt <= RTMP_FMT_TYPE1) { pp = (char*)&chunk->header.payload_length; pp[2] = *p++; pp[1] = *p++; pp[0] = *p++; pp[3] = 0; chunk->header.message_type = *p++; if (fmt == 0) { pp = (char*)&chunk->header.stream_id; pp[0] = *p++; pp[1] = *p++; pp[2] = *p++; pp[3] = *p++; srs_verbose("header read completed. fmt=%d, mh_size=%d, ext_time=%d, time=%d, payload=%d, type=%d, sid=%d", fmt, mh_size, chunk->extended_timestamp, chunk->header.timestamp, chunk->header.payload_length, chunk->header.message_type, chunk->header.stream_id); } else { srs_verbose("header read completed. fmt=%d, mh_size=%d, ext_time=%d, time=%d, payload=%d, type=%d", fmt, mh_size, chunk->extended_timestamp, chunk->header.timestamp, chunk->header.payload_length, chunk->header.message_type); } } else { srs_verbose("header read completed. fmt=%d, mh_size=%d, ext_time=%d, time=%d", fmt, mh_size, chunk->extended_timestamp, chunk->header.timestamp); } } else { // update the timestamp even fmt=3 for first stream if (is_fresh_packet && !chunk->extended_timestamp) { chunk->header.timestamp += chunk->header.timestamp_delta; } srs_verbose("header read completed. fmt=%d, size=%d, ext_time=%d", fmt, mh_size, chunk->extended_timestamp); } if (chunk->extended_timestamp) { mh_size += 4; required_size = bh_size + mh_size; srs_verbose("read header ext time. fmt=%d, ext_time=%d, mh_size=%d", fmt, chunk->extended_timestamp, mh_size); if ((ret = buffer->ensure_buffer_bytes(skt, required_size)) != ERROR_SUCCESS) { srs_error("read %dbytes message header failed. required_size=%d, ret=%d", mh_size, required_size, ret); return ret; } char* pp = (char*)&chunk->header.timestamp; pp[3] = *p++; pp[2] = *p++; pp[1] = *p++; pp[0] = *p++; srs_verbose("header read ext_time completed. time=%d", chunk->header.timestamp); } // valid message if (chunk->header.payload_length < 0) { ret = ERROR_RTMP_MSG_INVLIAD_SIZE; srs_error("RTMP message size must not be negative. size=%d, ret=%d", chunk->header.payload_length, ret); return ret; } // copy header to msg chunk->msg->header = chunk->header; // increase the msg count, the chunk stream can accept fmt=1/2/3 message now. chunk->msg_count++; return ret; } int SrsProtocol::read_message_payload(SrsChunkStream* chunk, int bh_size, int mh_size, int& payload_size, SrsCommonMessage** pmsg) { int ret = ERROR_SUCCESS; // empty message if (chunk->header.payload_length == 0) { // need erase the header in buffer. buffer->erase(bh_size + mh_size); srs_trace("get an empty RTMP " "message(type=%d, size=%d, time=%d, sid=%d)", chunk->header.message_type, chunk->header.payload_length, chunk->header.timestamp, chunk->header.stream_id); *pmsg = chunk->msg; chunk->msg = NULL; return ret; } srs_assert(chunk->header.payload_length > 0); // the chunk payload size. payload_size = chunk->header.payload_length - chunk->msg->size; payload_size = srs_min(payload_size, in_chunk_size); srs_verbose("chunk payload size is %d, message_size=%d, received_size=%d, in_chunk_size=%d", payload_size, chunk->header.payload_length, chunk->msg->size, in_chunk_size); // create msg payload if not initialized if (!chunk->msg->payload) { chunk->msg->payload = new int8_t[chunk->header.payload_length]; memset(chunk->msg->payload, 0, chunk->header.payload_length); srs_verbose("create empty payload for RTMP message. size=%d", chunk->header.payload_length); } // read payload to buffer int required_size = bh_size + mh_size + payload_size; if ((ret = buffer->ensure_buffer_bytes(skt, required_size)) != ERROR_SUCCESS) { srs_error("read payload failed. required_size=%d, ret=%d", required_size, ret); return ret; } memcpy(chunk->msg->payload + chunk->msg->size, buffer->bytes() + bh_size + mh_size, payload_size); buffer->erase(bh_size + mh_size + payload_size); chunk->msg->size += payload_size; srs_verbose("chunk payload read completed. bh_size=%d, mh_size=%d, payload_size=%d", bh_size, mh_size, payload_size); // got entire RTMP message? if (chunk->header.payload_length == chunk->msg->size) { *pmsg = chunk->msg; chunk->msg = NULL; srs_verbose("get entire RTMP message(type=%d, size=%d, time=%d, sid=%d)", chunk->header.message_type, chunk->header.payload_length, chunk->header.timestamp, chunk->header.stream_id); return ret; } srs_verbose("get partial RTMP message(type=%d, size=%d, time=%d, sid=%d), partial size=%d", chunk->header.message_type, chunk->header.payload_length, chunk->header.timestamp, chunk->header.stream_id, chunk->msg->size); return ret; } SrsMessageHeader::SrsMessageHeader() { message_type = 0; payload_length = 0; timestamp_delta = 0; stream_id = 0; timestamp = 0; } SrsMessageHeader::~SrsMessageHeader() { } bool SrsMessageHeader::is_audio() { return message_type == RTMP_MSG_AudioMessage; } bool SrsMessageHeader::is_video() { return message_type == RTMP_MSG_VideoMessage; } bool SrsMessageHeader::is_amf0_command() { return message_type == RTMP_MSG_AMF0CommandMessage; } bool SrsMessageHeader::is_amf0_data() { return message_type == RTMP_MSG_AMF0DataMessage; } bool SrsMessageHeader::is_amf3_command() { return message_type == RTMP_MSG_AMF3CommandMessage; } bool SrsMessageHeader::is_amf3_data() { return message_type == RTMP_MSG_AMF3DataMessage; } bool SrsMessageHeader::is_window_ackledgement_size() { return message_type == RTMP_MSG_WindowAcknowledgementSize; } bool SrsMessageHeader::is_set_chunk_size() { return message_type == RTMP_MSG_SetChunkSize; } SrsChunkStream::SrsChunkStream(int _cid) { fmt = 0; cid = _cid; extended_timestamp = false; msg = NULL; msg_count = 0; } SrsChunkStream::~SrsChunkStream() { srs_freep(msg); } ISrsMessage::ISrsMessage() { payload = NULL; size = 0; } ISrsMessage::~ISrsMessage() { } SrsCommonMessage::SrsCommonMessage() { stream = NULL; packet = NULL; } SrsCommonMessage::~SrsCommonMessage() { // we must directly free the ptrs, // nevery use the virtual functions to delete, // for in the destructor, the virtual functions is disabled. srs_freepa(payload); srs_freep(packet); srs_freep(stream); } bool SrsCommonMessage::can_decode() { return true; } int SrsCommonMessage::decode_packet() { int ret = ERROR_SUCCESS; srs_assert(payload != NULL); srs_assert(size > 0); if (packet) { srs_verbose("msg already decoded"); return ret; } if (!stream) { srs_verbose("create decode stream for message."); stream = new SrsStream(); } // initialize the decode stream for all message, // it's ok for the initialize if fast and without memory copy. if ((ret = stream->initialize((char*)payload, size)) != ERROR_SUCCESS) { srs_error("initialize stream failed. ret=%d", ret); return ret; } srs_verbose("decode stream initialized success"); // decode specified packet type if (header.is_amf0_command() || header.is_amf3_command() || header.is_amf0_data() || header.is_amf3_data()) { srs_verbose("start to decode AMF0/AMF3 command message."); // skip 1bytes to decode the amf3 command. if (header.is_amf3_command() && stream->require(1)) { srs_verbose("skip 1bytes to decode AMF3 command"); stream->skip(1); } // amf0 command message. // need to read the command name. std::string command; if ((ret = srs_amf0_read_string(stream, command)) != ERROR_SUCCESS) { srs_error("decode AMF0/AMF3 command name failed. ret=%d", ret); return ret; } srs_verbose("AMF0/AMF3 command message, command_name=%s", command.c_str()); // reset to zero(amf3 to 1) to restart decode. stream->reset(); if (header.is_amf3_command()) { stream->skip(1); } // decode command object. if (command == RTMP_AMF0_COMMAND_CONNECT) { srs_info("decode the AMF0/AMF3 command(connect vhost/app message)."); packet = new SrsConnectAppPacket(); return packet->decode(stream); } else if(command == RTMP_AMF0_COMMAND_CREATE_STREAM) { srs_info("decode the AMF0/AMF3 command(createStream message)."); packet = new SrsCreateStreamPacket(); return packet->decode(stream); } else if(command == RTMP_AMF0_COMMAND_PLAY) { srs_info("decode the AMF0/AMF3 command(paly message)."); packet = new SrsPlayPacket(); return packet->decode(stream); } else if(command == RTMP_AMF0_COMMAND_RELEASE_STREAM) { srs_info("decode the AMF0/AMF3 command(FMLE releaseStream message)."); packet = new SrsFMLEStartPacket(); return packet->decode(stream); } else if(command == RTMP_AMF0_COMMAND_FC_PUBLISH) { srs_info("decode the AMF0/AMF3 command(FMLE FCPublish message)."); packet = new SrsFMLEStartPacket(); return packet->decode(stream); } else if(command == RTMP_AMF0_COMMAND_PUBLISH) { srs_info("decode the AMF0/AMF3 command(publish message)."); packet = new SrsPublishPacket(); return packet->decode(stream); } else if(command == RTMP_AMF0_COMMAND_UNPUBLISH) { srs_info("decode the AMF0/AMF3 command(unpublish message)."); packet = new SrsFMLEStartPacket(); return packet->decode(stream); } else if(command == RTMP_AMF0_DATA_SET_DATAFRAME || command == RTMP_AMF0_DATA_ON_METADATA) { srs_info("decode the AMF0/AMF3 data(onMetaData message)."); packet = new SrsOnMetaDataPacket(); return packet->decode(stream); } // default packet to drop message. srs_trace("drop the AMF0/AMF3 command message, command_name=%s", command.c_str()); packet = new SrsPacket(); return ret; } else if(header.is_window_ackledgement_size()) { srs_verbose("start to decode set ack window size message."); packet = new SrsSetWindowAckSizePacket(); return packet->decode(stream); } else if(header.is_set_chunk_size()) { srs_verbose("start to decode set chunk size message."); packet = new SrsSetChunkSizePacket(); return packet->decode(stream); } else { // default packet to drop message. srs_trace("drop the unknown message, type=%d", header.message_type); packet = new SrsPacket(); } return ret; } SrsPacket* SrsCommonMessage::get_packet() { if (!packet) { srs_error("the payload is raw/undecoded, invoke decode_packet to decode it."); } srs_assert(packet != NULL); return packet; } int SrsCommonMessage::get_perfer_cid() { if (!packet) { return RTMP_CID_ProtocolControl; } // we donot use the complex basic header, // ensure the basic header is 1bytes. if (packet->get_perfer_cid() < 2) { return packet->get_perfer_cid(); } return packet->get_perfer_cid(); } void SrsCommonMessage::set_packet(SrsPacket* pkt, int stream_id) { srs_freep(packet); packet = pkt; header.message_type = packet->get_message_type(); header.payload_length = packet->get_payload_length(); header.stream_id = stream_id; } int SrsCommonMessage::encode_packet() { int ret = ERROR_SUCCESS; if (packet == NULL) { srs_warn("packet is empty, send out empty message."); return ret; } // realloc the payload. size = 0; srs_freepa(payload); return packet->encode(size, (char*&)payload); } SrsSharedPtrMessage::SrsSharedPtr::SrsSharedPtr() { payload = NULL; size = 0; perfer_cid = 0; shared_count = 0; } SrsSharedPtrMessage::SrsSharedPtr::~SrsSharedPtr() { srs_freepa(payload); } SrsSharedPtrMessage::SrsSharedPtrMessage() { ptr = NULL; } SrsSharedPtrMessage::~SrsSharedPtrMessage() { if (ptr) { if (ptr->shared_count == 0) { srs_freep(ptr); } else { ptr->shared_count--; } } } bool SrsSharedPtrMessage::can_decode() { return false; } int SrsSharedPtrMessage::initialize(ISrsMessage* msg, char* payload, int size) { int ret = ERROR_SUCCESS; srs_assert(msg != NULL); if (ptr) { ret = ERROR_SYSTEM_ASSERT_FAILED; srs_error("should not set the payload twice. ret=%d", ret); srs_assert(false); return ret; } header = msg->header; header.payload_length = size; ptr = new SrsSharedPtr(); ptr->payload = payload; ptr->size = size; if (msg->header.is_video()) { ptr->perfer_cid = RTMP_CID_Video; } else if (msg->header.is_audio()) { ptr->perfer_cid = RTMP_CID_Audio; } else { ptr->perfer_cid = RTMP_CID_OverConnection2; } super::payload = (int8_t*)ptr->payload; super::size = ptr->size; return ret; } SrsSharedPtrMessage* SrsSharedPtrMessage::copy() { if (!ptr) { srs_error("invoke initialize to initialize the ptr."); srs_assert(false); return NULL; } SrsSharedPtrMessage* copy = new SrsSharedPtrMessage(); copy->header = header; copy->ptr = ptr; ptr->shared_count++; copy->payload = (int8_t*)ptr->payload; copy->size = ptr->size; return copy; } int SrsSharedPtrMessage::get_perfer_cid() { if (!ptr) { return 0; } return ptr->perfer_cid; } int SrsSharedPtrMessage::encode_packet() { srs_verbose("shared message ignore the encode method."); return ERROR_SUCCESS; } SrsPacket::SrsPacket() { } SrsPacket::~SrsPacket() { } int SrsPacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; srs_assert(stream != NULL); ret = ERROR_SYSTEM_PACKET_INVALID; srs_error("current packet is not support to decode. " "paket=%s, ret=%d", get_class_name(), ret); return ret; } int SrsPacket::get_perfer_cid() { return 0; } int SrsPacket::get_message_type() { return 0; } int SrsPacket::get_payload_length() { return get_size(); } int SrsPacket::encode(int& psize, char*& ppayload) { int ret = ERROR_SUCCESS; int size = get_size(); char* payload = NULL; SrsStream stream; if (size > 0) { payload = new char[size]; if ((ret = stream.initialize(payload, size)) != ERROR_SUCCESS) { srs_error("initialize the stream failed. ret=%d", ret); srs_freepa(payload); return ret; } } if ((ret = encode_packet(&stream)) != ERROR_SUCCESS) { srs_error("encode the packet failed. ret=%d", ret); srs_freepa(payload); return ret; } psize = size; ppayload = payload; srs_verbose("encode the packet success. size=%d", size); return ret; } int SrsPacket::get_size() { return 0; } int SrsPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; srs_assert(stream != NULL); ret = ERROR_SYSTEM_PACKET_INVALID; srs_error("current packet is not support to encode. " "paket=%s, ret=%d", get_class_name(), ret); return ret; } SrsConnectAppPacket::SrsConnectAppPacket() { command_name = RTMP_AMF0_COMMAND_CONNECT; transaction_id = 1; command_object = NULL; } SrsConnectAppPacket::~SrsConnectAppPacket() { srs_freep(command_object); } int SrsConnectAppPacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("amf0 decode connect command_name failed. ret=%d", ret); return ret; } if (command_name.empty() || command_name != RTMP_AMF0_COMMAND_CONNECT) { ret = ERROR_RTMP_AMF0_DECODE; srs_error("amf0 decode connect command_name failed. " "command_name=%s, ret=%d", command_name.c_str(), ret); return ret; } if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("amf0 decode connect transaction_id failed. ret=%d", ret); return ret; } if (transaction_id != 1.0) { ret = ERROR_RTMP_AMF0_DECODE; srs_error("amf0 decode connect transaction_id failed. " "required=%.1f, actual=%.1f, ret=%d", 1.0, transaction_id, ret); return ret; } if ((ret = srs_amf0_read_object(stream, command_object)) != ERROR_SUCCESS) { srs_error("amf0 decode connect command_object failed. ret=%d", ret); return ret; } if (command_object == NULL) { ret = ERROR_RTMP_AMF0_DECODE; srs_error("amf0 decode connect command_object failed. ret=%d", ret); return ret; } srs_info("amf0 decode connect packet success"); return ret; } SrsConnectAppResPacket::SrsConnectAppResPacket() { command_name = RTMP_AMF0_COMMAND_RESULT; transaction_id = 1; props = new SrsAmf0Object(); info = new SrsAmf0Object(); } SrsConnectAppResPacket::~SrsConnectAppResPacket() { srs_freep(props); srs_freep(info); } int SrsConnectAppResPacket::get_perfer_cid() { return RTMP_CID_OverConnection; } int SrsConnectAppResPacket::get_message_type() { return RTMP_MSG_AMF0CommandMessage; } int SrsConnectAppResPacket::get_size() { return srs_amf0_get_string_size(command_name) + srs_amf0_get_number_size() + srs_amf0_get_object_size(props)+ srs_amf0_get_object_size(info); } int SrsConnectAppResPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("encode command_name failed. ret=%d", ret); return ret; } srs_verbose("encode command_name success."); if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("encode transaction_id failed. ret=%d", ret); return ret; } srs_verbose("encode transaction_id success."); if ((ret = srs_amf0_write_object(stream, props)) != ERROR_SUCCESS) { srs_error("encode props failed. ret=%d", ret); return ret; } srs_verbose("encode props success."); if ((ret = srs_amf0_write_object(stream, info)) != ERROR_SUCCESS) { srs_error("encode info failed. ret=%d", ret); return ret; } srs_verbose("encode info success."); srs_info("encode connect app response packet success."); return ret; } SrsCreateStreamPacket::SrsCreateStreamPacket() { command_name = RTMP_AMF0_COMMAND_CREATE_STREAM; transaction_id = 2; command_object = new SrsAmf0Null(); } SrsCreateStreamPacket::~SrsCreateStreamPacket() { srs_freep(command_object); } int SrsCreateStreamPacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("amf0 decode createStream command_name failed. ret=%d", ret); return ret; } if (command_name.empty() || command_name != RTMP_AMF0_COMMAND_CREATE_STREAM) { ret = ERROR_RTMP_AMF0_DECODE; srs_error("amf0 decode createStream command_name failed. " "command_name=%s, ret=%d", command_name.c_str(), ret); return ret; } if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("amf0 decode createStream transaction_id failed. ret=%d", ret); return ret; } if ((ret = srs_amf0_read_null(stream)) != ERROR_SUCCESS) { srs_error("amf0 decode createStream command_object failed. ret=%d", ret); return ret; } srs_info("amf0 decode createStream packet success"); return ret; } SrsCreateStreamResPacket::SrsCreateStreamResPacket(double _transaction_id, double _stream_id) { command_name = RTMP_AMF0_COMMAND_RESULT; transaction_id = _transaction_id; command_object = new SrsAmf0Null(); stream_id = _stream_id; } SrsCreateStreamResPacket::~SrsCreateStreamResPacket() { srs_freep(command_object); } int SrsCreateStreamResPacket::get_perfer_cid() { return RTMP_CID_OverConnection; } int SrsCreateStreamResPacket::get_message_type() { return RTMP_MSG_AMF0CommandMessage; } int SrsCreateStreamResPacket::get_size() { return srs_amf0_get_string_size(command_name) + srs_amf0_get_number_size() + srs_amf0_get_null_size() + srs_amf0_get_number_size(); } int SrsCreateStreamResPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("encode command_name failed. ret=%d", ret); return ret; } srs_verbose("encode command_name success."); if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("encode transaction_id failed. ret=%d", ret); return ret; } srs_verbose("encode transaction_id success."); if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) { srs_error("encode command_object failed. ret=%d", ret); return ret; } srs_verbose("encode command_object success."); if ((ret = srs_amf0_write_number(stream, stream_id)) != ERROR_SUCCESS) { srs_error("encode stream_id failed. ret=%d", ret); return ret; } srs_verbose("encode stream_id success."); srs_info("encode createStream response packet success."); return ret; } SrsFMLEStartPacket::SrsFMLEStartPacket() { command_name = RTMP_AMF0_COMMAND_CREATE_STREAM; transaction_id = 0; command_object = new SrsAmf0Null(); } SrsFMLEStartPacket::~SrsFMLEStartPacket() { srs_freep(command_object); } int SrsFMLEStartPacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("amf0 decode FMLE start command_name failed. ret=%d", ret); return ret; } if (command_name.empty() || (command_name != RTMP_AMF0_COMMAND_RELEASE_STREAM && command_name != RTMP_AMF0_COMMAND_FC_PUBLISH && command_name != RTMP_AMF0_COMMAND_UNPUBLISH) ) { ret = ERROR_RTMP_AMF0_DECODE; srs_error("amf0 decode FMLE start command_name failed. " "command_name=%s, ret=%d", command_name.c_str(), ret); return ret; } if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("amf0 decode FMLE start transaction_id failed. ret=%d", ret); return ret; } if ((ret = srs_amf0_read_null(stream)) != ERROR_SUCCESS) { srs_error("amf0 decode FMLE start command_object failed. ret=%d", ret); return ret; } if ((ret = srs_amf0_read_string(stream, stream_name)) != ERROR_SUCCESS) { srs_error("amf0 decode FMLE start stream_name failed. ret=%d", ret); return ret; } srs_info("amf0 decode FMLE start packet success"); return ret; } SrsFMLEStartResPacket::SrsFMLEStartResPacket(double _transaction_id) { command_name = RTMP_AMF0_COMMAND_RESULT; transaction_id = _transaction_id; command_object = new SrsAmf0Null(); args = new SrsAmf0Undefined(); } SrsFMLEStartResPacket::~SrsFMLEStartResPacket() { srs_freep(command_object); srs_freep(args); } int SrsFMLEStartResPacket::get_perfer_cid() { return RTMP_CID_OverConnection; } int SrsFMLEStartResPacket::get_message_type() { return RTMP_MSG_AMF0CommandMessage; } int SrsFMLEStartResPacket::get_size() { return srs_amf0_get_string_size(command_name) + srs_amf0_get_number_size() + srs_amf0_get_null_size() + srs_amf0_get_undefined_size(); } int SrsFMLEStartResPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("encode command_name failed. ret=%d", ret); return ret; } srs_verbose("encode command_name success."); if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("encode transaction_id failed. ret=%d", ret); return ret; } srs_verbose("encode transaction_id success."); if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) { srs_error("encode command_object failed. ret=%d", ret); return ret; } srs_verbose("encode command_object success."); if ((ret = srs_amf0_write_undefined(stream)) != ERROR_SUCCESS) { srs_error("encode args failed. ret=%d", ret); return ret; } srs_verbose("encode args success."); srs_info("encode FMLE start response packet success."); return ret; } SrsPublishPacket::SrsPublishPacket() { command_name = RTMP_AMF0_COMMAND_PUBLISH; transaction_id = 0; command_object = new SrsAmf0Null(); type = "live"; } SrsPublishPacket::~SrsPublishPacket() { srs_freep(command_object); } int SrsPublishPacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("amf0 decode publish command_name failed. ret=%d", ret); return ret; } if (command_name.empty() || command_name != RTMP_AMF0_COMMAND_PUBLISH) { ret = ERROR_RTMP_AMF0_DECODE; srs_error("amf0 decode publish command_name failed. " "command_name=%s, ret=%d", command_name.c_str(), ret); return ret; } if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("amf0 decode publish transaction_id failed. ret=%d", ret); return ret; } if ((ret = srs_amf0_read_null(stream)) != ERROR_SUCCESS) { srs_error("amf0 decode publish command_object failed. ret=%d", ret); return ret; } if ((ret = srs_amf0_read_string(stream, stream_name)) != ERROR_SUCCESS) { srs_error("amf0 decode publish stream_name failed. ret=%d", ret); return ret; } if ((ret = srs_amf0_read_string(stream, type)) != ERROR_SUCCESS) { srs_error("amf0 decode publish type failed. ret=%d", ret); return ret; } srs_info("amf0 decode publish packet success"); return ret; } SrsPlayPacket::SrsPlayPacket() { command_name = RTMP_AMF0_COMMAND_PLAY; transaction_id = 0; command_object = new SrsAmf0Null(); start = -2; duration = -1; reset = true; } SrsPlayPacket::~SrsPlayPacket() { srs_freep(command_object); } int SrsPlayPacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("amf0 decode play command_name failed. ret=%d", ret); return ret; } if (command_name.empty() || command_name != RTMP_AMF0_COMMAND_PLAY) { ret = ERROR_RTMP_AMF0_DECODE; srs_error("amf0 decode play command_name failed. " "command_name=%s, ret=%d", command_name.c_str(), ret); return ret; } if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("amf0 decode play transaction_id failed. ret=%d", ret); return ret; } if ((ret = srs_amf0_read_null(stream)) != ERROR_SUCCESS) { srs_error("amf0 decode play command_object failed. ret=%d", ret); return ret; } if ((ret = srs_amf0_read_string(stream, stream_name)) != ERROR_SUCCESS) { srs_error("amf0 decode play stream_name failed. ret=%d", ret); return ret; } if (!stream->empty() && (ret = srs_amf0_read_number(stream, start)) != ERROR_SUCCESS) { srs_error("amf0 decode play start failed. ret=%d", ret); return ret; } if (!stream->empty() && (ret = srs_amf0_read_number(stream, duration)) != ERROR_SUCCESS) { srs_error("amf0 decode play duration failed. ret=%d", ret); return ret; } if (!stream->empty() && (ret = srs_amf0_read_boolean(stream, reset)) != ERROR_SUCCESS) { srs_error("amf0 decode play reset failed. ret=%d", ret); return ret; } srs_info("amf0 decode play packet success"); return ret; } SrsPlayResPacket::SrsPlayResPacket() { command_name = RTMP_AMF0_COMMAND_RESULT; transaction_id = 0; command_object = new SrsAmf0Null(); desc = new SrsAmf0Object(); } SrsPlayResPacket::~SrsPlayResPacket() { srs_freep(command_object); srs_freep(desc); } int SrsPlayResPacket::get_perfer_cid() { return RTMP_CID_OverStream; } int SrsPlayResPacket::get_message_type() { return RTMP_MSG_AMF0CommandMessage; } int SrsPlayResPacket::get_size() { return srs_amf0_get_string_size(command_name) + srs_amf0_get_number_size() + srs_amf0_get_null_size() + srs_amf0_get_object_size(desc); } int SrsPlayResPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("encode command_name failed. ret=%d", ret); return ret; } srs_verbose("encode command_name success."); if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("encode transaction_id failed. ret=%d", ret); return ret; } srs_verbose("encode transaction_id success."); if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) { srs_error("encode command_object failed. ret=%d", ret); return ret; } srs_verbose("encode command_object success."); if ((ret = srs_amf0_write_object(stream, desc)) != ERROR_SUCCESS) { srs_error("encode desc failed. ret=%d", ret); return ret; } srs_verbose("encode desc success."); srs_info("encode play response packet success."); return ret; } SrsOnBWDonePacket::SrsOnBWDonePacket() { command_name = RTMP_AMF0_COMMAND_ON_BW_DONE; transaction_id = 0; args = new SrsAmf0Null(); } SrsOnBWDonePacket::~SrsOnBWDonePacket() { srs_freep(args); } int SrsOnBWDonePacket::get_perfer_cid() { return RTMP_CID_OverConnection; } int SrsOnBWDonePacket::get_message_type() { return RTMP_MSG_AMF0CommandMessage; } int SrsOnBWDonePacket::get_size() { return srs_amf0_get_string_size(command_name) + srs_amf0_get_number_size() + srs_amf0_get_null_size(); } int SrsOnBWDonePacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("encode command_name failed. ret=%d", ret); return ret; } srs_verbose("encode command_name success."); if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("encode transaction_id failed. ret=%d", ret); return ret; } srs_verbose("encode transaction_id success."); if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) { srs_error("encode args failed. ret=%d", ret); return ret; } srs_verbose("encode args success."); srs_info("encode onBWDone packet success."); return ret; } SrsOnStatusCallPacket::SrsOnStatusCallPacket() { command_name = RTMP_AMF0_COMMAND_ON_STATUS; transaction_id = 0; args = new SrsAmf0Null(); data = new SrsAmf0Object(); } SrsOnStatusCallPacket::~SrsOnStatusCallPacket() { srs_freep(args); srs_freep(data); } int SrsOnStatusCallPacket::get_perfer_cid() { return RTMP_CID_OverStream; } int SrsOnStatusCallPacket::get_message_type() { return RTMP_MSG_AMF0CommandMessage; } int SrsOnStatusCallPacket::get_size() { return srs_amf0_get_string_size(command_name) + srs_amf0_get_number_size() + srs_amf0_get_null_size() + srs_amf0_get_object_size(data); } int SrsOnStatusCallPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("encode command_name failed. ret=%d", ret); return ret; } srs_verbose("encode command_name success."); if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) { srs_error("encode transaction_id failed. ret=%d", ret); return ret; } srs_verbose("encode transaction_id success."); if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) { srs_error("encode args failed. ret=%d", ret); return ret; } srs_verbose("encode args success.");; if ((ret = srs_amf0_write_object(stream, data)) != ERROR_SUCCESS) { srs_error("encode data failed. ret=%d", ret); return ret; } srs_verbose("encode data success."); srs_info("encode onStatus(Call) packet success."); return ret; } SrsOnStatusDataPacket::SrsOnStatusDataPacket() { command_name = RTMP_AMF0_COMMAND_ON_STATUS; data = new SrsAmf0Object(); } SrsOnStatusDataPacket::~SrsOnStatusDataPacket() { srs_freep(data); } int SrsOnStatusDataPacket::get_perfer_cid() { return RTMP_CID_OverStream; } int SrsOnStatusDataPacket::get_message_type() { return RTMP_MSG_AMF0DataMessage; } int SrsOnStatusDataPacket::get_size() { return srs_amf0_get_string_size(command_name) + srs_amf0_get_object_size(data); } int SrsOnStatusDataPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("encode command_name failed. ret=%d", ret); return ret; } srs_verbose("encode command_name success."); if ((ret = srs_amf0_write_object(stream, data)) != ERROR_SUCCESS) { srs_error("encode data failed. ret=%d", ret); return ret; } srs_verbose("encode data success."); srs_info("encode onStatus(Data) packet success."); return ret; } SrsSampleAccessPacket::SrsSampleAccessPacket() { command_name = RTMP_AMF0_DATA_SAMPLE_ACCESS; video_sample_access = false; audio_sample_access = false; } SrsSampleAccessPacket::~SrsSampleAccessPacket() { } int SrsSampleAccessPacket::get_perfer_cid() { return RTMP_CID_OverStream; } int SrsSampleAccessPacket::get_message_type() { return RTMP_MSG_AMF0DataMessage; } int SrsSampleAccessPacket::get_size() { return srs_amf0_get_string_size(command_name) + srs_amf0_get_boolean_size() + srs_amf0_get_boolean_size(); } int SrsSampleAccessPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) { srs_error("encode command_name failed. ret=%d", ret); return ret; } srs_verbose("encode command_name success."); if ((ret = srs_amf0_write_boolean(stream, video_sample_access)) != ERROR_SUCCESS) { srs_error("encode video_sample_access failed. ret=%d", ret); return ret; } srs_verbose("encode video_sample_access success."); if ((ret = srs_amf0_write_boolean(stream, audio_sample_access)) != ERROR_SUCCESS) { srs_error("encode audio_sample_access failed. ret=%d", ret); return ret; } srs_verbose("encode audio_sample_access success.");; srs_info("encode |RtmpSampleAccess packet success."); return ret; } SrsOnMetaDataPacket::SrsOnMetaDataPacket() { name = RTMP_AMF0_DATA_ON_METADATA; metadata = new SrsAmf0Object(); } SrsOnMetaDataPacket::~SrsOnMetaDataPacket() { srs_freep(metadata); } int SrsOnMetaDataPacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_read_string(stream, name)) != ERROR_SUCCESS) { srs_error("decode metadata name failed. ret=%d", ret); return ret; } // ignore the @setDataFrame if (name == RTMP_AMF0_DATA_SET_DATAFRAME) { if ((ret = srs_amf0_read_string(stream, name)) != ERROR_SUCCESS) { srs_error("decode metadata name failed. ret=%d", ret); return ret; } } srs_verbose("decode metadata name success. name=%s", name.c_str()); // the metadata maybe object or ecma array SrsAmf0Any* any = NULL; if ((ret = srs_amf0_read_any(stream, any)) != ERROR_SUCCESS) { srs_error("decode metadata metadata failed. ret=%d", ret); return ret; } if (any->is_object()) { srs_freep(metadata); metadata = srs_amf0_convert<SrsAmf0Object>(any); srs_info("decode metadata object success"); return ret; } SrsASrsAmf0EcmaArray* arr = dynamic_cast<SrsASrsAmf0EcmaArray*>(any); if (!arr) { ret = ERROR_RTMP_AMF0_DECODE; srs_error("decode metadata array failed. ret=%d", ret); srs_freep(any); return ret; } for (int i = 0; i < arr->size(); i++) { metadata->set(arr->key_at(i), arr->value_at(i)); } arr->clear(); srs_info("decode metadata array success"); return ret; } int SrsOnMetaDataPacket::get_perfer_cid() { return RTMP_CID_OverConnection2; } int SrsOnMetaDataPacket::get_message_type() { return RTMP_MSG_AMF0DataMessage; } int SrsOnMetaDataPacket::get_size() { return srs_amf0_get_string_size(name) + srs_amf0_get_object_size(metadata); } int SrsOnMetaDataPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if ((ret = srs_amf0_write_string(stream, name)) != ERROR_SUCCESS) { srs_error("encode name failed. ret=%d", ret); return ret; } srs_verbose("encode name success."); if ((ret = srs_amf0_write_object(stream, metadata)) != ERROR_SUCCESS) { srs_error("encode metadata failed. ret=%d", ret); return ret; } srs_verbose("encode metadata success."); srs_info("encode onMetaData packet success."); return ret; } SrsSetWindowAckSizePacket::SrsSetWindowAckSizePacket() { ackowledgement_window_size = 0; } SrsSetWindowAckSizePacket::~SrsSetWindowAckSizePacket() { } int SrsSetWindowAckSizePacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; if (!stream->require(4)) { ret = ERROR_RTMP_MESSAGE_DECODE; srs_error("decode ack window size failed. ret=%d", ret); return ret; } ackowledgement_window_size = stream->read_4bytes(); srs_info("decode ack window size success"); return ret; } int SrsSetWindowAckSizePacket::get_perfer_cid() { return RTMP_CID_ProtocolControl; } int SrsSetWindowAckSizePacket::get_message_type() { return RTMP_MSG_WindowAcknowledgementSize; } int SrsSetWindowAckSizePacket::get_size() { return 4; } int SrsSetWindowAckSizePacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if (!stream->require(4)) { ret = ERROR_RTMP_MESSAGE_ENCODE; srs_error("encode ack size packet failed. ret=%d", ret); return ret; } stream->write_4bytes(ackowledgement_window_size); srs_verbose("encode ack size packet " "success. ack_size=%d", ackowledgement_window_size); return ret; } SrsSetChunkSizePacket::SrsSetChunkSizePacket() { chunk_size = RTMP_DEFAULT_CHUNK_SIZE; } SrsSetChunkSizePacket::~SrsSetChunkSizePacket() { } int SrsSetChunkSizePacket::decode(SrsStream* stream) { int ret = ERROR_SUCCESS; if (!stream->require(4)) { ret = ERROR_RTMP_MESSAGE_DECODE; srs_error("decode chunk size failed. ret=%d", ret); return ret; } chunk_size = stream->read_4bytes(); srs_info("decode chunk size success. chunk_size=%d", chunk_size); if (chunk_size < RTMP_MIN_CHUNK_SIZE) { ret = ERROR_RTMP_CHUNK_SIZE; srs_error("invalid chunk size. min=%d, actual=%d, ret=%d", ERROR_RTMP_CHUNK_SIZE, chunk_size, ret); return ret; } return ret; } int SrsSetChunkSizePacket::get_perfer_cid() { return RTMP_CID_ProtocolControl; } int SrsSetChunkSizePacket::get_message_type() { return RTMP_MSG_SetChunkSize; } int SrsSetChunkSizePacket::get_size() { return 4; } int SrsSetChunkSizePacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if (!stream->require(4)) { ret = ERROR_RTMP_MESSAGE_ENCODE; srs_error("encode chunk packet failed. ret=%d", ret); return ret; } stream->write_4bytes(chunk_size); srs_verbose("encode chunk packet success. ack_size=%d", chunk_size); return ret; } SrsSetPeerBandwidthPacket::SrsSetPeerBandwidthPacket() { bandwidth = 0; type = 2; } SrsSetPeerBandwidthPacket::~SrsSetPeerBandwidthPacket() { } int SrsSetPeerBandwidthPacket::get_perfer_cid() { return RTMP_CID_ProtocolControl; } int SrsSetPeerBandwidthPacket::get_message_type() { return RTMP_MSG_SetPeerBandwidth; } int SrsSetPeerBandwidthPacket::get_size() { return 5; } int SrsSetPeerBandwidthPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if (!stream->require(5)) { ret = ERROR_RTMP_MESSAGE_ENCODE; srs_error("encode set bandwidth packet failed. ret=%d", ret); return ret; } stream->write_4bytes(bandwidth); stream->write_1bytes(type); srs_verbose("encode set bandwidth packet " "success. bandwidth=%d, type=%d", bandwidth, type); return ret; } SrsPCUC4BytesPacket::SrsPCUC4BytesPacket() { event_type = 0; event_data = 0; } SrsPCUC4BytesPacket::~SrsPCUC4BytesPacket() { } int SrsPCUC4BytesPacket::get_perfer_cid() { return RTMP_CID_ProtocolControl; } int SrsPCUC4BytesPacket::get_message_type() { return RTMP_MSG_UserControlMessage; } int SrsPCUC4BytesPacket::get_size() { return 2 + 4; } int SrsPCUC4BytesPacket::encode_packet(SrsStream* stream) { int ret = ERROR_SUCCESS; if (!stream->require(6)) { ret = ERROR_RTMP_MESSAGE_ENCODE; srs_error("encode set bandwidth packet failed. ret=%d", ret); return ret; } stream->write_2bytes(event_type); stream->write_4bytes(event_data); srs_verbose("encode PCUC packet success. " "event_type=%d, event_data=%d", event_type, event_data); return ret; }
// // Copyright (c) 2008-2014 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "Precompiled.h" #include "Component.h" #include "Context.h" #include "Log.h" #include "MemoryBuffer.h" #include "ObjectAnimation.h" #include "Profiler.h" #include "ReplicationState.h" #include "Scene.h" #include "SceneEvents.h" #include "SmoothedTransform.h" #include "UnknownComponent.h" #include "XMLFile.h" #include "DebugNew.h" namespace Urho3D { Node::Node(Context* context) : Animatable(context), networkUpdate_(false), worldTransform_(Matrix3x4::IDENTITY), dirty_(false), enabled_(true), parent_(0), scene_(0), id_(0), position_(Vector3::ZERO), rotation_(Quaternion::IDENTITY), scale_(Vector3::ONE), worldRotation_(Quaternion::IDENTITY), owner_(0) { } Node::~Node() { RemoveAllChildren(); RemoveAllComponents(); // Remove from the scene if (scene_) scene_->NodeRemoved(this); } void Node::RegisterObject(Context* context) { context->RegisterFactory<Node>(); ACCESSOR_ATTRIBUTE(Node, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT); REF_ACCESSOR_ATTRIBUTE(Node, VAR_STRING, "Name", GetName, SetName, String, String::EMPTY, AM_DEFAULT); REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE); REF_ACCESSOR_ATTRIBUTE(Node, VAR_QUATERNION, "Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE); REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT); ATTRIBUTE(Node, VAR_VARIANTMAP, "Variables", vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Network Position", GetNetPositionAttr, SetNetPositionAttr, Vector3, Vector3::ZERO, AM_NET | AM_LATESTDATA | AM_NOEDIT); REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_LATESTDATA | AM_NOEDIT); REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Parent Node", GetNetParentAttr, SetNetParentAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_NOEDIT); } bool Node::Load(Deserializer& source, bool setInstanceDefault) { SceneResolver resolver; // Read own ID. Will not be applied, only stored for resolving possible references unsigned nodeID = source.ReadInt(); resolver.AddNode(nodeID, this); // Read attributes, components and child nodes bool success = Load(source, resolver); if (success) { resolver.Resolve(); ApplyAttributes(); } return success; } bool Node::Save(Serializer& dest) const { // Write node ID if (!dest.WriteUInt(id_)) return false; // Write attributes if (!Animatable::Save(dest)) return false; // Write components dest.WriteVLE(GetNumPersistentComponents()); for (unsigned i = 0; i < components_.Size(); ++i) { Component* component = components_[i]; if (component->IsTemporary()) continue; // Create a separate buffer to be able to skip failing components during deserialization VectorBuffer compBuffer; if (!component->Save(compBuffer)) return false; dest.WriteVLE(compBuffer.GetSize()); dest.Write(compBuffer.GetData(), compBuffer.GetSize()); } // Write child nodes dest.WriteVLE(GetNumPersistentChildren()); for (unsigned i = 0; i < children_.Size(); ++i) { Node* node = children_[i]; if (node->IsTemporary()) continue; if (!node->Save(dest)) return false; } return true; } bool Node::LoadXML(const XMLElement& source, bool setInstanceDefault) { SceneResolver resolver; // Read own ID. Will not be applied, only stored for resolving possible references unsigned nodeID = source.GetInt("id"); resolver.AddNode(nodeID, this); // Read attributes, components and child nodes bool success = LoadXML(source, resolver); if (success) { resolver.Resolve(); ApplyAttributes(); } return success; } bool Node::SaveXML(XMLElement& dest) const { // Write node ID if (!dest.SetInt("id", id_)) return false; // Write attributes if (!Animatable::SaveXML(dest)) return false; // Write components for (unsigned i = 0; i < components_.Size(); ++i) { Component* component = components_[i]; if (component->IsTemporary()) continue; XMLElement compElem = dest.CreateChild("component"); if (!component->SaveXML(compElem)) return false; } // Write child nodes for (unsigned i = 0; i < children_.Size(); ++i) { Node* node = children_[i]; if (node->IsTemporary()) continue; XMLElement childElem = dest.CreateChild("node"); if (!node->SaveXML(childElem)) return false; } return true; } void Node::ApplyAttributes() { for (unsigned i = 0; i < components_.Size(); ++i) components_[i]->ApplyAttributes(); for (unsigned i = 0; i < children_.Size(); ++i) children_[i]->ApplyAttributes(); } void Node::MarkNetworkUpdate() { if (!networkUpdate_ && scene_ && id_ < FIRST_LOCAL_ID) { scene_->MarkNetworkUpdate(this); networkUpdate_ = true; } } void Node::AddReplicationState(NodeReplicationState* state) { if (!networkState_) AllocateNetworkState(); networkState_->replicationStates_.Push(state); } bool Node::SaveXML(Serializer& dest) const { SharedPtr<XMLFile> xml(new XMLFile(context_)); XMLElement rootElem = xml->CreateRoot("node"); if (!SaveXML(rootElem)) return false; return xml->Save(dest); } void Node::SetName(const String& name) { if (name != name_) { name_ = name; nameHash_ = name_; MarkNetworkUpdate(); // Send change event if (scene_) { using namespace NodeNameChanged; VariantMap& eventData = GetEventDataMap(); eventData[P_SCENE] = scene_; eventData[P_NODE] = this; scene_->SendEvent(E_NODENAMECHANGED, eventData); } } } void Node::SetPosition(const Vector3& position) { position_ = position; MarkDirty(); MarkNetworkUpdate(); } void Node::SetRotation(const Quaternion& rotation) { rotation_ = rotation; MarkDirty(); MarkNetworkUpdate(); } void Node::SetDirection(const Vector3& direction) { SetRotation(Quaternion(Vector3::FORWARD, direction)); } void Node::SetScale(float scale) { SetScale(Vector3(scale, scale, scale)); } void Node::SetScale(const Vector3& scale) { scale_ = scale.Abs(); MarkDirty(); MarkNetworkUpdate(); } void Node::SetTransform(const Vector3& position, const Quaternion& rotation) { position_ = position; rotation_ = rotation; MarkDirty(); MarkNetworkUpdate(); } void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale) { SetTransform(position, rotation, Vector3(scale, scale, scale)); } void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale) { position_ = position; rotation_ = rotation; scale_ = scale; MarkDirty(); MarkNetworkUpdate(); } void Node::SetWorldPosition(const Vector3& position) { SetPosition((parent_ == scene_ || !parent_) ? position : parent_->GetWorldTransform().Inverse() * position); } void Node::SetWorldRotation(const Quaternion& rotation) { SetRotation((parent_ == scene_ || !parent_) ? rotation : parent_->GetWorldRotation().Inverse() * rotation); } void Node::SetWorldDirection(const Vector3& direction) { Vector3 localDirection = (parent_ == scene_ || !parent_) ? direction : parent_->GetWorldRotation().Inverse() * direction; SetRotation(Quaternion(Vector3::FORWARD, localDirection)); } void Node::SetWorldScale(float scale) { SetWorldScale(Vector3(scale, scale, scale)); } void Node::SetWorldScale(const Vector3& scale) { SetScale((parent_ == scene_ || !parent_) ? scale : scale / parent_->GetWorldScale()); } void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation) { SetWorldPosition(position); SetWorldRotation(rotation); } void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale) { SetWorldPosition(position); SetWorldRotation(rotation); SetWorldScale(scale); } void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale) { SetWorldPosition(position); SetWorldRotation(rotation); SetWorldScale(scale); } void Node::Translate(const Vector3& delta, TransformSpace space) { switch (space) { case TS_LOCAL: // Note: local space translation disregards local scale for scale-independent movement speed position_ += rotation_ * delta; break; case TS_PARENT: position_ += delta; break; case TS_WORLD: position_ += (parent_ == scene_ || !parent_) ? delta : parent_->GetWorldTransform().Inverse() * Vector4(delta, 0.0f); break; } MarkDirty(); MarkNetworkUpdate(); } void Node::Rotate(const Quaternion& delta, TransformSpace space) { switch (space) { case TS_LOCAL: rotation_ = (rotation_ * delta).Normalized(); break; case TS_PARENT: rotation_ = (delta * rotation_).Normalized(); break; case TS_WORLD: if (parent_ == scene_ || !parent_) rotation_ = (delta * rotation_).Normalized(); else { Quaternion worldRotation = GetWorldRotation(); rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation; } break; } MarkDirty(); MarkNetworkUpdate(); } void Node::RotateAround(const Vector3& point, const Quaternion& delta, TransformSpace space) { Vector3 parentSpacePoint; Quaternion oldRotation = rotation_; switch (space) { case TS_LOCAL: parentSpacePoint = GetTransform() * point; rotation_ = (rotation_ * delta).Normalized(); break; case TS_PARENT: parentSpacePoint = point; rotation_ = (delta * rotation_).Normalized(); break; case TS_WORLD: if (parent_ == scene_ || !parent_) { parentSpacePoint = point; rotation_ = (delta * rotation_).Normalized(); } else { parentSpacePoint = parent_->GetWorldTransform().Inverse() * point; Quaternion worldRotation = GetWorldRotation(); rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation; } break; } Vector3 oldRelativePos = oldRotation.Inverse() * (position_ - parentSpacePoint); position_ = rotation_ * oldRelativePos + parentSpacePoint; MarkDirty(); MarkNetworkUpdate(); } void Node::Yaw(float angle, TransformSpace space) { Rotate(Quaternion(angle, Vector3::UP), space); } void Node::Pitch(float angle, TransformSpace space) { Rotate(Quaternion(angle, Vector3::RIGHT), space); } void Node::Roll(float angle, TransformSpace space) { Rotate(Quaternion(angle, Vector3::FORWARD), space); } bool Node::LookAt(const Vector3& target, const Vector3& up, TransformSpace space) { Vector3 worldSpaceTarget; switch (space) { case TS_LOCAL: worldSpaceTarget = GetWorldTransform() * target; break; case TS_PARENT: worldSpaceTarget = (parent_ == scene_ || !parent_) ? target : parent_->GetWorldTransform() * target; break; case TS_WORLD: worldSpaceTarget = target; break; } Vector3 lookDir = target - GetWorldPosition(); // Check if target is very close, in that case can not reliably calculate lookat direction if (lookDir.Equals(Vector3::ZERO)) return false; Quaternion newRotation; // Do nothing if setting look rotation failed if (!newRotation.FromLookRotation(lookDir, up)) return false; SetWorldRotation(newRotation); return true; } void Node::Scale(float scale) { Scale(Vector3(scale, scale, scale)); } void Node::Scale(const Vector3& scale) { scale_ *= scale; MarkDirty(); MarkNetworkUpdate(); } void Node::SetEnabled(bool enable) { SetEnabled(enable, false); } void Node::SetEnabled(bool enable, bool recursive) { // The enabled state of the whole scene can not be changed. SetUpdateEnabled() is used instead to start/stop updates. if (GetType() == Scene::GetTypeStatic()) { LOGERROR("Can not change enabled state of the Scene"); return; } if (enable != enabled_) { enabled_ = enable; MarkNetworkUpdate(); // Notify listener components of the state change for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();) { if (*i) { (*i)->OnNodeSetEnabled(this); ++i; } // If listener has expired, erase from list else i = listeners_.Erase(i); } // Send change event if (scene_) { using namespace NodeEnabledChanged; VariantMap& eventData = GetEventDataMap(); eventData[P_SCENE] = scene_; eventData[P_NODE] = this; scene_->SendEvent(E_NODEENABLEDCHANGED, eventData); } for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i) { (*i)->OnSetEnabled(); // Send change event for the component if (scene_) { using namespace ComponentEnabledChanged; VariantMap& eventData = GetEventDataMap(); eventData[P_SCENE] = scene_; eventData[P_NODE] = this; eventData[P_COMPONENT] = (*i); scene_->SendEvent(E_COMPONENTENABLEDCHANGED, eventData); } } } if (recursive) { for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i) (*i)->SetEnabled(enable, recursive); } } void Node::SetOwner(Connection* owner) { owner_ = owner; } void Node::MarkDirty() { if (dirty_) return; dirty_ = true; // Notify listener components first, then mark child nodes for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();) { if (*i) { (*i)->OnMarkedDirty(this); ++i; } // If listener has expired, erase from list else i = listeners_.Erase(i); } for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i) (*i)->MarkDirty(); } Node* Node::CreateChild(const String& name, CreateMode mode, unsigned id) { Node* newNode = CreateChild(id, mode); newNode->SetName(name); return newNode; } void Node::AddChild(Node* node, unsigned index) { // Check for illegal or redundant parent assignment if (!node || node == this || node->parent_ == this) return; // Check for possible cyclic parent assignment Node* parent = parent_; while (parent) { if (parent == node) return; parent = parent->parent_; } // Add first, then remove from old parent, to ensure the node does not get deleted children_.Insert(index, SharedPtr<Node>(node)); node->Remove(); // Add to the scene if not added yet if (scene_ && node->GetScene() != scene_) scene_->NodeAdded(node); node->parent_ = this; node->MarkDirty(); node->MarkNetworkUpdate(); // Send change event if (scene_) { using namespace NodeAdded; VariantMap& eventData = GetEventDataMap(); eventData[P_SCENE] = scene_; eventData[P_PARENT] = this; eventData[P_NODE] = node; scene_->SendEvent(E_NODEADDED, eventData); } } void Node::RemoveChild(Node* node) { if (!node) return; for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i) { if (*i == node) { RemoveChild(i); return; } } } void Node::RemoveAllChildren() { RemoveChildren(true, true, true); } void Node::RemoveChildren(bool removeReplicated, bool removeLocal, bool recursive) { unsigned numRemoved = 0; for (unsigned i = children_.Size() - 1; i < children_.Size(); --i) { bool remove = false; Node* childNode = children_[i]; if (recursive) childNode->RemoveChildren(removeReplicated, removeLocal, true); if (childNode->GetID() < FIRST_LOCAL_ID && removeReplicated) remove = true; else if (childNode->GetID() >= FIRST_LOCAL_ID && removeLocal) remove = true; if (remove) { RemoveChild(children_.Begin() + i); ++numRemoved; } } // Mark node dirty in all replication states if (numRemoved) MarkReplicationDirty(); } Component* Node::CreateComponent(ShortStringHash type, CreateMode mode, unsigned id) { // Check that creation succeeds and that the object in fact is a component SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type)); if (!newComponent) { LOGERROR("Could not create unknown component type " + type.ToString()); return 0; } AddComponent(newComponent, id, mode); return newComponent; } Component* Node::GetOrCreateComponent(ShortStringHash type, CreateMode mode, unsigned id) { Component* oldComponent = GetComponent(type); if (oldComponent) return oldComponent; else return CreateComponent(type, mode, id); } Component* Node::CloneComponent(Component* component, unsigned id) { if (!component) { LOGERROR("Null source component given for CloneComponent"); return 0; } return CloneComponent(component, component->GetID() < FIRST_LOCAL_ID ? REPLICATED : LOCAL, id); } Component* Node::CloneComponent(Component* component, CreateMode mode, unsigned id) { if (!component) { LOGERROR("Null source component given for CloneComponent"); return 0; } Component* cloneComponent = SafeCreateComponent(component->GetTypeName(), component->GetType(), mode, 0); if (!cloneComponent) { LOGERROR("Could not clone component " + component->GetTypeName()); return 0; } const Vector<AttributeInfo>* compAttributes = component->GetAttributes(); if (compAttributes) { for (unsigned j = 0; j < compAttributes->Size(); ++j) { const AttributeInfo& attr = compAttributes->At(j); if (attr.mode_ & AM_FILE) { Variant value; component->OnGetAttribute(attr, value); cloneComponent->OnSetAttribute(attr, value); } } } return cloneComponent; } void Node::RemoveComponent(Component* component) { for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i) { if (*i == component) { RemoveComponent(i); // Mark node dirty in all replication states MarkReplicationDirty(); return; } } } void Node::RemoveComponent(ShortStringHash type) { for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i) { if ((*i)->GetType() == type) { RemoveComponent(i); // Mark node dirty in all replication states MarkReplicationDirty(); return; } } } void Node::RemoveAllComponents() { RemoveComponents(true, true); } void Node::RemoveComponents(bool removeReplicated, bool removeLocal) { unsigned numRemoved = 0; for (unsigned i = components_.Size() - 1; i < components_.Size(); --i) { bool remove = false; Component* component = components_[i]; if (component->GetID() < FIRST_LOCAL_ID && removeReplicated) remove = true; else if (component->GetID() >= FIRST_LOCAL_ID && removeLocal) remove = true; if (remove) { RemoveComponent(components_.Begin() + i); ++numRemoved; } } // Mark node dirty in all replication states if (numRemoved) MarkReplicationDirty(); } Node* Node::Clone(CreateMode mode) { // The scene itself can not be cloned if (this == scene_ || !parent_) { LOGERROR("Can not clone node without a parent"); return 0; } PROFILE(CloneNode); SceneResolver resolver; Node* clone = CloneRecursive(parent_, resolver, mode); resolver.Resolve(); clone->ApplyAttributes(); return clone; } void Node::Remove() { if (parent_) parent_->RemoveChild(this); } void Node::SetParent(Node* parent) { if (parent) { Matrix3x4 oldWorldTransform = GetWorldTransform(); parent->AddChild(this); if (parent != scene_) { Matrix3x4 newTransform = parent->GetWorldTransform().Inverse() * oldWorldTransform; SetTransform(newTransform.Translation(), newTransform.Rotation(), newTransform.Scale()); } else { // The root node is assumed to have identity transform, so can disregard it SetTransform(oldWorldTransform.Translation(), oldWorldTransform.Rotation(), oldWorldTransform.Scale()); } } } void Node::SetVar(ShortStringHash key, const Variant& value) { vars_[key] = value; MarkNetworkUpdate(); } void Node::AddListener(Component* component) { if (!component) return; // Check for not adding twice for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i) { if (*i == component) return; } listeners_.Push(WeakPtr<Component>(component)); // If the node is currently dirty, notify immediately if (dirty_) component->OnMarkedDirty(this); } void Node::RemoveListener(Component* component) { for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i) { if (*i == component) { listeners_.Erase(i); return; } } } Vector3 Node::LocalToWorld(const Vector3& position) const { return GetWorldTransform() * position; } Vector3 Node::LocalToWorld(const Vector4& vector) const { return GetWorldTransform() * vector; } Vector2 Node::LocalToWorld(const Vector2& vector) const { Vector3 result = LocalToWorld(Vector3(vector)); return Vector2(result.x_, result.y_); } Vector3 Node::WorldToLocal(const Vector3& position) const { return GetWorldTransform().Inverse() * position; } Vector3 Node::WorldToLocal(const Vector4& vector) const { return GetWorldTransform().Inverse() * vector; } Vector2 Node::WorldToLocal(const Vector2& vector) const { Vector3 result = WorldToLocal(Vector3(vector)); return Vector2(result.x_, result.y_); } unsigned Node::GetNumChildren(bool recursive) const { if (!recursive) return children_.Size(); else { unsigned allChildren = children_.Size(); for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) allChildren += (*i)->GetNumChildren(true); return allChildren; } } void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const { dest.Clear(); if (!recursive) { for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) dest.Push(*i); } else GetChildrenRecursive(dest); } void Node::GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive) const { dest.Clear(); if (!recursive) { for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) { if ((*i)->HasComponent(type)) dest.Push(*i); } } else GetChildrenWithComponentRecursive(dest, type); } Node* Node::GetChild(unsigned index) const { return index < children_.Size() ? children_[index].Get() : 0; } Node* Node::GetChild(const String& name, bool recursive) const { return GetChild(StringHash(name), recursive); } Node* Node::GetChild(const char* name, bool recursive) const { return GetChild(StringHash(name), recursive); } Node* Node::GetChild(StringHash nameHash, bool recursive) const { for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) { if ((*i)->GetNameHash() == nameHash) return *i; if (recursive) { Node* node = (*i)->GetChild(nameHash, true); if (node) return node; } } return 0; } unsigned Node::GetNumNetworkComponents() const { unsigned num = 0; for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i) { if ((*i)->GetID() < FIRST_LOCAL_ID) ++num; } return num; } void Node::GetComponents(PODVector<Component*>& dest, ShortStringHash type, bool recursive) const { dest.Clear(); if (!recursive) { for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i) { if ((*i)->GetType() == type) dest.Push(*i); } } else GetComponentsRecursive(dest, type); } bool Node::HasComponent(ShortStringHash type) const { for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i) { if ((*i)->GetType() == type) return true; } return false; } const Variant& Node::GetVar(ShortStringHash key) const { VariantMap::ConstIterator i = vars_.Find(key); return i != vars_.End() ? i->second_ : Variant::EMPTY; } Component* Node::GetComponent(ShortStringHash type) const { for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i) { if ((*i)->GetType() == type) return *i; } return 0; } void Node::SetID(unsigned id) { id_ = id; } void Node::SetScene(Scene* scene) { scene_ = scene; } void Node::ResetScene() { SetID(0); SetScene(0); SetOwner(0); } void Node::SetNetPositionAttr(const Vector3& value) { SmoothedTransform* transform = GetComponent<SmoothedTransform>(); if (transform) transform->SetTargetPosition(value); else SetPosition(value); } void Node::SetNetRotationAttr(const PODVector<unsigned char>& value) { MemoryBuffer buf(value); SmoothedTransform* transform = GetComponent<SmoothedTransform>(); if (transform) transform->SetTargetRotation(buf.ReadPackedQuaternion()); else SetRotation(buf.ReadPackedQuaternion()); } void Node::SetNetParentAttr(const PODVector<unsigned char>& value) { Scene* scene = GetScene(); if (!scene) return; MemoryBuffer buf(value); // If nothing in the buffer, parent is the root node if (buf.IsEof()) { scene->AddChild(this); return; } unsigned baseNodeID = buf.ReadNetID(); Node* baseNode = scene->GetNode(baseNodeID); if (!baseNode) { LOGWARNING("Failed to find parent node " + String(baseNodeID)); return; } // If buffer contains just an ID, the parent is replicated and we are done if (buf.IsEof()) baseNode->AddChild(this); else { // Else the parent is local and we must find it recursively by name hash StringHash nameHash = buf.ReadStringHash(); Node* parentNode = baseNode->GetChild(nameHash, true); if (!parentNode) LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString()); else parentNode->AddChild(this); } } const Vector3& Node::GetNetPositionAttr() const { return position_; } const PODVector<unsigned char>& Node::GetNetRotationAttr() const { attrBuffer_.Clear(); attrBuffer_.WritePackedQuaternion(rotation_); return attrBuffer_.GetBuffer(); } const PODVector<unsigned char>& Node::GetNetParentAttr() const { attrBuffer_.Clear(); Scene* scene = GetScene(); if (scene && parent_ && parent_ != scene) { // If parent is replicated, can write the ID directly unsigned parentID = parent_->GetID(); if (parentID < FIRST_LOCAL_ID) attrBuffer_.WriteNetID(parentID); else { // Parent is local: traverse hierarchy to find a non-local base node // This iteration always stops due to the scene (root) being non-local Node* current = parent_; while (current->GetID() >= FIRST_LOCAL_ID) current = current->GetParent(); // Then write the base node ID and the parent's name hash attrBuffer_.WriteNetID(current->GetID()); attrBuffer_.WriteStringHash(parent_->GetNameHash()); } } return attrBuffer_.GetBuffer(); } bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode) { // Remove all children and components first in case this is not a fresh load RemoveAllChildren(); RemoveAllComponents(); // ID has been read at the parent level if (!Animatable::Load(source)) return false; unsigned numComponents = source.ReadVLE(); for (unsigned i = 0; i < numComponents; ++i) { VectorBuffer compBuffer(source, source.ReadVLE()); ShortStringHash compType = compBuffer.ReadShortStringHash(); unsigned compID = compBuffer.ReadUInt(); Component* newComponent = SafeCreateComponent(String::EMPTY, compType, (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID); if (newComponent) { resolver.AddComponent(compID, newComponent); // Do not abort if component fails to load, as the component buffer is nested and we can skip to the next newComponent->Load(compBuffer); } } if (!readChildren) return true; unsigned numChildren = source.ReadVLE(); for (unsigned i = 0; i < numChildren; ++i) { unsigned nodeID = source.ReadUInt(); Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL); resolver.AddNode(nodeID, newNode); if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode)) return false; } return true; } bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode) { // Remove all children and components first in case this is not a fresh load RemoveAllChildren(); RemoveAllComponents(); if (!Animatable::LoadXML(source)) return false; XMLElement compElem = source.GetChild("component"); while (compElem) { String typeName = compElem.GetAttribute("type"); unsigned compID = compElem.GetInt("id"); Component* newComponent = SafeCreateComponent(typeName, ShortStringHash(typeName), (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID); if (newComponent) { resolver.AddComponent(compID, newComponent); if (!newComponent->LoadXML(compElem)) return false; } compElem = compElem.GetNext("component"); } if (!readChildren) return true; XMLElement childElem = source.GetChild("node"); while (childElem) { unsigned nodeID = childElem.GetInt("id"); Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL); resolver.AddNode(nodeID, newNode); if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode)) return false; childElem = childElem.GetNext("node"); } return true; } void Node::PrepareNetworkUpdate() { // Update dependency nodes list first dependencyNodes_.Clear(); // Add the parent node, but if it is local, traverse to the first non-local node if (parent_ && parent_ != scene_) { Node* current = parent_; while (current->id_ >= FIRST_LOCAL_ID) current = current->parent_; if (current && current != scene_) dependencyNodes_.Push(current); } // Let the components add their dependencies for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i) { Component* component = *i; if (component->GetID() < FIRST_LOCAL_ID) component->GetDependencyNodes(dependencyNodes_); } // Then check for node attribute changes if (!networkState_) AllocateNetworkState(); const Vector<AttributeInfo>* attributes = networkState_->attributes_; unsigned numAttributes = attributes->Size(); if (networkState_->currentValues_.Size() != numAttributes) { networkState_->currentValues_.Resize(numAttributes); networkState_->previousValues_.Resize(numAttributes); // Copy the default attribute values to the previous state as a starting point for (unsigned i = 0; i < numAttributes; ++i) networkState_->previousValues_[i] = attributes->At(i).defaultValue_; } // Check for attribute changes for (unsigned i = 0; i < numAttributes; ++i) { const AttributeInfo& attr = attributes->At(i); if (animationEnabled_ && IsAnimatedNetworkAttribute(attr)) continue; OnGetAttribute(attr, networkState_->currentValues_[i]); if (networkState_->currentValues_[i] != networkState_->previousValues_[i]) { networkState_->previousValues_[i] = networkState_->currentValues_[i]; // Mark the attribute dirty in all replication states that are tracking this node for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j != networkState_->replicationStates_.End(); ++j) { NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j); nodeState->dirtyAttributes_.Set(i); // Add node to the dirty set if not added yet if (!nodeState->markedDirty_) { nodeState->markedDirty_ = true; nodeState->sceneState_->dirtyNodes_.Insert(id_); } } } } // Finally check for user var changes for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i) { VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_); if (j == networkState_->previousVars_.End() || j->second_ != i->second_) { networkState_->previousVars_[i->first_] = i->second_; // Mark the var dirty in all replication states that are tracking this node for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j != networkState_->replicationStates_.End(); ++j) { NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j); nodeState->dirtyVars_.Insert(i->first_); if (!nodeState->markedDirty_) { nodeState->markedDirty_ = true; nodeState->sceneState_->dirtyNodes_.Insert(id_); } } } } networkUpdate_ = false; } void Node::CleanupConnection(Connection* connection) { if (owner_ == connection) owner_ = 0; if (networkState_) { for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i) { if (networkState_->replicationStates_[i]->connection_ == connection) networkState_->replicationStates_.Erase(i); } } } void Node::MarkReplicationDirty() { if (networkState_) { for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j != networkState_->replicationStates_.End(); ++j) { NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j); if (!nodeState->markedDirty_) { nodeState->markedDirty_ = true; nodeState->sceneState_->dirtyNodes_.Insert(id_); } } } } Node* Node::CreateChild(unsigned id, CreateMode mode) { SharedPtr<Node> newNode(new Node(context_)); // If zero ID specified, or the ID is already taken, let the scene assign if (scene_) { if (!id || scene_->GetNode(id)) id = scene_->GetFreeNodeID(mode); newNode->SetID(id); } else newNode->SetID(id); AddChild(newNode); return newNode; } void Node::AddComponent(Component* component, unsigned id, CreateMode mode) { if (!component) return; components_.Push(SharedPtr<Component>(component)); // If zero ID specified, or the ID is already taken, let the scene assign if (scene_) { if (!id || scene_->GetComponent(id)) id = scene_->GetFreeComponentID(mode); component->SetID(id); scene_->ComponentAdded(component); } else component->SetID(id); if(component->GetNode()) LOGWARNING("Component " + component->GetTypeName() + " already belongs to a node!"); component->SetNode(this); component->OnMarkedDirty(this); // Check attributes of the new component on next network update, and mark node dirty in all replication states component->MarkNetworkUpdate(); MarkNetworkUpdate(); MarkReplicationDirty(); // Send change event if (scene_) { using namespace ComponentAdded; VariantMap& eventData = GetEventDataMap(); eventData[P_SCENE] = scene_; eventData[P_NODE] = this; eventData[P_COMPONENT] = component; scene_->SendEvent(E_COMPONENTADDED, eventData); } } unsigned Node::GetNumPersistentChildren() const { unsigned ret = 0; for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) { if (!(*i)->IsTemporary()) ++ret; } return ret; } unsigned Node::GetNumPersistentComponents() const { unsigned ret = 0; for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i) { if (!(*i)->IsTemporary()) ++ret; } return ret; } void Node::OnAttributeAnimationAdded() { if (attributeAnimationInfos_.Size() == 1) SubscribeToEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE, HANDLER(Node, HandleAttributeAnimationUpdate)); } void Node::OnAttributeAnimationRemoved() { if (attributeAnimationInfos_.Empty()) UnsubscribeFromEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE); } Component* Node::SafeCreateComponent(const String& typeName, ShortStringHash type, CreateMode mode, unsigned id) { // First check if factory for type exists if (!context_->GetTypeName(type).Empty()) return CreateComponent(type, mode, id); else { LOGWARNING("Component type " + type.ToString() + " not known, creating UnknownComponent as placeholder"); // Else create as UnknownComponent SharedPtr<UnknownComponent> newComponent(new UnknownComponent(context_)); if (typeName.Empty() || typeName.StartsWith("Unknown", false)) newComponent->SetType(type); else newComponent->SetTypeName(typeName); AddComponent(newComponent, id, mode); return newComponent; } } void Node::UpdateWorldTransform() const { Matrix3x4 transform = GetTransform(); // Assume the root node (scene) has identity transform if (parent_ == scene_ || !parent_) { worldTransform_ = transform; worldRotation_ = rotation_; } else { worldTransform_ = parent_->GetWorldTransform() * transform; worldRotation_ = parent_->GetWorldRotation() * rotation_; } dirty_ = false; } void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i) { // Send change event. Do not send when already being destroyed if (Refs() > 0 && scene_) { using namespace NodeRemoved; VariantMap& eventData = GetEventDataMap(); eventData[P_SCENE] = scene_; eventData[P_PARENT] = this; eventData[P_NODE] = (*i).Get(); scene_->SendEvent(E_NODEREMOVED, eventData); } (*i)->parent_ = 0; (*i)->MarkDirty(); (*i)->MarkNetworkUpdate(); children_.Erase(i); } void Node::GetChildrenRecursive(PODVector<Node*>& dest) const { for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) { Node* node = *i; dest.Push(node); if (!node->children_.Empty()) node->GetChildrenRecursive(dest); } } void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const { for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) { Node* node = *i; if (node->HasComponent(type)) dest.Push(node); if (!node->children_.Empty()) node->GetChildrenWithComponentRecursive(dest, type); } } void Node::GetComponentsRecursive(PODVector<Component*>& dest, ShortStringHash type) const { for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i) { if ((*i)->GetType() == type) dest.Push(*i); } for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) (*i)->GetComponentsRecursive(dest, type); } Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode) { // Create clone node Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL); resolver.AddNode(id_, cloneNode); // Copy attributes const Vector<AttributeInfo>* attributes = GetAttributes(); for (unsigned j = 0; j < attributes->Size(); ++j) { const AttributeInfo& attr = attributes->At(j); // Do not copy network-only attributes, as they may have unintended side effects if (attr.mode_ & AM_FILE) { Variant value; OnGetAttribute(attr, value); cloneNode->OnSetAttribute(attr, value); } } // Clone components for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i) { Component* component = *i; Component* cloneComponent = cloneNode->CloneComponent(component, (mode == REPLICATED && component->GetID() < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, 0); if (cloneComponent) resolver.AddComponent(component->GetID(), cloneComponent); } // Clone child nodes recursively for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) { Node* node = *i; node->CloneRecursive(cloneNode, resolver, mode); } return cloneNode; } void Node::RemoveComponent(Vector<SharedPtr<Component> >::Iterator i) { WeakPtr<Component> componentWeak(*i); // Send node change event. Do not send when already being destroyed if (Refs() > 0 && scene_) { using namespace ComponentRemoved; VariantMap& eventData = GetEventDataMap(); eventData[P_SCENE] = scene_; eventData[P_NODE] = this; eventData[P_COMPONENT] = (*i).Get(); scene_->SendEvent(E_COMPONENTREMOVED, eventData); } RemoveListener(*i); if (scene_) scene_->ComponentRemoved(*i); components_.Erase(i); // If the component is still referenced elsewhere, reset its node pointer now if (componentWeak) componentWeak->SetNode(0); } void Node::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData) { using namespace AttributeAnimationUpdate; UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat()); } } Call ApplyAttributes() on the cloned component to make sure attribute side-effects happen. // // Copyright (c) 2008-2014 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "Precompiled.h" #include "Component.h" #include "Context.h" #include "Log.h" #include "MemoryBuffer.h" #include "ObjectAnimation.h" #include "Profiler.h" #include "ReplicationState.h" #include "Scene.h" #include "SceneEvents.h" #include "SmoothedTransform.h" #include "UnknownComponent.h" #include "XMLFile.h" #include "DebugNew.h" namespace Urho3D { Node::Node(Context* context) : Animatable(context), networkUpdate_(false), worldTransform_(Matrix3x4::IDENTITY), dirty_(false), enabled_(true), parent_(0), scene_(0), id_(0), position_(Vector3::ZERO), rotation_(Quaternion::IDENTITY), scale_(Vector3::ONE), worldRotation_(Quaternion::IDENTITY), owner_(0) { } Node::~Node() { RemoveAllChildren(); RemoveAllComponents(); // Remove from the scene if (scene_) scene_->NodeRemoved(this); } void Node::RegisterObject(Context* context) { context->RegisterFactory<Node>(); ACCESSOR_ATTRIBUTE(Node, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT); REF_ACCESSOR_ATTRIBUTE(Node, VAR_STRING, "Name", GetName, SetName, String, String::EMPTY, AM_DEFAULT); REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE); REF_ACCESSOR_ATTRIBUTE(Node, VAR_QUATERNION, "Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE); REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT); ATTRIBUTE(Node, VAR_VARIANTMAP, "Variables", vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Network Position", GetNetPositionAttr, SetNetPositionAttr, Vector3, Vector3::ZERO, AM_NET | AM_LATESTDATA | AM_NOEDIT); REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_LATESTDATA | AM_NOEDIT); REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Parent Node", GetNetParentAttr, SetNetParentAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_NOEDIT); } bool Node::Load(Deserializer& source, bool setInstanceDefault) { SceneResolver resolver; // Read own ID. Will not be applied, only stored for resolving possible references unsigned nodeID = source.ReadInt(); resolver.AddNode(nodeID, this); // Read attributes, components and child nodes bool success = Load(source, resolver); if (success) { resolver.Resolve(); ApplyAttributes(); } return success; } bool Node::Save(Serializer& dest) const { // Write node ID if (!dest.WriteUInt(id_)) return false; // Write attributes if (!Animatable::Save(dest)) return false; // Write components dest.WriteVLE(GetNumPersistentComponents()); for (unsigned i = 0; i < components_.Size(); ++i) { Component* component = components_[i]; if (component->IsTemporary()) continue; // Create a separate buffer to be able to skip failing components during deserialization VectorBuffer compBuffer; if (!component->Save(compBuffer)) return false; dest.WriteVLE(compBuffer.GetSize()); dest.Write(compBuffer.GetData(), compBuffer.GetSize()); } // Write child nodes dest.WriteVLE(GetNumPersistentChildren()); for (unsigned i = 0; i < children_.Size(); ++i) { Node* node = children_[i]; if (node->IsTemporary()) continue; if (!node->Save(dest)) return false; } return true; } bool Node::LoadXML(const XMLElement& source, bool setInstanceDefault) { SceneResolver resolver; // Read own ID. Will not be applied, only stored for resolving possible references unsigned nodeID = source.GetInt("id"); resolver.AddNode(nodeID, this); // Read attributes, components and child nodes bool success = LoadXML(source, resolver); if (success) { resolver.Resolve(); ApplyAttributes(); } return success; } bool Node::SaveXML(XMLElement& dest) const { // Write node ID if (!dest.SetInt("id", id_)) return false; // Write attributes if (!Animatable::SaveXML(dest)) return false; // Write components for (unsigned i = 0; i < components_.Size(); ++i) { Component* component = components_[i]; if (component->IsTemporary()) continue; XMLElement compElem = dest.CreateChild("component"); if (!component->SaveXML(compElem)) return false; } // Write child nodes for (unsigned i = 0; i < children_.Size(); ++i) { Node* node = children_[i]; if (node->IsTemporary()) continue; XMLElement childElem = dest.CreateChild("node"); if (!node->SaveXML(childElem)) return false; } return true; } void Node::ApplyAttributes() { for (unsigned i = 0; i < components_.Size(); ++i) components_[i]->ApplyAttributes(); for (unsigned i = 0; i < children_.Size(); ++i) children_[i]->ApplyAttributes(); } void Node::MarkNetworkUpdate() { if (!networkUpdate_ && scene_ && id_ < FIRST_LOCAL_ID) { scene_->MarkNetworkUpdate(this); networkUpdate_ = true; } } void Node::AddReplicationState(NodeReplicationState* state) { if (!networkState_) AllocateNetworkState(); networkState_->replicationStates_.Push(state); } bool Node::SaveXML(Serializer& dest) const { SharedPtr<XMLFile> xml(new XMLFile(context_)); XMLElement rootElem = xml->CreateRoot("node"); if (!SaveXML(rootElem)) return false; return xml->Save(dest); } void Node::SetName(const String& name) { if (name != name_) { name_ = name; nameHash_ = name_; MarkNetworkUpdate(); // Send change event if (scene_) { using namespace NodeNameChanged; VariantMap& eventData = GetEventDataMap(); eventData[P_SCENE] = scene_; eventData[P_NODE] = this; scene_->SendEvent(E_NODENAMECHANGED, eventData); } } } void Node::SetPosition(const Vector3& position) { position_ = position; MarkDirty(); MarkNetworkUpdate(); } void Node::SetRotation(const Quaternion& rotation) { rotation_ = rotation; MarkDirty(); MarkNetworkUpdate(); } void Node::SetDirection(const Vector3& direction) { SetRotation(Quaternion(Vector3::FORWARD, direction)); } void Node::SetScale(float scale) { SetScale(Vector3(scale, scale, scale)); } void Node::SetScale(const Vector3& scale) { scale_ = scale.Abs(); MarkDirty(); MarkNetworkUpdate(); } void Node::SetTransform(const Vector3& position, const Quaternion& rotation) { position_ = position; rotation_ = rotation; MarkDirty(); MarkNetworkUpdate(); } void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale) { SetTransform(position, rotation, Vector3(scale, scale, scale)); } void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale) { position_ = position; rotation_ = rotation; scale_ = scale; MarkDirty(); MarkNetworkUpdate(); } void Node::SetWorldPosition(const Vector3& position) { SetPosition((parent_ == scene_ || !parent_) ? position : parent_->GetWorldTransform().Inverse() * position); } void Node::SetWorldRotation(const Quaternion& rotation) { SetRotation((parent_ == scene_ || !parent_) ? rotation : parent_->GetWorldRotation().Inverse() * rotation); } void Node::SetWorldDirection(const Vector3& direction) { Vector3 localDirection = (parent_ == scene_ || !parent_) ? direction : parent_->GetWorldRotation().Inverse() * direction; SetRotation(Quaternion(Vector3::FORWARD, localDirection)); } void Node::SetWorldScale(float scale) { SetWorldScale(Vector3(scale, scale, scale)); } void Node::SetWorldScale(const Vector3& scale) { SetScale((parent_ == scene_ || !parent_) ? scale : scale / parent_->GetWorldScale()); } void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation) { SetWorldPosition(position); SetWorldRotation(rotation); } void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale) { SetWorldPosition(position); SetWorldRotation(rotation); SetWorldScale(scale); } void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale) { SetWorldPosition(position); SetWorldRotation(rotation); SetWorldScale(scale); } void Node::Translate(const Vector3& delta, TransformSpace space) { switch (space) { case TS_LOCAL: // Note: local space translation disregards local scale for scale-independent movement speed position_ += rotation_ * delta; break; case TS_PARENT: position_ += delta; break; case TS_WORLD: position_ += (parent_ == scene_ || !parent_) ? delta : parent_->GetWorldTransform().Inverse() * Vector4(delta, 0.0f); break; } MarkDirty(); MarkNetworkUpdate(); } void Node::Rotate(const Quaternion& delta, TransformSpace space) { switch (space) { case TS_LOCAL: rotation_ = (rotation_ * delta).Normalized(); break; case TS_PARENT: rotation_ = (delta * rotation_).Normalized(); break; case TS_WORLD: if (parent_ == scene_ || !parent_) rotation_ = (delta * rotation_).Normalized(); else { Quaternion worldRotation = GetWorldRotation(); rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation; } break; } MarkDirty(); MarkNetworkUpdate(); } void Node::RotateAround(const Vector3& point, const Quaternion& delta, TransformSpace space) { Vector3 parentSpacePoint; Quaternion oldRotation = rotation_; switch (space) { case TS_LOCAL: parentSpacePoint = GetTransform() * point; rotation_ = (rotation_ * delta).Normalized(); break; case TS_PARENT: parentSpacePoint = point; rotation_ = (delta * rotation_).Normalized(); break; case TS_WORLD: if (parent_ == scene_ || !parent_) { parentSpacePoint = point; rotation_ = (delta * rotation_).Normalized(); } else { parentSpacePoint = parent_->GetWorldTransform().Inverse() * point; Quaternion worldRotation = GetWorldRotation(); rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation; } break; } Vector3 oldRelativePos = oldRotation.Inverse() * (position_ - parentSpacePoint); position_ = rotation_ * oldRelativePos + parentSpacePoint; MarkDirty(); MarkNetworkUpdate(); } void Node::Yaw(float angle, TransformSpace space) { Rotate(Quaternion(angle, Vector3::UP), space); } void Node::Pitch(float angle, TransformSpace space) { Rotate(Quaternion(angle, Vector3::RIGHT), space); } void Node::Roll(float angle, TransformSpace space) { Rotate(Quaternion(angle, Vector3::FORWARD), space); } bool Node::LookAt(const Vector3& target, const Vector3& up, TransformSpace space) { Vector3 worldSpaceTarget; switch (space) { case TS_LOCAL: worldSpaceTarget = GetWorldTransform() * target; break; case TS_PARENT: worldSpaceTarget = (parent_ == scene_ || !parent_) ? target : parent_->GetWorldTransform() * target; break; case TS_WORLD: worldSpaceTarget = target; break; } Vector3 lookDir = target - GetWorldPosition(); // Check if target is very close, in that case can not reliably calculate lookat direction if (lookDir.Equals(Vector3::ZERO)) return false; Quaternion newRotation; // Do nothing if setting look rotation failed if (!newRotation.FromLookRotation(lookDir, up)) return false; SetWorldRotation(newRotation); return true; } void Node::Scale(float scale) { Scale(Vector3(scale, scale, scale)); } void Node::Scale(const Vector3& scale) { scale_ *= scale; MarkDirty(); MarkNetworkUpdate(); } void Node::SetEnabled(bool enable) { SetEnabled(enable, false); } void Node::SetEnabled(bool enable, bool recursive) { // The enabled state of the whole scene can not be changed. SetUpdateEnabled() is used instead to start/stop updates. if (GetType() == Scene::GetTypeStatic()) { LOGERROR("Can not change enabled state of the Scene"); return; } if (enable != enabled_) { enabled_ = enable; MarkNetworkUpdate(); // Notify listener components of the state change for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();) { if (*i) { (*i)->OnNodeSetEnabled(this); ++i; } // If listener has expired, erase from list else i = listeners_.Erase(i); } // Send change event if (scene_) { using namespace NodeEnabledChanged; VariantMap& eventData = GetEventDataMap(); eventData[P_SCENE] = scene_; eventData[P_NODE] = this; scene_->SendEvent(E_NODEENABLEDCHANGED, eventData); } for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i) { (*i)->OnSetEnabled(); // Send change event for the component if (scene_) { using namespace ComponentEnabledChanged; VariantMap& eventData = GetEventDataMap(); eventData[P_SCENE] = scene_; eventData[P_NODE] = this; eventData[P_COMPONENT] = (*i); scene_->SendEvent(E_COMPONENTENABLEDCHANGED, eventData); } } } if (recursive) { for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i) (*i)->SetEnabled(enable, recursive); } } void Node::SetOwner(Connection* owner) { owner_ = owner; } void Node::MarkDirty() { if (dirty_) return; dirty_ = true; // Notify listener components first, then mark child nodes for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();) { if (*i) { (*i)->OnMarkedDirty(this); ++i; } // If listener has expired, erase from list else i = listeners_.Erase(i); } for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i) (*i)->MarkDirty(); } Node* Node::CreateChild(const String& name, CreateMode mode, unsigned id) { Node* newNode = CreateChild(id, mode); newNode->SetName(name); return newNode; } void Node::AddChild(Node* node, unsigned index) { // Check for illegal or redundant parent assignment if (!node || node == this || node->parent_ == this) return; // Check for possible cyclic parent assignment Node* parent = parent_; while (parent) { if (parent == node) return; parent = parent->parent_; } // Add first, then remove from old parent, to ensure the node does not get deleted children_.Insert(index, SharedPtr<Node>(node)); node->Remove(); // Add to the scene if not added yet if (scene_ && node->GetScene() != scene_) scene_->NodeAdded(node); node->parent_ = this; node->MarkDirty(); node->MarkNetworkUpdate(); // Send change event if (scene_) { using namespace NodeAdded; VariantMap& eventData = GetEventDataMap(); eventData[P_SCENE] = scene_; eventData[P_PARENT] = this; eventData[P_NODE] = node; scene_->SendEvent(E_NODEADDED, eventData); } } void Node::RemoveChild(Node* node) { if (!node) return; for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i) { if (*i == node) { RemoveChild(i); return; } } } void Node::RemoveAllChildren() { RemoveChildren(true, true, true); } void Node::RemoveChildren(bool removeReplicated, bool removeLocal, bool recursive) { unsigned numRemoved = 0; for (unsigned i = children_.Size() - 1; i < children_.Size(); --i) { bool remove = false; Node* childNode = children_[i]; if (recursive) childNode->RemoveChildren(removeReplicated, removeLocal, true); if (childNode->GetID() < FIRST_LOCAL_ID && removeReplicated) remove = true; else if (childNode->GetID() >= FIRST_LOCAL_ID && removeLocal) remove = true; if (remove) { RemoveChild(children_.Begin() + i); ++numRemoved; } } // Mark node dirty in all replication states if (numRemoved) MarkReplicationDirty(); } Component* Node::CreateComponent(ShortStringHash type, CreateMode mode, unsigned id) { // Check that creation succeeds and that the object in fact is a component SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type)); if (!newComponent) { LOGERROR("Could not create unknown component type " + type.ToString()); return 0; } AddComponent(newComponent, id, mode); return newComponent; } Component* Node::GetOrCreateComponent(ShortStringHash type, CreateMode mode, unsigned id) { Component* oldComponent = GetComponent(type); if (oldComponent) return oldComponent; else return CreateComponent(type, mode, id); } Component* Node::CloneComponent(Component* component, unsigned id) { if (!component) { LOGERROR("Null source component given for CloneComponent"); return 0; } return CloneComponent(component, component->GetID() < FIRST_LOCAL_ID ? REPLICATED : LOCAL, id); } Component* Node::CloneComponent(Component* component, CreateMode mode, unsigned id) { if (!component) { LOGERROR("Null source component given for CloneComponent"); return 0; } Component* cloneComponent = SafeCreateComponent(component->GetTypeName(), component->GetType(), mode, 0); if (!cloneComponent) { LOGERROR("Could not clone component " + component->GetTypeName()); return 0; } const Vector<AttributeInfo>* compAttributes = component->GetAttributes(); if (compAttributes) { for (unsigned j = 0; j < compAttributes->Size(); ++j) { const AttributeInfo& attr = compAttributes->At(j); if (attr.mode_ & AM_FILE) { Variant value; component->OnGetAttribute(attr, value); cloneComponent->OnSetAttribute(attr, value); } } cloneComponent->ApplyAttributes(); } return cloneComponent; } void Node::RemoveComponent(Component* component) { for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i) { if (*i == component) { RemoveComponent(i); // Mark node dirty in all replication states MarkReplicationDirty(); return; } } } void Node::RemoveComponent(ShortStringHash type) { for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i) { if ((*i)->GetType() == type) { RemoveComponent(i); // Mark node dirty in all replication states MarkReplicationDirty(); return; } } } void Node::RemoveAllComponents() { RemoveComponents(true, true); } void Node::RemoveComponents(bool removeReplicated, bool removeLocal) { unsigned numRemoved = 0; for (unsigned i = components_.Size() - 1; i < components_.Size(); --i) { bool remove = false; Component* component = components_[i]; if (component->GetID() < FIRST_LOCAL_ID && removeReplicated) remove = true; else if (component->GetID() >= FIRST_LOCAL_ID && removeLocal) remove = true; if (remove) { RemoveComponent(components_.Begin() + i); ++numRemoved; } } // Mark node dirty in all replication states if (numRemoved) MarkReplicationDirty(); } Node* Node::Clone(CreateMode mode) { // The scene itself can not be cloned if (this == scene_ || !parent_) { LOGERROR("Can not clone node without a parent"); return 0; } PROFILE(CloneNode); SceneResolver resolver; Node* clone = CloneRecursive(parent_, resolver, mode); resolver.Resolve(); clone->ApplyAttributes(); return clone; } void Node::Remove() { if (parent_) parent_->RemoveChild(this); } void Node::SetParent(Node* parent) { if (parent) { Matrix3x4 oldWorldTransform = GetWorldTransform(); parent->AddChild(this); if (parent != scene_) { Matrix3x4 newTransform = parent->GetWorldTransform().Inverse() * oldWorldTransform; SetTransform(newTransform.Translation(), newTransform.Rotation(), newTransform.Scale()); } else { // The root node is assumed to have identity transform, so can disregard it SetTransform(oldWorldTransform.Translation(), oldWorldTransform.Rotation(), oldWorldTransform.Scale()); } } } void Node::SetVar(ShortStringHash key, const Variant& value) { vars_[key] = value; MarkNetworkUpdate(); } void Node::AddListener(Component* component) { if (!component) return; // Check for not adding twice for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i) { if (*i == component) return; } listeners_.Push(WeakPtr<Component>(component)); // If the node is currently dirty, notify immediately if (dirty_) component->OnMarkedDirty(this); } void Node::RemoveListener(Component* component) { for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i) { if (*i == component) { listeners_.Erase(i); return; } } } Vector3 Node::LocalToWorld(const Vector3& position) const { return GetWorldTransform() * position; } Vector3 Node::LocalToWorld(const Vector4& vector) const { return GetWorldTransform() * vector; } Vector2 Node::LocalToWorld(const Vector2& vector) const { Vector3 result = LocalToWorld(Vector3(vector)); return Vector2(result.x_, result.y_); } Vector3 Node::WorldToLocal(const Vector3& position) const { return GetWorldTransform().Inverse() * position; } Vector3 Node::WorldToLocal(const Vector4& vector) const { return GetWorldTransform().Inverse() * vector; } Vector2 Node::WorldToLocal(const Vector2& vector) const { Vector3 result = WorldToLocal(Vector3(vector)); return Vector2(result.x_, result.y_); } unsigned Node::GetNumChildren(bool recursive) const { if (!recursive) return children_.Size(); else { unsigned allChildren = children_.Size(); for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) allChildren += (*i)->GetNumChildren(true); return allChildren; } } void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const { dest.Clear(); if (!recursive) { for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) dest.Push(*i); } else GetChildrenRecursive(dest); } void Node::GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive) const { dest.Clear(); if (!recursive) { for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) { if ((*i)->HasComponent(type)) dest.Push(*i); } } else GetChildrenWithComponentRecursive(dest, type); } Node* Node::GetChild(unsigned index) const { return index < children_.Size() ? children_[index].Get() : 0; } Node* Node::GetChild(const String& name, bool recursive) const { return GetChild(StringHash(name), recursive); } Node* Node::GetChild(const char* name, bool recursive) const { return GetChild(StringHash(name), recursive); } Node* Node::GetChild(StringHash nameHash, bool recursive) const { for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) { if ((*i)->GetNameHash() == nameHash) return *i; if (recursive) { Node* node = (*i)->GetChild(nameHash, true); if (node) return node; } } return 0; } unsigned Node::GetNumNetworkComponents() const { unsigned num = 0; for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i) { if ((*i)->GetID() < FIRST_LOCAL_ID) ++num; } return num; } void Node::GetComponents(PODVector<Component*>& dest, ShortStringHash type, bool recursive) const { dest.Clear(); if (!recursive) { for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i) { if ((*i)->GetType() == type) dest.Push(*i); } } else GetComponentsRecursive(dest, type); } bool Node::HasComponent(ShortStringHash type) const { for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i) { if ((*i)->GetType() == type) return true; } return false; } const Variant& Node::GetVar(ShortStringHash key) const { VariantMap::ConstIterator i = vars_.Find(key); return i != vars_.End() ? i->second_ : Variant::EMPTY; } Component* Node::GetComponent(ShortStringHash type) const { for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i) { if ((*i)->GetType() == type) return *i; } return 0; } void Node::SetID(unsigned id) { id_ = id; } void Node::SetScene(Scene* scene) { scene_ = scene; } void Node::ResetScene() { SetID(0); SetScene(0); SetOwner(0); } void Node::SetNetPositionAttr(const Vector3& value) { SmoothedTransform* transform = GetComponent<SmoothedTransform>(); if (transform) transform->SetTargetPosition(value); else SetPosition(value); } void Node::SetNetRotationAttr(const PODVector<unsigned char>& value) { MemoryBuffer buf(value); SmoothedTransform* transform = GetComponent<SmoothedTransform>(); if (transform) transform->SetTargetRotation(buf.ReadPackedQuaternion()); else SetRotation(buf.ReadPackedQuaternion()); } void Node::SetNetParentAttr(const PODVector<unsigned char>& value) { Scene* scene = GetScene(); if (!scene) return; MemoryBuffer buf(value); // If nothing in the buffer, parent is the root node if (buf.IsEof()) { scene->AddChild(this); return; } unsigned baseNodeID = buf.ReadNetID(); Node* baseNode = scene->GetNode(baseNodeID); if (!baseNode) { LOGWARNING("Failed to find parent node " + String(baseNodeID)); return; } // If buffer contains just an ID, the parent is replicated and we are done if (buf.IsEof()) baseNode->AddChild(this); else { // Else the parent is local and we must find it recursively by name hash StringHash nameHash = buf.ReadStringHash(); Node* parentNode = baseNode->GetChild(nameHash, true); if (!parentNode) LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString()); else parentNode->AddChild(this); } } const Vector3& Node::GetNetPositionAttr() const { return position_; } const PODVector<unsigned char>& Node::GetNetRotationAttr() const { attrBuffer_.Clear(); attrBuffer_.WritePackedQuaternion(rotation_); return attrBuffer_.GetBuffer(); } const PODVector<unsigned char>& Node::GetNetParentAttr() const { attrBuffer_.Clear(); Scene* scene = GetScene(); if (scene && parent_ && parent_ != scene) { // If parent is replicated, can write the ID directly unsigned parentID = parent_->GetID(); if (parentID < FIRST_LOCAL_ID) attrBuffer_.WriteNetID(parentID); else { // Parent is local: traverse hierarchy to find a non-local base node // This iteration always stops due to the scene (root) being non-local Node* current = parent_; while (current->GetID() >= FIRST_LOCAL_ID) current = current->GetParent(); // Then write the base node ID and the parent's name hash attrBuffer_.WriteNetID(current->GetID()); attrBuffer_.WriteStringHash(parent_->GetNameHash()); } } return attrBuffer_.GetBuffer(); } bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode) { // Remove all children and components first in case this is not a fresh load RemoveAllChildren(); RemoveAllComponents(); // ID has been read at the parent level if (!Animatable::Load(source)) return false; unsigned numComponents = source.ReadVLE(); for (unsigned i = 0; i < numComponents; ++i) { VectorBuffer compBuffer(source, source.ReadVLE()); ShortStringHash compType = compBuffer.ReadShortStringHash(); unsigned compID = compBuffer.ReadUInt(); Component* newComponent = SafeCreateComponent(String::EMPTY, compType, (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID); if (newComponent) { resolver.AddComponent(compID, newComponent); // Do not abort if component fails to load, as the component buffer is nested and we can skip to the next newComponent->Load(compBuffer); } } if (!readChildren) return true; unsigned numChildren = source.ReadVLE(); for (unsigned i = 0; i < numChildren; ++i) { unsigned nodeID = source.ReadUInt(); Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL); resolver.AddNode(nodeID, newNode); if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode)) return false; } return true; } bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode) { // Remove all children and components first in case this is not a fresh load RemoveAllChildren(); RemoveAllComponents(); if (!Animatable::LoadXML(source)) return false; XMLElement compElem = source.GetChild("component"); while (compElem) { String typeName = compElem.GetAttribute("type"); unsigned compID = compElem.GetInt("id"); Component* newComponent = SafeCreateComponent(typeName, ShortStringHash(typeName), (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID); if (newComponent) { resolver.AddComponent(compID, newComponent); if (!newComponent->LoadXML(compElem)) return false; } compElem = compElem.GetNext("component"); } if (!readChildren) return true; XMLElement childElem = source.GetChild("node"); while (childElem) { unsigned nodeID = childElem.GetInt("id"); Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL); resolver.AddNode(nodeID, newNode); if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode)) return false; childElem = childElem.GetNext("node"); } return true; } void Node::PrepareNetworkUpdate() { // Update dependency nodes list first dependencyNodes_.Clear(); // Add the parent node, but if it is local, traverse to the first non-local node if (parent_ && parent_ != scene_) { Node* current = parent_; while (current->id_ >= FIRST_LOCAL_ID) current = current->parent_; if (current && current != scene_) dependencyNodes_.Push(current); } // Let the components add their dependencies for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i) { Component* component = *i; if (component->GetID() < FIRST_LOCAL_ID) component->GetDependencyNodes(dependencyNodes_); } // Then check for node attribute changes if (!networkState_) AllocateNetworkState(); const Vector<AttributeInfo>* attributes = networkState_->attributes_; unsigned numAttributes = attributes->Size(); if (networkState_->currentValues_.Size() != numAttributes) { networkState_->currentValues_.Resize(numAttributes); networkState_->previousValues_.Resize(numAttributes); // Copy the default attribute values to the previous state as a starting point for (unsigned i = 0; i < numAttributes; ++i) networkState_->previousValues_[i] = attributes->At(i).defaultValue_; } // Check for attribute changes for (unsigned i = 0; i < numAttributes; ++i) { const AttributeInfo& attr = attributes->At(i); if (animationEnabled_ && IsAnimatedNetworkAttribute(attr)) continue; OnGetAttribute(attr, networkState_->currentValues_[i]); if (networkState_->currentValues_[i] != networkState_->previousValues_[i]) { networkState_->previousValues_[i] = networkState_->currentValues_[i]; // Mark the attribute dirty in all replication states that are tracking this node for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j != networkState_->replicationStates_.End(); ++j) { NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j); nodeState->dirtyAttributes_.Set(i); // Add node to the dirty set if not added yet if (!nodeState->markedDirty_) { nodeState->markedDirty_ = true; nodeState->sceneState_->dirtyNodes_.Insert(id_); } } } } // Finally check for user var changes for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i) { VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_); if (j == networkState_->previousVars_.End() || j->second_ != i->second_) { networkState_->previousVars_[i->first_] = i->second_; // Mark the var dirty in all replication states that are tracking this node for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j != networkState_->replicationStates_.End(); ++j) { NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j); nodeState->dirtyVars_.Insert(i->first_); if (!nodeState->markedDirty_) { nodeState->markedDirty_ = true; nodeState->sceneState_->dirtyNodes_.Insert(id_); } } } } networkUpdate_ = false; } void Node::CleanupConnection(Connection* connection) { if (owner_ == connection) owner_ = 0; if (networkState_) { for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i) { if (networkState_->replicationStates_[i]->connection_ == connection) networkState_->replicationStates_.Erase(i); } } } void Node::MarkReplicationDirty() { if (networkState_) { for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j != networkState_->replicationStates_.End(); ++j) { NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j); if (!nodeState->markedDirty_) { nodeState->markedDirty_ = true; nodeState->sceneState_->dirtyNodes_.Insert(id_); } } } } Node* Node::CreateChild(unsigned id, CreateMode mode) { SharedPtr<Node> newNode(new Node(context_)); // If zero ID specified, or the ID is already taken, let the scene assign if (scene_) { if (!id || scene_->GetNode(id)) id = scene_->GetFreeNodeID(mode); newNode->SetID(id); } else newNode->SetID(id); AddChild(newNode); return newNode; } void Node::AddComponent(Component* component, unsigned id, CreateMode mode) { if (!component) return; components_.Push(SharedPtr<Component>(component)); // If zero ID specified, or the ID is already taken, let the scene assign if (scene_) { if (!id || scene_->GetComponent(id)) id = scene_->GetFreeComponentID(mode); component->SetID(id); scene_->ComponentAdded(component); } else component->SetID(id); if(component->GetNode()) LOGWARNING("Component " + component->GetTypeName() + " already belongs to a node!"); component->SetNode(this); component->OnMarkedDirty(this); // Check attributes of the new component on next network update, and mark node dirty in all replication states component->MarkNetworkUpdate(); MarkNetworkUpdate(); MarkReplicationDirty(); // Send change event if (scene_) { using namespace ComponentAdded; VariantMap& eventData = GetEventDataMap(); eventData[P_SCENE] = scene_; eventData[P_NODE] = this; eventData[P_COMPONENT] = component; scene_->SendEvent(E_COMPONENTADDED, eventData); } } unsigned Node::GetNumPersistentChildren() const { unsigned ret = 0; for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) { if (!(*i)->IsTemporary()) ++ret; } return ret; } unsigned Node::GetNumPersistentComponents() const { unsigned ret = 0; for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i) { if (!(*i)->IsTemporary()) ++ret; } return ret; } void Node::OnAttributeAnimationAdded() { if (attributeAnimationInfos_.Size() == 1) SubscribeToEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE, HANDLER(Node, HandleAttributeAnimationUpdate)); } void Node::OnAttributeAnimationRemoved() { if (attributeAnimationInfos_.Empty()) UnsubscribeFromEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE); } Component* Node::SafeCreateComponent(const String& typeName, ShortStringHash type, CreateMode mode, unsigned id) { // First check if factory for type exists if (!context_->GetTypeName(type).Empty()) return CreateComponent(type, mode, id); else { LOGWARNING("Component type " + type.ToString() + " not known, creating UnknownComponent as placeholder"); // Else create as UnknownComponent SharedPtr<UnknownComponent> newComponent(new UnknownComponent(context_)); if (typeName.Empty() || typeName.StartsWith("Unknown", false)) newComponent->SetType(type); else newComponent->SetTypeName(typeName); AddComponent(newComponent, id, mode); return newComponent; } } void Node::UpdateWorldTransform() const { Matrix3x4 transform = GetTransform(); // Assume the root node (scene) has identity transform if (parent_ == scene_ || !parent_) { worldTransform_ = transform; worldRotation_ = rotation_; } else { worldTransform_ = parent_->GetWorldTransform() * transform; worldRotation_ = parent_->GetWorldRotation() * rotation_; } dirty_ = false; } void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i) { // Send change event. Do not send when already being destroyed if (Refs() > 0 && scene_) { using namespace NodeRemoved; VariantMap& eventData = GetEventDataMap(); eventData[P_SCENE] = scene_; eventData[P_PARENT] = this; eventData[P_NODE] = (*i).Get(); scene_->SendEvent(E_NODEREMOVED, eventData); } (*i)->parent_ = 0; (*i)->MarkDirty(); (*i)->MarkNetworkUpdate(); children_.Erase(i); } void Node::GetChildrenRecursive(PODVector<Node*>& dest) const { for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) { Node* node = *i; dest.Push(node); if (!node->children_.Empty()) node->GetChildrenRecursive(dest); } } void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const { for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) { Node* node = *i; if (node->HasComponent(type)) dest.Push(node); if (!node->children_.Empty()) node->GetChildrenWithComponentRecursive(dest, type); } } void Node::GetComponentsRecursive(PODVector<Component*>& dest, ShortStringHash type) const { for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i) { if ((*i)->GetType() == type) dest.Push(*i); } for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) (*i)->GetComponentsRecursive(dest, type); } Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode) { // Create clone node Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL); resolver.AddNode(id_, cloneNode); // Copy attributes const Vector<AttributeInfo>* attributes = GetAttributes(); for (unsigned j = 0; j < attributes->Size(); ++j) { const AttributeInfo& attr = attributes->At(j); // Do not copy network-only attributes, as they may have unintended side effects if (attr.mode_ & AM_FILE) { Variant value; OnGetAttribute(attr, value); cloneNode->OnSetAttribute(attr, value); } } // Clone components for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i) { Component* component = *i; Component* cloneComponent = cloneNode->CloneComponent(component, (mode == REPLICATED && component->GetID() < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, 0); if (cloneComponent) resolver.AddComponent(component->GetID(), cloneComponent); } // Clone child nodes recursively for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i) { Node* node = *i; node->CloneRecursive(cloneNode, resolver, mode); } return cloneNode; } void Node::RemoveComponent(Vector<SharedPtr<Component> >::Iterator i) { WeakPtr<Component> componentWeak(*i); // Send node change event. Do not send when already being destroyed if (Refs() > 0 && scene_) { using namespace ComponentRemoved; VariantMap& eventData = GetEventDataMap(); eventData[P_SCENE] = scene_; eventData[P_NODE] = this; eventData[P_COMPONENT] = (*i).Get(); scene_->SendEvent(E_COMPONENTREMOVED, eventData); } RemoveListener(*i); if (scene_) scene_->ComponentRemoved(*i); components_.Erase(i); // If the component is still referenced elsewhere, reset its node pointer now if (componentWeak) componentWeak->SetNode(0); } void Node::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData) { using namespace AttributeAnimationUpdate; UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat()); } }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include "config.h" #include <string.h> #include <cstdlib> #include <cctype> #include <algorithm> #include <stdio.h> #include <sys/types.h> #include <fcntl.h> #include <sys/stat.h> #include <iostream> #include <fstream> #include "couch-kvstore/couch-kvstore.hh" #include "couch-kvstore/dirutils.hh" #include "ep_engine.h" #include "tools/cJSON.h" #include "common.hh" #define STATWRITER_NAMESPACE couchstore_engine #include "statwriter.hh" #undef STATWRITER_NAMESPACE using namespace CouchKVStoreDirectoryUtilities; static const int MUTATION_FAILED = -1; static const int DOC_NOT_FOUND = 0; static const int MUTATION_SUCCESS = 1; extern "C" { static int recordDbDumpC(Db *db, DocInfo *docinfo, void *ctx) { return CouchKVStore::recordDbDump(db, docinfo, ctx); } } extern "C" { static int getMultiCbC(Db *db, DocInfo *docinfo, void *ctx) { return CouchKVStore::getMultiCb(db, docinfo, ctx); } } static bool isJSON(const value_t &value) { bool isJSON = false; const char *ptr = value->getData(); size_t len = value->length(); size_t ii = 0; while (ii < len && isspace(*ptr)) { ++ptr; ++ii; } if (ii < len && *ptr == '{') { // This may be JSON. Unfortunately we don't know if it's zero // terminated std::string data(value->getData(), value->length()); cJSON *json = cJSON_Parse(data.c_str()); if (json != 0) { isJSON = true; cJSON_Delete(json); } } return isJSON; } static const std::string getJSONObjString(const cJSON *i) { if (i == NULL) { return ""; } if (i->type != cJSON_String) { abort(); } return i->valuestring; } static bool endWithCompact(const std::string &filename) { size_t pos = filename.find(".compact"); if (pos == std::string::npos || (filename.size() - sizeof(".compact")) != pos) { return false; } return true; } static int dbFileRev(const std::string &dbname) { size_t secondDot = dbname.rfind("."); return atoi(dbname.substr(secondDot + 1).c_str()); } static void discoverDbFiles(const std::string &dir, std::vector<std::string> &v) { std::vector<std::string> files = findFilesContaining(dir, ".couch"); std::vector<std::string>::iterator ii; for (ii = files.begin(); ii != files.end(); ++ii) { if (!endWithCompact(*ii)) { v.push_back(*ii); } } } static uint32_t computeMaxDeletedSeqNum(DocInfo **docinfos, const int numdocs) { uint32_t max = 0; uint32_t seqNum; for (int idx = 0; idx < numdocs; idx++) { if (docinfos[idx]->deleted) { // check seq number only from a deleted file seqNum = (uint32_t)docinfos[idx]->rev_seq; max = std::max(seqNum, max); } } return max; } static int getMutationStatus(couchstore_error_t errCode) { switch (errCode) { case COUCHSTORE_SUCCESS: return MUTATION_SUCCESS; case COUCHSTORE_ERROR_DOC_NOT_FOUND: // this return causes ep engine to drop the failed flush // of an item since it does not know about the itme any longer return DOC_NOT_FOUND; default: // this return causes ep engine to keep requeuing the failed // flush of an item return MUTATION_FAILED; } } static bool allDigit(std::string &input) { size_t numchar = input.length(); for(size_t i = 0; i < numchar; ++i) { if (!isdigit(input[i])) { return false; } } return true; } struct WarmupCookie { WarmupCookie(KVStore *s, Callback<GetValue>&c) : store(s), cb(c), engine(s->getEngine()), loaded(0), skipped(0), error(0) { /* EMPTY */ } KVStore *store; Callback<GetValue> &cb; EventuallyPersistentEngine *engine; size_t loaded; size_t skipped; size_t error; }; static void batchWarmupCallback(uint16_t vbId, std::vector<std::pair<std::string, uint64_t> > &fetches, void *arg) { WarmupCookie *c = static_cast<WarmupCookie *>(arg); EventuallyPersistentEngine *engine = c->engine; if (engine->stillWarmingUp()) { vb_bgfetch_queue_t items2fetch; std::vector<std::pair<std::string, uint64_t> >::iterator itm = fetches.begin(); for(; itm != fetches.end(); itm++) { assert(items2fetch.find((*itm).second) == items2fetch.end()); items2fetch[(*itm).second].push_back( new VBucketBGFetchItem((*itm).first, (*itm).second, NULL)); } c->store->getMulti(vbId, items2fetch); vb_bgfetch_queue_t::iterator items = items2fetch.begin(); for (; items != items2fetch.end(); items++) { VBucketBGFetchItem * fetchedItem = (*items).second.back(); GetValue &val = fetchedItem->value; if (val.getStatus() == ENGINE_SUCCESS) { c->loaded++; c->cb.callback(val); } else { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: warmup failed to load data for " "vBucket = %d key = %s error = %X\n", vbId, fetchedItem->key.c_str(), val.getStatus()); c->error++; } delete fetchedItem; } } else { c->skipped++; } } struct GetMultiCbCtx { CouchKVStore &cks; uint16_t vbId; vb_bgfetch_queue_t &fetches; }; struct StatResponseCtx { public: StatResponseCtx(std::map<std::pair<uint16_t, uint16_t>, vbucket_state> &sm, uint16_t vb) : statMap(sm), vbId(vb) { /* EMPTY */ } std::map<std::pair<uint16_t, uint16_t>, vbucket_state> &statMap; uint16_t vbId; }; struct LoadResponseCtx { shared_ptr<LoadCallback> callback; uint16_t vbucketId; bool keysonly; EventuallyPersistentEngine *engine; }; CouchRequest::CouchRequest(const Item &it, int rev, CouchRequestCallback &cb, bool del) : value(it.getValue()), valuelen(it.getNBytes()), vbucketId(it.getVBucketId()), fileRevNum(rev), key(it.getKey()), deleteItem(del) { bool isjson = false; uint64_t cas = htonll(it.getCas()); uint32_t flags = htonl(it.getFlags()); uint32_t exptime = htonl(it.getExptime()); itemId = (it.getId() <= 0) ? 1 : 0; dbDoc.id.buf = const_cast<char *>(key.c_str()); dbDoc.id.size = it.getNKey(); if (valuelen) { isjson = isJSON(value); dbDoc.data.buf = const_cast<char *>(value->getData()); dbDoc.data.size = valuelen; } else { dbDoc.data.buf = NULL; dbDoc.data.size = 0; } memcpy(meta, &cas, 8); memcpy(meta + 8, &exptime, 4); memcpy(meta + 12, &flags, 4); dbDocInfo.rev_meta.buf = reinterpret_cast<char *>(meta); dbDocInfo.rev_meta.size = COUCHSTORE_METADATA_SIZE; dbDocInfo.rev_seq = it.getSeqno(); dbDocInfo.size = dbDoc.data.size; if (del) { dbDocInfo.deleted = 1; callback.delCb = cb.delCb; } else { dbDocInfo.deleted = 0; callback.setCb = cb.setCb; } dbDocInfo.id = dbDoc.id; dbDocInfo.content_meta = isjson ? COUCH_DOC_IS_JSON : COUCH_DOC_NON_JSON_MODE; start = gethrtime(); } CouchKVStore::CouchKVStore(EventuallyPersistentEngine &theEngine, bool read_only) : KVStore(read_only), engine(theEngine), epStats(theEngine.getEpStats()), configuration(theEngine.getConfiguration()), dbname(configuration.getDbname()), mc(NULL), pendingCommitCnt(0), intransaction(false) { open(); } CouchKVStore::CouchKVStore(const CouchKVStore &copyFrom) : KVStore(copyFrom), engine(copyFrom.engine), epStats(copyFrom.epStats), configuration(copyFrom.configuration), dbname(copyFrom.dbname), mc(NULL), pendingCommitCnt(0), intransaction(false) { open(); dbFileMap = copyFrom.dbFileMap; } void CouchKVStore::reset() { assert(!isReadOnly()); // TODO CouchKVStore::flush() when couchstore api ready RememberingCallback<bool> cb; mc->flush(cb); cb.waitForValue(); vbucket_map_t::iterator itor = cachedVBStates.begin(); for (; itor != cachedVBStates.end(); ++itor) { uint16_t vbucket = itor->first; itor->second.checkpointId = 0; itor->second.maxDeletedSeqno = 0; updateDbFileMap(vbucket, 1, true); } } void CouchKVStore::set(const Item &itm, Callback<mutation_result> &cb) { assert(!isReadOnly()); assert(intransaction); bool deleteItem = false; CouchRequestCallback requestcb; std::string dbFile; requestcb.setCb = &cb; if (!(getDbFile(itm.getVBucketId(), dbFile))) { ++st.numSetFailure; getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to set data, cannot locate database file %s\n", dbFile.c_str()); mutation_result p(MUTATION_FAILED, 0); cb.callback(p); return; } // each req will be de-allocated after commit CouchRequest *req = new CouchRequest(itm, dbFileRev(dbFile), requestcb, deleteItem); queueItem(req); } void CouchKVStore::get(const std::string &key, uint64_t, uint16_t vb, Callback<GetValue> &cb) { hrtime_t start = gethrtime(); Db *db = NULL; DocInfo *docInfo = NULL; std::string dbFile; GetValue rv; sized_buf id; if (!(getDbFile(vb, dbFile))) { ++st.numGetFailure; getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to retrieve data from vBucketId = %d " "[key=%s], cannot locate database file %s\n", vb, key.c_str(), dbFile.c_str()); rv.setStatus(ENGINE_NOT_MY_VBUCKET); cb.callback(rv); return; } couchstore_error_t errCode = openDB(vb, dbFileRev(dbFile), &db, 0, NULL); if (errCode != COUCHSTORE_SUCCESS) { ++st.numGetFailure; getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to open database, name=%s error=%s\n", dbFile.c_str(), couchstore_strerror(errCode)); rv.setStatus(couchErr2EngineErr(errCode)); cb.callback(rv); return; } RememberingCallback<GetValue> *rc = dynamic_cast<RememberingCallback<GetValue> *>(&cb); bool getMetaOnly = rc && rc->val.isPartial(); id.size = key.size(); id.buf = const_cast<char *>(key.c_str()); errCode = couchstore_docinfo_by_id(db, (uint8_t *)id.buf, id.size, &docInfo); if (errCode != COUCHSTORE_SUCCESS) { if (!getMetaOnly) { // log error only if this is non-xdcr case getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to retrieve doc info from " "database, name=%s key=%s error=%s\n", dbFile.c_str(), id.buf, couchstore_strerror(errCode)); } } else { errCode = fetchDoc(db, docInfo, rv, vb, getMetaOnly); if (errCode != COUCHSTORE_SUCCESS) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to retrieve key value from " "database, name=%s key=%s error=%s deleted=%s\n", dbFile.c_str(), id.buf, couchstore_strerror(errCode), docInfo->deleted ? "yes" : "no"); } // record stats st.readTimeHisto.add((gethrtime() - start) / 1000); st.readSizeHisto.add(key.length() + rv.getValue()->getNBytes()); } if(errCode != COUCHSTORE_SUCCESS) { ++st.numGetFailure; } couchstore_free_docinfo(docInfo); closeDatabaseHandle(db); rv.setStatus(couchErr2EngineErr(errCode)); cb.callback(rv); } void CouchKVStore::getMulti(uint16_t vb, vb_bgfetch_queue_t &itms) { Db *db = NULL; GetValue returnVal; std::string dbFile; int numItems = itms.size(); couchstore_error_t errCode; if (!(getDbFile(vb, dbFile))) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: cannot locate database file for data fetch, " "vBucketId = %d file = %s numDocs = %d\n", vb, dbFile.c_str(), numItems); st.numGetFailure += numItems; // populate error return value for each requested item vb_bgfetch_queue_t::iterator itr = itms.begin(); for (; itr != itms.end(); itr++) { std::list<VBucketBGFetchItem *> &fetches = (*itr).second; std::list<VBucketBGFetchItem *>::iterator fitr = fetches.begin(); for (; fitr != fetches.end(); fitr++) { (*fitr)->value.setStatus(ENGINE_NOT_MY_VBUCKET); } } return; } errCode = openDB(vb, dbFileRev(dbFile), &db, 0); if (errCode != COUCHSTORE_SUCCESS) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to open database for data fetch, " "vBucketId = %d file = %s numDocs = %d error = %s\n", vb, dbFile.c_str(), numItems, couchstore_strerror(errCode)); st.numGetFailure += numItems; vb_bgfetch_queue_t::iterator itr = itms.begin(); for (; itr != itms.end(); itr++) { std::list<VBucketBGFetchItem *> &fetches = (*itr).second; std::list<VBucketBGFetchItem *>::iterator fitr = fetches.begin(); for (; fitr != fetches.end(); fitr++) { (*fitr)->value.setStatus(ENGINE_NOT_MY_VBUCKET); } } return; } std::vector<uint64_t> seqIds; VBucketBGFetchItem *item2fetch; vb_bgfetch_queue_t::iterator itr = itms.begin(); for (; itr != itms.end(); itr++) { item2fetch = (*itr).second.front(); seqIds.push_back(item2fetch->value.getId()); } GetMultiCbCtx ctx = {*this, vb, itms}; errCode = couchstore_docinfos_by_sequence(db, &seqIds[0], seqIds.size(), 0, getMultiCbC, &ctx); if (errCode != COUCHSTORE_SUCCESS) { st.numGetFailure += numItems; for (itr = itms.begin(); itr != itms.end(); itr++) { std::list<VBucketBGFetchItem *> &fetches = (*itr).second; std::list<VBucketBGFetchItem *>::iterator fitr = fetches.begin(); for (; fitr != fetches.end(); fitr++) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to read database by " "sequence id = %lld, vBucketId = %d " "key = %s file = %s error = %s\n", (*fitr)->value.getId(), vb, (*fitr)->key.c_str(), dbFile.c_str(), couchstore_strerror(errCode)); (*fitr)->value.setStatus(couchErr2EngineErr(errCode)); } } } closeDatabaseHandle(db); } void CouchKVStore::del(const Item &itm, uint64_t, Callback<int> &cb) { assert(!isReadOnly()); assert(intransaction); std::string dbFile; if (getDbFile(itm.getVBucketId(), dbFile)) { CouchRequestCallback requestcb; requestcb.delCb = &cb; // each req will be de-allocated after commit CouchRequest *req = new CouchRequest(itm, dbFileRev(dbFile), requestcb, true); queueItem(req); } else { ++st.numDelFailure; getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to delete data, cannot locate " "database file %s\n", dbFile.c_str()); int value = DOC_NOT_FOUND; cb.callback(value); } } bool CouchKVStore::delVBucket(uint16_t vbucket) { assert(!isReadOnly()); assert(mc); RememberingCallback<bool> cb; mc->delVBucket(vbucket, cb); cb.waitForValue(); cachedVBStates.erase(vbucket); updateDbFileMap(vbucket, 1, false); return cb.val; } vbucket_map_t CouchKVStore::listPersistedVbuckets() { std::vector<std::string> files; if (dbFileMap.empty()) { // warmup, first discover db files from local directory discoverDbFiles(dbname, files); populateFileNameMap(files); } if (!cachedVBStates.empty()) { cachedVBStates.clear(); } Db *db = NULL; couchstore_error_t errorCode; std::map<uint16_t, int>::iterator itr = dbFileMap.begin(); for (; itr != dbFileMap.end(); itr++) { errorCode = openDB(itr->first, itr->second, &db, 0); if (errorCode != COUCHSTORE_SUCCESS) { std::stringstream rev, vbid; rev << itr->second; vbid << itr->first; std::string fileName = dbname + "/" + vbid.str() + ".couch." + rev.str(); getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to open database file, name=%s error=%s\n", fileName.c_str(), couchstore_strerror(errorCode)); remVBucketFromDbFileMap(itr->first); } else { vbucket_state vb_state; uint16_t vbID = itr->first; /* read state of VBucket from db file */ readVBState(db, vbID, vb_state); /* insert populated state to the array to return to the caller */ cachedVBStates[vbID] = vb_state; /* update stat */ ++st.numLoadedVb; closeDatabaseHandle(db); } db = NULL; } return cachedVBStates; } void CouchKVStore::getPersistedStats(std::map<std::string, std::string> &stats) { char *buffer = NULL; std::string fname = dbname + "/stats.json"; std::ifstream session_stats; session_stats.exceptions (session_stats.failbit | session_stats.badbit); try { session_stats.open(fname.c_str(), ios::binary); session_stats.seekg (0, ios::end); int flen = session_stats.tellg(); session_stats.seekg (0, ios::beg); buffer = new char[flen]; session_stats.read(buffer, flen); cJSON *json_obj = cJSON_Parse(buffer); if (!json_obj) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to parse the session stats json doc!!!\n"); delete[] buffer; return; } int json_arr_size = cJSON_GetArraySize(json_obj); for (int i = 0; i < json_arr_size; ++i) { cJSON *obj = cJSON_GetArrayItem(json_obj, i); if (obj) { stats[obj->string] = obj->valuestring; } } cJSON_Delete(json_obj); session_stats.close(); } catch (const std::ifstream::failure& e) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to load the engine session stats " " due to IO exception \"%s\"", e.what()); } delete[] buffer; } bool CouchKVStore::snapshotVBuckets(const vbucket_map_t &m) { assert(!isReadOnly()); vbucket_map_t::const_reverse_iterator iter; bool success = true; for (iter = m.rbegin(); iter != m.rend(); ++iter) { uint16_t vbucketId = iter->first; vbucket_state vbstate = iter->second; vbucket_map_t::iterator it = cachedVBStates.find(vbucketId); bool state_changed = true; if (it != cachedVBStates.end()) { if (it->second.state == vbstate.state && it->second.checkpointId == vbstate.checkpointId) { continue; // no changes } else { if (it->second.state == vbstate.state) { state_changed = false; } it->second.state = vbstate.state; it->second.checkpointId = vbstate.checkpointId; // Note that the max deleted seq number is maintained within CouchKVStore vbstate.maxDeletedSeqno = it->second.maxDeletedSeqno; } } else { cachedVBStates[vbucketId] = vbstate; } success = setVBucketState(vbucketId, vbstate, state_changed, false); if (!success) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to set new state, %s, for vbucket %d\n", VBucket::toString(vbstate.state), vbucketId); break; } } return success; } bool CouchKVStore::snapshotStats(const std::map<std::string, std::string> &stats) { assert(!isReadOnly()); size_t count = 0; size_t size = stats.size(); std::stringstream stats_buf; stats_buf << "{"; std::map<std::string, std::string>::const_iterator it = stats.begin(); for (; it != stats.end(); ++it) { stats_buf << "\"" << it->first << "\": \"" << it->second << "\""; ++count; if (count < size) { stats_buf << ", "; } } stats_buf << "}"; // TODO: This stats json should be written into the master database. However, // we don't support the write synchronization between CouchKVStore in C++ and // compaction manager in the erlang side for the master database yet. At this time, // we simply log the engine stats into a separate json file. As part of futhre work, // we need to get rid of the tight coupling between those two components. bool rv = true; std::string next_fname = dbname + "/stats.json.new"; std::ofstream new_stats; new_stats.exceptions (new_stats.failbit | new_stats.badbit); try { new_stats.open(next_fname.c_str()); new_stats << stats_buf.str().c_str() << std::endl; new_stats.flush(); new_stats.close(); } catch (const std::ofstream::failure& e) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to log the engine stats due to IO exception " "\"%s\"", e.what()); rv = false; } if (rv) { std::string old_fname = dbname + "/stats.json.old"; std::string stats_fname = dbname + "/stats.json"; if (access(old_fname.c_str(), F_OK) == 0 && remove(old_fname.c_str()) != 0) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "FATAL: Failed to remove '%s': %s", old_fname.c_str(), strerror(errno)); remove(next_fname.c_str()); rv = false; } else if (access(stats_fname.c_str(), F_OK) == 0 && rename(stats_fname.c_str(), old_fname.c_str()) != 0) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to rename '%s' to '%s': %s", stats_fname.c_str(), old_fname.c_str(), strerror(errno)); remove(next_fname.c_str()); rv = false; } else if (rename(next_fname.c_str(), stats_fname.c_str()) != 0) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to rename '%s' to '%s': %s", next_fname.c_str(), stats_fname.c_str(), strerror(errno)); remove(next_fname.c_str()); rv = false; } } return rv; } bool CouchKVStore::setVBucketState(uint16_t vbucketId, vbucket_state vbstate, bool stateChanged, bool newfile) { Db *db = NULL; couchstore_error_t errorCode; uint16_t fileRev, newFileRev; std::stringstream id; std::string dbFileName; std::map<uint16_t, int>::iterator mapItr; int rev; id << vbucketId; dbFileName = dbname + "/" + id.str() + ".couch"; if (newfile) { fileRev = 1; // create a db file with rev = 1 } else { mapItr = dbFileMap.find(vbucketId); if (mapItr == dbFileMap.end()) { rev = checkNewRevNum(dbFileName, true); if (rev == 0) { fileRev = 1; newfile = true; } else { fileRev = rev; } } else { fileRev = mapItr->second; } } bool retry = true; while (retry) { retry = false; errorCode = openDB(vbucketId, fileRev, &db, (uint64_t)COUCHSTORE_OPEN_FLAG_CREATE, &newFileRev); if (errorCode != COUCHSTORE_SUCCESS) { std::stringstream filename; filename << dbname << "/" << vbucketId << ".couch." << fileRev; ++st.numVbSetFailure; getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to open database, name=%s error=%s\n", filename.str().c_str(), couchstore_strerror(errorCode)); return false; } fileRev = newFileRev; errorCode = saveVBState(db, vbstate); if (errorCode != COUCHSTORE_SUCCESS) { ++st.numVbSetFailure; getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to save local doc, name=%s error=%s\n", dbFileName.c_str(), couchstore_strerror(errorCode)); closeDatabaseHandle(db); return false; } errorCode = couchstore_commit(db); if (errorCode != COUCHSTORE_SUCCESS) { ++st.numVbSetFailure; getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: commit failed, vbid=%u rev=%u error=%s", vbucketId, fileRev, couchstore_strerror(errorCode)); closeDatabaseHandle(db); return false; } else { uint64_t newHeaderPos = couchstore_get_header_position(db); RememberingCallback<uint16_t> lcb; mc->notify_update(vbucketId, fileRev, newHeaderPos, stateChanged, vbstate.state, vbstate.checkpointId, lcb); if (lcb.val != PROTOCOL_BINARY_RESPONSE_SUCCESS) { if (lcb.val == PROTOCOL_BINARY_RESPONSE_ETMPFAIL) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Retry notify CouchDB of update, " "vbid=%u rev=%u\n", vbucketId, fileRev); retry = true; } else { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to notify CouchDB of update, " "vbid=%u rev=%u error=0x%x\n", vbucketId, fileRev, lcb.val); abort(); } } } closeDatabaseHandle(db); } return true; } void CouchKVStore::dump(shared_ptr<Callback<GetValue> > cb) { shared_ptr<RememberingCallback<bool> > wait(new RememberingCallback<bool>()); shared_ptr<LoadCallback> callback(new LoadCallback(cb, wait)); loadDB(callback, false, NULL, COUCHSTORE_NO_DELETES); } void CouchKVStore::dump(uint16_t vb, shared_ptr<Callback<GetValue> > cb) { shared_ptr<RememberingCallback<bool> > wait(new RememberingCallback<bool>()); shared_ptr<LoadCallback> callback(new LoadCallback(cb, wait)); std::vector<uint16_t> vbids; vbids.push_back(vb); loadDB(callback, false, &vbids); } void CouchKVStore::dumpKeys(const std::vector<uint16_t> &vbids, shared_ptr<Callback<GetValue> > cb) { shared_ptr<RememberingCallback<bool> > wait(new RememberingCallback<bool>()); shared_ptr<LoadCallback> callback(new LoadCallback(cb, wait)); (void)vbids; loadDB(callback, true, NULL, COUCHSTORE_NO_DELETES); } void CouchKVStore::dumpDeleted(uint16_t vb, shared_ptr<Callback<GetValue> > cb) { shared_ptr<RememberingCallback<bool> > wait(new RememberingCallback<bool>()); shared_ptr<LoadCallback> callback(new LoadCallback(cb, wait)); std::vector<uint16_t> vbids; vbids.push_back(vb); loadDB(callback, true, &vbids, COUCHSTORE_DELETES_ONLY); } StorageProperties CouchKVStore::getStorageProperties() { size_t concurrency(10); StorageProperties rv(concurrency, concurrency - 1, 1, true, true, true, true); return rv; } bool CouchKVStore::commit(void) { assert(!isReadOnly()); // TODO get rid of bogus intransaction business assert(intransaction); intransaction = commit2couchstore() ? false : true; return !intransaction; } void CouchKVStore::addStats(const std::string &prefix, ADD_STAT add_stat, const void *c) { const char *prefix_str = prefix.c_str(); /* stats for both read-only and read-write threads */ addStat(prefix_str, "backend_type", "couchstore", add_stat, c); addStat(prefix_str, "open", st.numOpen, add_stat, c); addStat(prefix_str, "close", st.numClose, add_stat, c); addStat(prefix_str, "readTime", st.readTimeHisto, add_stat, c); addStat(prefix_str, "readSize", st.readSizeHisto, add_stat, c); addStat(prefix_str, "numLoadedVb", st.numLoadedVb, add_stat, c); // failure stats addStat(prefix_str, "failure_open", st.numOpenFailure, add_stat, c); addStat(prefix_str, "failure_get", st.numGetFailure, add_stat, c); // stats for read-write thread only if( prefix.compare("rw") == 0 ) { addStat(prefix_str, "delete", st.delTimeHisto, add_stat, c); addStat(prefix_str, "failure_set", st.numSetFailure, add_stat, c); addStat(prefix_str, "failure_del", st.numDelFailure, add_stat, c); addStat(prefix_str, "failure_vbset", st.numVbSetFailure, add_stat, c); addStat(prefix_str, "writeTime", st.writeTimeHisto, add_stat, c); addStat(prefix_str, "writeSize", st.writeSizeHisto, add_stat, c); addStat(prefix_str, "lastCommDocs", st.docsCommitted, add_stat, c); } } template <typename T> void CouchKVStore::addStat(const std::string &prefix, const char *stat, T &val, ADD_STAT add_stat, const void *c) { std::stringstream fullstat; fullstat << prefix << ":" << stat; add_casted_stat(fullstat.str().c_str(), val, add_stat, c); } void CouchKVStore::optimizeWrites(std::vector<queued_item> &items) { assert(!isReadOnly()); if (items.empty()) { return; } CompareQueuedItemsByVBAndKey cq; std::sort(items.begin(), items.end(), cq); } void CouchKVStore::loadDB(shared_ptr<LoadCallback> cb, bool keysOnly, std::vector<uint16_t> *vbids, couchstore_docinfos_options options) { std::vector<std::string> files = std::vector<std::string>(); std::map<uint16_t, int> &filemap = dbFileMap; std::map<uint16_t, int> vbmap; std::vector< std::pair<uint16_t, int> > vbuckets; std::vector< std::pair<uint16_t, int> > replicaVbuckets; bool loadingData = !vbids && !keysOnly; if (dbFileMap.empty()) { // warmup, first discover db files from local directory discoverDbFiles(dbname, files); populateFileNameMap(files); } if (vbids) { // get entries for given vbucket(s) from dbFileMap std::string dirname = dbname; getFileNameMap(vbids, dirname, vbmap); filemap = vbmap; } // order vbuckets data loading by using vbucket states if (loadingData && cachedVBStates.empty()) { listPersistedVbuckets(); } std::map<uint16_t, int>::iterator fitr = filemap.begin(); for (; fitr != filemap.end(); fitr++) { if (loadingData) { vbucket_map_t::const_iterator vsit = cachedVBStates.find(fitr->first); if (vsit != cachedVBStates.end()) { vbucket_state vbs = vsit->second; // ignore loading dead vbuckets during warmup if (vbs.state == vbucket_state_active) { vbuckets.push_back(make_pair(fitr->first, fitr->second)); } else if (vbs.state == vbucket_state_replica) { replicaVbuckets.push_back(make_pair(fitr->first, fitr->second)); } } } else { vbuckets.push_back(make_pair(fitr->first, fitr->second)); } } if (loadingData) { std::vector< std::pair<uint16_t, int> >::iterator it = replicaVbuckets.begin(); for (; it != replicaVbuckets.end(); it++) { vbuckets.push_back(*it); } } Db *db = NULL; couchstore_error_t errorCode; int keyNum = 0; std::vector< std::pair<uint16_t, int> >::iterator itr = vbuckets.begin(); for (; itr != vbuckets.end(); itr++, keyNum++) { errorCode = openDB(itr->first, itr->second, &db, 0); if (errorCode != COUCHSTORE_SUCCESS) { std::stringstream rev, vbid; rev << itr->second; vbid << itr->first; std::string dbName = dbname + "/" + vbid.str() + ".couch." + rev.str(); getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to open database, name=%s error=%s", dbName.c_str(), couchstore_strerror(errorCode)); remVBucketFromDbFileMap(itr->first); } else { LoadResponseCtx ctx; ctx.vbucketId = itr->first; ctx.keysonly = keysOnly; ctx.callback = cb; ctx.engine = &engine; errorCode = couchstore_changes_since(db, 0, options, recordDbDumpC, static_cast<void *>(&ctx)); if (errorCode != COUCHSTORE_SUCCESS) { if (errorCode == COUCHSTORE_ERROR_CANCEL) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Canceling loading database, warmup has completed\n"); closeDatabaseHandle(db); break; } else { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: couchstore_changes_since failed, error=%s\n", couchstore_strerror(errorCode)); remVBucketFromDbFileMap(itr->first); } } closeDatabaseHandle(db); } db = NULL; } bool success = true; cb->complete->callback(success); } void CouchKVStore::open() { // TODO intransaction, is it needed? intransaction = false; if (!isReadOnly()) { delete mc; mc = new MemcachedEngine(&engine, configuration); } struct stat dbstat; bool havedir = false; if (stat(dbname.c_str(), &dbstat) == 0 && (dbstat.st_mode & S_IFDIR) == S_IFDIR) { havedir = true; } if (!havedir) { if (mkdir(dbname.c_str(), S_IRWXU) == -1) { std::stringstream ss; ss << "Warning: Failed to create data directory [" << dbname << "]: " << strerror(errno); throw std::runtime_error(ss.str()); } } } void CouchKVStore::close() { intransaction = false; if (!isReadOnly()) { delete mc; } mc = NULL; } bool CouchKVStore::getDbFile(uint16_t vbucketId, std::string &dbFileName) { std::stringstream fileName; fileName << dbname << "/" << vbucketId << ".couch"; std::map<uint16_t, int>::iterator itr; itr = dbFileMap.find(vbucketId); if (itr == dbFileMap.end()) { dbFileName = fileName.str(); int rev = checkNewRevNum(dbFileName, true); if (rev > 0) { updateDbFileMap(vbucketId, rev, true); fileName << "." << rev; } else { return false; } } else { fileName << "." << itr->second; } dbFileName = fileName.str(); return true; } int CouchKVStore::checkNewRevNum(std::string &dbFileName, bool newFile) { using namespace CouchKVStoreDirectoryUtilities; int newrev = 0; std::string revnum, nameKey; size_t secondDot; if (!newFile) { // extract out the file revision number first secondDot = dbFileName.rfind("."); nameKey = dbFileName.substr(0, secondDot); } else { nameKey = dbFileName; } nameKey.append("."); const std::vector<std::string> files = findFilesWithPrefix(nameKey); std::vector<std::string>::const_iterator itor; // found file(s) whoes name has the same key name pair with different // revision number for (itor = files.begin(); itor != files.end(); ++itor) { const std::string &filename = *itor; if (endWithCompact(filename)) { continue; } secondDot = filename.rfind("."); revnum = filename.substr(secondDot + 1); if (newrev < atoi(revnum.c_str())) { newrev = atoi(revnum.c_str()); dbFileName = filename; } } return newrev; } void CouchKVStore::updateDbFileMap(uint16_t vbucketId, int newFileRev, bool insertImmediately) { if (insertImmediately) { dbFileMap.insert(std::pair<uint16_t, int>(vbucketId, newFileRev)); return; } std::map<uint16_t, int>::iterator itr; itr = dbFileMap.find(vbucketId); if (itr != dbFileMap.end()) { itr->second = newFileRev; } else { dbFileMap.insert(std::pair<uint16_t, int>(vbucketId, newFileRev)); } } static std::string getDBFileName(const std::string &dbname, uint16_t vbid) { std::stringstream ss; ss << dbname << "/" << vbid << ".couch"; return ss.str(); } static std::string getDBFileName(const std::string &dbname, uint16_t vbid, uint16_t rev) { std::stringstream ss; ss << dbname << "/" << vbid << ".couch." << rev; return ss.str(); } couchstore_error_t CouchKVStore::openDB(uint16_t vbucketId, uint16_t fileRev, Db **db, uint64_t options, uint16_t *newFileRev) { couchstore_error_t errorCode; std::string dbFileName = getDBFileName(dbname, vbucketId, fileRev); int newRevNum = fileRev; // first try to open database without options, we don't want to create // a duplicate db that has the same name with different revision number if ((errorCode = couchstore_open_db(dbFileName.c_str(), 0, db))) { if ((newRevNum = checkNewRevNum(dbFileName))) { errorCode = couchstore_open_db(dbFileName.c_str(), 0, db); if (errorCode == COUCHSTORE_SUCCESS) { updateDbFileMap(vbucketId, newRevNum); } } else { if (options) { newRevNum = fileRev; errorCode = couchstore_open_db(dbFileName.c_str(), options, db); if (errorCode == COUCHSTORE_SUCCESS) { updateDbFileMap(vbucketId, newRevNum, true); } } } } if (newFileRev != NULL) { *newFileRev = newRevNum; } if (errorCode) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "open_db() failed, name=%s error=%d\n", dbFileName.c_str(), errorCode); } /* update command statistics */ st.numOpen++; if (errorCode) { st.numOpenFailure++; } return errorCode; } void CouchKVStore::getFileNameMap(std::vector<uint16_t> *vbids, std::string &dirname, std::map<uint16_t, int> &filemap) { std::vector<uint16_t>::iterator vbidItr; std::map<uint16_t, int>::iterator dbFileItr; for (vbidItr = vbids->begin(); vbidItr != vbids->end(); vbidItr++) { std::string dbFileName = getDBFileName(dirname, *vbidItr); dbFileItr = dbFileMap.find(*vbidItr); if (dbFileItr == dbFileMap.end()) { int rev = checkNewRevNum(dbFileName, true); if (rev > 0) { filemap.insert(std::pair<uint16_t, int>(*vbidItr, rev)); } else { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: database file does not exist, %s\n", dbFileName.c_str()); } } else { filemap.insert(std::pair<uint16_t, int>(dbFileItr->first, dbFileItr->second)); } } } void CouchKVStore::populateFileNameMap(std::vector<std::string> &filenames) { std::vector<std::string>::iterator fileItr; for (fileItr = filenames.begin(); fileItr != filenames.end(); fileItr++) { const std::string &filename = *fileItr; size_t secondDot = filename.rfind("."); std::string nameKey = filename.substr(0, secondDot); size_t firstDot = nameKey.rfind("."); size_t firstSlash = nameKey.rfind("/"); std::string revNumStr = filename.substr(secondDot + 1); int revNum = atoi(revNumStr.c_str()); std::string vbIdStr = nameKey.substr(firstSlash + 1, (firstDot - firstSlash) - 1); if (allDigit(vbIdStr)) { int vbId = atoi(vbIdStr.c_str()); std::map<uint16_t, int>::iterator mapItr = dbFileMap.find(vbId); if (mapItr == dbFileMap.end()) { dbFileMap.insert(std::pair<uint16_t, int>(vbId, revNum)); } else { // duplicate key if (mapItr->second < revNum) { mapItr->second = revNum; } } } else { // skip non-vbucket database file, master.couch etc getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Non-vbucket database file, %s, skip adding " "to CouchKVStore dbFileMap\n", filename.c_str()); } } } couchstore_error_t CouchKVStore::fetchDoc(Db *db, DocInfo *docinfo, GetValue &docValue, uint16_t vbId, bool metaOnly) { assert(docinfo && db); uint32_t itemFlags; void *valuePtr = NULL; size_t valuelen = 0; uint64_t cas; time_t exptime; sized_buf metadata; Item *it; Doc *doc = NULL; couchstore_error_t errCode = COUCHSTORE_SUCCESS; metadata = docinfo->rev_meta; assert(metadata.size == 16); memcpy(&cas, (metadata.buf), 8); cas = ntohll(cas); memcpy(&exptime, (metadata.buf) + 8, 4); exptime = ntohl(exptime); memcpy(&itemFlags, (metadata.buf) + 12, 4); itemFlags = ntohl(itemFlags); if (metaOnly) { // we should allow a metadata disk fetch for deleted items only assert(docinfo->deleted); it = new Item(docinfo->id.buf, (size_t)docinfo->id.size, docinfo->size, itemFlags, (time_t)exptime, cas); it->setSeqno(docinfo->rev_seq); docValue = GetValue(it); // update ep-engine IO stats ++epStats.io_num_read; epStats.io_read_bytes += docinfo->id.size; } else { errCode = couchstore_open_doc_with_docinfo(db, docinfo, &doc, 0); if (errCode == COUCHSTORE_SUCCESS) { if (docinfo->deleted) { // cannot read a doc that is marked deleted, just return // document not found error code errCode = COUCHSTORE_ERROR_DOC_NOT_FOUND; } else { assert(doc && (doc->id.size <= UINT16_MAX)); valuelen = doc->data.size; valuePtr = doc->data.buf; it = new Item(docinfo->id.buf, (size_t)docinfo->id.size, itemFlags, (time_t)exptime, valuePtr, valuelen, cas, -1, vbId); docValue = GetValue(it); couchstore_free_document(doc); // update ep-engine IO stats ++epStats.io_num_read; epStats.io_read_bytes += docinfo->id.size + valuelen; } } } return errCode; } int CouchKVStore::recordDbDump(Db *db, DocInfo *docinfo, void *ctx) { Item *it = NULL; Doc *doc = NULL; LoadResponseCtx *loadCtx = (LoadResponseCtx *)ctx; shared_ptr<LoadCallback> callback = loadCtx->callback; EventuallyPersistentEngine *engine= loadCtx->engine; bool warmup = engine->stillWarmingUp(); // TODO enable below when couchstore is ready // bool compressed = (docinfo->content_meta & 0x80); // uint8_t metaflags = (docinfo->content_meta & ~0x80); void *valuePtr; size_t valuelen; sized_buf metadata = docinfo->rev_meta; uint32_t itemflags; uint16_t vbucketId = loadCtx->vbucketId; sized_buf key = docinfo->id; uint64_t cas; uint32_t exptime; assert(key.size <= UINT16_MAX); assert(metadata.size == 16); memcpy(&cas, metadata.buf, 8); memcpy(&exptime, (metadata.buf) + 8, 4); memcpy(&itemflags, (metadata.buf) + 12, 4); itemflags = ntohl(itemflags); exptime = ntohl(exptime); cas = ntohll(cas); valuePtr = NULL; valuelen = 0; if (!loadCtx->keysonly && !docinfo->deleted) { couchstore_error_t errCode ; errCode = couchstore_open_doc_with_docinfo(db, docinfo, &doc, 0); if (errCode == COUCHSTORE_SUCCESS) { if (doc->data.size) { valuelen = doc->data.size; valuePtr = doc->data.buf; } } else { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to retrieve key value from database " "database, vBucket=%d key=%s error=%s\n", vbucketId, key.buf, couchstore_strerror(errCode)); return 0; } } it = new Item((void *)key.buf, key.size, itemflags, (time_t)exptime, valuePtr, valuelen, cas, docinfo->db_seq, // return seq number being persisted on disk vbucketId, docinfo->rev_seq); GetValue rv(it, ENGINE_SUCCESS, -1, loadCtx->keysonly); callback->cb->callback(rv); couchstore_free_document(doc); int returnCode = COUCHSTORE_SUCCESS; if (warmup) { if (!engine->stillWarmingUp()) { // warmup has completed, return COUCHSTORE_ERROR_CANCEL to // cancel remaining data dumps from couchstore getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Engine warmup is complete, request to stop " "loading remaining database\n"); returnCode = COUCHSTORE_ERROR_CANCEL; } } return returnCode; } bool CouchKVStore::commit2couchstore(void) { Doc **docs; DocInfo **docinfos; uint16_t vbucket2flush, vbucketId; int reqIndex, flushStartIndex, numDocs2save; couchstore_error_t errCode; bool success = true; std::string dbName; CouchRequest *req = NULL; CouchRequest **committedReqs; if (pendingCommitCnt == 0) { return success; } committedReqs = new CouchRequest *[pendingCommitCnt]; docs = new Doc *[pendingCommitCnt]; docinfos = new DocInfo *[pendingCommitCnt]; if ((req = pendingReqsQ.front()) == NULL) { abort(); } vbucket2flush = req->getVBucketId(); for (reqIndex = 0, flushStartIndex = 0, numDocs2save = 0; pendingCommitCnt > 0; reqIndex++, numDocs2save++, pendingCommitCnt--) { if ((req = pendingReqsQ.front()) == NULL) { abort(); } committedReqs[reqIndex] = req; docs[reqIndex] = req->getDbDoc(); docinfos[reqIndex] = req->getDbDocInfo(); vbucketId = req->getVBucketId(); pendingReqsQ.pop_front(); if (vbucketId != vbucket2flush) { errCode = saveDocs(vbucket2flush, committedReqs[flushStartIndex]->getRevNum(), &docs[flushStartIndex], &docinfos[flushStartIndex], numDocs2save); if (errCode) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: commit failed, cannot save CouchDB " "docs for vbucket = %d rev = %d error = %d\n", vbucket2flush, committedReqs[flushStartIndex]->getRevNum(), (int)errCode); ++epStats.commitFailed; } commitCallback(&committedReqs[flushStartIndex], numDocs2save, errCode); numDocs2save = 0; flushStartIndex = reqIndex; vbucket2flush = vbucketId; } } if (reqIndex - flushStartIndex) { // flush the rest errCode = saveDocs(vbucket2flush, committedReqs[flushStartIndex]->getRevNum(), &docs[flushStartIndex], &docinfos[flushStartIndex], numDocs2save); if (errCode) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: commit failed, cannot save CouchDB docs " "for vbucket = %d rev = %d error = %d\n", vbucket2flush, committedReqs[flushStartIndex]->getRevNum(), (int)errCode); ++epStats.commitFailed; } commitCallback(&committedReqs[flushStartIndex], numDocs2save, errCode); } while (reqIndex--) { delete committedReqs[reqIndex]; } delete [] committedReqs; delete [] docs; delete [] docinfos; return success; } couchstore_error_t CouchKVStore::saveDocs(uint16_t vbid, int rev, Doc **docs, DocInfo **docinfos, int docCount) { couchstore_error_t errCode; int fileRev; uint16_t newFileRev; Db *db = NULL; bool retry_save_docs; fileRev = rev; assert(fileRev); do { retry_save_docs = false; errCode = openDB(vbid, fileRev, &db, (uint64_t)COUCHSTORE_OPEN_FLAG_CREATE, &newFileRev); if (errCode != COUCHSTORE_SUCCESS) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to open database, vbucketId = %d " "fileRev = %d error = %d\n", vbid, fileRev, errCode); return errCode; } else { uint32_t max = computeMaxDeletedSeqNum(docinfos, docCount); // update max_deleted_seq in the local doc (vbstate) // before save docs for the given vBucket if (max > 0) { vbucket_map_t::iterator it = cachedVBStates.find(vbid); if (it != cachedVBStates.end() && it->second.maxDeletedSeqno < max) { it->second.maxDeletedSeqno = max; errCode = saveVBState(db, it->second); if (errCode != COUCHSTORE_SUCCESS) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to save local doc for, " "vBucket = %d error = %s\n", vbid, couchstore_strerror(errCode)); closeDatabaseHandle(db); return errCode; } } } errCode = couchstore_save_documents(db, docs, docinfos, docCount, 0 /* no options */); if (errCode != COUCHSTORE_SUCCESS) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Failed to save docs to database, error = %s\n", couchstore_strerror(errCode)); closeDatabaseHandle(db); return errCode; } errCode = couchstore_commit(db); if (errCode) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Commit failed: %s", couchstore_strerror(errCode)); closeDatabaseHandle(db); return errCode; } RememberingCallback<uint16_t> cb; uint64_t newHeaderPos = couchstore_get_header_position(db); mc->notify_headerpos_update(vbid, newFileRev, newHeaderPos, cb); if (cb.val != PROTOCOL_BINARY_RESPONSE_SUCCESS) { if (cb.val == PROTOCOL_BINARY_RESPONSE_ETMPFAIL) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Retry notify CouchDB of update, vbucket=%d rev=%d\n", vbid, newFileRev); fileRev = newFileRev; retry_save_docs = true; } else { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to notify CouchDB of " "update for vbucket=%d, error=0x%x\n", vbid, cb.val); abort(); } } closeDatabaseHandle(db); } } while (retry_save_docs); /* update stat */ if(errCode == COUCHSTORE_SUCCESS) { st.docsCommitted = docCount; } return errCode; } void CouchKVStore::queueItem(CouchRequest *req) { pendingReqsQ.push_back(req); pendingCommitCnt++; } void CouchKVStore::remVBucketFromDbFileMap(uint16_t vbucketId) { std::map<uint16_t, int>::iterator itr; itr = dbFileMap.find(vbucketId); if (itr != dbFileMap.end()) { dbFileMap.erase(itr); } } void CouchKVStore::commitCallback(CouchRequest **committedReqs, int numReqs, couchstore_error_t errCode) { for (int index = 0; index < numReqs; index++) { size_t dataSize = committedReqs[index]->getNBytes(); size_t keySize = committedReqs[index]->getKey().length(); /* update ep stats */ ++epStats.io_num_write; epStats.io_write_bytes += keySize + dataSize; if (committedReqs[index]->isDelete()) { int rv = getMutationStatus(errCode); if (errCode) { ++st.numDelFailure; } else { st.delTimeHisto.add(committedReqs[index]->getDelta() / 1000); } committedReqs[index]->getDelCallback()->callback(rv); } else { int rv = getMutationStatus(errCode); int64_t newItemId = committedReqs[index]->getDbDocInfo()->db_seq; if (errCode) { ++st.numSetFailure; newItemId = 0; } else { st.writeTimeHisto.add(committedReqs[index]->getDelta() / 1000); st.writeSizeHisto.add(dataSize + keySize); } mutation_result p(rv, newItemId); committedReqs[index]->getSetCallback()->callback(p); } } } void CouchKVStore::readVBState(Db *db, uint16_t vbId, vbucket_state &vbState) { sized_buf id; LocalDoc *ldoc = NULL; couchstore_error_t errCode; vbState.state = vbucket_state_dead; vbState.checkpointId = 0; vbState.maxDeletedSeqno = 0; id.buf = (char *)"_local/vbstate"; id.size = sizeof("_local/vbstate") - 1; errCode = couchstore_open_local_document(db, (void *)id.buf, id.size, &ldoc); if (errCode != COUCHSTORE_SUCCESS) { getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Warning: failed to retrieve stat info for vBucket=%d error=%d\n", vbId, (int)errCode); } else { const std::string statjson(ldoc->json.buf, ldoc->json.size); cJSON *jsonObj = cJSON_Parse(statjson.c_str()); const std::string state = getJSONObjString(cJSON_GetObjectItem(jsonObj, "state")); const std::string checkpoint_id = getJSONObjString(cJSON_GetObjectItem(jsonObj, "checkpoint_id")); const std::string max_deleted_seqno = getJSONObjString(cJSON_GetObjectItem(jsonObj, "max_deleted_seqno")); if (state.compare("") == 0 || checkpoint_id.compare("") == 0 || max_deleted_seqno.compare("") == 0) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: state JSON doc for vbucket %d is in the wrong format: %s\n", vbId, statjson.c_str()); } else { vbState.state = VBucket::fromString(state.c_str()); parseUint32(max_deleted_seqno.c_str(), &vbState.maxDeletedSeqno); parseUint64(checkpoint_id.c_str(), &vbState.checkpointId); } cJSON_Delete(jsonObj); couchstore_free_local_document(ldoc); } } couchstore_error_t CouchKVStore::saveVBState(Db *db, vbucket_state &vbState) { LocalDoc lDoc; std::stringstream jsonState; std::string state; jsonState << "{\"state\": \"" << VBucket::toString(vbState.state) << "\", \"checkpoint_id\": \"" << vbState.checkpointId << "\", \"max_deleted_seqno\": \"" << vbState.maxDeletedSeqno << "\"}"; lDoc.id.buf = (char *)"_local/vbstate"; lDoc.id.size = sizeof("_local/vbstate") - 1; state = jsonState.str(); lDoc.json.buf = (char *)state.c_str(); lDoc.json.size = state.size(); lDoc.deleted = 0; return couchstore_save_local_document(db, &lDoc); } int CouchKVStore::getMultiCb(Db *db, DocInfo *docinfo, void *ctx) { couchstore_error_t errCode; std::string keyStr(docinfo->id.buf, docinfo->id.size); assert(ctx); GetMultiCbCtx *cbCtx = static_cast<GetMultiCbCtx *>(ctx); CouchKVStoreStats &st = cbCtx->cks.getCKVStoreStat(); vb_bgfetch_queue_t::iterator qitr; qitr = cbCtx->fetches.find(docinfo->db_seq); assert(qitr != cbCtx->fetches.end()); std::list<VBucketBGFetchItem *> &fetches = (*qitr).second; GetValue returnVal; errCode = cbCtx->cks.fetchDoc(db, docinfo, returnVal, cbCtx->vbId, false); if (errCode != COUCHSTORE_SUCCESS) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to fetch data from database, " "vBucket=%d key=%s error=%s\n", cbCtx->vbId, keyStr.c_str(), couchstore_strerror(errCode)); st.numGetFailure++; } returnVal.setStatus(cbCtx->cks.couchErr2EngineErr(errCode)); std::list<VBucketBGFetchItem *>::iterator itr = fetches.begin(); for (; itr != fetches.end(); itr++) { // populate return value for remaining fetch items with the // same seqid (*itr)->value = returnVal; st.readTimeHisto.add((gethrtime() - (*itr)->initTime) / 1000); st.readSizeHisto.add(returnVal.getValue()->getKey().length() + returnVal.getValue()->getNBytes()); } return 0; } void CouchKVStore::closeDatabaseHandle(Db *db) { couchstore_error_t ret = couchstore_close_db(db); if (ret != COUCHSTORE_SUCCESS) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Failed to close database handle: %s", couchstore_strerror(ret)); } st.numClose++; } ENGINE_ERROR_CODE CouchKVStore::couchErr2EngineErr(couchstore_error_t errCode) { switch (errCode) { case COUCHSTORE_SUCCESS: return ENGINE_SUCCESS; case COUCHSTORE_ERROR_ALLOC_FAIL: return ENGINE_ENOMEM; case COUCHSTORE_ERROR_DOC_NOT_FOUND: return ENGINE_KEY_ENOENT; case COUCHSTORE_ERROR_NO_SUCH_FILE: return ENGINE_NOT_MY_VBUCKET; default: // same as the general error return code of // EvetuallyPersistentStore::getInternal return ENGINE_TMPFAIL; } } size_t CouchKVStore::warmup(MutationLog &lf, const std::map<uint16_t, vbucket_state> &vbmap, Callback<GetValue> &cb, Callback<size_t> &estimate) { assert(engine.getEpStore()->multiBGFetchEnabled()); MutationLogHarvester harvester(lf); std::map<uint16_t, vbucket_state>::const_iterator it; for (it = vbmap.begin(); it != vbmap.end(); ++it) { harvester.setVBucket(it->first); } hrtime_t start = gethrtime(); if (!harvester.load()) { return -1; } hrtime_t end = gethrtime(); size_t total = harvester.total(); estimate.callback(total); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Completed log read in %s with %ld entries\n", hrtime2text(end - start).c_str(), total); start = gethrtime(); WarmupCookie cookie(this, cb); harvester.apply(&cookie, &batchWarmupCallback); end = gethrtime(); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Populated log in %s with (l: %ld, s: %ld, e: %ld)", hrtime2text(end - start).c_str(), cookie.loaded, cookie.skipped, cookie.error); return cookie.loaded; } /* end of couch-kvstore.cc */ MB-5955 Update disk read timings iff the operation was successful Change-Id: Icb851dca3b62d239ec078e277f6f2bf2f644548d Reviewed-on: http://review.couchbase.org/18611 Reviewed-by: Liang Guo <863407acb9e207441ec9e80d0debd4fe4489aa9b@couchbase.com> Tested-by: Chiyoung Seo <8b279095f11c26cc21045fda5a3e51debb005aa9@gmail.com> /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include "config.h" #include <string.h> #include <cstdlib> #include <cctype> #include <algorithm> #include <stdio.h> #include <sys/types.h> #include <fcntl.h> #include <sys/stat.h> #include <iostream> #include <fstream> #include "couch-kvstore/couch-kvstore.hh" #include "couch-kvstore/dirutils.hh" #include "ep_engine.h" #include "tools/cJSON.h" #include "common.hh" #define STATWRITER_NAMESPACE couchstore_engine #include "statwriter.hh" #undef STATWRITER_NAMESPACE using namespace CouchKVStoreDirectoryUtilities; static const int MUTATION_FAILED = -1; static const int DOC_NOT_FOUND = 0; static const int MUTATION_SUCCESS = 1; extern "C" { static int recordDbDumpC(Db *db, DocInfo *docinfo, void *ctx) { return CouchKVStore::recordDbDump(db, docinfo, ctx); } } extern "C" { static int getMultiCbC(Db *db, DocInfo *docinfo, void *ctx) { return CouchKVStore::getMultiCb(db, docinfo, ctx); } } static bool isJSON(const value_t &value) { bool isJSON = false; const char *ptr = value->getData(); size_t len = value->length(); size_t ii = 0; while (ii < len && isspace(*ptr)) { ++ptr; ++ii; } if (ii < len && *ptr == '{') { // This may be JSON. Unfortunately we don't know if it's zero // terminated std::string data(value->getData(), value->length()); cJSON *json = cJSON_Parse(data.c_str()); if (json != 0) { isJSON = true; cJSON_Delete(json); } } return isJSON; } static const std::string getJSONObjString(const cJSON *i) { if (i == NULL) { return ""; } if (i->type != cJSON_String) { abort(); } return i->valuestring; } static bool endWithCompact(const std::string &filename) { size_t pos = filename.find(".compact"); if (pos == std::string::npos || (filename.size() - sizeof(".compact")) != pos) { return false; } return true; } static int dbFileRev(const std::string &dbname) { size_t secondDot = dbname.rfind("."); return atoi(dbname.substr(secondDot + 1).c_str()); } static void discoverDbFiles(const std::string &dir, std::vector<std::string> &v) { std::vector<std::string> files = findFilesContaining(dir, ".couch"); std::vector<std::string>::iterator ii; for (ii = files.begin(); ii != files.end(); ++ii) { if (!endWithCompact(*ii)) { v.push_back(*ii); } } } static uint32_t computeMaxDeletedSeqNum(DocInfo **docinfos, const int numdocs) { uint32_t max = 0; uint32_t seqNum; for (int idx = 0; idx < numdocs; idx++) { if (docinfos[idx]->deleted) { // check seq number only from a deleted file seqNum = (uint32_t)docinfos[idx]->rev_seq; max = std::max(seqNum, max); } } return max; } static int getMutationStatus(couchstore_error_t errCode) { switch (errCode) { case COUCHSTORE_SUCCESS: return MUTATION_SUCCESS; case COUCHSTORE_ERROR_DOC_NOT_FOUND: // this return causes ep engine to drop the failed flush // of an item since it does not know about the itme any longer return DOC_NOT_FOUND; default: // this return causes ep engine to keep requeuing the failed // flush of an item return MUTATION_FAILED; } } static bool allDigit(std::string &input) { size_t numchar = input.length(); for(size_t i = 0; i < numchar; ++i) { if (!isdigit(input[i])) { return false; } } return true; } struct WarmupCookie { WarmupCookie(KVStore *s, Callback<GetValue>&c) : store(s), cb(c), engine(s->getEngine()), loaded(0), skipped(0), error(0) { /* EMPTY */ } KVStore *store; Callback<GetValue> &cb; EventuallyPersistentEngine *engine; size_t loaded; size_t skipped; size_t error; }; static void batchWarmupCallback(uint16_t vbId, std::vector<std::pair<std::string, uint64_t> > &fetches, void *arg) { WarmupCookie *c = static_cast<WarmupCookie *>(arg); EventuallyPersistentEngine *engine = c->engine; if (engine->stillWarmingUp()) { vb_bgfetch_queue_t items2fetch; std::vector<std::pair<std::string, uint64_t> >::iterator itm = fetches.begin(); for(; itm != fetches.end(); itm++) { assert(items2fetch.find((*itm).second) == items2fetch.end()); items2fetch[(*itm).second].push_back( new VBucketBGFetchItem((*itm).first, (*itm).second, NULL)); } c->store->getMulti(vbId, items2fetch); vb_bgfetch_queue_t::iterator items = items2fetch.begin(); for (; items != items2fetch.end(); items++) { VBucketBGFetchItem * fetchedItem = (*items).second.back(); GetValue &val = fetchedItem->value; if (val.getStatus() == ENGINE_SUCCESS) { c->loaded++; c->cb.callback(val); } else { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: warmup failed to load data for " "vBucket = %d key = %s error = %X\n", vbId, fetchedItem->key.c_str(), val.getStatus()); c->error++; } delete fetchedItem; } } else { c->skipped++; } } struct GetMultiCbCtx { CouchKVStore &cks; uint16_t vbId; vb_bgfetch_queue_t &fetches; }; struct StatResponseCtx { public: StatResponseCtx(std::map<std::pair<uint16_t, uint16_t>, vbucket_state> &sm, uint16_t vb) : statMap(sm), vbId(vb) { /* EMPTY */ } std::map<std::pair<uint16_t, uint16_t>, vbucket_state> &statMap; uint16_t vbId; }; struct LoadResponseCtx { shared_ptr<LoadCallback> callback; uint16_t vbucketId; bool keysonly; EventuallyPersistentEngine *engine; }; CouchRequest::CouchRequest(const Item &it, int rev, CouchRequestCallback &cb, bool del) : value(it.getValue()), valuelen(it.getNBytes()), vbucketId(it.getVBucketId()), fileRevNum(rev), key(it.getKey()), deleteItem(del) { bool isjson = false; uint64_t cas = htonll(it.getCas()); uint32_t flags = htonl(it.getFlags()); uint32_t exptime = htonl(it.getExptime()); itemId = (it.getId() <= 0) ? 1 : 0; dbDoc.id.buf = const_cast<char *>(key.c_str()); dbDoc.id.size = it.getNKey(); if (valuelen) { isjson = isJSON(value); dbDoc.data.buf = const_cast<char *>(value->getData()); dbDoc.data.size = valuelen; } else { dbDoc.data.buf = NULL; dbDoc.data.size = 0; } memcpy(meta, &cas, 8); memcpy(meta + 8, &exptime, 4); memcpy(meta + 12, &flags, 4); dbDocInfo.rev_meta.buf = reinterpret_cast<char *>(meta); dbDocInfo.rev_meta.size = COUCHSTORE_METADATA_SIZE; dbDocInfo.rev_seq = it.getSeqno(); dbDocInfo.size = dbDoc.data.size; if (del) { dbDocInfo.deleted = 1; callback.delCb = cb.delCb; } else { dbDocInfo.deleted = 0; callback.setCb = cb.setCb; } dbDocInfo.id = dbDoc.id; dbDocInfo.content_meta = isjson ? COUCH_DOC_IS_JSON : COUCH_DOC_NON_JSON_MODE; start = gethrtime(); } CouchKVStore::CouchKVStore(EventuallyPersistentEngine &theEngine, bool read_only) : KVStore(read_only), engine(theEngine), epStats(theEngine.getEpStats()), configuration(theEngine.getConfiguration()), dbname(configuration.getDbname()), mc(NULL), pendingCommitCnt(0), intransaction(false) { open(); } CouchKVStore::CouchKVStore(const CouchKVStore &copyFrom) : KVStore(copyFrom), engine(copyFrom.engine), epStats(copyFrom.epStats), configuration(copyFrom.configuration), dbname(copyFrom.dbname), mc(NULL), pendingCommitCnt(0), intransaction(false) { open(); dbFileMap = copyFrom.dbFileMap; } void CouchKVStore::reset() { assert(!isReadOnly()); // TODO CouchKVStore::flush() when couchstore api ready RememberingCallback<bool> cb; mc->flush(cb); cb.waitForValue(); vbucket_map_t::iterator itor = cachedVBStates.begin(); for (; itor != cachedVBStates.end(); ++itor) { uint16_t vbucket = itor->first; itor->second.checkpointId = 0; itor->second.maxDeletedSeqno = 0; updateDbFileMap(vbucket, 1, true); } } void CouchKVStore::set(const Item &itm, Callback<mutation_result> &cb) { assert(!isReadOnly()); assert(intransaction); bool deleteItem = false; CouchRequestCallback requestcb; std::string dbFile; requestcb.setCb = &cb; if (!(getDbFile(itm.getVBucketId(), dbFile))) { ++st.numSetFailure; getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to set data, cannot locate database file %s\n", dbFile.c_str()); mutation_result p(MUTATION_FAILED, 0); cb.callback(p); return; } // each req will be de-allocated after commit CouchRequest *req = new CouchRequest(itm, dbFileRev(dbFile), requestcb, deleteItem); queueItem(req); } void CouchKVStore::get(const std::string &key, uint64_t, uint16_t vb, Callback<GetValue> &cb) { hrtime_t start = gethrtime(); Db *db = NULL; DocInfo *docInfo = NULL; std::string dbFile; GetValue rv; sized_buf id; if (!(getDbFile(vb, dbFile))) { ++st.numGetFailure; getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to retrieve data from vBucketId = %d " "[key=%s], cannot locate database file %s\n", vb, key.c_str(), dbFile.c_str()); rv.setStatus(ENGINE_NOT_MY_VBUCKET); cb.callback(rv); return; } couchstore_error_t errCode = openDB(vb, dbFileRev(dbFile), &db, 0, NULL); if (errCode != COUCHSTORE_SUCCESS) { ++st.numGetFailure; getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to open database, name=%s error=%s\n", dbFile.c_str(), couchstore_strerror(errCode)); rv.setStatus(couchErr2EngineErr(errCode)); cb.callback(rv); return; } RememberingCallback<GetValue> *rc = dynamic_cast<RememberingCallback<GetValue> *>(&cb); bool getMetaOnly = rc && rc->val.isPartial(); id.size = key.size(); id.buf = const_cast<char *>(key.c_str()); errCode = couchstore_docinfo_by_id(db, (uint8_t *)id.buf, id.size, &docInfo); if (errCode != COUCHSTORE_SUCCESS) { if (!getMetaOnly) { // log error only if this is non-xdcr case getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to retrieve doc info from " "database, name=%s key=%s error=%s\n", dbFile.c_str(), id.buf, couchstore_strerror(errCode)); } } else { errCode = fetchDoc(db, docInfo, rv, vb, getMetaOnly); if (errCode != COUCHSTORE_SUCCESS) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to retrieve key value from " "database, name=%s key=%s error=%s deleted=%s\n", dbFile.c_str(), id.buf, couchstore_strerror(errCode), docInfo->deleted ? "yes" : "no"); } // record stats st.readTimeHisto.add((gethrtime() - start) / 1000); if (errCode == COUCHSTORE_SUCCESS) { st.readSizeHisto.add(key.length() + rv.getValue()->getNBytes()); } } if(errCode != COUCHSTORE_SUCCESS) { ++st.numGetFailure; } couchstore_free_docinfo(docInfo); closeDatabaseHandle(db); rv.setStatus(couchErr2EngineErr(errCode)); cb.callback(rv); } void CouchKVStore::getMulti(uint16_t vb, vb_bgfetch_queue_t &itms) { Db *db = NULL; GetValue returnVal; std::string dbFile; int numItems = itms.size(); couchstore_error_t errCode; if (!(getDbFile(vb, dbFile))) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: cannot locate database file for data fetch, " "vBucketId = %d file = %s numDocs = %d\n", vb, dbFile.c_str(), numItems); st.numGetFailure += numItems; // populate error return value for each requested item vb_bgfetch_queue_t::iterator itr = itms.begin(); for (; itr != itms.end(); itr++) { std::list<VBucketBGFetchItem *> &fetches = (*itr).second; std::list<VBucketBGFetchItem *>::iterator fitr = fetches.begin(); for (; fitr != fetches.end(); fitr++) { (*fitr)->value.setStatus(ENGINE_NOT_MY_VBUCKET); } } return; } errCode = openDB(vb, dbFileRev(dbFile), &db, 0); if (errCode != COUCHSTORE_SUCCESS) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to open database for data fetch, " "vBucketId = %d file = %s numDocs = %d error = %s\n", vb, dbFile.c_str(), numItems, couchstore_strerror(errCode)); st.numGetFailure += numItems; vb_bgfetch_queue_t::iterator itr = itms.begin(); for (; itr != itms.end(); itr++) { std::list<VBucketBGFetchItem *> &fetches = (*itr).second; std::list<VBucketBGFetchItem *>::iterator fitr = fetches.begin(); for (; fitr != fetches.end(); fitr++) { (*fitr)->value.setStatus(ENGINE_NOT_MY_VBUCKET); } } return; } std::vector<uint64_t> seqIds; VBucketBGFetchItem *item2fetch; vb_bgfetch_queue_t::iterator itr = itms.begin(); for (; itr != itms.end(); itr++) { item2fetch = (*itr).second.front(); seqIds.push_back(item2fetch->value.getId()); } GetMultiCbCtx ctx = {*this, vb, itms}; errCode = couchstore_docinfos_by_sequence(db, &seqIds[0], seqIds.size(), 0, getMultiCbC, &ctx); if (errCode != COUCHSTORE_SUCCESS) { st.numGetFailure += numItems; for (itr = itms.begin(); itr != itms.end(); itr++) { std::list<VBucketBGFetchItem *> &fetches = (*itr).second; std::list<VBucketBGFetchItem *>::iterator fitr = fetches.begin(); for (; fitr != fetches.end(); fitr++) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to read database by " "sequence id = %lld, vBucketId = %d " "key = %s file = %s error = %s\n", (*fitr)->value.getId(), vb, (*fitr)->key.c_str(), dbFile.c_str(), couchstore_strerror(errCode)); (*fitr)->value.setStatus(couchErr2EngineErr(errCode)); } } } closeDatabaseHandle(db); } void CouchKVStore::del(const Item &itm, uint64_t, Callback<int> &cb) { assert(!isReadOnly()); assert(intransaction); std::string dbFile; if (getDbFile(itm.getVBucketId(), dbFile)) { CouchRequestCallback requestcb; requestcb.delCb = &cb; // each req will be de-allocated after commit CouchRequest *req = new CouchRequest(itm, dbFileRev(dbFile), requestcb, true); queueItem(req); } else { ++st.numDelFailure; getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to delete data, cannot locate " "database file %s\n", dbFile.c_str()); int value = DOC_NOT_FOUND; cb.callback(value); } } bool CouchKVStore::delVBucket(uint16_t vbucket) { assert(!isReadOnly()); assert(mc); RememberingCallback<bool> cb; mc->delVBucket(vbucket, cb); cb.waitForValue(); cachedVBStates.erase(vbucket); updateDbFileMap(vbucket, 1, false); return cb.val; } vbucket_map_t CouchKVStore::listPersistedVbuckets() { std::vector<std::string> files; if (dbFileMap.empty()) { // warmup, first discover db files from local directory discoverDbFiles(dbname, files); populateFileNameMap(files); } if (!cachedVBStates.empty()) { cachedVBStates.clear(); } Db *db = NULL; couchstore_error_t errorCode; std::map<uint16_t, int>::iterator itr = dbFileMap.begin(); for (; itr != dbFileMap.end(); itr++) { errorCode = openDB(itr->first, itr->second, &db, 0); if (errorCode != COUCHSTORE_SUCCESS) { std::stringstream rev, vbid; rev << itr->second; vbid << itr->first; std::string fileName = dbname + "/" + vbid.str() + ".couch." + rev.str(); getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to open database file, name=%s error=%s\n", fileName.c_str(), couchstore_strerror(errorCode)); remVBucketFromDbFileMap(itr->first); } else { vbucket_state vb_state; uint16_t vbID = itr->first; /* read state of VBucket from db file */ readVBState(db, vbID, vb_state); /* insert populated state to the array to return to the caller */ cachedVBStates[vbID] = vb_state; /* update stat */ ++st.numLoadedVb; closeDatabaseHandle(db); } db = NULL; } return cachedVBStates; } void CouchKVStore::getPersistedStats(std::map<std::string, std::string> &stats) { char *buffer = NULL; std::string fname = dbname + "/stats.json"; std::ifstream session_stats; session_stats.exceptions (session_stats.failbit | session_stats.badbit); try { session_stats.open(fname.c_str(), ios::binary); session_stats.seekg (0, ios::end); int flen = session_stats.tellg(); session_stats.seekg (0, ios::beg); buffer = new char[flen]; session_stats.read(buffer, flen); cJSON *json_obj = cJSON_Parse(buffer); if (!json_obj) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to parse the session stats json doc!!!\n"); delete[] buffer; return; } int json_arr_size = cJSON_GetArraySize(json_obj); for (int i = 0; i < json_arr_size; ++i) { cJSON *obj = cJSON_GetArrayItem(json_obj, i); if (obj) { stats[obj->string] = obj->valuestring; } } cJSON_Delete(json_obj); session_stats.close(); } catch (const std::ifstream::failure& e) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to load the engine session stats " " due to IO exception \"%s\"", e.what()); } delete[] buffer; } bool CouchKVStore::snapshotVBuckets(const vbucket_map_t &m) { assert(!isReadOnly()); vbucket_map_t::const_reverse_iterator iter; bool success = true; for (iter = m.rbegin(); iter != m.rend(); ++iter) { uint16_t vbucketId = iter->first; vbucket_state vbstate = iter->second; vbucket_map_t::iterator it = cachedVBStates.find(vbucketId); bool state_changed = true; if (it != cachedVBStates.end()) { if (it->second.state == vbstate.state && it->second.checkpointId == vbstate.checkpointId) { continue; // no changes } else { if (it->second.state == vbstate.state) { state_changed = false; } it->second.state = vbstate.state; it->second.checkpointId = vbstate.checkpointId; // Note that the max deleted seq number is maintained within CouchKVStore vbstate.maxDeletedSeqno = it->second.maxDeletedSeqno; } } else { cachedVBStates[vbucketId] = vbstate; } success = setVBucketState(vbucketId, vbstate, state_changed, false); if (!success) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to set new state, %s, for vbucket %d\n", VBucket::toString(vbstate.state), vbucketId); break; } } return success; } bool CouchKVStore::snapshotStats(const std::map<std::string, std::string> &stats) { assert(!isReadOnly()); size_t count = 0; size_t size = stats.size(); std::stringstream stats_buf; stats_buf << "{"; std::map<std::string, std::string>::const_iterator it = stats.begin(); for (; it != stats.end(); ++it) { stats_buf << "\"" << it->first << "\": \"" << it->second << "\""; ++count; if (count < size) { stats_buf << ", "; } } stats_buf << "}"; // TODO: This stats json should be written into the master database. However, // we don't support the write synchronization between CouchKVStore in C++ and // compaction manager in the erlang side for the master database yet. At this time, // we simply log the engine stats into a separate json file. As part of futhre work, // we need to get rid of the tight coupling between those two components. bool rv = true; std::string next_fname = dbname + "/stats.json.new"; std::ofstream new_stats; new_stats.exceptions (new_stats.failbit | new_stats.badbit); try { new_stats.open(next_fname.c_str()); new_stats << stats_buf.str().c_str() << std::endl; new_stats.flush(); new_stats.close(); } catch (const std::ofstream::failure& e) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to log the engine stats due to IO exception " "\"%s\"", e.what()); rv = false; } if (rv) { std::string old_fname = dbname + "/stats.json.old"; std::string stats_fname = dbname + "/stats.json"; if (access(old_fname.c_str(), F_OK) == 0 && remove(old_fname.c_str()) != 0) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "FATAL: Failed to remove '%s': %s", old_fname.c_str(), strerror(errno)); remove(next_fname.c_str()); rv = false; } else if (access(stats_fname.c_str(), F_OK) == 0 && rename(stats_fname.c_str(), old_fname.c_str()) != 0) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to rename '%s' to '%s': %s", stats_fname.c_str(), old_fname.c_str(), strerror(errno)); remove(next_fname.c_str()); rv = false; } else if (rename(next_fname.c_str(), stats_fname.c_str()) != 0) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to rename '%s' to '%s': %s", next_fname.c_str(), stats_fname.c_str(), strerror(errno)); remove(next_fname.c_str()); rv = false; } } return rv; } bool CouchKVStore::setVBucketState(uint16_t vbucketId, vbucket_state vbstate, bool stateChanged, bool newfile) { Db *db = NULL; couchstore_error_t errorCode; uint16_t fileRev, newFileRev; std::stringstream id; std::string dbFileName; std::map<uint16_t, int>::iterator mapItr; int rev; id << vbucketId; dbFileName = dbname + "/" + id.str() + ".couch"; if (newfile) { fileRev = 1; // create a db file with rev = 1 } else { mapItr = dbFileMap.find(vbucketId); if (mapItr == dbFileMap.end()) { rev = checkNewRevNum(dbFileName, true); if (rev == 0) { fileRev = 1; newfile = true; } else { fileRev = rev; } } else { fileRev = mapItr->second; } } bool retry = true; while (retry) { retry = false; errorCode = openDB(vbucketId, fileRev, &db, (uint64_t)COUCHSTORE_OPEN_FLAG_CREATE, &newFileRev); if (errorCode != COUCHSTORE_SUCCESS) { std::stringstream filename; filename << dbname << "/" << vbucketId << ".couch." << fileRev; ++st.numVbSetFailure; getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to open database, name=%s error=%s\n", filename.str().c_str(), couchstore_strerror(errorCode)); return false; } fileRev = newFileRev; errorCode = saveVBState(db, vbstate); if (errorCode != COUCHSTORE_SUCCESS) { ++st.numVbSetFailure; getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to save local doc, name=%s error=%s\n", dbFileName.c_str(), couchstore_strerror(errorCode)); closeDatabaseHandle(db); return false; } errorCode = couchstore_commit(db); if (errorCode != COUCHSTORE_SUCCESS) { ++st.numVbSetFailure; getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: commit failed, vbid=%u rev=%u error=%s", vbucketId, fileRev, couchstore_strerror(errorCode)); closeDatabaseHandle(db); return false; } else { uint64_t newHeaderPos = couchstore_get_header_position(db); RememberingCallback<uint16_t> lcb; mc->notify_update(vbucketId, fileRev, newHeaderPos, stateChanged, vbstate.state, vbstate.checkpointId, lcb); if (lcb.val != PROTOCOL_BINARY_RESPONSE_SUCCESS) { if (lcb.val == PROTOCOL_BINARY_RESPONSE_ETMPFAIL) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Retry notify CouchDB of update, " "vbid=%u rev=%u\n", vbucketId, fileRev); retry = true; } else { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to notify CouchDB of update, " "vbid=%u rev=%u error=0x%x\n", vbucketId, fileRev, lcb.val); abort(); } } } closeDatabaseHandle(db); } return true; } void CouchKVStore::dump(shared_ptr<Callback<GetValue> > cb) { shared_ptr<RememberingCallback<bool> > wait(new RememberingCallback<bool>()); shared_ptr<LoadCallback> callback(new LoadCallback(cb, wait)); loadDB(callback, false, NULL, COUCHSTORE_NO_DELETES); } void CouchKVStore::dump(uint16_t vb, shared_ptr<Callback<GetValue> > cb) { shared_ptr<RememberingCallback<bool> > wait(new RememberingCallback<bool>()); shared_ptr<LoadCallback> callback(new LoadCallback(cb, wait)); std::vector<uint16_t> vbids; vbids.push_back(vb); loadDB(callback, false, &vbids); } void CouchKVStore::dumpKeys(const std::vector<uint16_t> &vbids, shared_ptr<Callback<GetValue> > cb) { shared_ptr<RememberingCallback<bool> > wait(new RememberingCallback<bool>()); shared_ptr<LoadCallback> callback(new LoadCallback(cb, wait)); (void)vbids; loadDB(callback, true, NULL, COUCHSTORE_NO_DELETES); } void CouchKVStore::dumpDeleted(uint16_t vb, shared_ptr<Callback<GetValue> > cb) { shared_ptr<RememberingCallback<bool> > wait(new RememberingCallback<bool>()); shared_ptr<LoadCallback> callback(new LoadCallback(cb, wait)); std::vector<uint16_t> vbids; vbids.push_back(vb); loadDB(callback, true, &vbids, COUCHSTORE_DELETES_ONLY); } StorageProperties CouchKVStore::getStorageProperties() { size_t concurrency(10); StorageProperties rv(concurrency, concurrency - 1, 1, true, true, true, true); return rv; } bool CouchKVStore::commit(void) { assert(!isReadOnly()); // TODO get rid of bogus intransaction business assert(intransaction); intransaction = commit2couchstore() ? false : true; return !intransaction; } void CouchKVStore::addStats(const std::string &prefix, ADD_STAT add_stat, const void *c) { const char *prefix_str = prefix.c_str(); /* stats for both read-only and read-write threads */ addStat(prefix_str, "backend_type", "couchstore", add_stat, c); addStat(prefix_str, "open", st.numOpen, add_stat, c); addStat(prefix_str, "close", st.numClose, add_stat, c); addStat(prefix_str, "readTime", st.readTimeHisto, add_stat, c); addStat(prefix_str, "readSize", st.readSizeHisto, add_stat, c); addStat(prefix_str, "numLoadedVb", st.numLoadedVb, add_stat, c); // failure stats addStat(prefix_str, "failure_open", st.numOpenFailure, add_stat, c); addStat(prefix_str, "failure_get", st.numGetFailure, add_stat, c); // stats for read-write thread only if( prefix.compare("rw") == 0 ) { addStat(prefix_str, "delete", st.delTimeHisto, add_stat, c); addStat(prefix_str, "failure_set", st.numSetFailure, add_stat, c); addStat(prefix_str, "failure_del", st.numDelFailure, add_stat, c); addStat(prefix_str, "failure_vbset", st.numVbSetFailure, add_stat, c); addStat(prefix_str, "writeTime", st.writeTimeHisto, add_stat, c); addStat(prefix_str, "writeSize", st.writeSizeHisto, add_stat, c); addStat(prefix_str, "lastCommDocs", st.docsCommitted, add_stat, c); } } template <typename T> void CouchKVStore::addStat(const std::string &prefix, const char *stat, T &val, ADD_STAT add_stat, const void *c) { std::stringstream fullstat; fullstat << prefix << ":" << stat; add_casted_stat(fullstat.str().c_str(), val, add_stat, c); } void CouchKVStore::optimizeWrites(std::vector<queued_item> &items) { assert(!isReadOnly()); if (items.empty()) { return; } CompareQueuedItemsByVBAndKey cq; std::sort(items.begin(), items.end(), cq); } void CouchKVStore::loadDB(shared_ptr<LoadCallback> cb, bool keysOnly, std::vector<uint16_t> *vbids, couchstore_docinfos_options options) { std::vector<std::string> files = std::vector<std::string>(); std::map<uint16_t, int> &filemap = dbFileMap; std::map<uint16_t, int> vbmap; std::vector< std::pair<uint16_t, int> > vbuckets; std::vector< std::pair<uint16_t, int> > replicaVbuckets; bool loadingData = !vbids && !keysOnly; if (dbFileMap.empty()) { // warmup, first discover db files from local directory discoverDbFiles(dbname, files); populateFileNameMap(files); } if (vbids) { // get entries for given vbucket(s) from dbFileMap std::string dirname = dbname; getFileNameMap(vbids, dirname, vbmap); filemap = vbmap; } // order vbuckets data loading by using vbucket states if (loadingData && cachedVBStates.empty()) { listPersistedVbuckets(); } std::map<uint16_t, int>::iterator fitr = filemap.begin(); for (; fitr != filemap.end(); fitr++) { if (loadingData) { vbucket_map_t::const_iterator vsit = cachedVBStates.find(fitr->first); if (vsit != cachedVBStates.end()) { vbucket_state vbs = vsit->second; // ignore loading dead vbuckets during warmup if (vbs.state == vbucket_state_active) { vbuckets.push_back(make_pair(fitr->first, fitr->second)); } else if (vbs.state == vbucket_state_replica) { replicaVbuckets.push_back(make_pair(fitr->first, fitr->second)); } } } else { vbuckets.push_back(make_pair(fitr->first, fitr->second)); } } if (loadingData) { std::vector< std::pair<uint16_t, int> >::iterator it = replicaVbuckets.begin(); for (; it != replicaVbuckets.end(); it++) { vbuckets.push_back(*it); } } Db *db = NULL; couchstore_error_t errorCode; int keyNum = 0; std::vector< std::pair<uint16_t, int> >::iterator itr = vbuckets.begin(); for (; itr != vbuckets.end(); itr++, keyNum++) { errorCode = openDB(itr->first, itr->second, &db, 0); if (errorCode != COUCHSTORE_SUCCESS) { std::stringstream rev, vbid; rev << itr->second; vbid << itr->first; std::string dbName = dbname + "/" + vbid.str() + ".couch." + rev.str(); getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to open database, name=%s error=%s", dbName.c_str(), couchstore_strerror(errorCode)); remVBucketFromDbFileMap(itr->first); } else { LoadResponseCtx ctx; ctx.vbucketId = itr->first; ctx.keysonly = keysOnly; ctx.callback = cb; ctx.engine = &engine; errorCode = couchstore_changes_since(db, 0, options, recordDbDumpC, static_cast<void *>(&ctx)); if (errorCode != COUCHSTORE_SUCCESS) { if (errorCode == COUCHSTORE_ERROR_CANCEL) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Canceling loading database, warmup has completed\n"); closeDatabaseHandle(db); break; } else { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: couchstore_changes_since failed, error=%s\n", couchstore_strerror(errorCode)); remVBucketFromDbFileMap(itr->first); } } closeDatabaseHandle(db); } db = NULL; } bool success = true; cb->complete->callback(success); } void CouchKVStore::open() { // TODO intransaction, is it needed? intransaction = false; if (!isReadOnly()) { delete mc; mc = new MemcachedEngine(&engine, configuration); } struct stat dbstat; bool havedir = false; if (stat(dbname.c_str(), &dbstat) == 0 && (dbstat.st_mode & S_IFDIR) == S_IFDIR) { havedir = true; } if (!havedir) { if (mkdir(dbname.c_str(), S_IRWXU) == -1) { std::stringstream ss; ss << "Warning: Failed to create data directory [" << dbname << "]: " << strerror(errno); throw std::runtime_error(ss.str()); } } } void CouchKVStore::close() { intransaction = false; if (!isReadOnly()) { delete mc; } mc = NULL; } bool CouchKVStore::getDbFile(uint16_t vbucketId, std::string &dbFileName) { std::stringstream fileName; fileName << dbname << "/" << vbucketId << ".couch"; std::map<uint16_t, int>::iterator itr; itr = dbFileMap.find(vbucketId); if (itr == dbFileMap.end()) { dbFileName = fileName.str(); int rev = checkNewRevNum(dbFileName, true); if (rev > 0) { updateDbFileMap(vbucketId, rev, true); fileName << "." << rev; } else { return false; } } else { fileName << "." << itr->second; } dbFileName = fileName.str(); return true; } int CouchKVStore::checkNewRevNum(std::string &dbFileName, bool newFile) { using namespace CouchKVStoreDirectoryUtilities; int newrev = 0; std::string revnum, nameKey; size_t secondDot; if (!newFile) { // extract out the file revision number first secondDot = dbFileName.rfind("."); nameKey = dbFileName.substr(0, secondDot); } else { nameKey = dbFileName; } nameKey.append("."); const std::vector<std::string> files = findFilesWithPrefix(nameKey); std::vector<std::string>::const_iterator itor; // found file(s) whoes name has the same key name pair with different // revision number for (itor = files.begin(); itor != files.end(); ++itor) { const std::string &filename = *itor; if (endWithCompact(filename)) { continue; } secondDot = filename.rfind("."); revnum = filename.substr(secondDot + 1); if (newrev < atoi(revnum.c_str())) { newrev = atoi(revnum.c_str()); dbFileName = filename; } } return newrev; } void CouchKVStore::updateDbFileMap(uint16_t vbucketId, int newFileRev, bool insertImmediately) { if (insertImmediately) { dbFileMap.insert(std::pair<uint16_t, int>(vbucketId, newFileRev)); return; } std::map<uint16_t, int>::iterator itr; itr = dbFileMap.find(vbucketId); if (itr != dbFileMap.end()) { itr->second = newFileRev; } else { dbFileMap.insert(std::pair<uint16_t, int>(vbucketId, newFileRev)); } } static std::string getDBFileName(const std::string &dbname, uint16_t vbid) { std::stringstream ss; ss << dbname << "/" << vbid << ".couch"; return ss.str(); } static std::string getDBFileName(const std::string &dbname, uint16_t vbid, uint16_t rev) { std::stringstream ss; ss << dbname << "/" << vbid << ".couch." << rev; return ss.str(); } couchstore_error_t CouchKVStore::openDB(uint16_t vbucketId, uint16_t fileRev, Db **db, uint64_t options, uint16_t *newFileRev) { couchstore_error_t errorCode; std::string dbFileName = getDBFileName(dbname, vbucketId, fileRev); int newRevNum = fileRev; // first try to open database without options, we don't want to create // a duplicate db that has the same name with different revision number if ((errorCode = couchstore_open_db(dbFileName.c_str(), 0, db))) { if ((newRevNum = checkNewRevNum(dbFileName))) { errorCode = couchstore_open_db(dbFileName.c_str(), 0, db); if (errorCode == COUCHSTORE_SUCCESS) { updateDbFileMap(vbucketId, newRevNum); } } else { if (options) { newRevNum = fileRev; errorCode = couchstore_open_db(dbFileName.c_str(), options, db); if (errorCode == COUCHSTORE_SUCCESS) { updateDbFileMap(vbucketId, newRevNum, true); } } } } if (newFileRev != NULL) { *newFileRev = newRevNum; } if (errorCode) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "open_db() failed, name=%s error=%d\n", dbFileName.c_str(), errorCode); } /* update command statistics */ st.numOpen++; if (errorCode) { st.numOpenFailure++; } return errorCode; } void CouchKVStore::getFileNameMap(std::vector<uint16_t> *vbids, std::string &dirname, std::map<uint16_t, int> &filemap) { std::vector<uint16_t>::iterator vbidItr; std::map<uint16_t, int>::iterator dbFileItr; for (vbidItr = vbids->begin(); vbidItr != vbids->end(); vbidItr++) { std::string dbFileName = getDBFileName(dirname, *vbidItr); dbFileItr = dbFileMap.find(*vbidItr); if (dbFileItr == dbFileMap.end()) { int rev = checkNewRevNum(dbFileName, true); if (rev > 0) { filemap.insert(std::pair<uint16_t, int>(*vbidItr, rev)); } else { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: database file does not exist, %s\n", dbFileName.c_str()); } } else { filemap.insert(std::pair<uint16_t, int>(dbFileItr->first, dbFileItr->second)); } } } void CouchKVStore::populateFileNameMap(std::vector<std::string> &filenames) { std::vector<std::string>::iterator fileItr; for (fileItr = filenames.begin(); fileItr != filenames.end(); fileItr++) { const std::string &filename = *fileItr; size_t secondDot = filename.rfind("."); std::string nameKey = filename.substr(0, secondDot); size_t firstDot = nameKey.rfind("."); size_t firstSlash = nameKey.rfind("/"); std::string revNumStr = filename.substr(secondDot + 1); int revNum = atoi(revNumStr.c_str()); std::string vbIdStr = nameKey.substr(firstSlash + 1, (firstDot - firstSlash) - 1); if (allDigit(vbIdStr)) { int vbId = atoi(vbIdStr.c_str()); std::map<uint16_t, int>::iterator mapItr = dbFileMap.find(vbId); if (mapItr == dbFileMap.end()) { dbFileMap.insert(std::pair<uint16_t, int>(vbId, revNum)); } else { // duplicate key if (mapItr->second < revNum) { mapItr->second = revNum; } } } else { // skip non-vbucket database file, master.couch etc getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Non-vbucket database file, %s, skip adding " "to CouchKVStore dbFileMap\n", filename.c_str()); } } } couchstore_error_t CouchKVStore::fetchDoc(Db *db, DocInfo *docinfo, GetValue &docValue, uint16_t vbId, bool metaOnly) { assert(docinfo && db); uint32_t itemFlags; void *valuePtr = NULL; size_t valuelen = 0; uint64_t cas; time_t exptime; sized_buf metadata; Item *it; Doc *doc = NULL; couchstore_error_t errCode = COUCHSTORE_SUCCESS; metadata = docinfo->rev_meta; assert(metadata.size == 16); memcpy(&cas, (metadata.buf), 8); cas = ntohll(cas); memcpy(&exptime, (metadata.buf) + 8, 4); exptime = ntohl(exptime); memcpy(&itemFlags, (metadata.buf) + 12, 4); itemFlags = ntohl(itemFlags); if (metaOnly) { // we should allow a metadata disk fetch for deleted items only assert(docinfo->deleted); it = new Item(docinfo->id.buf, (size_t)docinfo->id.size, docinfo->size, itemFlags, (time_t)exptime, cas); it->setSeqno(docinfo->rev_seq); docValue = GetValue(it); // update ep-engine IO stats ++epStats.io_num_read; epStats.io_read_bytes += docinfo->id.size; } else { errCode = couchstore_open_doc_with_docinfo(db, docinfo, &doc, 0); if (errCode == COUCHSTORE_SUCCESS) { if (docinfo->deleted) { // cannot read a doc that is marked deleted, just return // document not found error code errCode = COUCHSTORE_ERROR_DOC_NOT_FOUND; } else { assert(doc && (doc->id.size <= UINT16_MAX)); valuelen = doc->data.size; valuePtr = doc->data.buf; it = new Item(docinfo->id.buf, (size_t)docinfo->id.size, itemFlags, (time_t)exptime, valuePtr, valuelen, cas, -1, vbId); docValue = GetValue(it); couchstore_free_document(doc); // update ep-engine IO stats ++epStats.io_num_read; epStats.io_read_bytes += docinfo->id.size + valuelen; } } } return errCode; } int CouchKVStore::recordDbDump(Db *db, DocInfo *docinfo, void *ctx) { Item *it = NULL; Doc *doc = NULL; LoadResponseCtx *loadCtx = (LoadResponseCtx *)ctx; shared_ptr<LoadCallback> callback = loadCtx->callback; EventuallyPersistentEngine *engine= loadCtx->engine; bool warmup = engine->stillWarmingUp(); // TODO enable below when couchstore is ready // bool compressed = (docinfo->content_meta & 0x80); // uint8_t metaflags = (docinfo->content_meta & ~0x80); void *valuePtr; size_t valuelen; sized_buf metadata = docinfo->rev_meta; uint32_t itemflags; uint16_t vbucketId = loadCtx->vbucketId; sized_buf key = docinfo->id; uint64_t cas; uint32_t exptime; assert(key.size <= UINT16_MAX); assert(metadata.size == 16); memcpy(&cas, metadata.buf, 8); memcpy(&exptime, (metadata.buf) + 8, 4); memcpy(&itemflags, (metadata.buf) + 12, 4); itemflags = ntohl(itemflags); exptime = ntohl(exptime); cas = ntohll(cas); valuePtr = NULL; valuelen = 0; if (!loadCtx->keysonly && !docinfo->deleted) { couchstore_error_t errCode ; errCode = couchstore_open_doc_with_docinfo(db, docinfo, &doc, 0); if (errCode == COUCHSTORE_SUCCESS) { if (doc->data.size) { valuelen = doc->data.size; valuePtr = doc->data.buf; } } else { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to retrieve key value from database " "database, vBucket=%d key=%s error=%s\n", vbucketId, key.buf, couchstore_strerror(errCode)); return 0; } } it = new Item((void *)key.buf, key.size, itemflags, (time_t)exptime, valuePtr, valuelen, cas, docinfo->db_seq, // return seq number being persisted on disk vbucketId, docinfo->rev_seq); GetValue rv(it, ENGINE_SUCCESS, -1, loadCtx->keysonly); callback->cb->callback(rv); couchstore_free_document(doc); int returnCode = COUCHSTORE_SUCCESS; if (warmup) { if (!engine->stillWarmingUp()) { // warmup has completed, return COUCHSTORE_ERROR_CANCEL to // cancel remaining data dumps from couchstore getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Engine warmup is complete, request to stop " "loading remaining database\n"); returnCode = COUCHSTORE_ERROR_CANCEL; } } return returnCode; } bool CouchKVStore::commit2couchstore(void) { Doc **docs; DocInfo **docinfos; uint16_t vbucket2flush, vbucketId; int reqIndex, flushStartIndex, numDocs2save; couchstore_error_t errCode; bool success = true; std::string dbName; CouchRequest *req = NULL; CouchRequest **committedReqs; if (pendingCommitCnt == 0) { return success; } committedReqs = new CouchRequest *[pendingCommitCnt]; docs = new Doc *[pendingCommitCnt]; docinfos = new DocInfo *[pendingCommitCnt]; if ((req = pendingReqsQ.front()) == NULL) { abort(); } vbucket2flush = req->getVBucketId(); for (reqIndex = 0, flushStartIndex = 0, numDocs2save = 0; pendingCommitCnt > 0; reqIndex++, numDocs2save++, pendingCommitCnt--) { if ((req = pendingReqsQ.front()) == NULL) { abort(); } committedReqs[reqIndex] = req; docs[reqIndex] = req->getDbDoc(); docinfos[reqIndex] = req->getDbDocInfo(); vbucketId = req->getVBucketId(); pendingReqsQ.pop_front(); if (vbucketId != vbucket2flush) { errCode = saveDocs(vbucket2flush, committedReqs[flushStartIndex]->getRevNum(), &docs[flushStartIndex], &docinfos[flushStartIndex], numDocs2save); if (errCode) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: commit failed, cannot save CouchDB " "docs for vbucket = %d rev = %d error = %d\n", vbucket2flush, committedReqs[flushStartIndex]->getRevNum(), (int)errCode); ++epStats.commitFailed; } commitCallback(&committedReqs[flushStartIndex], numDocs2save, errCode); numDocs2save = 0; flushStartIndex = reqIndex; vbucket2flush = vbucketId; } } if (reqIndex - flushStartIndex) { // flush the rest errCode = saveDocs(vbucket2flush, committedReqs[flushStartIndex]->getRevNum(), &docs[flushStartIndex], &docinfos[flushStartIndex], numDocs2save); if (errCode) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: commit failed, cannot save CouchDB docs " "for vbucket = %d rev = %d error = %d\n", vbucket2flush, committedReqs[flushStartIndex]->getRevNum(), (int)errCode); ++epStats.commitFailed; } commitCallback(&committedReqs[flushStartIndex], numDocs2save, errCode); } while (reqIndex--) { delete committedReqs[reqIndex]; } delete [] committedReqs; delete [] docs; delete [] docinfos; return success; } couchstore_error_t CouchKVStore::saveDocs(uint16_t vbid, int rev, Doc **docs, DocInfo **docinfos, int docCount) { couchstore_error_t errCode; int fileRev; uint16_t newFileRev; Db *db = NULL; bool retry_save_docs; fileRev = rev; assert(fileRev); do { retry_save_docs = false; errCode = openDB(vbid, fileRev, &db, (uint64_t)COUCHSTORE_OPEN_FLAG_CREATE, &newFileRev); if (errCode != COUCHSTORE_SUCCESS) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to open database, vbucketId = %d " "fileRev = %d error = %d\n", vbid, fileRev, errCode); return errCode; } else { uint32_t max = computeMaxDeletedSeqNum(docinfos, docCount); // update max_deleted_seq in the local doc (vbstate) // before save docs for the given vBucket if (max > 0) { vbucket_map_t::iterator it = cachedVBStates.find(vbid); if (it != cachedVBStates.end() && it->second.maxDeletedSeqno < max) { it->second.maxDeletedSeqno = max; errCode = saveVBState(db, it->second); if (errCode != COUCHSTORE_SUCCESS) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to save local doc for, " "vBucket = %d error = %s\n", vbid, couchstore_strerror(errCode)); closeDatabaseHandle(db); return errCode; } } } errCode = couchstore_save_documents(db, docs, docinfos, docCount, 0 /* no options */); if (errCode != COUCHSTORE_SUCCESS) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Failed to save docs to database, error = %s\n", couchstore_strerror(errCode)); closeDatabaseHandle(db); return errCode; } errCode = couchstore_commit(db); if (errCode) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Commit failed: %s", couchstore_strerror(errCode)); closeDatabaseHandle(db); return errCode; } RememberingCallback<uint16_t> cb; uint64_t newHeaderPos = couchstore_get_header_position(db); mc->notify_headerpos_update(vbid, newFileRev, newHeaderPos, cb); if (cb.val != PROTOCOL_BINARY_RESPONSE_SUCCESS) { if (cb.val == PROTOCOL_BINARY_RESPONSE_ETMPFAIL) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Retry notify CouchDB of update, vbucket=%d rev=%d\n", vbid, newFileRev); fileRev = newFileRev; retry_save_docs = true; } else { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to notify CouchDB of " "update for vbucket=%d, error=0x%x\n", vbid, cb.val); abort(); } } closeDatabaseHandle(db); } } while (retry_save_docs); /* update stat */ if(errCode == COUCHSTORE_SUCCESS) { st.docsCommitted = docCount; } return errCode; } void CouchKVStore::queueItem(CouchRequest *req) { pendingReqsQ.push_back(req); pendingCommitCnt++; } void CouchKVStore::remVBucketFromDbFileMap(uint16_t vbucketId) { std::map<uint16_t, int>::iterator itr; itr = dbFileMap.find(vbucketId); if (itr != dbFileMap.end()) { dbFileMap.erase(itr); } } void CouchKVStore::commitCallback(CouchRequest **committedReqs, int numReqs, couchstore_error_t errCode) { for (int index = 0; index < numReqs; index++) { size_t dataSize = committedReqs[index]->getNBytes(); size_t keySize = committedReqs[index]->getKey().length(); /* update ep stats */ ++epStats.io_num_write; epStats.io_write_bytes += keySize + dataSize; if (committedReqs[index]->isDelete()) { int rv = getMutationStatus(errCode); if (errCode) { ++st.numDelFailure; } else { st.delTimeHisto.add(committedReqs[index]->getDelta() / 1000); } committedReqs[index]->getDelCallback()->callback(rv); } else { int rv = getMutationStatus(errCode); int64_t newItemId = committedReqs[index]->getDbDocInfo()->db_seq; if (errCode) { ++st.numSetFailure; newItemId = 0; } else { st.writeTimeHisto.add(committedReqs[index]->getDelta() / 1000); st.writeSizeHisto.add(dataSize + keySize); } mutation_result p(rv, newItemId); committedReqs[index]->getSetCallback()->callback(p); } } } void CouchKVStore::readVBState(Db *db, uint16_t vbId, vbucket_state &vbState) { sized_buf id; LocalDoc *ldoc = NULL; couchstore_error_t errCode; vbState.state = vbucket_state_dead; vbState.checkpointId = 0; vbState.maxDeletedSeqno = 0; id.buf = (char *)"_local/vbstate"; id.size = sizeof("_local/vbstate") - 1; errCode = couchstore_open_local_document(db, (void *)id.buf, id.size, &ldoc); if (errCode != COUCHSTORE_SUCCESS) { getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Warning: failed to retrieve stat info for vBucket=%d error=%d\n", vbId, (int)errCode); } else { const std::string statjson(ldoc->json.buf, ldoc->json.size); cJSON *jsonObj = cJSON_Parse(statjson.c_str()); const std::string state = getJSONObjString(cJSON_GetObjectItem(jsonObj, "state")); const std::string checkpoint_id = getJSONObjString(cJSON_GetObjectItem(jsonObj, "checkpoint_id")); const std::string max_deleted_seqno = getJSONObjString(cJSON_GetObjectItem(jsonObj, "max_deleted_seqno")); if (state.compare("") == 0 || checkpoint_id.compare("") == 0 || max_deleted_seqno.compare("") == 0) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: state JSON doc for vbucket %d is in the wrong format: %s\n", vbId, statjson.c_str()); } else { vbState.state = VBucket::fromString(state.c_str()); parseUint32(max_deleted_seqno.c_str(), &vbState.maxDeletedSeqno); parseUint64(checkpoint_id.c_str(), &vbState.checkpointId); } cJSON_Delete(jsonObj); couchstore_free_local_document(ldoc); } } couchstore_error_t CouchKVStore::saveVBState(Db *db, vbucket_state &vbState) { LocalDoc lDoc; std::stringstream jsonState; std::string state; jsonState << "{\"state\": \"" << VBucket::toString(vbState.state) << "\", \"checkpoint_id\": \"" << vbState.checkpointId << "\", \"max_deleted_seqno\": \"" << vbState.maxDeletedSeqno << "\"}"; lDoc.id.buf = (char *)"_local/vbstate"; lDoc.id.size = sizeof("_local/vbstate") - 1; state = jsonState.str(); lDoc.json.buf = (char *)state.c_str(); lDoc.json.size = state.size(); lDoc.deleted = 0; return couchstore_save_local_document(db, &lDoc); } int CouchKVStore::getMultiCb(Db *db, DocInfo *docinfo, void *ctx) { couchstore_error_t errCode; std::string keyStr(docinfo->id.buf, docinfo->id.size); assert(ctx); GetMultiCbCtx *cbCtx = static_cast<GetMultiCbCtx *>(ctx); CouchKVStoreStats &st = cbCtx->cks.getCKVStoreStat(); vb_bgfetch_queue_t::iterator qitr; qitr = cbCtx->fetches.find(docinfo->db_seq); assert(qitr != cbCtx->fetches.end()); std::list<VBucketBGFetchItem *> &fetches = (*qitr).second; GetValue returnVal; errCode = cbCtx->cks.fetchDoc(db, docinfo, returnVal, cbCtx->vbId, false); if (errCode != COUCHSTORE_SUCCESS) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Warning: failed to fetch data from database, " "vBucket=%d key=%s error=%s\n", cbCtx->vbId, keyStr.c_str(), couchstore_strerror(errCode)); st.numGetFailure++; } returnVal.setStatus(cbCtx->cks.couchErr2EngineErr(errCode)); std::list<VBucketBGFetchItem *>::iterator itr = fetches.begin(); for (; itr != fetches.end(); itr++) { // populate return value for remaining fetch items with the // same seqid (*itr)->value = returnVal; st.readTimeHisto.add((gethrtime() - (*itr)->initTime) / 1000); if (errCode == COUCHSTORE_SUCCESS) { st.readSizeHisto.add(returnVal.getValue()->getKey().length() + returnVal.getValue()->getNBytes()); } } return 0; } void CouchKVStore::closeDatabaseHandle(Db *db) { couchstore_error_t ret = couchstore_close_db(db); if (ret != COUCHSTORE_SUCCESS) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Failed to close database handle: %s", couchstore_strerror(ret)); } st.numClose++; } ENGINE_ERROR_CODE CouchKVStore::couchErr2EngineErr(couchstore_error_t errCode) { switch (errCode) { case COUCHSTORE_SUCCESS: return ENGINE_SUCCESS; case COUCHSTORE_ERROR_ALLOC_FAIL: return ENGINE_ENOMEM; case COUCHSTORE_ERROR_DOC_NOT_FOUND: return ENGINE_KEY_ENOENT; case COUCHSTORE_ERROR_NO_SUCH_FILE: return ENGINE_NOT_MY_VBUCKET; default: // same as the general error return code of // EvetuallyPersistentStore::getInternal return ENGINE_TMPFAIL; } } size_t CouchKVStore::warmup(MutationLog &lf, const std::map<uint16_t, vbucket_state> &vbmap, Callback<GetValue> &cb, Callback<size_t> &estimate) { assert(engine.getEpStore()->multiBGFetchEnabled()); MutationLogHarvester harvester(lf); std::map<uint16_t, vbucket_state>::const_iterator it; for (it = vbmap.begin(); it != vbmap.end(); ++it) { harvester.setVBucket(it->first); } hrtime_t start = gethrtime(); if (!harvester.load()) { return -1; } hrtime_t end = gethrtime(); size_t total = harvester.total(); estimate.callback(total); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Completed log read in %s with %ld entries\n", hrtime2text(end - start).c_str(), total); start = gethrtime(); WarmupCookie cookie(this, cb); harvester.apply(&cookie, &batchWarmupCallback); end = gethrtime(); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Populated log in %s with (l: %ld, s: %ld, e: %ld)", hrtime2text(end - start).c_str(), cookie.loaded, cookie.skipped, cookie.error); return cookie.loaded; } /* end of couch-kvstore.cc */
/** ****************************************************************************** * @file main.cpp * @author Michal Prevratil * @version V1.0 * @date 01-December-2013 * @brief Default main function. ****************************************************************************** */ #include "main.h" #include "Kalman.h" #include "math.h" using namespace flyhero; #define PI 3.14159265358979323846 #ifdef LOG extern "C" void initialise_monitor_handles(void); #endif unsigned char *mpl_key = (unsigned char*)"eMPL 5.1"; ESP *esp = ESP8266::Instance(); PWM_Generator *pwm = PWM_Generator::Instance(); MPU6050 *mpu = MPU6050::Instance(); MS5611 *ms5611 = MS5611::Instance(); NEO_M8N *neo = NEO_M8N::Instance(); Logger *logger = Logger::Instance(); void InitI2C(I2C_HandleTypeDef*); void Arm_Callback(); void IPD_Callback(uint8_t link_ID, uint8_t *data, uint16_t length); void Calculate(); PID PID_Roll, PID_Pitch, PID_Yaw; bool connected = false; bool start = false; bool data_received = false; bool inverse_yaw = false; uint16_t throttle = 0; IWDG_HandleTypeDef hiwdg; /* Testing */ /*Kalman kalmanX, kalmanY; double gyroXangle, gyroYangle; // Angle calculate using the gyro only double compAngleX, compAngleY; // Calculated angle using a complementary filter double kalAngleX, kalAngleY; // Calculated angle using a Kalman filter uint32_t kalman_time; double dt; MPU6050::Sensor_Data accel_data; MPU6050::Sensor_Data gyro_data;*/ MPU6050::Sensor_Data euler_data; //double roll, pitch; /* End Testing */ int main(void) { HAL_Init(); #ifdef LOG initialise_monitor_handles(); #endif uint8_t status; uint32_t timestamp; float data[3]; long FL, BL, FR, BR; FL = BL = FR = BR = 0; long pitchCorrection, rollCorrection, yawCorrection; double reference_yaw; PID_Roll.imax(50); PID_Pitch.imax(50); PID_Yaw.imax(50); LEDs::Init(); hiwdg.Instance = IWDG; hiwdg.Init.Prescaler = IWDG_PRESCALER_32; hiwdg.Init.Reload = 480; // timeout after 2 s I2C_HandleTypeDef hI2C_Handle; InitI2C(&hI2C_Handle); esp->Init(&IPD_Callback); timestamp = HAL_GetTick(); // not yet implemented //Timer::Start_Task([]{ LEDs::Toggle(LEDs::Green); }, 750); while (!connected) { if (HAL_GetTick() - timestamp >= 750) { LEDs::Toggle(LEDs::Green); timestamp = HAL_GetTick(); } esp->Process_Data(); } LEDs::TurnOff(LEDs::Green); pwm->Init(); pwm->Arm(&Arm_Callback); // reset gyro if (mpu->Init(&hI2C_Handle)) { LEDs::TurnOn(LEDs::Yellow); while (true); } if (mpu->SelfTest()) LEDs::TurnOn(LEDs::Green); else LEDs::TurnOn(LEDs::Yellow); LEDs::TurnOff(LEDs::Green); mpu->CheckNewData(); mpu->ReadEuler(&euler_data); double x = euler_data.z; double dx, dt; dx = dt = 1; timestamp = HAL_GetTick(); // wait until calibration of yaw done do { mpu->CheckNewData(); if (HAL_GetTick() - timestamp >= 500) { dt = HAL_GetTick() - timestamp; mpu->ReadEuler(&euler_data); dx = euler_data.z - x; x = euler_data.z; timestamp = HAL_GetTick(); } esp->Process_Data(); } while (fabs(dx / dt) > 0.0001); reference_yaw = euler_data.z; pwm->SetPulse(1100, 1); pwm->SetPulse(1100, 2); pwm->SetPulse(1100, 3); pwm->SetPulse(1100, 4); Timer::Delay_ms(250); pwm->SetPulse(940, 4); pwm->SetPulse(940, 1); pwm->SetPulse(940, 3); pwm->SetPulse(940, 2); while (!start) { if (HAL_GetTick() - timestamp >= 750) { LEDs::Toggle(LEDs::Green); timestamp = HAL_GetTick(); } mpu->CheckNewData(); esp->Process_Data(); } /*while (!mpu->ReadAccel(&accel_data)); roll = atan2(accel_data.y, accel_data.z) * 180 / PI; pitch = atan(-accel_data.x / sqrt(accel_data.y * accel_data.y + accel_data.z * accel_data.z)) * 180 / PI; kalmanX.setAngle(roll); kalmanY.setAngle(pitch); gyroXangle = roll; gyroYangle = pitch; compAngleX = roll; compAngleY = pitch; kalman_time = HAL_GetTick();*/ LEDs::TurnOn(LEDs::Green); #ifndef LOG HAL_IWDG_Init(&hiwdg); #endif throttle = 0; while (true) { status = mpu->CheckNewData(); if (status == 1) { if (data_received) HAL_IWDG_Refresh(&hiwdg); data_received = false; //mpu->ReadAccel(&accel_data); //mpu->ReadGyro(&gyro_data); mpu->ReadEuler(&euler_data); //Calculate(); data[0] = euler_data.x; data[1] = euler_data.y; data[2] = euler_data.z; /*uint8_t logData[16]; int32_t tdata[3]; tdata[0] = data[0] * 65536.f; tdata[1] = data[1] * 65536.f; tdata[2] = data[2] * 65536.f; logData[0] = (tdata[0] >> 24) & 0xFF; logData[1] = (tdata[0] >> 16) & 0xFF; logData[2] = (tdata[0] >> 8) & 0xFF; logData[3] = tdata[0] & 0xFF; logData[4] = (tdata[1] >> 24) & 0xFF; logData[5] = (tdata[1] >> 16) & 0xFF; logData[6] = (tdata[1] >> 8) & 0xFF; logData[7] = tdata[1] & 0xFF; logData[8] = (tdata[2] >> 24) & 0xFF; logData[9] = (tdata[2] >> 16) & 0xFF; logData[10] = (tdata[2] >> 8) & 0xFF; logData[11] = tdata[2] & 0xFF; logData[12] = (throttle >> 24) & 0xFF; logData[13] = (throttle >> 16) & 0xFF; logData[14] = (throttle >> 8) & 0xFF; logData[15] = throttle & 0xFF; esp->Get_Connection('4')->Connection_Send_Begin(logData, 16); while (esp->Get_Connection('4')->Get_State() != CONNECTION_READY && esp->Get_Connection('4')->Get_State() != CONNECTION_CLOSED) { esp->Get_Connection('4')->Connection_Send_Continue(); }*/ } if (status == 1 && throttle >= 1050) { pitchCorrection = PID_Pitch.get_pid(data[1], 1); rollCorrection = PID_Roll.get_pid(data[0], 1); yawCorrection = PID_Yaw.get_pid(data[2] - reference_yaw, 1); // not sure about yaw signs if (!inverse_yaw) { FL = throttle + rollCorrection + pitchCorrection + yawCorrection; // PB2 BL = throttle + rollCorrection - pitchCorrection - yawCorrection; // PA15 FR = throttle - rollCorrection + pitchCorrection - yawCorrection; // PB10 BR = throttle - rollCorrection - pitchCorrection + yawCorrection; // PA1 } else { FL = throttle + rollCorrection + pitchCorrection - yawCorrection; // PB2 BL = throttle + rollCorrection - pitchCorrection + yawCorrection; // PA15 FR = throttle - rollCorrection + pitchCorrection + yawCorrection; // PB10 BR = throttle - rollCorrection - pitchCorrection - yawCorrection; // PA1 } if (FL > 2000) FL = 2000; else if (FL < 1050) FL = 940; if (BL > 2000) BL = 2000; else if (BL < 1050) BL = 940; if (FR > 2000) FR = 2000; else if (FR < 1050) FR = 940; if (BR > 2000) BR = 2000; else if (BR < 1050) BR = 940; pwm->SetPulse(FL, 3); pwm->SetPulse(BL, 2); pwm->SetPulse(FR, 4); pwm->SetPulse(BR, 1); } else if (status == 2) LEDs::TurnOn(LEDs::Orange); if (throttle < 1050) { pwm->SetPulse(940, 4); pwm->SetPulse(940, 1); pwm->SetPulse(940, 3); pwm->SetPulse(940, 2); reference_yaw = euler_data.z; } esp->Process_Data(); } } void IPD_Callback(uint8_t link_ID, uint8_t *data, uint16_t length) { switch (length) { case 22: if (data[0] == 0x5D) { uint16_t roll_kP, pitch_kP, yaw_kP; uint16_t roll_kI, pitch_kI, yaw_kI; uint16_t roll_kD, pitch_kD, yaw_kD; data_received = true; throttle = data[1] << 8; throttle |= data[2]; roll_kP = data[3] << 8; roll_kP |= data[4]; roll_kI = data[5] << 8; roll_kI |= data[6]; roll_kD = data[7] << 8; roll_kD |= data[8]; PID_Roll.kP(roll_kP / 100.0); PID_Roll.kI(roll_kI / 100.0); PID_Roll.kD(roll_kD / 100.0); pitch_kP = data[9] << 8; pitch_kP |= data[10]; pitch_kI = data[11] << 8; pitch_kI |= data[12]; pitch_kD = data[13] << 8; pitch_kD |= data[14]; PID_Pitch.kP(pitch_kP / 100.0); PID_Pitch.kI(pitch_kI / 100.0); PID_Pitch.kD(pitch_kD / 100.0); yaw_kP = data[15] << 8; yaw_kP |= data[16]; yaw_kI = data[17] << 8; yaw_kI |= data[18]; yaw_kD = data[19] << 8; yaw_kD |= data[20]; PID_Yaw.kP(yaw_kP / 100.0); PID_Yaw.kI(yaw_kI / 100.0); PID_Yaw.kD(yaw_kD / 100.0); inverse_yaw = (data[21] == 0x01); throttle += 1000; } break; case 3: if (data[0] == 0x3D) { start = true; } if (data[0] == 0x5D) { connected = true; } break; } } void Arm_Callback() { esp->Process_Data(); //HAL_IWDG_Refresh(&hiwdg); } void InitI2C(I2C_HandleTypeDef *I2C_Handle) { if (__GPIOB_IS_CLK_DISABLED()) __GPIOB_CLK_ENABLE(); if (__I2C1_IS_CLK_DISABLED()) __I2C1_CLK_ENABLE(); GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.Pin = GPIO_PIN_8 | GPIO_PIN_9; GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF4_I2C1; HAL_GPIO_DeInit(GPIOB, GPIO_PIN_8 | GPIO_PIN_9); HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); I2C_Handle->Instance = I2C1; I2C_Handle->Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; I2C_Handle->Init.ClockSpeed = 400000; I2C_Handle->Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; I2C_Handle->Init.DutyCycle = I2C_DUTYCYCLE_2; I2C_Handle->Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; I2C_Handle->Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; I2C_Handle->Init.OwnAddress1 = 0; I2C_Handle->Init.OwnAddress2 = 0; __HAL_I2C_RESET_HANDLE_STATE(I2C_Handle); if (HAL_I2C_DeInit(I2C_Handle) != HAL_OK) LEDs::TurnOn(LEDs::Orange); if (HAL_I2C_Init(I2C_Handle) != HAL_OK) LEDs::TurnOn(LEDs::Orange); } /*void Calculate() { dt = (HAL_GetTick() - kalman_time) / 1000.0; kalman_time = HAL_GetTick(); roll = atan2(accel_data.y, accel_data.z) * 180 / PI; pitch = atan(-accel_data.x / sqrt(accel_data.y * accel_data.y + accel_data.z * accel_data.z)) * 180 / PI; double gyroXrate = gyro_data.x; double gyroYrate = gyro_data.y; // This fixes the transition problem when the accelerometer angle jumps between -180 and 180 degrees if ((roll < -90 && kalAngleX > 90) || (roll > 90 && kalAngleX < -90)) { kalmanX.setAngle(roll); compAngleX = roll; kalAngleX = roll; gyroXangle = roll; } else kalAngleX = kalmanX.getAngle(roll, gyroXrate, dt); // Calculate the angle using a Kalman filter if (abs(kalAngleX) > 90) gyroYrate = -gyroYrate; // Invert rate, so it fits the restriced accelerometer reading kalAngleY = kalmanY.getAngle(pitch, gyroYrate, dt); gyroXangle += gyroXrate * dt; // Calculate gyro angle without any filter gyroYangle += gyroYrate * dt; //gyroXangle += kalmanX.getRate() * dt; // Calculate gyro angle using the unbiased rate //gyroYangle += kalmanY.getRate() * dt; compAngleX = 0.93 * (compAngleX + gyroXrate * dt) + 0.07 * roll; // Calculate the angle using a Complimentary filter compAngleY = 0.93 * (compAngleY + gyroYrate * dt) + 0.07 * pitch; // Reset the gyro angle when it has drifted too much if (gyroXangle < -180 || gyroXangle > 180) gyroXangle = kalAngleX; if (gyroYangle < -180 || gyroYangle > 180) gyroYangle = kalAngleY; }*/ On start read a setting byte whether to log data over wifi or not /** ****************************************************************************** * @file main.cpp * @author Michal Prevratil * @version V1.0 * @date 01-December-2013 * @brief Default main function. ****************************************************************************** */ #include "main.h" #include "Kalman.h" #include "math.h" using namespace flyhero; #define PI 3.14159265358979323846 #ifdef LOG extern "C" void initialise_monitor_handles(void); #endif unsigned char *mpl_key = (unsigned char*)"eMPL 5.1"; ESP *esp = ESP8266::Instance(); PWM_Generator *pwm = PWM_Generator::Instance(); MPU6050 *mpu = MPU6050::Instance(); MS5611 *ms5611 = MS5611::Instance(); NEO_M8N *neo = NEO_M8N::Instance(); Logger *logger = Logger::Instance(); void InitI2C(I2C_HandleTypeDef*); void Arm_Callback(); void IPD_Callback(uint8_t link_ID, uint8_t *data, uint16_t length); void Calculate(); PID PID_Roll, PID_Pitch, PID_Yaw; bool connected = false; bool log_data = false; bool start = false; bool data_received = false; bool inverse_yaw = false; uint16_t throttle = 0; IWDG_HandleTypeDef hiwdg; /* Testing */ /*Kalman kalmanX, kalmanY; double gyroXangle, gyroYangle; // Angle calculate using the gyro only double compAngleX, compAngleY; // Calculated angle using a complementary filter double kalAngleX, kalAngleY; // Calculated angle using a Kalman filter uint32_t kalman_time; double dt; MPU6050::Sensor_Data accel_data; MPU6050::Sensor_Data gyro_data;*/ MPU6050::Sensor_Data euler_data; //double roll, pitch; /* End Testing */ int main(void) { HAL_Init(); #ifdef LOG initialise_monitor_handles(); #endif uint8_t status; uint32_t timestamp; float data[3]; long FL, BL, FR, BR; FL = BL = FR = BR = 0; long pitchCorrection, rollCorrection, yawCorrection; double reference_yaw; PID_Roll.imax(50); PID_Pitch.imax(50); PID_Yaw.imax(50); LEDs::Init(); hiwdg.Instance = IWDG; hiwdg.Init.Prescaler = IWDG_PRESCALER_32; hiwdg.Init.Reload = 480; // timeout after 2 s I2C_HandleTypeDef hI2C_Handle; InitI2C(&hI2C_Handle); esp->Init(&IPD_Callback); timestamp = HAL_GetTick(); // not yet implemented //Timer::Start_Task([]{ LEDs::Toggle(LEDs::Green); }, 750); while (!connected) { if (HAL_GetTick() - timestamp >= 750) { LEDs::Toggle(LEDs::Green); timestamp = HAL_GetTick(); } esp->Process_Data(); } LEDs::TurnOff(LEDs::Green); pwm->Init(); pwm->Arm(&Arm_Callback); // reset gyro if (mpu->Init(&hI2C_Handle)) { LEDs::TurnOn(LEDs::Yellow); while (true); } if (mpu->SelfTest()) LEDs::TurnOn(LEDs::Green); else LEDs::TurnOn(LEDs::Yellow); LEDs::TurnOff(LEDs::Green); mpu->CheckNewData(); mpu->ReadEuler(&euler_data); double x = euler_data.z; double dx, dt; dx = dt = 1; timestamp = HAL_GetTick(); // wait until calibration of yaw done do { mpu->CheckNewData(); if (HAL_GetTick() - timestamp >= 500) { dt = HAL_GetTick() - timestamp; mpu->ReadEuler(&euler_data); dx = euler_data.z - x; x = euler_data.z; timestamp = HAL_GetTick(); } esp->Process_Data(); } while (fabs(dx / dt) > 0.0001); reference_yaw = euler_data.z; pwm->SetPulse(1100, 1); pwm->SetPulse(1100, 2); pwm->SetPulse(1100, 3); pwm->SetPulse(1100, 4); Timer::Delay_ms(250); pwm->SetPulse(940, 4); pwm->SetPulse(940, 1); pwm->SetPulse(940, 3); pwm->SetPulse(940, 2); while (!start) { if (HAL_GetTick() - timestamp >= 750) { LEDs::Toggle(LEDs::Green); timestamp = HAL_GetTick(); } mpu->CheckNewData(); esp->Process_Data(); } /*while (!mpu->ReadAccel(&accel_data)); roll = atan2(accel_data.y, accel_data.z) * 180 / PI; pitch = atan(-accel_data.x / sqrt(accel_data.y * accel_data.y + accel_data.z * accel_data.z)) * 180 / PI; kalmanX.setAngle(roll); kalmanY.setAngle(pitch); gyroXangle = roll; gyroYangle = pitch; compAngleX = roll; compAngleY = pitch; kalman_time = HAL_GetTick();*/ LEDs::TurnOn(LEDs::Green); #ifndef LOG HAL_IWDG_Init(&hiwdg); #endif throttle = 0; while (true) { status = mpu->CheckNewData(); if (status == 1) { if (data_received) HAL_IWDG_Refresh(&hiwdg); data_received = false; //mpu->ReadAccel(&accel_data); //mpu->ReadGyro(&gyro_data); mpu->ReadEuler(&euler_data); //Calculate(); data[0] = euler_data.x; data[1] = euler_data.y; data[2] = euler_data.z; if (log_data) { uint8_t logData[16]; int32_t tdata[3]; tdata[0] = data[0] * 65536.f; tdata[1] = data[1] * 65536.f; tdata[2] = data[2] * 65536.f; logData[0] = (tdata[0] >> 24) & 0xFF; logData[1] = (tdata[0] >> 16) & 0xFF; logData[2] = (tdata[0] >> 8) & 0xFF; logData[3] = tdata[0] & 0xFF; logData[4] = (tdata[1] >> 24) & 0xFF; logData[5] = (tdata[1] >> 16) & 0xFF; logData[6] = (tdata[1] >> 8) & 0xFF; logData[7] = tdata[1] & 0xFF; logData[8] = (tdata[2] >> 24) & 0xFF; logData[9] = (tdata[2] >> 16) & 0xFF; logData[10] = (tdata[2] >> 8) & 0xFF; logData[11] = tdata[2] & 0xFF; logData[12] = (throttle >> 24) & 0xFF; logData[13] = (throttle >> 16) & 0xFF; logData[14] = (throttle >> 8) & 0xFF; logData[15] = throttle & 0xFF; esp->Get_Connection('4')->Connection_Send_Begin(logData, 16); while (esp->Get_Connection('4')->Get_State() != CONNECTION_READY && esp->Get_Connection('4')->Get_State() != CONNECTION_CLOSED) { esp->Get_Connection('4')->Connection_Send_Continue(); } } } if (status == 1 && throttle >= 1050) { pitchCorrection = PID_Pitch.get_pid(data[1], 1); rollCorrection = PID_Roll.get_pid(data[0], 1); yawCorrection = PID_Yaw.get_pid(data[2] - reference_yaw, 1); // not sure about yaw signs if (!inverse_yaw) { FL = throttle + rollCorrection + pitchCorrection + yawCorrection; // PB2 BL = throttle + rollCorrection - pitchCorrection - yawCorrection; // PA15 FR = throttle - rollCorrection + pitchCorrection - yawCorrection; // PB10 BR = throttle - rollCorrection - pitchCorrection + yawCorrection; // PA1 } else { FL = throttle + rollCorrection + pitchCorrection - yawCorrection; // PB2 BL = throttle + rollCorrection - pitchCorrection + yawCorrection; // PA15 FR = throttle - rollCorrection + pitchCorrection + yawCorrection; // PB10 BR = throttle - rollCorrection - pitchCorrection - yawCorrection; // PA1 } if (FL > 2000) FL = 2000; else if (FL < 1050) FL = 940; if (BL > 2000) BL = 2000; else if (BL < 1050) BL = 940; if (FR > 2000) FR = 2000; else if (FR < 1050) FR = 940; if (BR > 2000) BR = 2000; else if (BR < 1050) BR = 940; pwm->SetPulse(FL, 3); pwm->SetPulse(BL, 2); pwm->SetPulse(FR, 4); pwm->SetPulse(BR, 1); } else if (status == 2) LEDs::TurnOn(LEDs::Orange); if (throttle < 1050) { pwm->SetPulse(940, 4); pwm->SetPulse(940, 1); pwm->SetPulse(940, 3); pwm->SetPulse(940, 2); reference_yaw = euler_data.z; } esp->Process_Data(); } } void IPD_Callback(uint8_t link_ID, uint8_t *data, uint16_t length) { switch (length) { case 22: if (data[0] == 0x5D) { uint16_t roll_kP, pitch_kP, yaw_kP; uint16_t roll_kI, pitch_kI, yaw_kI; uint16_t roll_kD, pitch_kD, yaw_kD; data_received = true; throttle = data[1] << 8; throttle |= data[2]; roll_kP = data[3] << 8; roll_kP |= data[4]; roll_kI = data[5] << 8; roll_kI |= data[6]; roll_kD = data[7] << 8; roll_kD |= data[8]; PID_Roll.kP(roll_kP / 100.0); PID_Roll.kI(roll_kI / 100.0); PID_Roll.kD(roll_kD / 100.0); pitch_kP = data[9] << 8; pitch_kP |= data[10]; pitch_kI = data[11] << 8; pitch_kI |= data[12]; pitch_kD = data[13] << 8; pitch_kD |= data[14]; PID_Pitch.kP(pitch_kP / 100.0); PID_Pitch.kI(pitch_kI / 100.0); PID_Pitch.kD(pitch_kD / 100.0); yaw_kP = data[15] << 8; yaw_kP |= data[16]; yaw_kI = data[17] << 8; yaw_kI |= data[18]; yaw_kD = data[19] << 8; yaw_kD |= data[20]; PID_Yaw.kP(yaw_kP / 100.0); PID_Yaw.kI(yaw_kI / 100.0); PID_Yaw.kD(yaw_kD / 100.0); inverse_yaw = (data[21] == 0x01); throttle += 1000; } break; case 3: if (data[0] == 0x3D) { start = true; } if (data[0] == 0x5D) { connected = true; log_data = (data[1] == 0x01 ? true : false); } break; } } void Arm_Callback() { esp->Process_Data(); //HAL_IWDG_Refresh(&hiwdg); } void InitI2C(I2C_HandleTypeDef *I2C_Handle) { if (__GPIOB_IS_CLK_DISABLED()) __GPIOB_CLK_ENABLE(); if (__I2C1_IS_CLK_DISABLED()) __I2C1_CLK_ENABLE(); GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.Pin = GPIO_PIN_8 | GPIO_PIN_9; GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF4_I2C1; HAL_GPIO_DeInit(GPIOB, GPIO_PIN_8 | GPIO_PIN_9); HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); I2C_Handle->Instance = I2C1; I2C_Handle->Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; I2C_Handle->Init.ClockSpeed = 400000; I2C_Handle->Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; I2C_Handle->Init.DutyCycle = I2C_DUTYCYCLE_2; I2C_Handle->Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; I2C_Handle->Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; I2C_Handle->Init.OwnAddress1 = 0; I2C_Handle->Init.OwnAddress2 = 0; __HAL_I2C_RESET_HANDLE_STATE(I2C_Handle); if (HAL_I2C_DeInit(I2C_Handle) != HAL_OK) LEDs::TurnOn(LEDs::Orange); if (HAL_I2C_Init(I2C_Handle) != HAL_OK) LEDs::TurnOn(LEDs::Orange); } /*void Calculate() { dt = (HAL_GetTick() - kalman_time) / 1000.0; kalman_time = HAL_GetTick(); roll = atan2(accel_data.y, accel_data.z) * 180 / PI; pitch = atan(-accel_data.x / sqrt(accel_data.y * accel_data.y + accel_data.z * accel_data.z)) * 180 / PI; double gyroXrate = gyro_data.x; double gyroYrate = gyro_data.y; // This fixes the transition problem when the accelerometer angle jumps between -180 and 180 degrees if ((roll < -90 && kalAngleX > 90) || (roll > 90 && kalAngleX < -90)) { kalmanX.setAngle(roll); compAngleX = roll; kalAngleX = roll; gyroXangle = roll; } else kalAngleX = kalmanX.getAngle(roll, gyroXrate, dt); // Calculate the angle using a Kalman filter if (abs(kalAngleX) > 90) gyroYrate = -gyroYrate; // Invert rate, so it fits the restriced accelerometer reading kalAngleY = kalmanY.getAngle(pitch, gyroYrate, dt); gyroXangle += gyroXrate * dt; // Calculate gyro angle without any filter gyroYangle += gyroYrate * dt; //gyroXangle += kalmanX.getRate() * dt; // Calculate gyro angle using the unbiased rate //gyroYangle += kalmanY.getRate() * dt; compAngleX = 0.93 * (compAngleX + gyroXrate * dt) + 0.07 * roll; // Calculate the angle using a Complimentary filter compAngleY = 0.93 * (compAngleY + gyroYrate * dt) + 0.07 * pitch; // Reset the gyro angle when it has drifted too much if (gyroXangle < -180 || gyroXangle > 180) gyroXangle = kalAngleX; if (gyroYangle < -180 || gyroYangle > 180) gyroYangle = kalAngleY; }*/
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "DistributedGeneratedMeshGenerator.h" #include "libmesh/mesh_generation.h" #include "libmesh/string_to_enum.h" #include "libmesh/periodic_boundaries.h" #include "libmesh/periodic_boundary_base.h" #include "libmesh/unstructured_mesh.h" #include "libmesh/partitioner.h" #include "libmesh/metis_csr_graph.h" #include "libmesh/edge_edge2.h" #include "libmesh/edge_edge3.h" #include "libmesh/edge_edge4.h" #include "libmesh/mesh_communication.h" #include "libmesh/remote_elem.h" #include "libmesh/face_quad4.h" #include "libmesh/cell_hex8.h" #include "CastUniquePointer.h" // C++ includes #include <cmath> // provides round, not std::round (see http://www.cplusplus.com/reference/cmath/round/) #ifdef LIBMESH_HAVE_METIS // MIPSPro 7.4.2 gets confused about these nested namespaces #ifdef __sgi #include <cstdarg> #endif namespace Metis { extern "C" { #include "libmesh/ignore_warnings.h" #include "metis.h" #include "libmesh/restore_warnings.h" } } #else #include "libmesh/sfc_partitioner.h" #endif //registerMooseObject("MooseApp", DistributedGeneratedMeshGenerator); template <> InputParameters validParams<DistributedGeneratedMeshGenerator>() { InputParameters params = validParams<MeshGenerator>(); params.addParam<bool>("verbose", false, "Turn on verbose printing for the mesh generation"); MooseEnum elem_types( "EDGE EDGE2 EDGE3 EDGE4 QUAD QUAD4 QUAD8 QUAD9 TRI3 TRI6 HEX HEX8 HEX20 HEX27 TET4 TET10 " "PRISM6 PRISM15 PRISM18 PYRAMID5 PYRAMID13 PYRAMID14"); // no default MooseEnum dims("1=1 2 3"); params.addRequiredParam<MooseEnum>( "dim", dims, "The dimension of the mesh to be generated"); // Make this parameter required params.addParam<dof_id_type>("nx", 1, "Number of elements in the X direction"); params.addParam<dof_id_type>("ny", 1, "Number of elements in the Y direction"); params.addParam<dof_id_type>("nz", 1, "Number of elements in the Z direction"); params.addParam<Real>("xmin", 0.0, "Lower X Coordinate of the generated mesh"); params.addParam<Real>("ymin", 0.0, "Lower Y Coordinate of the generated mesh"); params.addParam<Real>("zmin", 0.0, "Lower Z Coordinate of the generated mesh"); params.addParam<Real>("xmax", 1.0, "Upper X Coordinate of the generated mesh"); params.addParam<Real>("ymax", 1.0, "Upper Y Coordinate of the generated mesh"); params.addParam<Real>("zmax", 1.0, "Upper Z Coordinate of the generated mesh"); params.addParam<MooseEnum>("elem_type", elem_types, "The type of element from libMesh to " "generate (default: linear element for " "requested dimension)"); params.addRangeCheckedParam<Real>( "bias_x", 1., "bias_x>=0.5 & bias_x<=2", "The amount by which to grow (or shrink) the cells in the x-direction."); params.addRangeCheckedParam<Real>( "bias_y", 1., "bias_y>=0.5 & bias_y<=2", "The amount by which to grow (or shrink) the cells in the y-direction."); params.addRangeCheckedParam<Real>( "bias_z", 1., "bias_z>=0.5 & bias_z<=2", "The amount by which to grow (or shrink) the cells in the z-direction."); params.addParamNamesToGroup("dim", "Main"); params.addClassDescription( "Create a line, square, or cube mesh with uniformly spaced or biased elements."); // This mesh is always distributed // params.set<MooseEnum>("parallel_type") = "DISTRIBUTED"; return params; } DistributedGeneratedMeshGenerator::DistributedGeneratedMeshGenerator( const InputParameters & parameters) : MeshGenerator(parameters), _verbose(getParam<bool>("verbose")), _dim(getParam<MooseEnum>("dim")), _nx(getParam<dof_id_type>("nx")), _ny(getParam<dof_id_type>("ny")), _nz(getParam<dof_id_type>("nz")), _xmin(getParam<Real>("xmin")), _xmax(getParam<Real>("xmax")), _ymin(getParam<Real>("ymin")), _ymax(getParam<Real>("ymax")), _zmin(getParam<Real>("zmin")), _zmax(getParam<Real>("zmax")), _bias_x(getParam<Real>("bias_x")), _bias_y(getParam<Real>("bias_y")), _bias_z(getParam<Real>("bias_z")) { } namespace { /** * Get the element ID for a given hex * * @param nx The number of elements in the x direction * @param ny The number of elements in the y direction * @param i The x index of this element * @param j The y index of this element * @param k The z index of this element * @return The ID of the i,j element */ template <typename T> inline dof_id_type elem_id(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type /*i*/, const dof_id_type /*j*/, const dof_id_type /*k*/) { mooseError("elem_id not implemented for this element type in DistributedGeneratedMesh"); } /** * Get the number of neighbors this element will have * * @param nx The number of elements in the x direction * @param ny The number of elements in the y direction * @param nz The number of elements in the z direction * @param i The x index of this element * @param j The y index of this element * @param k The z index of this element * @return The number of neighboring elements */ template <typename T> inline dof_id_type num_neighbors(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const dof_id_type /*i*/, const dof_id_type /*j*/, const dof_id_type /*k*/) { mooseError("num_neighbors not implemented for this element type in DistributedGeneratedMesh"); } /** * Get the IDs of the neighbors of a given element * * @param nx The number of elements in the x direction * @param nx The number of elements in the y direction * @param nz The number of elements in the z direction * @param i The x index of this element * @param j The y index of this element * @param k The z index of this element * @param neighbors This will be filled with the IDs of the two neighbors or invalid_dof_id if there * is no neighbor. THIS MUST be of size 6 BEFORE calling this function */ template <typename T> inline void get_neighbors(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const dof_id_type /*i*/, const dof_id_type /*j*/, const dof_id_type /*k*/, std::vector<dof_id_type> & /*neighbors*/) { mooseError("get_neighbors not implemented for this element type in DistributedGeneratedMesh"); } /** * The ID of the i,j,k node * * @param type The element type * @param nx The number of elements in the x direction * @param nx The number of elements in the y direction * @param nz The number of elements in the z direction * @param i The x index of this node * @param j The y index of this node * @param k The z index of this node */ template <typename T> inline dof_id_type node_id(const ElemType /*type*/, const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type /*i*/, const dof_id_type /*j*/, const dof_id_type /*k*/) { mooseError("node_id not implemented for this element type in DistributedGeneratedMesh"); } /** * Add a node to the mesh * * @param nx The number of elements in the x direction * @param nx The number of elements in the y direction * @param nz The number of elements in the z direction * @param i The x index of this node * @param j The y index of this node * @param k The z index of this node * @param type The element type * @param mesh The mesh to add it to */ template <typename T> Node * add_point(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const dof_id_type /*i*/, const dof_id_type /*j*/, const dof_id_type /*k*/, const ElemType /*type*/, MeshBase & /*mesh*/) { mooseError("add_point not implemented for this element type in DistributedGeneratedMesh"); } /** * Adds an element to the mesh * * @param nx The number of elements in the x direction * @param ny The number of elements in the y direction * @param nz The number of elements in the z direction * @param i The x index of this element * @param j The y index of this element * @param k The z index of this element * @param elem_id The element ID of the element to add * @param pid The processor ID to assign it to * @param type The type of element to add * @param mesh The mesh to add it to * @param verbose Whether or not to print out verbose statements */ template <typename T> void add_element(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const dof_id_type /*i*/, const dof_id_type /*j*/, const dof_id_type /*k*/, const dof_id_type /*elem_id*/, const processor_id_type /*pid*/, const ElemType /*type*/, MeshBase & /*mesh*/, bool /*verbose*/) { mooseError("add_element not implemented for this element type in DistributedGeneratedMesh"); } /** * Compute the i,j,k indices of a given element ID * * @param nx The number of elements in the x direction * @param ny The number of elements in the y direction * @param elem_id The ID of the element * @param i Output: The index in the x direction * @param j Output: The index in the y direction * @param k Output: The index in the z direction */ template <typename T> inline void get_indices(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type /*elem_id*/, dof_id_type & /*i*/, dof_id_type & /*j*/, dof_id_type & /*k*/) { mooseError("get_indices not implemented for this element type in DistributedGeneratedMesh"); } /** * Find the elements and sides that need ghost elements * * @param nx The number of elements in the x direction * @param ny The number of elements in the y direction * @param mesh The mesh - without any ghost elements * @param ghost_elems The ghost elems that need to be added */ template <typename T> inline void get_ghost_neighbors(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const MeshBase & /*mesh*/, std::set<dof_id_type> & /*ghost_elems*/) { mooseError( "get_ghost_neighbors not implemented for this element type in DistributedGeneratedMesh"); } /** * Set the boundary names for any added boundary ideas * * @boundary_info The BoundaryInfo object to set the boundary names on */ template <typename T> void set_boundary_names(BoundaryInfo & /*boundary_info*/) { mooseError( "set_boundary_names not implemented for this element type in DistributedGeneratedMesh"); } /** * All meshes are generated on the unit square. This function stretches the mesh * out to fill the correct area. */ template <typename T> void scale_nodal_positions(dof_id_type /*nx*/, dof_id_type /*ny*/, dof_id_type /*nz*/, Real /*xmin*/, Real /*xmax*/, Real /*ymin*/, Real /*ymax*/, Real /*zmin*/, Real /*zmax*/, MeshBase & /*mesh*/) { mooseError( "scale_nodal_positions not implemented for this element type in DistributedGeneratedMesh"); } template <> inline dof_id_type num_neighbors<Edge2>(const dof_id_type nx, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const dof_id_type i, const dof_id_type /*j*/, const dof_id_type /*k*/) { // The ends only have one neighbor if (i == 0 || i == nx - 1) return 1; return 2; } template <> inline void get_neighbors<Edge2>(const dof_id_type nx, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const dof_id_type i, const dof_id_type /*j*/, const dof_id_type /*k*/, std::vector<dof_id_type> & neighbors) { neighbors[0] = i - 1; neighbors[1] = i + 1; // First element doesn't have a left neighbor if (i == 0) neighbors[0] = Elem::invalid_id; // Last element doesn't have a right neighbor if (i == nx - 1) neighbors[1] = Elem::invalid_id; } template <> inline void get_indices<Edge2>(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type elem_id, dof_id_type & i, dof_id_type & /*j*/, dof_id_type & /*k*/) { i = elem_id; } template <> inline void get_ghost_neighbors<Edge2>(const dof_id_type nx, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const MeshBase & mesh, std::set<dof_id_type> & ghost_elems) { auto & boundary_info = mesh.get_boundary_info(); std::vector<dof_id_type> neighbors(2); for (auto elem_ptr : mesh.element_ptr_range()) { for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) { // No current neighbor if (!elem_ptr->neighbor_ptr(s)) { // Not on a boundary if (!boundary_info.n_boundary_ids(elem_ptr, s)) { get_neighbors<Edge2>(nx, 0, 0, elem_ptr->id(), 0, 0, neighbors); ghost_elems.insert(neighbors[s]); } } } } } template <> inline dof_id_type elem_id<Edge2>(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type i, const dof_id_type /*j*/, const dof_id_type /*k*/) { return i; } template <> void add_element<Edge2>(const dof_id_type nx, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const dof_id_type /*i*/, const dof_id_type /*j*/, const dof_id_type /*k*/, const dof_id_type elem_id, const processor_id_type pid, const ElemType /*type*/, MeshBase & mesh, bool verbose) { BoundaryInfo & boundary_info = mesh.get_boundary_info(); if (verbose) Moose::out << "Adding elem: " << elem_id << " pid: " << pid << std::endl; auto node_offset = elem_id; auto node0_ptr = mesh.add_point(Point(static_cast<Real>(node_offset) / nx, 0, 0), node_offset); node0_ptr->set_unique_id() = node_offset; auto node1_ptr = mesh.add_point(Point(static_cast<Real>(node_offset + 1) / nx, 0, 0), node_offset + 1); node1_ptr->set_unique_id() = node_offset + 1; if (verbose) Moose::out << "Adding elem: " << elem_id << std::endl; Elem * elem = new Edge2; elem->set_id(elem_id); elem->processor_id() = pid; elem->set_unique_id() = elem_id; elem = mesh.add_elem(elem); elem->set_node(0) = node0_ptr; elem->set_node(1) = node1_ptr; if (elem_id == 0) boundary_info.add_side(elem, 0, 0); if (elem_id == nx - 1) boundary_info.add_side(elem, 1, 1); } template <> void set_boundary_names<Edge2>(BoundaryInfo & boundary_info) { boundary_info.sideset_name(0) = "left"; boundary_info.sideset_name(1) = "right"; } template <> void scale_nodal_positions<Edge2>(dof_id_type /*nx*/, dof_id_type /*ny*/, dof_id_type /*nz*/, Real xmin, Real xmax, Real /*ymin*/, Real /*ymax*/, Real /*zmin*/, Real /*zmax*/, MeshBase & mesh) { for (auto & node_ptr : mesh.node_ptr_range()) (*node_ptr)(0) = (*node_ptr)(0) * (xmax - xmin) + xmin; } template <> inline dof_id_type num_neighbors<Quad4>(const dof_id_type nx, const dof_id_type ny, const dof_id_type /*nz*/, const dof_id_type i, const dof_id_type j, const dof_id_type /*k*/) { dof_id_type n = 4; if (i == 0) n--; if (i == nx - 1) n--; if (j == 0) n--; if (j == ny - 1) n--; return n; } template <> inline dof_id_type elem_id<Quad4>(const dof_id_type nx, const dof_id_type /*nx*/, const dof_id_type i, const dof_id_type j, const dof_id_type /*k*/) { return (j * nx) + i; } template <> inline void get_neighbors<Quad4>(const dof_id_type nx, const dof_id_type ny, const dof_id_type /*nz*/, const dof_id_type i, const dof_id_type j, const dof_id_type /*k*/, std::vector<dof_id_type> & neighbors) { std::fill(neighbors.begin(), neighbors.end(), Elem::invalid_id); // Bottom if (j != 0) neighbors[0] = elem_id<Quad4>(nx, 0, i, j - 1, 0); // Right if (i != nx - 1) neighbors[1] = elem_id<Quad4>(nx, 0, i + 1, j, 0); // Top if (j != ny - 1) neighbors[2] = elem_id<Quad4>(nx, 0, i, j + 1, 0); // Left if (i != 0) neighbors[3] = elem_id<Quad4>(nx, 0, i - 1, j, 0); } template <> inline void get_indices<Quad4>(const dof_id_type nx, const dof_id_type /*ny*/, const dof_id_type elem_id, dof_id_type & i, dof_id_type & j, dof_id_type & /*k*/) { i = elem_id % nx; j = (elem_id - i) / nx; } template <> inline void get_ghost_neighbors<Quad4>(const dof_id_type nx, const dof_id_type ny, const dof_id_type /*nz*/, const MeshBase & mesh, std::set<dof_id_type> & ghost_elems) { auto & boundary_info = mesh.get_boundary_info(); dof_id_type i, j, k; std::vector<dof_id_type> neighbors(4); for (auto elem_ptr : mesh.element_ptr_range()) { for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) { // No current neighbor if (!elem_ptr->neighbor_ptr(s)) { // Not on a boundary if (!boundary_info.n_boundary_ids(elem_ptr, s)) { auto elem_id = elem_ptr->id(); get_indices<Quad4>(nx, 0, elem_id, i, j, k); get_neighbors<Quad4>(nx, ny, 0, i, j, 0, neighbors); ghost_elems.insert(neighbors[s]); } } } } } template <> inline dof_id_type node_id<Quad4>(const ElemType /*type*/, const dof_id_type nx, const dof_id_type /*ny*/, const dof_id_type i, const dof_id_type j, const dof_id_type /*k*/) { return i + j * (nx + 1); } template <> void add_element<Quad4>(const dof_id_type nx, const dof_id_type ny, const dof_id_type /*nz*/, const dof_id_type i, const dof_id_type j, const dof_id_type /*k*/, const dof_id_type elem_id, const processor_id_type pid, const ElemType type, MeshBase & mesh, bool verbose) { BoundaryInfo & boundary_info = mesh.get_boundary_info(); if (verbose) Moose::out << "Adding elem: " << elem_id << " pid: " << pid << std::endl; // Bottom Left auto node0_ptr = mesh.add_point(Point(static_cast<Real>(i) / nx, static_cast<Real>(j) / ny, 0), node_id<Quad4>(type, nx, 0, i, j, 0)); node0_ptr->set_unique_id() = node_id<Quad4>(type, nx, 0, i, j, 0); // Bottom Right auto node1_ptr = mesh.add_point(Point(static_cast<Real>(i + 1) / nx, static_cast<Real>(j) / ny, 0), node_id<Quad4>(type, nx, 0, i + 1, j, 0)); node1_ptr->set_unique_id() = node_id<Quad4>(type, nx, 0, i + 1, j, 0); // Top Right auto node2_ptr = mesh.add_point(Point(static_cast<Real>(i + 1) / nx, static_cast<Real>(j + 1) / ny, 0), node_id<Quad4>(type, nx, 0, i + 1, j + 1, 0)); node2_ptr->set_unique_id() = node_id<Quad4>(type, nx, 0, i + 1, j + 1, 0); // Top Left auto node3_ptr = mesh.add_point(Point(static_cast<Real>(i) / nx, static_cast<Real>(j + 1) / ny, 0), node_id<Quad4>(type, nx, 0, i, j + 1, 0)); node3_ptr->set_unique_id() = node_id<Quad4>(type, nx, 0, i, j + 1, 0); Elem * elem = new Quad4; elem->set_id(elem_id); elem->processor_id() = pid; elem->set_unique_id() = elem_id; elem = mesh.add_elem(elem); elem->set_node(0) = node0_ptr; elem->set_node(1) = node1_ptr; elem->set_node(2) = node2_ptr; elem->set_node(3) = node3_ptr; // Bottom if (j == 0) boundary_info.add_side(elem, 0, 0); // Right if (i == nx - 1) boundary_info.add_side(elem, 1, 1); // Top if (j == ny - 1) boundary_info.add_side(elem, 2, 2); // Left if (i == 0) boundary_info.add_side(elem, 3, 3); } template <> void set_boundary_names<Quad4>(BoundaryInfo & boundary_info) { boundary_info.sideset_name(0) = "bottom"; boundary_info.sideset_name(1) = "right"; boundary_info.sideset_name(2) = "top"; boundary_info.sideset_name(3) = "left"; } template <> void scale_nodal_positions<Quad4>(dof_id_type /*nx*/, dof_id_type /*ny*/, dof_id_type /*nz*/, Real xmin, Real xmax, Real ymin, Real ymax, Real /*zmin*/, Real /*zmax*/, MeshBase & mesh) { for (auto & node_ptr : mesh.node_ptr_range()) { (*node_ptr)(0) = (*node_ptr)(0) * (xmax - xmin) + xmin; (*node_ptr)(1) = (*node_ptr)(1) * (ymax - ymin) + ymin; } } template <> inline dof_id_type elem_id<Hex8>(const dof_id_type nx, const dof_id_type ny, const dof_id_type i, const dof_id_type j, const dof_id_type k) { return i + (j * nx) + (k * nx * ny); } template <> inline dof_id_type num_neighbors<Hex8>(const dof_id_type nx, const dof_id_type ny, const dof_id_type nz, const dof_id_type i, const dof_id_type j, const dof_id_type k) { dof_id_type n = 6; if (i == 0) n--; if (i == nx - 1) n--; if (j == 0) n--; if (j == ny - 1) n--; if (k == 0) n--; if (k == nz - 1) n--; return n; } template <> inline void get_neighbors<Hex8>(const dof_id_type nx, const dof_id_type ny, const dof_id_type nz, const dof_id_type i, const dof_id_type j, const dof_id_type k, std::vector<dof_id_type> & neighbors) { std::fill(neighbors.begin(), neighbors.end(), Elem::invalid_id); // Back if (k != 0) neighbors[0] = elem_id<Hex8>(nx, ny, i, j, k - 1); // Bottom if (j != 0) neighbors[1] = elem_id<Hex8>(nx, ny, i, j - 1, k); // Right if (i != nx - 1) neighbors[2] = elem_id<Hex8>(nx, ny, i + 1, j, k); // Top if (j != ny - 1) neighbors[3] = elem_id<Hex8>(nx, ny, i, j + 1, k); // Left if (i != 0) neighbors[4] = elem_id<Hex8>(nx, ny, i - 1, j, k); // Front if (k != nz - 1) neighbors[5] = elem_id<Hex8>(nx, ny, i, j, k + 1); } template <> inline dof_id_type node_id<Hex8>(const ElemType /*type*/, const dof_id_type nx, const dof_id_type ny, const dof_id_type i, const dof_id_type j, const dof_id_type k) { return i + (nx + 1) * (j + k * (ny + 1)); } template <> Node * add_point<Hex8>(const dof_id_type nx, const dof_id_type ny, const dof_id_type nz, const dof_id_type i, const dof_id_type j, const dof_id_type k, const ElemType type, MeshBase & mesh) { auto id = node_id<Hex8>(type, nx, ny, i, j, k); auto node_ptr = mesh.add_point( Point(static_cast<Real>(i) / nx, static_cast<Real>(j) / ny, static_cast<Real>(k) / nz), id); node_ptr->set_unique_id() = id; return node_ptr; } template <> void add_element<Hex8>(const dof_id_type nx, const dof_id_type ny, const dof_id_type nz, const dof_id_type i, const dof_id_type j, const dof_id_type k, const dof_id_type elem_id, const processor_id_type pid, const ElemType type, MeshBase & mesh, bool verbose) { BoundaryInfo & boundary_info = mesh.get_boundary_info(); if (verbose) { Moose::out << "Adding elem: " << elem_id << " pid: " << pid << std::endl; Moose::out << "Type: " << type << " " << HEX8 << std::endl; } // This ordering was picked to match the ordering in mesh_generation.C auto node0_ptr = add_point<Hex8>(nx, ny, nz, i, j, k, type, mesh); auto node1_ptr = add_point<Hex8>(nx, ny, nz, i + 1, j, k, type, mesh); auto node2_ptr = add_point<Hex8>(nx, ny, nz, i + 1, j + 1, k, type, mesh); auto node3_ptr = add_point<Hex8>(nx, ny, nz, i, j + 1, k, type, mesh); auto node4_ptr = add_point<Hex8>(nx, ny, nz, i, j, k + 1, type, mesh); auto node5_ptr = add_point<Hex8>(nx, ny, nz, i + 1, j, k + 1, type, mesh); auto node6_ptr = add_point<Hex8>(nx, ny, nz, i + 1, j + 1, k + 1, type, mesh); auto node7_ptr = add_point<Hex8>(nx, ny, nz, i, j + 1, k + 1, type, mesh); Elem * elem = new Hex8; elem->set_id(elem_id); elem->processor_id() = pid; elem->set_unique_id() = elem_id; elem = mesh.add_elem(elem); elem->set_node(0) = node0_ptr; elem->set_node(1) = node1_ptr; elem->set_node(2) = node2_ptr; elem->set_node(3) = node3_ptr; elem->set_node(4) = node4_ptr; elem->set_node(5) = node5_ptr; elem->set_node(6) = node6_ptr; elem->set_node(7) = node7_ptr; if (k == 0) boundary_info.add_side(elem, 0, 0); if (k == (nz - 1)) boundary_info.add_side(elem, 5, 5); if (j == 0) boundary_info.add_side(elem, 1, 1); if (j == (ny - 1)) boundary_info.add_side(elem, 3, 3); if (i == 0) boundary_info.add_side(elem, 4, 4); if (i == (nx - 1)) boundary_info.add_side(elem, 2, 2); } template <> inline void get_indices<Hex8>(const dof_id_type nx, const dof_id_type ny, const dof_id_type elem_id, dof_id_type & i, dof_id_type & j, dof_id_type & k) { i = elem_id % nx; j = (((elem_id - i) / nx) % ny); k = ((elem_id - i) - (j * nx)) / (nx * ny); } template <> inline void get_ghost_neighbors<Hex8>(const dof_id_type nx, const dof_id_type ny, const dof_id_type nz, const MeshBase & mesh, std::set<dof_id_type> & ghost_elems) { auto & boundary_info = mesh.get_boundary_info(); dof_id_type i, j, k; std::vector<dof_id_type> neighbors(6); for (auto elem_ptr : mesh.element_ptr_range()) { for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) { // No current neighbor if (!elem_ptr->neighbor_ptr(s)) { // Not on a boundary if (!boundary_info.n_boundary_ids(elem_ptr, s)) { auto elem_id = elem_ptr->id(); get_indices<Hex8>(nx, ny, elem_id, i, j, k); get_neighbors<Hex8>(nx, ny, nz, i, j, k, neighbors); ghost_elems.insert(neighbors[s]); } } } } } template <> void set_boundary_names<Hex8>(BoundaryInfo & boundary_info) { boundary_info.sideset_name(0) = "back"; boundary_info.sideset_name(1) = "bottom"; boundary_info.sideset_name(2) = "right"; boundary_info.sideset_name(3) = "top"; boundary_info.sideset_name(4) = "left"; boundary_info.sideset_name(5) = "front"; } template <> void scale_nodal_positions<Hex8>(dof_id_type /*nx*/, dof_id_type /*ny*/, dof_id_type /*nz*/, Real xmin, Real xmax, Real ymin, Real ymax, Real zmin, Real zmax, MeshBase & mesh) { for (auto & node_ptr : mesh.node_ptr_range()) { (*node_ptr)(0) = (*node_ptr)(0) * (xmax - xmin) + xmin; (*node_ptr)(1) = (*node_ptr)(1) * (ymax - ymin) + ymin; (*node_ptr)(2) = (*node_ptr)(2) * (zmax - zmin) + zmin; } } } template <typename T> void build_cube(UnstructuredMesh & mesh, const unsigned int nx, unsigned int ny, unsigned int nz, const Real xmin, const Real xmax, const Real ymin, const Real ymax, const Real zmin, const Real zmax, const ElemType type, bool verbose) { if (verbose) Moose::out << "nx: " << nx << "\n ny: " << ny << "\n nz: " << nz << std::endl; /// Here's the plan: /// 1. Create a (dual) graph of the elements /// 2. Partition the graph /// 3. The partitioning tells this processsor which elements to create dof_id_type num_elems = nx * ny * nz; const auto n_pieces = mesh.comm().size(); const auto pid = mesh.comm().rank(); std::unique_ptr<Elem> canonical_elem = libmesh_make_unique<T>(); // Will get used to find the neighbors of an element std::vector<dof_id_type> neighbors(canonical_elem->n_neighbors()); // Data structure that Metis will fill up on processor 0 and broadcast. std::vector<Metis::idx_t> part(num_elems); if (mesh.processor_id() == 0) { // Data structures and parameters needed only on processor 0 by Metis. // std::vector<Metis::idx_t> options(5); // Weight by the number of nodes std::vector<Metis::idx_t> vwgt(num_elems, canonical_elem->n_nodes()); Metis::idx_t n = num_elems, // number of "nodes" (elements) in the graph nparts = n_pieces, // number of subdomains to create edgecut = 0; // the numbers of edges cut by the resulting partition METIS_CSR_Graph<Metis::idx_t> csr_graph; csr_graph.offsets.resize(num_elems + 1, 0); for (dof_id_type k = 0; k < nz; k++) { for (dof_id_type j = 0; j < ny; j++) { for (dof_id_type i = 0; i < nx; i++) { auto n_neighbors = num_neighbors<T>(nx, ny, nz, i, j, k); auto e_id = elem_id<T>(nx, ny, i, j, k); if (verbose) Moose::out << e_id << " num_neighbors: " << n_neighbors << std::endl; csr_graph.prep_n_nonzeros(e_id, n_neighbors); } } } csr_graph.prepare_for_use(); if (verbose) for (auto offset : csr_graph.offsets) Moose::out << "offset: " << offset << std::endl; for (dof_id_type k = 0; k < nz; k++) { for (dof_id_type j = 0; j < ny; j++) { for (dof_id_type i = 0; i < nx; i++) { auto e_id = elem_id<T>(nx, ny, i, j, k); dof_id_type connection = 0; get_neighbors<T>(nx, ny, nz, i, j, k, neighbors); for (auto neighbor : neighbors) { if (neighbor != Elem::invalid_id) { if (verbose) Moose::out << e_id << ": " << connection << " = " << neighbor << std::endl; csr_graph(e_id, connection++) = neighbor; } } } } } if (n_pieces == 1) { // Just assign them all to proc 0 for (auto & elem_pid : part) elem_pid = 0; } else { Metis::idx_t ncon = 1; // Use recursive if the number of partitions is less than or equal to 8 if (n_pieces <= 8) Metis::METIS_PartGraphRecursive(&n, &ncon, &csr_graph.offsets[0], &csr_graph.vals[0], &vwgt[0], libmesh_nullptr, libmesh_nullptr, &nparts, libmesh_nullptr, libmesh_nullptr, libmesh_nullptr, &edgecut, &part[0]); // Otherwise use kway else Metis::METIS_PartGraphKway(&n, &ncon, &csr_graph.offsets[0], &csr_graph.vals[0], &vwgt[0], libmesh_nullptr, libmesh_nullptr, &nparts, libmesh_nullptr, libmesh_nullptr, libmesh_nullptr, &edgecut, &part[0]); } } // end processor 0 part // Broadcast the resulting partition mesh.comm().broadcast(part); if (verbose) for (auto proc_id : part) Moose::out << "Part: " << proc_id << std::endl; BoundaryInfo & boundary_info = mesh.get_boundary_info(); // Add elements this processor owns for (dof_id_type k = 0; k < nz; k++) { for (dof_id_type j = 0; j < ny; j++) { for (dof_id_type i = 0; i < nx; i++) { auto e_id = elem_id<Hex8>(nx, ny, i, j, k); if (static_cast<processor_id_type>(part[e_id]) == pid) add_element<T>(nx, ny, nz, i, j, k, e_id, pid, type, mesh, verbose); } } } if (verbose) for (auto & elem_ptr : mesh.element_ptr_range()) for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) Moose::out << "Elem neighbor: " << elem_ptr->neighbor_ptr(s) << " is remote " << (elem_ptr->neighbor_ptr(s) == remote_elem) << std::endl; // Need to link up the local elements before we can know what's missing mesh.find_neighbors(); if (verbose) Moose::out << "After first find_neighbors" << std::endl; if (verbose) for (auto & elem_ptr : mesh.element_ptr_range()) for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) Moose::out << "Elem neighbor: " << elem_ptr->neighbor_ptr(s) << " is remote " << (elem_ptr->neighbor_ptr(s) == remote_elem) << std::endl; // Get the ghosts (missing face neighbors) std::set<dof_id_type> ghost_elems; get_ghost_neighbors<T>(nx, ny, nz, mesh, ghost_elems); // Add the ghosts to the mesh for (auto & ghost_id : ghost_elems) { dof_id_type i = 0; dof_id_type j = 0; dof_id_type k = 0; get_indices<T>(nx, ny, ghost_id, i, j, k); add_element<T>(nx, ny, nz, i, j, k, ghost_id, part[ghost_id], type, mesh, verbose); } if (verbose) Moose::out << "After adding ghosts" << std::endl; if (verbose) for (auto & elem_ptr : mesh.element_ptr_range()) for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) Moose::out << "Elem neighbor: " << elem_ptr->neighbor_ptr(s) << " is remote " << (elem_ptr->neighbor_ptr(s) == remote_elem) << std::endl; mesh.find_neighbors(true); if (verbose) Moose::out << "After second find neighbors " << std::endl; if (verbose) for (auto & elem_ptr : mesh.element_ptr_range()) for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) Moose::out << "Elem neighbor: " << elem_ptr->neighbor_ptr(s) << " is remote " << (elem_ptr->neighbor_ptr(s) == remote_elem) << std::endl; // Set RemoteElem neighbors for (auto & elem_ptr : mesh.element_ptr_range()) for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) if (!elem_ptr->neighbor_ptr(s) && !boundary_info.n_boundary_ids(elem_ptr, s)) elem_ptr->set_neighbor(s, const_cast<RemoteElem *>(remote_elem)); if (verbose) Moose::out << "After adding remote elements" << std::endl; if (verbose) for (auto & elem_ptr : mesh.element_ptr_range()) for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) Moose::out << "Elem neighbor: " << elem_ptr->neighbor_ptr(s) << " is remote " << (elem_ptr->neighbor_ptr(s) == remote_elem) << std::endl; set_boundary_names<T>(boundary_info); Partitioner::set_node_processor_ids(mesh); if (verbose) Moose::out << "mesh dim: " << mesh.mesh_dimension() << std::endl; if (verbose) for (auto & node_ptr : mesh.node_ptr_range()) Moose::out << node_ptr->id() << ":" << node_ptr->processor_id() << std::endl; // Already partitioned! mesh.skip_partitioning(true); if (verbose) for (auto & elem_ptr : mesh.element_ptr_range()) Moose::out << "Elem: " << elem_ptr->id() << " pid: " << elem_ptr->processor_id() << " uid: " << elem_ptr->unique_id() << std::endl; if (verbose) Moose::out << "Getting ready to prepare for use" << std::endl; // No need to renumber or find neighbors - done did it. // Avoid deprecation message/error by _also_ setting // allow_renumbering(false). This is a bit silly, but we want to // catch cases where people are purely using the old "skip" // interface and not the new flag setting one. mesh.allow_renumbering(false); mesh.prepare_for_use(/*skip_renumber (ignored!) = */ false, /*skip_find_neighbors = */ true); if (verbose) for (auto & elem_ptr : mesh.element_ptr_range()) Moose::out << "Elem: " << elem_ptr->id() << " pid: " << elem_ptr->processor_id() << std::endl; if (verbose) for (auto & node_ptr : mesh.node_ptr_range()) Moose::out << node_ptr->id() << ":" << node_ptr->processor_id() << std::endl; if (verbose) Moose::out << "mesh dim: " << mesh.mesh_dimension() << std::endl; // Scale the nodal positions scale_nodal_positions<T>(nx, ny, nz, xmin, xmax, ymin, ymax, zmin, zmax, mesh); if (verbose) mesh.print_info(); } std::unique_ptr<MeshBase> DistributedGeneratedMeshGenerator::generate() { std::unique_ptr<ReplicatedMesh> mesh = libmesh_make_unique<ReplicatedMesh>(comm(), 2); MooseEnum elem_type_enum = getParam<MooseEnum>("elem_type"); if (!isParamValid("elem_type")) { // Switching on MooseEnum switch (_dim) { case 1: elem_type_enum = "EDGE2"; break; case 2: elem_type_enum = "QUAD4"; break; case 3: elem_type_enum = "HEX8"; break; } } _elem_type = Utility::string_to_enum<ElemType>(elem_type_enum); mesh->set_mesh_dimension(_dim); mesh->set_spatial_dimension(_dim); // Switching on MooseEnum switch (_dim) { // The build_XYZ mesh generation functions take an // UnstructuredMesh& as the first argument, hence the dynamic_cast. case 1: build_cube<Edge2>(static_cast<UnstructuredMesh &>(*mesh), _nx, 1, 1, _xmin, _xmax, 0, 0, 0, 0, _elem_type, _verbose); break; case 2: build_cube<Quad4>(static_cast<UnstructuredMesh &>(*mesh), _nx, _ny, 1, _xmin, _xmax, _ymin, _ymax, 0, 0, _elem_type, _verbose); break; case 3: build_cube<Hex8>(static_cast<UnstructuredMesh &>(*mesh), _nx, _ny, _nz, _xmin, _xmax, _ymin, _ymax, _zmin, _zmax, _elem_type, _verbose); break; default: mooseError(getParam<MooseEnum>("elem_type"), " is not a currently supported element type for DistributedGeneratedMesh"); } // Apply the bias if any exists if (_bias_x != 1.0 || _bias_y != 1.0 || _bias_z != 1.0) { // Biases Real bias[3] = {_bias_x, _bias_y, _bias_z}; // "width" of the mesh in each direction Real width[3] = {_xmax - _xmin, _ymax - _ymin, _zmax - _zmin}; // Min mesh extent in each direction. Real mins[3] = {_xmin, _ymin, _zmin}; // Number of elements in each direction. dof_id_type nelem[3] = {_nx, _ny, _nz}; // We will need the biases raised to integer powers in each // direction, so let's pre-compute those... std::vector<std::vector<Real>> pows(LIBMESH_DIM); for (dof_id_type dir = 0; dir < LIBMESH_DIM; ++dir) { pows[dir].resize(nelem[dir] + 1); for (dof_id_type i = 0; i < pows[dir].size(); ++i) pows[dir][i] = std::pow(bias[dir], static_cast<int>(i)); } // Loop over the nodes and move them to the desired location for (auto & node_ptr : mesh->node_ptr_range()) { Node & node = *node_ptr; for (dof_id_type dir = 0; dir < LIBMESH_DIM; ++dir) { if (width[dir] != 0. && bias[dir] != 1.) { // Compute the scaled "index" of the current point. This // will either be close to a whole integer or a whole // integer+0.5 for quadratic nodes. Real float_index = (node(dir) - mins[dir]) * nelem[dir] / width[dir]; Real integer_part = 0; Real fractional_part = std::modf(float_index, &integer_part); // Figure out where to move the node... if (std::abs(fractional_part) < TOLERANCE || std::abs(fractional_part - 1.0) < TOLERANCE) { // If the fractional_part ~ 0.0 or 1.0, this is a vertex node, so // we don't need an average. // // Compute the "index" we are at in the current direction. We // round to the nearest integral value to get this instead // of using "integer_part", since that could be off by a // lot (e.g. we want 3.9999 to map to 4.0 instead of 3.0). int index = round(float_index); // Move node to biased location. node(dir) = mins[dir] + width[dir] * (1. - pows[dir][index]) / (1. - pows[dir][nelem[dir]]); } else if (std::abs(fractional_part - 0.5) < TOLERANCE) { // If the fractional_part ~ 0.5, this is a midedge/face // (i.e. quadratic) node. We don't move those with the same // bias as the vertices, instead we put them midway between // their respective vertices. // // Also, since the fractional part is nearly 0.5, we know that // the integer_part will be the index of the vertex to the // left, and integer_part+1 will be the index of the // vertex to the right. node(dir) = mins[dir] + width[dir] * (1. - 0.5 * (pows[dir][integer_part] + pows[dir][integer_part + 1])) / (1. - pows[dir][nelem[dir]]); } else { // We don't yet handle anything higher order than quadratic... mooseError("Unable to bias node at node(", dir, ")=", node(dir)); } } } } } return dynamic_pointer_cast<MeshBase>(mesh); } Applay clang-format. Refs #12409. //* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "DistributedGeneratedMeshGenerator.h" #include "libmesh/mesh_generation.h" #include "libmesh/string_to_enum.h" #include "libmesh/periodic_boundaries.h" #include "libmesh/periodic_boundary_base.h" #include "libmesh/unstructured_mesh.h" #include "libmesh/partitioner.h" #include "libmesh/metis_csr_graph.h" #include "libmesh/edge_edge2.h" #include "libmesh/edge_edge3.h" #include "libmesh/edge_edge4.h" #include "libmesh/mesh_communication.h" #include "libmesh/remote_elem.h" #include "libmesh/face_quad4.h" #include "libmesh/cell_hex8.h" #include "CastUniquePointer.h" // C++ includes #include <cmath> // provides round, not std::round (see http://www.cplusplus.com/reference/cmath/round/) #ifdef LIBMESH_HAVE_METIS // MIPSPro 7.4.2 gets confused about these nested namespaces #ifdef __sgi #include <cstdarg> #endif namespace Metis { extern "C" { #include "libmesh/ignore_warnings.h" #include "metis.h" #include "libmesh/restore_warnings.h" } } #else #include "libmesh/sfc_partitioner.h" #endif // registerMooseObject("MooseApp", DistributedGeneratedMeshGenerator); template <> InputParameters validParams<DistributedGeneratedMeshGenerator>() { InputParameters params = validParams<MeshGenerator>(); params.addParam<bool>("verbose", false, "Turn on verbose printing for the mesh generation"); MooseEnum elem_types( "EDGE EDGE2 EDGE3 EDGE4 QUAD QUAD4 QUAD8 QUAD9 TRI3 TRI6 HEX HEX8 HEX20 HEX27 TET4 TET10 " "PRISM6 PRISM15 PRISM18 PYRAMID5 PYRAMID13 PYRAMID14"); // no default MooseEnum dims("1=1 2 3"); params.addRequiredParam<MooseEnum>( "dim", dims, "The dimension of the mesh to be generated"); // Make this parameter required params.addParam<dof_id_type>("nx", 1, "Number of elements in the X direction"); params.addParam<dof_id_type>("ny", 1, "Number of elements in the Y direction"); params.addParam<dof_id_type>("nz", 1, "Number of elements in the Z direction"); params.addParam<Real>("xmin", 0.0, "Lower X Coordinate of the generated mesh"); params.addParam<Real>("ymin", 0.0, "Lower Y Coordinate of the generated mesh"); params.addParam<Real>("zmin", 0.0, "Lower Z Coordinate of the generated mesh"); params.addParam<Real>("xmax", 1.0, "Upper X Coordinate of the generated mesh"); params.addParam<Real>("ymax", 1.0, "Upper Y Coordinate of the generated mesh"); params.addParam<Real>("zmax", 1.0, "Upper Z Coordinate of the generated mesh"); params.addParam<MooseEnum>("elem_type", elem_types, "The type of element from libMesh to " "generate (default: linear element for " "requested dimension)"); params.addRangeCheckedParam<Real>( "bias_x", 1., "bias_x>=0.5 & bias_x<=2", "The amount by which to grow (or shrink) the cells in the x-direction."); params.addRangeCheckedParam<Real>( "bias_y", 1., "bias_y>=0.5 & bias_y<=2", "The amount by which to grow (or shrink) the cells in the y-direction."); params.addRangeCheckedParam<Real>( "bias_z", 1., "bias_z>=0.5 & bias_z<=2", "The amount by which to grow (or shrink) the cells in the z-direction."); params.addParamNamesToGroup("dim", "Main"); params.addClassDescription( "Create a line, square, or cube mesh with uniformly spaced or biased elements."); // This mesh is always distributed // params.set<MooseEnum>("parallel_type") = "DISTRIBUTED"; return params; } DistributedGeneratedMeshGenerator::DistributedGeneratedMeshGenerator( const InputParameters & parameters) : MeshGenerator(parameters), _verbose(getParam<bool>("verbose")), _dim(getParam<MooseEnum>("dim")), _nx(getParam<dof_id_type>("nx")), _ny(getParam<dof_id_type>("ny")), _nz(getParam<dof_id_type>("nz")), _xmin(getParam<Real>("xmin")), _xmax(getParam<Real>("xmax")), _ymin(getParam<Real>("ymin")), _ymax(getParam<Real>("ymax")), _zmin(getParam<Real>("zmin")), _zmax(getParam<Real>("zmax")), _bias_x(getParam<Real>("bias_x")), _bias_y(getParam<Real>("bias_y")), _bias_z(getParam<Real>("bias_z")) { } namespace { /** * Get the element ID for a given hex * * @param nx The number of elements in the x direction * @param ny The number of elements in the y direction * @param i The x index of this element * @param j The y index of this element * @param k The z index of this element * @return The ID of the i,j element */ template <typename T> inline dof_id_type elem_id(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type /*i*/, const dof_id_type /*j*/, const dof_id_type /*k*/) { mooseError("elem_id not implemented for this element type in DistributedGeneratedMesh"); } /** * Get the number of neighbors this element will have * * @param nx The number of elements in the x direction * @param ny The number of elements in the y direction * @param nz The number of elements in the z direction * @param i The x index of this element * @param j The y index of this element * @param k The z index of this element * @return The number of neighboring elements */ template <typename T> inline dof_id_type num_neighbors(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const dof_id_type /*i*/, const dof_id_type /*j*/, const dof_id_type /*k*/) { mooseError("num_neighbors not implemented for this element type in DistributedGeneratedMesh"); } /** * Get the IDs of the neighbors of a given element * * @param nx The number of elements in the x direction * @param nx The number of elements in the y direction * @param nz The number of elements in the z direction * @param i The x index of this element * @param j The y index of this element * @param k The z index of this element * @param neighbors This will be filled with the IDs of the two neighbors or invalid_dof_id if there * is no neighbor. THIS MUST be of size 6 BEFORE calling this function */ template <typename T> inline void get_neighbors(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const dof_id_type /*i*/, const dof_id_type /*j*/, const dof_id_type /*k*/, std::vector<dof_id_type> & /*neighbors*/) { mooseError("get_neighbors not implemented for this element type in DistributedGeneratedMesh"); } /** * The ID of the i,j,k node * * @param type The element type * @param nx The number of elements in the x direction * @param nx The number of elements in the y direction * @param nz The number of elements in the z direction * @param i The x index of this node * @param j The y index of this node * @param k The z index of this node */ template <typename T> inline dof_id_type node_id(const ElemType /*type*/, const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type /*i*/, const dof_id_type /*j*/, const dof_id_type /*k*/) { mooseError("node_id not implemented for this element type in DistributedGeneratedMesh"); } /** * Add a node to the mesh * * @param nx The number of elements in the x direction * @param nx The number of elements in the y direction * @param nz The number of elements in the z direction * @param i The x index of this node * @param j The y index of this node * @param k The z index of this node * @param type The element type * @param mesh The mesh to add it to */ template <typename T> Node * add_point(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const dof_id_type /*i*/, const dof_id_type /*j*/, const dof_id_type /*k*/, const ElemType /*type*/, MeshBase & /*mesh*/) { mooseError("add_point not implemented for this element type in DistributedGeneratedMesh"); } /** * Adds an element to the mesh * * @param nx The number of elements in the x direction * @param ny The number of elements in the y direction * @param nz The number of elements in the z direction * @param i The x index of this element * @param j The y index of this element * @param k The z index of this element * @param elem_id The element ID of the element to add * @param pid The processor ID to assign it to * @param type The type of element to add * @param mesh The mesh to add it to * @param verbose Whether or not to print out verbose statements */ template <typename T> void add_element(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const dof_id_type /*i*/, const dof_id_type /*j*/, const dof_id_type /*k*/, const dof_id_type /*elem_id*/, const processor_id_type /*pid*/, const ElemType /*type*/, MeshBase & /*mesh*/, bool /*verbose*/) { mooseError("add_element not implemented for this element type in DistributedGeneratedMesh"); } /** * Compute the i,j,k indices of a given element ID * * @param nx The number of elements in the x direction * @param ny The number of elements in the y direction * @param elem_id The ID of the element * @param i Output: The index in the x direction * @param j Output: The index in the y direction * @param k Output: The index in the z direction */ template <typename T> inline void get_indices(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type /*elem_id*/, dof_id_type & /*i*/, dof_id_type & /*j*/, dof_id_type & /*k*/) { mooseError("get_indices not implemented for this element type in DistributedGeneratedMesh"); } /** * Find the elements and sides that need ghost elements * * @param nx The number of elements in the x direction * @param ny The number of elements in the y direction * @param mesh The mesh - without any ghost elements * @param ghost_elems The ghost elems that need to be added */ template <typename T> inline void get_ghost_neighbors(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const MeshBase & /*mesh*/, std::set<dof_id_type> & /*ghost_elems*/) { mooseError( "get_ghost_neighbors not implemented for this element type in DistributedGeneratedMesh"); } /** * Set the boundary names for any added boundary ideas * * @boundary_info The BoundaryInfo object to set the boundary names on */ template <typename T> void set_boundary_names(BoundaryInfo & /*boundary_info*/) { mooseError( "set_boundary_names not implemented for this element type in DistributedGeneratedMesh"); } /** * All meshes are generated on the unit square. This function stretches the mesh * out to fill the correct area. */ template <typename T> void scale_nodal_positions(dof_id_type /*nx*/, dof_id_type /*ny*/, dof_id_type /*nz*/, Real /*xmin*/, Real /*xmax*/, Real /*ymin*/, Real /*ymax*/, Real /*zmin*/, Real /*zmax*/, MeshBase & /*mesh*/) { mooseError( "scale_nodal_positions not implemented for this element type in DistributedGeneratedMesh"); } template <> inline dof_id_type num_neighbors<Edge2>(const dof_id_type nx, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const dof_id_type i, const dof_id_type /*j*/, const dof_id_type /*k*/) { // The ends only have one neighbor if (i == 0 || i == nx - 1) return 1; return 2; } template <> inline void get_neighbors<Edge2>(const dof_id_type nx, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const dof_id_type i, const dof_id_type /*j*/, const dof_id_type /*k*/, std::vector<dof_id_type> & neighbors) { neighbors[0] = i - 1; neighbors[1] = i + 1; // First element doesn't have a left neighbor if (i == 0) neighbors[0] = Elem::invalid_id; // Last element doesn't have a right neighbor if (i == nx - 1) neighbors[1] = Elem::invalid_id; } template <> inline void get_indices<Edge2>(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type elem_id, dof_id_type & i, dof_id_type & /*j*/, dof_id_type & /*k*/) { i = elem_id; } template <> inline void get_ghost_neighbors<Edge2>(const dof_id_type nx, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const MeshBase & mesh, std::set<dof_id_type> & ghost_elems) { auto & boundary_info = mesh.get_boundary_info(); std::vector<dof_id_type> neighbors(2); for (auto elem_ptr : mesh.element_ptr_range()) { for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) { // No current neighbor if (!elem_ptr->neighbor_ptr(s)) { // Not on a boundary if (!boundary_info.n_boundary_ids(elem_ptr, s)) { get_neighbors<Edge2>(nx, 0, 0, elem_ptr->id(), 0, 0, neighbors); ghost_elems.insert(neighbors[s]); } } } } } template <> inline dof_id_type elem_id<Edge2>(const dof_id_type /*nx*/, const dof_id_type /*ny*/, const dof_id_type i, const dof_id_type /*j*/, const dof_id_type /*k*/) { return i; } template <> void add_element<Edge2>(const dof_id_type nx, const dof_id_type /*ny*/, const dof_id_type /*nz*/, const dof_id_type /*i*/, const dof_id_type /*j*/, const dof_id_type /*k*/, const dof_id_type elem_id, const processor_id_type pid, const ElemType /*type*/, MeshBase & mesh, bool verbose) { BoundaryInfo & boundary_info = mesh.get_boundary_info(); if (verbose) Moose::out << "Adding elem: " << elem_id << " pid: " << pid << std::endl; auto node_offset = elem_id; auto node0_ptr = mesh.add_point(Point(static_cast<Real>(node_offset) / nx, 0, 0), node_offset); node0_ptr->set_unique_id() = node_offset; auto node1_ptr = mesh.add_point(Point(static_cast<Real>(node_offset + 1) / nx, 0, 0), node_offset + 1); node1_ptr->set_unique_id() = node_offset + 1; if (verbose) Moose::out << "Adding elem: " << elem_id << std::endl; Elem * elem = new Edge2; elem->set_id(elem_id); elem->processor_id() = pid; elem->set_unique_id() = elem_id; elem = mesh.add_elem(elem); elem->set_node(0) = node0_ptr; elem->set_node(1) = node1_ptr; if (elem_id == 0) boundary_info.add_side(elem, 0, 0); if (elem_id == nx - 1) boundary_info.add_side(elem, 1, 1); } template <> void set_boundary_names<Edge2>(BoundaryInfo & boundary_info) { boundary_info.sideset_name(0) = "left"; boundary_info.sideset_name(1) = "right"; } template <> void scale_nodal_positions<Edge2>(dof_id_type /*nx*/, dof_id_type /*ny*/, dof_id_type /*nz*/, Real xmin, Real xmax, Real /*ymin*/, Real /*ymax*/, Real /*zmin*/, Real /*zmax*/, MeshBase & mesh) { for (auto & node_ptr : mesh.node_ptr_range()) (*node_ptr)(0) = (*node_ptr)(0) * (xmax - xmin) + xmin; } template <> inline dof_id_type num_neighbors<Quad4>(const dof_id_type nx, const dof_id_type ny, const dof_id_type /*nz*/, const dof_id_type i, const dof_id_type j, const dof_id_type /*k*/) { dof_id_type n = 4; if (i == 0) n--; if (i == nx - 1) n--; if (j == 0) n--; if (j == ny - 1) n--; return n; } template <> inline dof_id_type elem_id<Quad4>(const dof_id_type nx, const dof_id_type /*nx*/, const dof_id_type i, const dof_id_type j, const dof_id_type /*k*/) { return (j * nx) + i; } template <> inline void get_neighbors<Quad4>(const dof_id_type nx, const dof_id_type ny, const dof_id_type /*nz*/, const dof_id_type i, const dof_id_type j, const dof_id_type /*k*/, std::vector<dof_id_type> & neighbors) { std::fill(neighbors.begin(), neighbors.end(), Elem::invalid_id); // Bottom if (j != 0) neighbors[0] = elem_id<Quad4>(nx, 0, i, j - 1, 0); // Right if (i != nx - 1) neighbors[1] = elem_id<Quad4>(nx, 0, i + 1, j, 0); // Top if (j != ny - 1) neighbors[2] = elem_id<Quad4>(nx, 0, i, j + 1, 0); // Left if (i != 0) neighbors[3] = elem_id<Quad4>(nx, 0, i - 1, j, 0); } template <> inline void get_indices<Quad4>(const dof_id_type nx, const dof_id_type /*ny*/, const dof_id_type elem_id, dof_id_type & i, dof_id_type & j, dof_id_type & /*k*/) { i = elem_id % nx; j = (elem_id - i) / nx; } template <> inline void get_ghost_neighbors<Quad4>(const dof_id_type nx, const dof_id_type ny, const dof_id_type /*nz*/, const MeshBase & mesh, std::set<dof_id_type> & ghost_elems) { auto & boundary_info = mesh.get_boundary_info(); dof_id_type i, j, k; std::vector<dof_id_type> neighbors(4); for (auto elem_ptr : mesh.element_ptr_range()) { for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) { // No current neighbor if (!elem_ptr->neighbor_ptr(s)) { // Not on a boundary if (!boundary_info.n_boundary_ids(elem_ptr, s)) { auto elem_id = elem_ptr->id(); get_indices<Quad4>(nx, 0, elem_id, i, j, k); get_neighbors<Quad4>(nx, ny, 0, i, j, 0, neighbors); ghost_elems.insert(neighbors[s]); } } } } } template <> inline dof_id_type node_id<Quad4>(const ElemType /*type*/, const dof_id_type nx, const dof_id_type /*ny*/, const dof_id_type i, const dof_id_type j, const dof_id_type /*k*/) { return i + j * (nx + 1); } template <> void add_element<Quad4>(const dof_id_type nx, const dof_id_type ny, const dof_id_type /*nz*/, const dof_id_type i, const dof_id_type j, const dof_id_type /*k*/, const dof_id_type elem_id, const processor_id_type pid, const ElemType type, MeshBase & mesh, bool verbose) { BoundaryInfo & boundary_info = mesh.get_boundary_info(); if (verbose) Moose::out << "Adding elem: " << elem_id << " pid: " << pid << std::endl; // Bottom Left auto node0_ptr = mesh.add_point(Point(static_cast<Real>(i) / nx, static_cast<Real>(j) / ny, 0), node_id<Quad4>(type, nx, 0, i, j, 0)); node0_ptr->set_unique_id() = node_id<Quad4>(type, nx, 0, i, j, 0); // Bottom Right auto node1_ptr = mesh.add_point(Point(static_cast<Real>(i + 1) / nx, static_cast<Real>(j) / ny, 0), node_id<Quad4>(type, nx, 0, i + 1, j, 0)); node1_ptr->set_unique_id() = node_id<Quad4>(type, nx, 0, i + 1, j, 0); // Top Right auto node2_ptr = mesh.add_point(Point(static_cast<Real>(i + 1) / nx, static_cast<Real>(j + 1) / ny, 0), node_id<Quad4>(type, nx, 0, i + 1, j + 1, 0)); node2_ptr->set_unique_id() = node_id<Quad4>(type, nx, 0, i + 1, j + 1, 0); // Top Left auto node3_ptr = mesh.add_point(Point(static_cast<Real>(i) / nx, static_cast<Real>(j + 1) / ny, 0), node_id<Quad4>(type, nx, 0, i, j + 1, 0)); node3_ptr->set_unique_id() = node_id<Quad4>(type, nx, 0, i, j + 1, 0); Elem * elem = new Quad4; elem->set_id(elem_id); elem->processor_id() = pid; elem->set_unique_id() = elem_id; elem = mesh.add_elem(elem); elem->set_node(0) = node0_ptr; elem->set_node(1) = node1_ptr; elem->set_node(2) = node2_ptr; elem->set_node(3) = node3_ptr; // Bottom if (j == 0) boundary_info.add_side(elem, 0, 0); // Right if (i == nx - 1) boundary_info.add_side(elem, 1, 1); // Top if (j == ny - 1) boundary_info.add_side(elem, 2, 2); // Left if (i == 0) boundary_info.add_side(elem, 3, 3); } template <> void set_boundary_names<Quad4>(BoundaryInfo & boundary_info) { boundary_info.sideset_name(0) = "bottom"; boundary_info.sideset_name(1) = "right"; boundary_info.sideset_name(2) = "top"; boundary_info.sideset_name(3) = "left"; } template <> void scale_nodal_positions<Quad4>(dof_id_type /*nx*/, dof_id_type /*ny*/, dof_id_type /*nz*/, Real xmin, Real xmax, Real ymin, Real ymax, Real /*zmin*/, Real /*zmax*/, MeshBase & mesh) { for (auto & node_ptr : mesh.node_ptr_range()) { (*node_ptr)(0) = (*node_ptr)(0) * (xmax - xmin) + xmin; (*node_ptr)(1) = (*node_ptr)(1) * (ymax - ymin) + ymin; } } template <> inline dof_id_type elem_id<Hex8>(const dof_id_type nx, const dof_id_type ny, const dof_id_type i, const dof_id_type j, const dof_id_type k) { return i + (j * nx) + (k * nx * ny); } template <> inline dof_id_type num_neighbors<Hex8>(const dof_id_type nx, const dof_id_type ny, const dof_id_type nz, const dof_id_type i, const dof_id_type j, const dof_id_type k) { dof_id_type n = 6; if (i == 0) n--; if (i == nx - 1) n--; if (j == 0) n--; if (j == ny - 1) n--; if (k == 0) n--; if (k == nz - 1) n--; return n; } template <> inline void get_neighbors<Hex8>(const dof_id_type nx, const dof_id_type ny, const dof_id_type nz, const dof_id_type i, const dof_id_type j, const dof_id_type k, std::vector<dof_id_type> & neighbors) { std::fill(neighbors.begin(), neighbors.end(), Elem::invalid_id); // Back if (k != 0) neighbors[0] = elem_id<Hex8>(nx, ny, i, j, k - 1); // Bottom if (j != 0) neighbors[1] = elem_id<Hex8>(nx, ny, i, j - 1, k); // Right if (i != nx - 1) neighbors[2] = elem_id<Hex8>(nx, ny, i + 1, j, k); // Top if (j != ny - 1) neighbors[3] = elem_id<Hex8>(nx, ny, i, j + 1, k); // Left if (i != 0) neighbors[4] = elem_id<Hex8>(nx, ny, i - 1, j, k); // Front if (k != nz - 1) neighbors[5] = elem_id<Hex8>(nx, ny, i, j, k + 1); } template <> inline dof_id_type node_id<Hex8>(const ElemType /*type*/, const dof_id_type nx, const dof_id_type ny, const dof_id_type i, const dof_id_type j, const dof_id_type k) { return i + (nx + 1) * (j + k * (ny + 1)); } template <> Node * add_point<Hex8>(const dof_id_type nx, const dof_id_type ny, const dof_id_type nz, const dof_id_type i, const dof_id_type j, const dof_id_type k, const ElemType type, MeshBase & mesh) { auto id = node_id<Hex8>(type, nx, ny, i, j, k); auto node_ptr = mesh.add_point( Point(static_cast<Real>(i) / nx, static_cast<Real>(j) / ny, static_cast<Real>(k) / nz), id); node_ptr->set_unique_id() = id; return node_ptr; } template <> void add_element<Hex8>(const dof_id_type nx, const dof_id_type ny, const dof_id_type nz, const dof_id_type i, const dof_id_type j, const dof_id_type k, const dof_id_type elem_id, const processor_id_type pid, const ElemType type, MeshBase & mesh, bool verbose) { BoundaryInfo & boundary_info = mesh.get_boundary_info(); if (verbose) { Moose::out << "Adding elem: " << elem_id << " pid: " << pid << std::endl; Moose::out << "Type: " << type << " " << HEX8 << std::endl; } // This ordering was picked to match the ordering in mesh_generation.C auto node0_ptr = add_point<Hex8>(nx, ny, nz, i, j, k, type, mesh); auto node1_ptr = add_point<Hex8>(nx, ny, nz, i + 1, j, k, type, mesh); auto node2_ptr = add_point<Hex8>(nx, ny, nz, i + 1, j + 1, k, type, mesh); auto node3_ptr = add_point<Hex8>(nx, ny, nz, i, j + 1, k, type, mesh); auto node4_ptr = add_point<Hex8>(nx, ny, nz, i, j, k + 1, type, mesh); auto node5_ptr = add_point<Hex8>(nx, ny, nz, i + 1, j, k + 1, type, mesh); auto node6_ptr = add_point<Hex8>(nx, ny, nz, i + 1, j + 1, k + 1, type, mesh); auto node7_ptr = add_point<Hex8>(nx, ny, nz, i, j + 1, k + 1, type, mesh); Elem * elem = new Hex8; elem->set_id(elem_id); elem->processor_id() = pid; elem->set_unique_id() = elem_id; elem = mesh.add_elem(elem); elem->set_node(0) = node0_ptr; elem->set_node(1) = node1_ptr; elem->set_node(2) = node2_ptr; elem->set_node(3) = node3_ptr; elem->set_node(4) = node4_ptr; elem->set_node(5) = node5_ptr; elem->set_node(6) = node6_ptr; elem->set_node(7) = node7_ptr; if (k == 0) boundary_info.add_side(elem, 0, 0); if (k == (nz - 1)) boundary_info.add_side(elem, 5, 5); if (j == 0) boundary_info.add_side(elem, 1, 1); if (j == (ny - 1)) boundary_info.add_side(elem, 3, 3); if (i == 0) boundary_info.add_side(elem, 4, 4); if (i == (nx - 1)) boundary_info.add_side(elem, 2, 2); } template <> inline void get_indices<Hex8>(const dof_id_type nx, const dof_id_type ny, const dof_id_type elem_id, dof_id_type & i, dof_id_type & j, dof_id_type & k) { i = elem_id % nx; j = (((elem_id - i) / nx) % ny); k = ((elem_id - i) - (j * nx)) / (nx * ny); } template <> inline void get_ghost_neighbors<Hex8>(const dof_id_type nx, const dof_id_type ny, const dof_id_type nz, const MeshBase & mesh, std::set<dof_id_type> & ghost_elems) { auto & boundary_info = mesh.get_boundary_info(); dof_id_type i, j, k; std::vector<dof_id_type> neighbors(6); for (auto elem_ptr : mesh.element_ptr_range()) { for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) { // No current neighbor if (!elem_ptr->neighbor_ptr(s)) { // Not on a boundary if (!boundary_info.n_boundary_ids(elem_ptr, s)) { auto elem_id = elem_ptr->id(); get_indices<Hex8>(nx, ny, elem_id, i, j, k); get_neighbors<Hex8>(nx, ny, nz, i, j, k, neighbors); ghost_elems.insert(neighbors[s]); } } } } } template <> void set_boundary_names<Hex8>(BoundaryInfo & boundary_info) { boundary_info.sideset_name(0) = "back"; boundary_info.sideset_name(1) = "bottom"; boundary_info.sideset_name(2) = "right"; boundary_info.sideset_name(3) = "top"; boundary_info.sideset_name(4) = "left"; boundary_info.sideset_name(5) = "front"; } template <> void scale_nodal_positions<Hex8>(dof_id_type /*nx*/, dof_id_type /*ny*/, dof_id_type /*nz*/, Real xmin, Real xmax, Real ymin, Real ymax, Real zmin, Real zmax, MeshBase & mesh) { for (auto & node_ptr : mesh.node_ptr_range()) { (*node_ptr)(0) = (*node_ptr)(0) * (xmax - xmin) + xmin; (*node_ptr)(1) = (*node_ptr)(1) * (ymax - ymin) + ymin; (*node_ptr)(2) = (*node_ptr)(2) * (zmax - zmin) + zmin; } } } template <typename T> void build_cube(UnstructuredMesh & mesh, const unsigned int nx, unsigned int ny, unsigned int nz, const Real xmin, const Real xmax, const Real ymin, const Real ymax, const Real zmin, const Real zmax, const ElemType type, bool verbose) { if (verbose) Moose::out << "nx: " << nx << "\n ny: " << ny << "\n nz: " << nz << std::endl; /// Here's the plan: /// 1. Create a (dual) graph of the elements /// 2. Partition the graph /// 3. The partitioning tells this processsor which elements to create dof_id_type num_elems = nx * ny * nz; const auto n_pieces = mesh.comm().size(); const auto pid = mesh.comm().rank(); std::unique_ptr<Elem> canonical_elem = libmesh_make_unique<T>(); // Will get used to find the neighbors of an element std::vector<dof_id_type> neighbors(canonical_elem->n_neighbors()); // Data structure that Metis will fill up on processor 0 and broadcast. std::vector<Metis::idx_t> part(num_elems); if (mesh.processor_id() == 0) { // Data structures and parameters needed only on processor 0 by Metis. // std::vector<Metis::idx_t> options(5); // Weight by the number of nodes std::vector<Metis::idx_t> vwgt(num_elems, canonical_elem->n_nodes()); Metis::idx_t n = num_elems, // number of "nodes" (elements) in the graph nparts = n_pieces, // number of subdomains to create edgecut = 0; // the numbers of edges cut by the resulting partition METIS_CSR_Graph<Metis::idx_t> csr_graph; csr_graph.offsets.resize(num_elems + 1, 0); for (dof_id_type k = 0; k < nz; k++) { for (dof_id_type j = 0; j < ny; j++) { for (dof_id_type i = 0; i < nx; i++) { auto n_neighbors = num_neighbors<T>(nx, ny, nz, i, j, k); auto e_id = elem_id<T>(nx, ny, i, j, k); if (verbose) Moose::out << e_id << " num_neighbors: " << n_neighbors << std::endl; csr_graph.prep_n_nonzeros(e_id, n_neighbors); } } } csr_graph.prepare_for_use(); if (verbose) for (auto offset : csr_graph.offsets) Moose::out << "offset: " << offset << std::endl; for (dof_id_type k = 0; k < nz; k++) { for (dof_id_type j = 0; j < ny; j++) { for (dof_id_type i = 0; i < nx; i++) { auto e_id = elem_id<T>(nx, ny, i, j, k); dof_id_type connection = 0; get_neighbors<T>(nx, ny, nz, i, j, k, neighbors); for (auto neighbor : neighbors) { if (neighbor != Elem::invalid_id) { if (verbose) Moose::out << e_id << ": " << connection << " = " << neighbor << std::endl; csr_graph(e_id, connection++) = neighbor; } } } } } if (n_pieces == 1) { // Just assign them all to proc 0 for (auto & elem_pid : part) elem_pid = 0; } else { Metis::idx_t ncon = 1; // Use recursive if the number of partitions is less than or equal to 8 if (n_pieces <= 8) Metis::METIS_PartGraphRecursive(&n, &ncon, &csr_graph.offsets[0], &csr_graph.vals[0], &vwgt[0], libmesh_nullptr, libmesh_nullptr, &nparts, libmesh_nullptr, libmesh_nullptr, libmesh_nullptr, &edgecut, &part[0]); // Otherwise use kway else Metis::METIS_PartGraphKway(&n, &ncon, &csr_graph.offsets[0], &csr_graph.vals[0], &vwgt[0], libmesh_nullptr, libmesh_nullptr, &nparts, libmesh_nullptr, libmesh_nullptr, libmesh_nullptr, &edgecut, &part[0]); } } // end processor 0 part // Broadcast the resulting partition mesh.comm().broadcast(part); if (verbose) for (auto proc_id : part) Moose::out << "Part: " << proc_id << std::endl; BoundaryInfo & boundary_info = mesh.get_boundary_info(); // Add elements this processor owns for (dof_id_type k = 0; k < nz; k++) { for (dof_id_type j = 0; j < ny; j++) { for (dof_id_type i = 0; i < nx; i++) { auto e_id = elem_id<Hex8>(nx, ny, i, j, k); if (static_cast<processor_id_type>(part[e_id]) == pid) add_element<T>(nx, ny, nz, i, j, k, e_id, pid, type, mesh, verbose); } } } if (verbose) for (auto & elem_ptr : mesh.element_ptr_range()) for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) Moose::out << "Elem neighbor: " << elem_ptr->neighbor_ptr(s) << " is remote " << (elem_ptr->neighbor_ptr(s) == remote_elem) << std::endl; // Need to link up the local elements before we can know what's missing mesh.find_neighbors(); if (verbose) Moose::out << "After first find_neighbors" << std::endl; if (verbose) for (auto & elem_ptr : mesh.element_ptr_range()) for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) Moose::out << "Elem neighbor: " << elem_ptr->neighbor_ptr(s) << " is remote " << (elem_ptr->neighbor_ptr(s) == remote_elem) << std::endl; // Get the ghosts (missing face neighbors) std::set<dof_id_type> ghost_elems; get_ghost_neighbors<T>(nx, ny, nz, mesh, ghost_elems); // Add the ghosts to the mesh for (auto & ghost_id : ghost_elems) { dof_id_type i = 0; dof_id_type j = 0; dof_id_type k = 0; get_indices<T>(nx, ny, ghost_id, i, j, k); add_element<T>(nx, ny, nz, i, j, k, ghost_id, part[ghost_id], type, mesh, verbose); } if (verbose) Moose::out << "After adding ghosts" << std::endl; if (verbose) for (auto & elem_ptr : mesh.element_ptr_range()) for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) Moose::out << "Elem neighbor: " << elem_ptr->neighbor_ptr(s) << " is remote " << (elem_ptr->neighbor_ptr(s) == remote_elem) << std::endl; mesh.find_neighbors(true); if (verbose) Moose::out << "After second find neighbors " << std::endl; if (verbose) for (auto & elem_ptr : mesh.element_ptr_range()) for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) Moose::out << "Elem neighbor: " << elem_ptr->neighbor_ptr(s) << " is remote " << (elem_ptr->neighbor_ptr(s) == remote_elem) << std::endl; // Set RemoteElem neighbors for (auto & elem_ptr : mesh.element_ptr_range()) for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) if (!elem_ptr->neighbor_ptr(s) && !boundary_info.n_boundary_ids(elem_ptr, s)) elem_ptr->set_neighbor(s, const_cast<RemoteElem *>(remote_elem)); if (verbose) Moose::out << "After adding remote elements" << std::endl; if (verbose) for (auto & elem_ptr : mesh.element_ptr_range()) for (unsigned int s = 0; s < elem_ptr->n_sides(); s++) Moose::out << "Elem neighbor: " << elem_ptr->neighbor_ptr(s) << " is remote " << (elem_ptr->neighbor_ptr(s) == remote_elem) << std::endl; set_boundary_names<T>(boundary_info); Partitioner::set_node_processor_ids(mesh); if (verbose) Moose::out << "mesh dim: " << mesh.mesh_dimension() << std::endl; if (verbose) for (auto & node_ptr : mesh.node_ptr_range()) Moose::out << node_ptr->id() << ":" << node_ptr->processor_id() << std::endl; // Already partitioned! mesh.skip_partitioning(true); if (verbose) for (auto & elem_ptr : mesh.element_ptr_range()) Moose::out << "Elem: " << elem_ptr->id() << " pid: " << elem_ptr->processor_id() << " uid: " << elem_ptr->unique_id() << std::endl; if (verbose) Moose::out << "Getting ready to prepare for use" << std::endl; // No need to renumber or find neighbors - done did it. // Avoid deprecation message/error by _also_ setting // allow_renumbering(false). This is a bit silly, but we want to // catch cases where people are purely using the old "skip" // interface and not the new flag setting one. mesh.allow_renumbering(false); mesh.prepare_for_use(/*skip_renumber (ignored!) = */ false, /*skip_find_neighbors = */ true); if (verbose) for (auto & elem_ptr : mesh.element_ptr_range()) Moose::out << "Elem: " << elem_ptr->id() << " pid: " << elem_ptr->processor_id() << std::endl; if (verbose) for (auto & node_ptr : mesh.node_ptr_range()) Moose::out << node_ptr->id() << ":" << node_ptr->processor_id() << std::endl; if (verbose) Moose::out << "mesh dim: " << mesh.mesh_dimension() << std::endl; // Scale the nodal positions scale_nodal_positions<T>(nx, ny, nz, xmin, xmax, ymin, ymax, zmin, zmax, mesh); if (verbose) mesh.print_info(); } std::unique_ptr<MeshBase> DistributedGeneratedMeshGenerator::generate() { std::unique_ptr<ReplicatedMesh> mesh = libmesh_make_unique<ReplicatedMesh>(comm(), 2); MooseEnum elem_type_enum = getParam<MooseEnum>("elem_type"); if (!isParamValid("elem_type")) { // Switching on MooseEnum switch (_dim) { case 1: elem_type_enum = "EDGE2"; break; case 2: elem_type_enum = "QUAD4"; break; case 3: elem_type_enum = "HEX8"; break; } } _elem_type = Utility::string_to_enum<ElemType>(elem_type_enum); mesh->set_mesh_dimension(_dim); mesh->set_spatial_dimension(_dim); // Switching on MooseEnum switch (_dim) { // The build_XYZ mesh generation functions take an // UnstructuredMesh& as the first argument, hence the dynamic_cast. case 1: build_cube<Edge2>(static_cast<UnstructuredMesh &>(*mesh), _nx, 1, 1, _xmin, _xmax, 0, 0, 0, 0, _elem_type, _verbose); break; case 2: build_cube<Quad4>(static_cast<UnstructuredMesh &>(*mesh), _nx, _ny, 1, _xmin, _xmax, _ymin, _ymax, 0, 0, _elem_type, _verbose); break; case 3: build_cube<Hex8>(static_cast<UnstructuredMesh &>(*mesh), _nx, _ny, _nz, _xmin, _xmax, _ymin, _ymax, _zmin, _zmax, _elem_type, _verbose); break; default: mooseError(getParam<MooseEnum>("elem_type"), " is not a currently supported element type for DistributedGeneratedMesh"); } // Apply the bias if any exists if (_bias_x != 1.0 || _bias_y != 1.0 || _bias_z != 1.0) { // Biases Real bias[3] = {_bias_x, _bias_y, _bias_z}; // "width" of the mesh in each direction Real width[3] = {_xmax - _xmin, _ymax - _ymin, _zmax - _zmin}; // Min mesh extent in each direction. Real mins[3] = {_xmin, _ymin, _zmin}; // Number of elements in each direction. dof_id_type nelem[3] = {_nx, _ny, _nz}; // We will need the biases raised to integer powers in each // direction, so let's pre-compute those... std::vector<std::vector<Real>> pows(LIBMESH_DIM); for (dof_id_type dir = 0; dir < LIBMESH_DIM; ++dir) { pows[dir].resize(nelem[dir] + 1); for (dof_id_type i = 0; i < pows[dir].size(); ++i) pows[dir][i] = std::pow(bias[dir], static_cast<int>(i)); } // Loop over the nodes and move them to the desired location for (auto & node_ptr : mesh->node_ptr_range()) { Node & node = *node_ptr; for (dof_id_type dir = 0; dir < LIBMESH_DIM; ++dir) { if (width[dir] != 0. && bias[dir] != 1.) { // Compute the scaled "index" of the current point. This // will either be close to a whole integer or a whole // integer+0.5 for quadratic nodes. Real float_index = (node(dir) - mins[dir]) * nelem[dir] / width[dir]; Real integer_part = 0; Real fractional_part = std::modf(float_index, &integer_part); // Figure out where to move the node... if (std::abs(fractional_part) < TOLERANCE || std::abs(fractional_part - 1.0) < TOLERANCE) { // If the fractional_part ~ 0.0 or 1.0, this is a vertex node, so // we don't need an average. // // Compute the "index" we are at in the current direction. We // round to the nearest integral value to get this instead // of using "integer_part", since that could be off by a // lot (e.g. we want 3.9999 to map to 4.0 instead of 3.0). int index = round(float_index); // Move node to biased location. node(dir) = mins[dir] + width[dir] * (1. - pows[dir][index]) / (1. - pows[dir][nelem[dir]]); } else if (std::abs(fractional_part - 0.5) < TOLERANCE) { // If the fractional_part ~ 0.5, this is a midedge/face // (i.e. quadratic) node. We don't move those with the same // bias as the vertices, instead we put them midway between // their respective vertices. // // Also, since the fractional part is nearly 0.5, we know that // the integer_part will be the index of the vertex to the // left, and integer_part+1 will be the index of the // vertex to the right. node(dir) = mins[dir] + width[dir] * (1. - 0.5 * (pows[dir][integer_part] + pows[dir][integer_part + 1])) / (1. - pows[dir][nelem[dir]]); } else { // We don't yet handle anything higher order than quadratic... mooseError("Unable to bias node at node(", dir, ")=", node(dir)); } } } } } return dynamic_pointer_cast<MeshBase>(mesh); }
/***************************************************************************** * Project: RooFit * * Package: RooFitCore * * @(#)root/roofitcore:$Id$ * Authors: * * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * * * * Copyright (c) 2000-2005, Regents of the University of California * * and Stanford University. All rights reserved. * * * * Redistribution and use in source and binary forms, * * with or without modification, are permitted according to the terms * * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ /** \file RooAbsData.cxx \class RooAbsData \ingroup Roofitcore RooAbsData is the common abstract base class for binned and unbinned datasets. The abstract interface defines plotting and tabulating entry points for its contents and provides an iterator over its elements (bins for binned data sets, data points for unbinned datasets). **/ #include "RooAbsData.h" #include "RooFit.h" #include <iostream> #include "TBuffer.h" #include "TClass.h" #include "TMath.h" #include "TTree.h" #include "strlcpy.h" #include "RooFormulaVar.h" #include "RooCmdConfig.h" #include "RooAbsRealLValue.h" #include "RooMsgService.h" #include "RooMultiCategory.h" #include "Roo1DTable.h" #include "RooAbsDataStore.h" #include "RooVectorDataStore.h" #include "RooTreeDataStore.h" #include "RooDataHist.h" #include "RooCompositeDataStore.h" #include "RooCategory.h" #include "RooTrace.h" #include "RooUniformBinning.h" #include "RooRealVar.h" #include "RooGlobalFunc.h" #include "RooPlot.h" #include "RooCurve.h" #include "RooHist.h" #include "TMatrixDSym.h" #include "TPaveText.h" #include "TH1.h" #include "TH2.h" #include "TH3.h" #include "Math/Util.h" using namespace std; ClassImp(RooAbsData); ; static std::map<RooAbsData*,int> _dcc ; RooAbsData::StorageType RooAbsData::defaultStorageType=RooAbsData::Vector ; //////////////////////////////////////////////////////////////////////////////// void RooAbsData::setDefaultStorageType(RooAbsData::StorageType s) { if (RooAbsData::Composite == s) { cout << "Composite storage is not a valid *default* storage type." << endl; } else { defaultStorageType = s; } } //////////////////////////////////////////////////////////////////////////////// RooAbsData::StorageType RooAbsData::getDefaultStorageType( ) { return defaultStorageType; } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::claimVars(RooAbsData* data) { _dcc[data]++ ; //cout << "RooAbsData(" << data << ") claim incremented to " << _dcc[data] << endl ; } //////////////////////////////////////////////////////////////////////////////// /// If return value is true variables can be deleted Bool_t RooAbsData::releaseVars(RooAbsData* data) { if (_dcc[data]>0) { _dcc[data]-- ; } //cout << "RooAbsData(" << data << ") claim decremented to " << _dcc[data] << endl ; return (_dcc[data]==0) ; } //////////////////////////////////////////////////////////////////////////////// /// Default constructor RooAbsData::RooAbsData() { claimVars(this) ; _dstore = 0 ; storageType = defaultStorageType; RooTrace::create(this) ; } //////////////////////////////////////////////////////////////////////////////// /// Constructor from a set of variables. Only fundamental elements of vars /// (RooRealVar,RooCategory etc) are stored as part of the dataset RooAbsData::RooAbsData(const char *name, const char *title, const RooArgSet& vars, RooAbsDataStore* dstore) : TNamed(name,title), _vars("Dataset Variables"), _cachedVars("Cached Variables"), _dstore(dstore) { if (dynamic_cast<RooTreeDataStore *>(dstore)) { storageType = RooAbsData::Tree; } else if (dynamic_cast<RooVectorDataStore *>(dstore)) { storageType = RooAbsData::Vector; } else { storageType = RooAbsData::Composite; } // cout << "created dataset " << this << endl ; claimVars(this); // clone the fundamentals of the given data set into internal buffer for (const auto var : vars) { if (!var->isFundamental()) { coutE(InputArguments) << "RooAbsDataStore::initialize(" << GetName() << "): Data set cannot contain non-fundamental types, ignoring " << var->GetName() << endl; throw std::invalid_argument(std::string("Only fundamental variables can be placed into datasets. This is violated for ") + var->GetName()); } else { _vars.addClone(*var); } } // reconnect any parameterized ranges to internal dataset observables for (auto var : _vars) { var->attachDataSet(*this); } RooTrace::create(this); } //////////////////////////////////////////////////////////////////////////////// /// Copy constructor RooAbsData::RooAbsData(const RooAbsData& other, const char* newname) : TNamed(newname?newname:other.GetName(),other.GetTitle()), RooPrintable(other), _vars(), _cachedVars("Cached Variables") { //cout << "created dataset " << this << endl ; claimVars(this) ; _vars.addClone(other._vars) ; // reconnect any parameterized ranges to internal dataset observables for (const auto var : _vars) { var->attachDataSet(*this) ; } if (other._ownedComponents.size()>0) { // copy owned components here map<string,RooAbsDataStore*> smap ; for (auto& itero : other._ownedComponents) { RooAbsData* dclone = (RooAbsData*) itero.second->Clone(); _ownedComponents[itero.first] = dclone; smap[itero.first] = dclone->store(); } RooCategory* idx = (RooCategory*) _vars.find(*((RooCompositeDataStore*)other.store())->index()) ; _dstore = new RooCompositeDataStore(newname?newname:other.GetName(),other.GetTitle(),_vars,*idx,smap) ; storageType = RooAbsData::Composite; } else { // Convert to vector store if default is vector _dstore = other._dstore->clone(_vars,newname?newname:other.GetName()) ; storageType = other.storageType; } RooTrace::create(this) ; } RooAbsData& RooAbsData::operator=(const RooAbsData& other) { TNamed::operator=(other); RooPrintable::operator=(other); claimVars(this); _vars.Clear(); _vars.addClone(other._vars); // reconnect any parameterized ranges to internal dataset observables for (const auto var : _vars) { var->attachDataSet(*this) ; } if (other._ownedComponents.size()>0) { // copy owned components here map<string,RooAbsDataStore*> smap ; for (auto& itero : other._ownedComponents) { RooAbsData* dclone = (RooAbsData*) itero.second->Clone(); _ownedComponents[itero.first] = dclone; smap[itero.first] = dclone->store(); } RooCategory* idx = (RooCategory*) _vars.find(*((RooCompositeDataStore*)other.store())->index()) ; _dstore = new RooCompositeDataStore(GetName(), GetTitle(), _vars, *idx, smap); storageType = RooAbsData::Composite; } else { // Convert to vector store if default is vector _dstore = other._dstore->clone(_vars); storageType = other.storageType; } return *this; } //////////////////////////////////////////////////////////////////////////////// /// Destructor RooAbsData::~RooAbsData() { if (releaseVars(this)) { // will cause content to be deleted subsequently in dtor } else { _vars.releaseOwnership() ; } // delete owned contents. delete _dstore ; // Delete owned dataset components for(map<std::string,RooAbsData*>::iterator iter = _ownedComponents.begin() ; iter!= _ownedComponents.end() ; ++iter) { delete iter->second ; } RooTrace::destroy(this) ; } //////////////////////////////////////////////////////////////////////////////// /// Convert tree-based storage to vector-based storage void RooAbsData::convertToVectorStore() { if (storageType == RooAbsData::Tree) { RooVectorDataStore *newStore = new RooVectorDataStore(*(RooTreeDataStore *)_dstore, _vars, GetName()); delete _dstore; _dstore = newStore; storageType = RooAbsData::Vector; } } //////////////////////////////////////////////////////////////////////////////// Bool_t RooAbsData::changeObservableName(const char* from, const char* to) { Bool_t ret = _dstore->changeObservableName(from,to) ; RooAbsArg* tmp = _vars.find(from) ; if (tmp) { tmp->SetName(to) ; } return ret ; } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::fill() { _dstore->fill() ; } //////////////////////////////////////////////////////////////////////////////// Int_t RooAbsData::numEntries() const { return nullptr != _dstore ? _dstore->numEntries() : 0; } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::reset() { _dstore->reset() ; } //////////////////////////////////////////////////////////////////////////////// const RooArgSet* RooAbsData::get(Int_t index) const { checkInit() ; return _dstore->get(index) ; } //////////////////////////////////////////////////////////////////////////////// /// Internal method -- Cache given set of functions with data void RooAbsData::cacheArgs(const RooAbsArg* cacheOwner, RooArgSet& varSet, const RooArgSet* nset, Bool_t skipZeroWeights) { _dstore->cacheArgs(cacheOwner,varSet,nset,skipZeroWeights) ; } //////////////////////////////////////////////////////////////////////////////// /// Internal method -- Remove cached function values void RooAbsData::resetCache() { _dstore->resetCache() ; _cachedVars.removeAll() ; } //////////////////////////////////////////////////////////////////////////////// /// Internal method -- Attach dataset copied with cache contents to copied instances of functions void RooAbsData::attachCache(const RooAbsArg* newOwner, const RooArgSet& cachedVars) { _dstore->attachCache(newOwner, cachedVars) ; } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::setArgStatus(const RooArgSet& set, Bool_t active) { _dstore->setArgStatus(set,active) ; } //////////////////////////////////////////////////////////////////////////////// /// Control propagation of dirty flags from observables in dataset void RooAbsData::setDirtyProp(Bool_t flag) { _dstore->setDirtyProp(flag) ; } //////////////////////////////////////////////////////////////////////////////// /// Create a reduced copy of this dataset. The caller takes ownership of the returned dataset /// /// The following optional named arguments are accepted /// <table> /// <tr><td> `SelectVars(const RooArgSet& vars)` <td> Only retain the listed observables in the output dataset /// <tr><td> `Cut(const char* expression)` <td> Only retain event surviving the given cut expression /// <tr><td> `Cut(const RooFormulaVar& expr)` <td> Only retain event surviving the given cut formula /// <tr><td> `CutRange(const char* name)` <td> Only retain events inside range with given name. Multiple CutRange /// arguments may be given to select multiple ranges /// <tr><td> `EventRange(int lo, int hi)` <td> Only retain events with given sequential event numbers /// <tr><td> `Name(const char* name)` <td> Give specified name to output dataset /// <tr><td> `Title(const char* name)` <td> Give specified title to output dataset /// </table> RooAbsData* RooAbsData::reduce(const RooCmdArg& arg1,const RooCmdArg& arg2,const RooCmdArg& arg3,const RooCmdArg& arg4, const RooCmdArg& arg5,const RooCmdArg& arg6,const RooCmdArg& arg7,const RooCmdArg& arg8) { // Define configuration for this method RooCmdConfig pc(Form("RooAbsData::reduce(%s)",GetName())) ; pc.defineString("name","Name",0,"") ; pc.defineString("title","Title",0,"") ; pc.defineString("cutRange","CutRange",0,"") ; pc.defineString("cutSpec","CutSpec",0,"") ; pc.defineObject("cutVar","CutVar",0,0) ; pc.defineInt("evtStart","EventRange",0,0) ; pc.defineInt("evtStop","EventRange",1,std::numeric_limits<int>::max()) ; pc.defineObject("varSel","SelectVars",0,0) ; pc.defineMutex("CutVar","CutSpec") ; // Process & check varargs pc.process(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) ; if (!pc.ok(kTRUE)) { return 0 ; } // Extract values from named arguments const char* cutRange = pc.getString("cutRange",0,kTRUE) ; const char* cutSpec = pc.getString("cutSpec",0,kTRUE) ; RooFormulaVar* cutVar = static_cast<RooFormulaVar*>(pc.getObject("cutVar",0)) ; Int_t nStart = pc.getInt("evtStart",0) ; Int_t nStop = pc.getInt("evtStop",std::numeric_limits<int>::max()) ; RooArgSet* varSet = static_cast<RooArgSet*>(pc.getObject("varSel")) ; const char* name = pc.getString("name",0,kTRUE) ; const char* title = pc.getString("title",0,kTRUE) ; // Make sure varSubset doesn't contain any variable not in this dataset RooArgSet varSubset ; if (varSet) { varSubset.add(*varSet) ; for (const auto arg : varSubset) { if (!_vars.find(arg->GetName())) { coutW(InputArguments) << "RooAbsData::reduce(" << GetName() << ") WARNING: variable " << arg->GetName() << " not in dataset, ignored" << endl ; varSubset.remove(*arg) ; } } } else { varSubset.add(*get()) ; } RooAbsData* ret = 0 ; if (cutSpec) { RooFormulaVar cutVarTmp(cutSpec,cutSpec,*get()) ; ret = reduceEng(varSubset,&cutVarTmp,cutRange,nStart,nStop,kFALSE) ; } else if (cutVar) { ret = reduceEng(varSubset,cutVar,cutRange,nStart,nStop,kFALSE) ; } else { ret = reduceEng(varSubset,0,cutRange,nStart,nStop,kFALSE) ; } if (!ret) return 0 ; if (name) { ret->SetName(name) ; } if (title) { ret->SetTitle(title) ; } return ret ; } //////////////////////////////////////////////////////////////////////////////// /// Create a subset of the data set by applying the given cut on the data points. /// The cut expression can refer to any variable in the data set. For cuts involving /// other variables, such as intermediate formula objects, use the equivalent /// reduce method specifying the as a RooFormulVar reference. RooAbsData* RooAbsData::reduce(const char* cut) { RooFormulaVar cutVar(cut,cut,*get()) ; return reduceEng(*get(),&cutVar,0,0,std::numeric_limits<std::size_t>::max(),kFALSE) ; } //////////////////////////////////////////////////////////////////////////////// /// Create a subset of the data set by applying the given cut on the data points. /// The 'cutVar' formula variable is used to select the subset of data points to be /// retained in the reduced data collection. RooAbsData* RooAbsData::reduce(const RooFormulaVar& cutVar) { return reduceEng(*get(),&cutVar,0,0,std::numeric_limits<std::size_t>::max(),kFALSE) ; } //////////////////////////////////////////////////////////////////////////////// /// Create a subset of the data set by applying the given cut on the data points /// and reducing the dimensions to the specified set. /// /// The cut expression can refer to any variable in the data set. For cuts involving /// other variables, such as intermediate formula objects, use the equivalent /// reduce method specifying the as a RooFormulVar reference. RooAbsData* RooAbsData::reduce(const RooArgSet& varSubset, const char* cut) { // Make sure varSubset doesn't contain any variable not in this dataset RooArgSet varSubset2(varSubset) ; for (const auto arg : varSubset) { if (!_vars.find(arg->GetName())) { coutW(InputArguments) << "RooAbsData::reduce(" << GetName() << ") WARNING: variable " << arg->GetName() << " not in dataset, ignored" << endl ; varSubset2.remove(*arg) ; } } if (cut && strlen(cut)>0) { RooFormulaVar cutVar(cut, cut, *get(), false); return reduceEng(varSubset2,&cutVar,0,0,std::numeric_limits<std::size_t>::max(),kFALSE) ; } return reduceEng(varSubset2,0,0,0,std::numeric_limits<std::size_t>::max(),kFALSE) ; } //////////////////////////////////////////////////////////////////////////////// /// Create a subset of the data set by applying the given cut on the data points /// and reducing the dimensions to the specified set. /// /// The 'cutVar' formula variable is used to select the subset of data points to be /// retained in the reduced data collection. RooAbsData* RooAbsData::reduce(const RooArgSet& varSubset, const RooFormulaVar& cutVar) { // Make sure varSubset doesn't contain any variable not in this dataset RooArgSet varSubset2(varSubset) ; TIterator* iter = varSubset.createIterator() ; RooAbsArg* arg ; while((arg=(RooAbsArg*)iter->Next())) { if (!_vars.find(arg->GetName())) { coutW(InputArguments) << "RooAbsData::reduce(" << GetName() << ") WARNING: variable " << arg->GetName() << " not in dataset, ignored" << endl ; varSubset2.remove(*arg) ; } } delete iter ; return reduceEng(varSubset2,&cutVar,0,0,std::numeric_limits<std::size_t>::max(),kFALSE) ; } //////////////////////////////////////////////////////////////////////////////// /// Return error on current weight (dummy implementation returning zero) Double_t RooAbsData::weightError(ErrorType) const { return 0 ; } //////////////////////////////////////////////////////////////////////////////// /// Return asymmetric error on weight. (Dummy implementation returning zero) void RooAbsData::weightError(Double_t& lo, Double_t& hi, ErrorType) const { lo=0 ; hi=0 ; } RooPlot* RooAbsData::plotOn(RooPlot* frame, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) const { RooLinkedList l ; l.Add((TObject*)&arg1) ; l.Add((TObject*)&arg2) ; l.Add((TObject*)&arg3) ; l.Add((TObject*)&arg4) ; l.Add((TObject*)&arg5) ; l.Add((TObject*)&arg6) ; l.Add((TObject*)&arg7) ; l.Add((TObject*)&arg8) ; return plotOn(frame,l) ; } //////////////////////////////////////////////////////////////////////////////// /// Create and fill a ROOT histogram TH1,TH2 or TH3 with the values of this dataset for the variables with given names /// The range of each observable that is histogrammed is always automatically calculated from the distribution in /// the dataset. The number of bins can be controlled using the [xyz]bins parameters. For a greater degree of control /// use the createHistogram() method below with named arguments /// /// The caller takes ownership of the returned histogram TH1 *RooAbsData::createHistogram(const char* varNameList, Int_t xbins, Int_t ybins, Int_t zbins) const { // Parse list of variable names char buf[1024] ; strlcpy(buf,varNameList,1024) ; char* varName = strtok(buf,",:") ; RooRealVar* xvar = (RooRealVar*) get()->find(varName) ; if (!xvar) { coutE(InputArguments) << "RooAbsData::createHistogram(" << GetName() << ") ERROR: dataset does not contain an observable named " << varName << endl ; return 0 ; } varName = strtok(0,",") ; RooRealVar* yvar = varName ? (RooRealVar*) get()->find(varName) : 0 ; if (varName && !yvar) { coutE(InputArguments) << "RooAbsData::createHistogram(" << GetName() << ") ERROR: dataset does not contain an observable named " << varName << endl ; return 0 ; } varName = strtok(0,",") ; RooRealVar* zvar = varName ? (RooRealVar*) get()->find(varName) : 0 ; if (varName && !zvar) { coutE(InputArguments) << "RooAbsData::createHistogram(" << GetName() << ") ERROR: dataset does not contain an observable named " << varName << endl ; return 0 ; } // Construct list of named arguments to pass to the implementation version of createHistogram() RooLinkedList argList ; if (xbins<=0 || !xvar->hasMax() || !xvar->hasMin() ) { argList.Add(RooFit::AutoBinning(xbins==0?xvar->numBins():abs(xbins)).Clone()) ; } else { argList.Add(RooFit::Binning(xbins).Clone()) ; } if (yvar) { if (ybins<=0 || !yvar->hasMax() || !yvar->hasMin() ) { argList.Add(RooFit::YVar(*yvar,RooFit::AutoBinning(ybins==0?yvar->numBins():abs(ybins))).Clone()) ; } else { argList.Add(RooFit::YVar(*yvar,RooFit::Binning(ybins)).Clone()) ; } } if (zvar) { if (zbins<=0 || !zvar->hasMax() || !zvar->hasMin() ) { argList.Add(RooFit::ZVar(*zvar,RooFit::AutoBinning(zbins==0?zvar->numBins():abs(zbins))).Clone()) ; } else { argList.Add(RooFit::ZVar(*zvar,RooFit::Binning(zbins)).Clone()) ; } } // Call implementation function TH1* result = createHistogram(GetName(),*xvar,argList) ; // Delete temporary list of RooCmdArgs argList.Delete() ; return result ; } TH1 *RooAbsData::createHistogram(const char *name, const RooAbsRealLValue& xvar, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) const { RooLinkedList l ; l.Add((TObject*)&arg1) ; l.Add((TObject*)&arg2) ; l.Add((TObject*)&arg3) ; l.Add((TObject*)&arg4) ; l.Add((TObject*)&arg5) ; l.Add((TObject*)&arg6) ; l.Add((TObject*)&arg7) ; l.Add((TObject*)&arg8) ; return createHistogram(name,xvar,l) ; } //////////////////////////////////////////////////////////////////////////////// /// /// This function accepts the following arguments /// /// \param[in] name Name of the ROOT histogram /// \param[in] xvar Observable to be mapped on x axis of ROOT histogram /// \return Histogram now owned by user. /// /// <table> /// <tr><td> `AutoBinning(Int_t nbins, Double_y margin)` <td> Automatically calculate range with given added fractional margin, set binning to nbins /// <tr><td> `AutoSymBinning(Int_t nbins, Double_y margin)` <td> Automatically calculate range with given added fractional margin, /// with additional constraint that mean of data is in center of range, set binning to nbins /// <tr><td> `Binning(const char* name)` <td> Apply binning with given name to x axis of histogram /// <tr><td> `Binning(RooAbsBinning& binning)` <td> Apply specified binning to x axis of histogram /// <tr><td> `Binning(int nbins, double lo, double hi)` <td> Apply specified binning to x axis of histogram /// /// <tr><td> `YVar(const RooAbsRealLValue& var,...)` <td> Observable to be mapped on y axis of ROOT histogram /// <tr><td> `ZVar(const RooAbsRealLValue& var,...)` <td> Observable to be mapped on z axis of ROOT histogram /// </table> /// /// The YVar() and ZVar() arguments can be supplied with optional Binning() Auto(Sym)Range() arguments to control the binning of the Y and Z axes, e.g. /// ``` /// createHistogram("histo",x,Binning(-1,1,20), YVar(y,Binning(-1,1,30)), ZVar(z,Binning("zbinning"))) /// ``` /// /// The caller takes ownership of the returned histogram TH1 *RooAbsData::createHistogram(const char *name, const RooAbsRealLValue& xvar, const RooLinkedList& argListIn) const { RooLinkedList argList(argListIn) ; // Define configuration for this method RooCmdConfig pc(Form("RooAbsData::createHistogram(%s)",GetName())) ; pc.defineString("cutRange","CutRange",0,"",kTRUE) ; pc.defineString("cutString","CutSpec",0,"") ; pc.defineObject("yvar","YVar",0,0) ; pc.defineObject("zvar","ZVar",0,0) ; pc.allowUndefined() ; // Process & check varargs pc.process(argList) ; if (!pc.ok(kTRUE)) { return 0 ; } const char* cutSpec = pc.getString("cutString",0,kTRUE) ; const char* cutRange = pc.getString("cutRange",0,kTRUE) ; RooArgList vars(xvar) ; RooAbsArg* yvar = static_cast<RooAbsArg*>(pc.getObject("yvar")) ; if (yvar) { vars.add(*yvar) ; } RooAbsArg* zvar = static_cast<RooAbsArg*>(pc.getObject("zvar")) ; if (zvar) { vars.add(*zvar) ; } pc.stripCmdList(argList,"CutRange,CutSpec") ; // Swap Auto(Sym)RangeData with a Binning command RooLinkedList ownedCmds ; RooCmdArg* autoRD = (RooCmdArg*) argList.find("AutoRangeData") ; if (autoRD) { Double_t xmin,xmax ; if (!getRange((RooRealVar&)xvar,xmin,xmax,autoRD->getDouble(0),autoRD->getInt(0))) { RooCmdArg* bincmd = (RooCmdArg*) RooFit::Binning(autoRD->getInt(1),xmin,xmax).Clone() ; ownedCmds.Add(bincmd) ; argList.Replace(autoRD,bincmd) ; } } if (yvar) { RooCmdArg* autoRDY = (RooCmdArg*) ((RooCmdArg*)argList.find("YVar"))->subArgs().find("AutoRangeData") ; if (autoRDY) { Double_t ymin,ymax ; if (!getRange((RooRealVar&)(*yvar),ymin,ymax,autoRDY->getDouble(0),autoRDY->getInt(0))) { RooCmdArg* bincmd = (RooCmdArg*) RooFit::Binning(autoRDY->getInt(1),ymin,ymax).Clone() ; //ownedCmds.Add(bincmd) ; ((RooCmdArg*)argList.find("YVar"))->subArgs().Replace(autoRDY,bincmd) ; } delete autoRDY ; } } if (zvar) { RooCmdArg* autoRDZ = (RooCmdArg*) ((RooCmdArg*)argList.find("ZVar"))->subArgs().find("AutoRangeData") ; if (autoRDZ) { Double_t zmin,zmax ; if (!getRange((RooRealVar&)(*zvar),zmin,zmax,autoRDZ->getDouble(0),autoRDZ->getInt(0))) { RooCmdArg* bincmd = (RooCmdArg*) RooFit::Binning(autoRDZ->getInt(1),zmin,zmax).Clone() ; //ownedCmds.Add(bincmd) ; ((RooCmdArg*)argList.find("ZVar"))->subArgs().Replace(autoRDZ,bincmd) ; } delete autoRDZ ; } } TH1* histo = xvar.createHistogram(name,argList) ; fillHistogram(histo,vars,cutSpec,cutRange) ; ownedCmds.Delete() ; return histo ; } //////////////////////////////////////////////////////////////////////////////// /// Construct table for product of categories in catSet Roo1DTable* RooAbsData::table(const RooArgSet& catSet, const char* cuts, const char* opts) const { RooArgSet catSet2 ; string prodName("(") ; TIterator* iter = catSet.createIterator() ; RooAbsArg* arg ; while((arg=(RooAbsArg*)iter->Next())) { if (dynamic_cast<RooAbsCategory*>(arg)) { RooAbsCategory* varsArg = dynamic_cast<RooAbsCategory*>(_vars.find(arg->GetName())) ; if (varsArg != 0) catSet2.add(*varsArg) ; else catSet2.add(*arg) ; if (prodName.length()>1) { prodName += " x " ; } prodName += arg->GetName() ; } else { coutW(InputArguments) << "RooAbsData::table(" << GetName() << ") non-RooAbsCategory input argument " << arg->GetName() << " ignored" << endl ; } } prodName += ")" ; delete iter ; RooMultiCategory tmp(prodName.c_str(),prodName.c_str(),catSet2) ; return table(tmp,cuts,opts) ; } //////////////////////////////////////////////////////////////////////////////// /// Print name of dataset void RooAbsData::printName(ostream& os) const { os << GetName() ; } //////////////////////////////////////////////////////////////////////////////// /// Print title of dataset void RooAbsData::printTitle(ostream& os) const { os << GetTitle() ; } //////////////////////////////////////////////////////////////////////////////// /// Print class name of dataset void RooAbsData::printClassName(ostream& os) const { os << IsA()->GetName() ; } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::printMultiline(ostream& os, Int_t contents, Bool_t verbose, TString indent) const { _dstore->printMultiline(os,contents,verbose,indent) ; } //////////////////////////////////////////////////////////////////////////////// /// Define default print options, for a given print style Int_t RooAbsData::defaultPrintContents(Option_t* /*opt*/) const { return kName|kClassName|kArgs|kValue ; } //////////////////////////////////////////////////////////////////////////////// /// Calculate standardized moment. /// /// \param[in] var Variable to be used for calculating the moment. /// \param[in] order Order of the moment. /// \param[in] cutSpec If specified, the moment is calculated on the subset of the data which pass the C++ cut specification expression 'cutSpec' /// \param[in] cutRange If specified, calculate inside the range named 'cutRange' (also applies cut spec) /// \return \f$ \frac{\left< \left( X - \left< X \right> \right)^n \right>}{\sigma^n} \f$, where n = order. Double_t RooAbsData::standMoment(const RooRealVar &var, Double_t order, const char* cutSpec, const char* cutRange) const { // Hardwire invariant answer for first and second moment if (order==1) return 0 ; if (order==2) return 1 ; return moment(var,order,cutSpec,cutRange) / TMath::Power(sigma(var,cutSpec,cutRange),order) ; } //////////////////////////////////////////////////////////////////////////////// /// Calculate moment of requested order. /// /// \param[in] var Variable to be used for calculating the moment. /// \param[in] order Order of the moment. /// \param[in] cutSpec If specified, the moment is calculated on the subset of the data which pass the C++ cut specification expression 'cutSpec' /// \param[in] cutRange If specified, calculate inside the range named 'cutRange' (also applies cut spec) /// \return \f$ \left< \left( X - \left< X \right> \right)^n \right> \f$ of order \f$n\f$. /// Double_t RooAbsData::moment(const RooRealVar& var, Double_t order, const char* cutSpec, const char* cutRange) const { Double_t offset = order>1 ? moment(var,1,cutSpec,cutRange) : 0 ; return moment(var,order,offset,cutSpec,cutRange) ; } //////////////////////////////////////////////////////////////////////////////// /// Return the 'order'-ed moment of observable 'var' in this dataset. If offset is non-zero it is subtracted /// from the values of 'var' prior to the moment calculation. If cutSpec and/or cutRange are specified /// the moment is calculated on the subset of the data which pass the C++ cut specification expression 'cutSpec' /// and/or are inside the range named 'cutRange' Double_t RooAbsData::moment(const RooRealVar& var, Double_t order, Double_t offset, const char* cutSpec, const char* cutRange) const { // Lookup variable in dataset auto arg = _vars.find(var.GetName()); if (!arg) { coutE(InputArguments) << "RooDataSet::moment(" << GetName() << ") ERROR: unknown variable: " << var.GetName() << endl ; return 0; } auto varPtr = dynamic_cast<const RooRealVar*>(arg); // Check if found variable is of type RooRealVar if (!varPtr) { coutE(InputArguments) << "RooDataSet::moment(" << GetName() << ") ERROR: variable " << var.GetName() << " is not of type RooRealVar" << endl ; return 0; } // Check if dataset is not empty if(sumEntries(cutSpec, cutRange) == 0.) { coutE(InputArguments) << "RooDataSet::moment(" << GetName() << ") WARNING: empty dataset" << endl ; return 0; } // Setup RooFormulaVar for cutSpec if it is present std::unique_ptr<RooFormula> select; if (cutSpec) { select.reset(new RooFormula("select",cutSpec,*get())); } // Calculate requested moment ROOT::Math::KahanSum<double> sum; for(Int_t index= 0; index < numEntries(); index++) { const RooArgSet* vars = get(index) ; if (select && select->eval()==0) continue ; if (cutRange && vars->allInRange(cutRange)) continue ; sum += weight() * TMath::Power(varPtr->getVal() - offset,order); } return sum/sumEntries(cutSpec, cutRange); } //////////////////////////////////////////////////////////////////////////////// /// Internal method to check if given RooRealVar maps to a RooRealVar in this dataset RooRealVar* RooAbsData::dataRealVar(const char* methodname, const RooRealVar& extVar) const { // Lookup variable in dataset RooRealVar *xdata = (RooRealVar*) _vars.find(extVar.GetName()); if(!xdata) { coutE(InputArguments) << "RooDataSet::" << methodname << "(" << GetName() << ") ERROR: variable : " << extVar.GetName() << " is not in data" << endl ; return 0; } // Check if found variable is of type RooRealVar if (!dynamic_cast<RooRealVar*>(xdata)) { coutE(InputArguments) << "RooDataSet::" << methodname << "(" << GetName() << ") ERROR: variable : " << extVar.GetName() << " is not of type RooRealVar in data" << endl ; return 0; } return xdata; } //////////////////////////////////////////////////////////////////////////////// /// Internal method to calculate single correlation and covariance elements Double_t RooAbsData::corrcov(const RooRealVar &x, const RooRealVar &y, const char* cutSpec, const char* cutRange, Bool_t corr) const { // Lookup variable in dataset RooRealVar *xdata = dataRealVar(corr?"correlation":"covariance",x) ; RooRealVar *ydata = dataRealVar(corr?"correlation":"covariance",y) ; if (!xdata||!ydata) return 0 ; // Check if dataset is not empty if(sumEntries(cutSpec, cutRange) == 0.) { coutW(InputArguments) << "RooDataSet::" << (corr?"correlation":"covariance") << "(" << GetName() << ") WARNING: empty dataset, returning zero" << endl ; return 0; } // Setup RooFormulaVar for cutSpec if it is present RooFormula* select = cutSpec ? new RooFormula("select",cutSpec,*get()) : 0 ; // Calculate requested moment Double_t xysum(0),xsum(0),ysum(0),x2sum(0),y2sum(0); const RooArgSet* vars ; for(Int_t index= 0; index < numEntries(); index++) { vars = get(index) ; if (select && select->eval()==0) continue ; if (cutRange && vars->allInRange(cutRange)) continue ; xysum += weight()*xdata->getVal()*ydata->getVal() ; xsum += weight()*xdata->getVal() ; ysum += weight()*ydata->getVal() ; if (corr) { x2sum += weight()*xdata->getVal()*xdata->getVal() ; y2sum += weight()*ydata->getVal()*ydata->getVal() ; } } // Normalize entries xysum/=sumEntries(cutSpec, cutRange) ; xsum/=sumEntries(cutSpec, cutRange) ; ysum/=sumEntries(cutSpec, cutRange) ; if (corr) { x2sum/=sumEntries(cutSpec, cutRange) ; y2sum/=sumEntries(cutSpec, cutRange) ; } // Cleanup if (select) delete select ; // Return covariance or correlation as requested if (corr) { return (xysum-xsum*ysum)/(sqrt(x2sum-(xsum*xsum))*sqrt(y2sum-(ysum*ysum))) ; } else { return (xysum-xsum*ysum); } } //////////////////////////////////////////////////////////////////////////////// /// Return covariance matrix from data for given list of observables TMatrixDSym* RooAbsData::corrcovMatrix(const RooArgList& vars, const char* cutSpec, const char* cutRange, Bool_t corr) const { RooArgList varList ; TIterator* iter = vars.createIterator() ; RooRealVar* var ; while((var=(RooRealVar*)iter->Next())) { RooRealVar* datavar = dataRealVar("covarianceMatrix",*var) ; if (!datavar) { delete iter ; return 0 ; } varList.add(*datavar) ; } delete iter ; // Check if dataset is not empty if(sumEntries(cutSpec, cutRange) == 0.) { coutW(InputArguments) << "RooDataSet::covariance(" << GetName() << ") WARNING: empty dataset, returning zero" << endl ; return 0; } // Setup RooFormulaVar for cutSpec if it is present RooFormula* select = cutSpec ? new RooFormula("select",cutSpec,*get()) : 0 ; iter = varList.createIterator() ; TIterator* iter2 = varList.createIterator() ; TMatrixDSym xysum(varList.getSize()) ; vector<double> xsum(varList.getSize()) ; vector<double> x2sum(varList.getSize()) ; // Calculate <x_i> and <x_i y_j> for(Int_t index= 0; index < numEntries(); index++) { const RooArgSet* dvars = get(index) ; if (select && select->eval()==0) continue ; if (cutRange && dvars->allInRange(cutRange)) continue ; RooRealVar* varx, *vary ; iter->Reset() ; Int_t ix=0,iy=0 ; while((varx=(RooRealVar*)iter->Next())) { xsum[ix] += weight()*varx->getVal() ; if (corr) { x2sum[ix] += weight()*varx->getVal()*varx->getVal() ; } *iter2=*iter ; iy=ix ; vary=varx ; while(vary) { xysum(ix,iy) += weight()*varx->getVal()*vary->getVal() ; xysum(iy,ix) = xysum(ix,iy) ; iy++ ; vary=(RooRealVar*)iter2->Next() ; } ix++ ; } } // Normalize sums for (Int_t ix=0 ; ix<varList.getSize() ; ix++) { xsum[ix] /= sumEntries(cutSpec, cutRange) ; if (corr) { x2sum[ix] /= sumEntries(cutSpec, cutRange) ; } for (Int_t iy=0 ; iy<varList.getSize() ; iy++) { xysum(ix,iy) /= sumEntries(cutSpec, cutRange) ; } } // Calculate covariance matrix TMatrixDSym* C = new TMatrixDSym(varList.getSize()) ; for (Int_t ix=0 ; ix<varList.getSize() ; ix++) { for (Int_t iy=0 ; iy<varList.getSize() ; iy++) { (*C)(ix,iy) = xysum(ix,iy)-xsum[ix]*xsum[iy] ; if (corr) { (*C)(ix,iy) /= sqrt((x2sum[ix]-(xsum[ix]*xsum[ix]))*(x2sum[iy]-(xsum[iy]*xsum[iy]))) ; } } } if (select) delete select ; delete iter ; delete iter2 ; return C ; } //////////////////////////////////////////////////////////////////////////////// /// Create a RooRealVar containing the mean of observable 'var' in /// this dataset. If cutSpec and/or cutRange are specified the /// moment is calculated on the subset of the data which pass the C++ /// cut specification expression 'cutSpec' and/or are inside the /// range named 'cutRange' RooRealVar* RooAbsData::meanVar(const RooRealVar &var, const char* cutSpec, const char* cutRange) const { // Create a new variable with appropriate strings. The error is calculated as // RMS/Sqrt(N) which is generally valid. // Create holder variable for mean TString name(var.GetName()),title("Mean of ") ; name.Append("Mean"); title.Append(var.GetTitle()); RooRealVar *meanv= new RooRealVar(name,title,0) ; meanv->setConstant(kFALSE) ; // Adjust plot label TString label("<") ; label.Append(var.getPlotLabel()); label.Append(">"); meanv->setPlotLabel(label.Data()); // fill in this variable's value and error Double_t meanVal=moment(var,1,0,cutSpec,cutRange) ; Double_t N(sumEntries(cutSpec,cutRange)) ; Double_t rmsVal= sqrt(moment(var,2,meanVal,cutSpec,cutRange)*N/(N-1)); meanv->setVal(meanVal) ; meanv->setError(N > 0 ? rmsVal/sqrt(N) : 0); return meanv; } //////////////////////////////////////////////////////////////////////////////// /// Create a RooRealVar containing the RMS of observable 'var' in /// this dataset. If cutSpec and/or cutRange are specified the /// moment is calculated on the subset of the data which pass the C++ /// cut specification expression 'cutSpec' and/or are inside the /// range named 'cutRange' RooRealVar* RooAbsData::rmsVar(const RooRealVar &var, const char* cutSpec, const char* cutRange) const { // Create a new variable with appropriate strings. The error is calculated as // RMS/(2*Sqrt(N)) which is only valid if the variable has a Gaussian distribution. // Create RMS value holder TString name(var.GetName()),title("RMS of ") ; name.Append("RMS"); title.Append(var.GetTitle()); RooRealVar *rms= new RooRealVar(name,title,0) ; rms->setConstant(kFALSE) ; // Adjust plot label TString label(var.getPlotLabel()); label.Append("_{RMS}"); rms->setPlotLabel(label); // Fill in this variable's value and error Double_t meanVal(moment(var,1,0,cutSpec,cutRange)) ; Double_t N(sumEntries(cutSpec, cutRange)); Double_t rmsVal= sqrt(moment(var,2,meanVal,cutSpec,cutRange)*N/(N-1)); rms->setVal(rmsVal) ; rms->setError(rmsVal/sqrt(2*N)); return rms; } //////////////////////////////////////////////////////////////////////////////// /// Add a box with statistics information to the specified frame. By default a box with the /// event count, mean and rms of the plotted variable is added. /// /// The following optional named arguments are accepted /// <table> /// <tr><td> `What(const char* whatstr)` <td> Controls what is printed: "N" = count, "M" is mean, "R" is RMS. /// <tr><td> `Format(const char* optStr)` <td> \deprecated Classing parameter formatting options, provided for backward compatibility /// /// <tr><td> `Format(const char* what,...)` <td> Parameter formatting options. /// <table> /// <tr><td> const char* what <td> Controls what is shown: /// - "N" adds name /// - "E" adds error /// - "A" shows asymmetric error /// - "U" shows unit /// - "H" hides the value /// <tr><td> `FixedPrecision(int n)` <td> Controls precision, set fixed number of digits /// <tr><td> `AutoPrecision(int n)` <td> Controls precision. Number of shown digits is calculated from error + n specified additional digits (1 is sensible default) /// <tr><td> `VerbatimName(Bool_t flag)` <td> Put variable name in a \\verb+ + clause. /// </table> /// <tr><td> `Label(const chat* label)` <td> Add header label to parameter box /// <tr><td> `Layout(Double_t xmin, Double_t xmax, Double_t ymax)` <td> Specify relative position of left,right side of box and top of box. Position of /// bottom of box is calculated automatically from number lines in box /// <tr><td> `Cut(const char* expression)` <td> Apply given cut expression to data when calculating statistics /// <tr><td> `CutRange(const char* rangeName)` <td> Only consider events within given range when calculating statistics. Multiple /// CutRange() argument may be specified to combine ranges. /// /// </table> RooPlot* RooAbsData::statOn(RooPlot* frame, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) { // Stuff all arguments in a list RooLinkedList cmdList; cmdList.Add(const_cast<RooCmdArg*>(&arg1)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg2)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg3)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg4)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg5)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg6)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg7)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg8)) ; // Select the pdf-specific commands RooCmdConfig pc(Form("RooTreeData::statOn(%s)",GetName())) ; pc.defineString("what","What",0,"MNR") ; pc.defineString("label","Label",0,"") ; pc.defineDouble("xmin","Layout",0,0.65) ; pc.defineDouble("xmax","Layout",1,0.99) ; pc.defineInt("ymaxi","Layout",0,Int_t(0.95*10000)) ; pc.defineString("formatStr","Format",0,"NELU") ; pc.defineInt("sigDigit","Format",0,2) ; pc.defineInt("dummy","FormatArgs",0,0) ; pc.defineString("cutRange","CutRange",0,"",kTRUE) ; pc.defineString("cutString","CutSpec",0,"") ; pc.defineMutex("Format","FormatArgs") ; // Process and check varargs pc.process(cmdList) ; if (!pc.ok(kTRUE)) { return frame ; } const char* label = pc.getString("label") ; Double_t xmin = pc.getDouble("xmin") ; Double_t xmax = pc.getDouble("xmax") ; Double_t ymax = pc.getInt("ymaxi") / 10000. ; const char* formatStr = pc.getString("formatStr") ; Int_t sigDigit = pc.getInt("sigDigit") ; const char* what = pc.getString("what") ; const char* cutSpec = pc.getString("cutString",0,kTRUE) ; const char* cutRange = pc.getString("cutRange",0,kTRUE) ; if (pc.hasProcessed("FormatArgs")) { RooCmdArg* formatCmd = static_cast<RooCmdArg*>(cmdList.FindObject("FormatArgs")) ; return statOn(frame,what,label,0,0,xmin,xmax,ymax,cutSpec,cutRange,formatCmd) ; } else { return statOn(frame,what,label,sigDigit,formatStr,xmin,xmax,ymax,cutSpec,cutRange) ; } } //////////////////////////////////////////////////////////////////////////////// /// Implementation back-end of statOn() method with named arguments RooPlot* RooAbsData::statOn(RooPlot* frame, const char* what, const char *label, Int_t sigDigits, Option_t *options, Double_t xmin, Double_t xmax, Double_t ymax, const char* cutSpec, const char* cutRange, const RooCmdArg* formatCmd) { Bool_t showLabel= (label != 0 && strlen(label) > 0); TString whatStr(what) ; whatStr.ToUpper() ; Bool_t showN = whatStr.Contains("N") ; Bool_t showR = whatStr.Contains("R") ; Bool_t showM = whatStr.Contains("M") ; Int_t nPar= 0; if (showN) nPar++ ; if (showR) nPar++ ; if (showM) nPar++ ; // calculate the box's size Double_t dy(0.06), ymin(ymax-nPar*dy); if(showLabel) ymin-= dy; // create the box and set its options TPaveText *box= new TPaveText(xmin,ymax,xmax,ymin,"BRNDC"); if(!box) return 0; box->SetName(Form("%s_statBox",GetName())) ; box->SetFillColor(0); box->SetBorderSize(1); box->SetTextAlign(12); box->SetTextSize(0.04F); box->SetFillStyle(1001); // add formatted text for each statistic RooRealVar N("N","Number of Events",sumEntries(cutSpec,cutRange)); N.setPlotLabel("Entries") ; RooRealVar *meanv= meanVar(*(RooRealVar*)frame->getPlotVar(),cutSpec,cutRange); meanv->setPlotLabel("Mean") ; RooRealVar *rms= rmsVar(*(RooRealVar*)frame->getPlotVar(),cutSpec,cutRange); rms->setPlotLabel("RMS") ; TString *rmsText, *meanText, *NText ; if (options) { rmsText= rms->format(sigDigits,options); meanText= meanv->format(sigDigits,options); NText= N.format(sigDigits,options); } else { rmsText= rms->format(*formatCmd); meanText= meanv->format(*formatCmd); NText= N.format(*formatCmd); } if (showR) box->AddText(rmsText->Data()); if (showM) box->AddText(meanText->Data()); if (showN) box->AddText(NText->Data()); // cleanup heap memory delete NText; delete meanText; delete rmsText; delete meanv; delete rms; // add the optional label if specified if(showLabel) box->AddText(label); frame->addObject(box) ; return frame ; } //////////////////////////////////////////////////////////////////////////////// /// Loop over columns of our tree data and fill the input histogram. Returns a pointer to the /// input histogram, or zero in case of an error. The input histogram can be any TH1 subclass, and /// therefore of arbitrary dimension. Variables are matched with the (x,y,...) dimensions of the input /// histogram according to the order in which they appear in the input plotVars list. TH1 *RooAbsData::fillHistogram(TH1 *hist, const RooArgList &plotVars, const char *cuts, const char* cutRange) const { // Do we have a valid histogram to use? if(0 == hist) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: no valid histogram to fill" << endl; return 0; } // Check that the number of plotVars matches the input histogram's dimension Int_t hdim= hist->GetDimension(); if(hdim != plotVars.getSize()) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: plotVars has the wrong dimension" << endl; return 0; } // Check that the plot variables are all actually RooAbsReal's and print a warning if we do not // explicitly depend on one of them. Clone any variables that we do not contain directly and // redirect them to use our event data. RooArgSet plotClones,localVars; for(Int_t index= 0; index < plotVars.getSize(); index++) { const RooAbsArg *var= plotVars.at(index); const RooAbsReal *realVar= dynamic_cast<const RooAbsReal*>(var); if(0 == realVar) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: cannot plot variable \"" << var->GetName() << "\" of type " << var->ClassName() << endl; return 0; } RooAbsArg *found= _vars.find(realVar->GetName()); if(!found) { RooAbsArg *clone= plotClones.addClone(*realVar,kTRUE); // do not complain about duplicates assert(0 != clone); if(!clone->dependsOn(_vars)) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: Data does not contain the variable '" << realVar->GetName() << "'." << endl; return nullptr; } else { clone->recursiveRedirectServers(_vars); } localVars.add(*clone); } else { localVars.add(*found); } } // Create selection formula if selection cuts are specified std::unique_ptr<RooFormula> select; if (cuts != nullptr && strlen(cuts) > 0) { select.reset(new RooFormula(cuts, cuts, _vars, false)); if (!select || !select->ok()) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: invalid cuts \"" << cuts << "\"" << endl; return 0 ; } } // Lookup each of the variables we are binning in our tree variables const RooAbsReal *xvar = 0; const RooAbsReal *yvar = 0; const RooAbsReal *zvar = 0; switch(hdim) { case 3: zvar= dynamic_cast<RooAbsReal*>(localVars.find(plotVars.at(2)->GetName())); assert(0 != zvar); // fall through to next case... case 2: yvar= dynamic_cast<RooAbsReal*>(localVars.find(plotVars.at(1)->GetName())); assert(0 != yvar); // fall through to next case... case 1: xvar= dynamic_cast<RooAbsReal*>(localVars.find(plotVars.at(0)->GetName())); assert(0 != xvar); break; default: coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: cannot fill histogram with " << hdim << " dimensions" << endl; break; } // Parse cutRange specification vector<string> cutVec ; if (cutRange && strlen(cutRange)>0) { if (strchr(cutRange,',')==0) { cutVec.push_back(cutRange) ; } else { const size_t bufSize = strlen(cutRange)+1; char* buf = new char[bufSize] ; strlcpy(buf,cutRange,bufSize) ; const char* oneRange = strtok(buf,",") ; while(oneRange) { cutVec.push_back(oneRange) ; oneRange = strtok(0,",") ; } delete[] buf ; } } // Loop over events and fill the histogram if (hist->GetSumw2()->fN==0) { hist->Sumw2() ; } Int_t nevent= numEntries() ; //(Int_t)_tree->GetEntries(); for(Int_t i=0; i < nevent; ++i) { //Int_t entryNumber= _tree->GetEntryNumber(i); //if (entryNumber<0) break; get(i); // Apply expression based selection criteria if (select && select->eval()==0) { continue ; } // Apply range based selection criteria Bool_t selectByRange = kTRUE ; if (cutRange) { for (const auto arg : _vars) { Bool_t selectThisArg = kFALSE ; UInt_t icut ; for (icut=0 ; icut<cutVec.size() ; icut++) { if (arg->inRange(cutVec[icut].c_str())) { selectThisArg = kTRUE ; break ; } } if (!selectThisArg) { selectByRange = kFALSE ; break ; } } } if (!selectByRange) { // Go to next event in loop over events continue ; } Int_t bin(0); switch(hdim) { case 1: bin= hist->FindBin(xvar->getVal()); hist->Fill(xvar->getVal(),weight()) ; break; case 2: bin= hist->FindBin(xvar->getVal(),yvar->getVal()); static_cast<TH2*>(hist)->Fill(xvar->getVal(),yvar->getVal(),weight()) ; break; case 3: bin= hist->FindBin(xvar->getVal(),yvar->getVal(),zvar->getVal()); static_cast<TH3*>(hist)->Fill(xvar->getVal(),yvar->getVal(),zvar->getVal(),weight()) ; break; default: assert(hdim < 3); break; } Double_t error2 = TMath::Power(hist->GetBinError(bin),2)-TMath::Power(weight(),2) ; Double_t we = weightError(RooAbsData::SumW2) ; if (we==0) we = weight() ; error2 += TMath::Power(we,2) ; // Double_t we = weightError(RooAbsData::SumW2) ; // Double_t error2(0) ; // if (we==0) { // we = weight() ; //sqrt(weight()) ; // error2 = TMath::Power(hist->GetBinError(bin),2)-TMath::Power(weight(),2) + TMath::Power(we,2) ; // } else { // error2 = TMath::Power(hist->GetBinError(bin),2)-TMath::Power(weight(),2) + TMath::Power(we,2) ; // } //hist->AddBinContent(bin,weight()); hist->SetBinError(bin,sqrt(error2)) ; //cout << "RooTreeData::fillHistogram() bin = " << bin << " weight() = " << weight() << " we = " << we << endl ; } return hist; } //////////////////////////////////////////////////////////////////////////////// /// Split dataset into subsets based on states of given splitCat in this dataset. /// A TList of RooDataSets is returned in which each RooDataSet is named /// after the state name of splitCat of which it contains the dataset subset. /// The observables splitCat itself is no longer present in the sub datasets. /// If createEmptyDataSets is kFALSE (default) this method only creates datasets for states /// which have at least one entry The caller takes ownership of the returned list and its contents TList* RooAbsData::split(const RooAbsCategory& splitCat, Bool_t createEmptyDataSets) const { // Sanity check if (!splitCat.dependsOn(*get())) { coutE(InputArguments) << "RooTreeData::split(" << GetName() << ") ERROR category " << splitCat.GetName() << " doesn't depend on any variable in this dataset" << endl ; return 0 ; } // Clone splitting category and attach to self RooAbsCategory* cloneCat =0; RooArgSet* cloneSet = 0; if (splitCat.isDerived()) { cloneSet = (RooArgSet*) RooArgSet(splitCat).snapshot(kTRUE) ; if (!cloneSet) { coutE(InputArguments) << "RooTreeData::split(" << GetName() << ") Couldn't deep-clone splitting category, abort." << endl ; return 0 ; } cloneCat = (RooAbsCategory*) cloneSet->find(splitCat.GetName()) ; cloneCat->attachDataSet(*this) ; } else { cloneCat = dynamic_cast<RooAbsCategory*>(get()->find(splitCat.GetName())) ; if (!cloneCat) { coutE(InputArguments) << "RooTreeData::split(" << GetName() << ") ERROR category " << splitCat.GetName() << " is fundamental and does not appear in this dataset" << endl ; return 0 ; } } // Split a dataset in a series of subsets, each corresponding // to a state of splitCat TList* dsetList = new TList ; // Construct set of variables to be included in split sets = full set - split category RooArgSet subsetVars(*get()) ; if (splitCat.isDerived()) { RooArgSet* vars = splitCat.getVariables() ; subsetVars.remove(*vars,kTRUE,kTRUE) ; delete vars ; } else { subsetVars.remove(splitCat,kTRUE,kTRUE) ; } // Add weight variable explicitly if dataset has weights, but no top-level weight // variable exists (can happen with composite datastores) Bool_t addWV(kFALSE) ; RooRealVar newweight("weight","weight",-1e9,1e9) ; if (isWeighted() && !IsA()->InheritsFrom(RooDataHist::Class())) { subsetVars.add(newweight) ; addWV = kTRUE ; } // If createEmptyDataSets is true, prepopulate with empty sets corresponding to all states if (createEmptyDataSets) { for (const auto& nameIdx : *cloneCat) { RooAbsData* subset = emptyClone(nameIdx.first.c_str(), nameIdx.first.c_str(), &subsetVars,(addWV?"weight":0)) ; dsetList->Add((RooAbsArg*)subset) ; } } // Loop over dataset and copy event to matching subset const bool propWeightSquared = isWeighted(); for (Int_t i = 0; i < numEntries(); ++i) { const RooArgSet* row = get(i); RooAbsData* subset = (RooAbsData*) dsetList->FindObject(cloneCat->getCurrentLabel()); if (!subset) { subset = emptyClone(cloneCat->getCurrentLabel(),cloneCat->getCurrentLabel(),&subsetVars,(addWV?"weight":0)); dsetList->Add((RooAbsArg*)subset); } if (!propWeightSquared) { subset->add(*row, weight()); } else { subset->add(*row, weight(), weightSquared()); } } delete cloneSet; return dsetList; } //////////////////////////////////////////////////////////////////////////////// /// Plot dataset on specified frame. /// /// By default: /// - An unbinned dataset will use the default binning of the target frame. /// - A binned dataset will retain its intrinsic binning. /// /// The following optional named arguments can be used to modify the behaviour: /// /// <table> /// <tr><th> <th> Data representation options /// <tr><td> `Asymmetry(const RooCategory& c)` <td> Show the asymmetry of the data in given two-state category [F(+)-F(-)] / [F(+)+F(-)]. /// Category must have two states with indices -1 and +1 or three states with indices -1,0 and +1. /// <tr><td> `Efficiency(const RooCategory& c)` <td> Show the efficiency F(acc)/[F(acc)+F(rej)]. Category must have two states with indices 0 and 1 /// <tr><td> `DataError(RooAbsData::EType)` <td> Select the type of error drawn: /// - `Auto(default)` results in Poisson for unweighted data and SumW2 for weighted data /// - `Poisson` draws asymmetric Poisson confidence intervals. /// - `SumW2` draws symmetric sum-of-weights error ( \f$ \left( \sum w \right)^2 / \sum\left(w^2\right) \f$ ) /// - `None` draws no error bars /// <tr><td> `Binning(int nbins, double xlo, double xhi)` <td> Use specified binning to draw dataset /// <tr><td> `Binning(const RooAbsBinning&)` <td> Use specified binning to draw dataset /// <tr><td> `Binning(const char* name)` <td> Use binning with specified name to draw dataset /// <tr><td> `RefreshNorm(Bool_t flag)` <td> Force refreshing for PDF normalization information in frame. /// If set, any subsequent PDF will normalize to this dataset, even if it is /// not the first one added to the frame. By default only the 1st dataset /// added to a frame will update the normalization information /// <tr><td> `Rescale(Double_t f)` <td> Rescale drawn histogram by given factor. /// <tr><td> `Cut(const char*)` <td> Only plot entries that pass the given cut. /// Apart from cutting in continuous variables `Cut("x>5")`, this can also be used to plot a specific /// category state. Use something like `Cut("myCategory == myCategory::stateA")`, where /// `myCategory` resolves to the state number for a given entry and /// `myCategory::stateA` resolves to the state number of the state named "stateA". /// /// <tr><td> `CutRange(const char*)` <td> Only plot data from given range. Separate multiple ranges with ",". /// \note This often requires passing the normalisation when plotting the PDF because RooFit does not save /// how many events were being plotted (it will only work for cutting slices out of uniformly distributed variables). /// ``` /// data->plotOn(frame01, CutRange("SB1")); /// const double nData = data->sumEntries("", "SB1"); /// // Make clear that the target normalisation is nData. The enumerator NumEvent /// // is needed to switch between relative and absolute scaling. /// model.plotOn(frame01, Normalization(nData, RooAbsReal::NumEvent), /// ProjectionRange("SB1")); /// ``` /// /// <tr><th> <th> Histogram drawing options /// <tr><td> `DrawOption(const char* opt)` <td> Select ROOT draw option for resulting TGraph object /// <tr><td> `LineStyle(Int_t style)` <td> Select line style by ROOT line style code, default is solid /// <tr><td> `LineColor(Int_t color)` <td> Select line color by ROOT color code, default is black /// <tr><td> `LineWidth(Int_t width)` <td> Select line with in pixels, default is 3 /// <tr><td> `MarkerStyle(Int_t style)` <td> Select the ROOT marker style, default is 21 /// <tr><td> `MarkerColor(Int_t color)` <td> Select the ROOT marker color, default is black /// <tr><td> `MarkerSize(Double_t size)` <td> Select the ROOT marker size /// <tr><td> `FillStyle(Int_t style)` <td> Select fill style, default is filled. /// <tr><td> `FillColor(Int_t color)` <td> Select fill color by ROOT color code /// <tr><td> `XErrorSize(Double_t frac)` <td> Select size of X error bar as fraction of the bin width, default is 1 /// /// /// <tr><th> <th> Misc. other options /// <tr><td> `Name(const chat* name)` <td> Give curve specified name in frame. Useful if curve is to be referenced later /// <tr><td> `Invisible()` <td> Add curve to frame, but do not display. Useful in combination AddTo() /// <tr><td> `AddTo(const char* name, double_t wgtSelf, double_t wgtOther)` <td> Add constructed histogram to already existing histogram with given name and relative weight factors /// </table> RooPlot* RooAbsData::plotOn(RooPlot* frame, const RooLinkedList& argList) const { // New experimental plotOn() with varargs... // Define configuration for this method RooCmdConfig pc(Form("RooAbsData::plotOn(%s)",GetName())) ; pc.defineString("drawOption","DrawOption",0,"P") ; pc.defineString("cutRange","CutRange",0,"",kTRUE) ; pc.defineString("cutString","CutSpec",0,"") ; pc.defineString("histName","Name",0,"") ; pc.defineObject("cutVar","CutVar",0) ; pc.defineObject("binning","Binning",0) ; pc.defineString("binningName","BinningName",0,"") ; pc.defineInt("nbins","BinningSpec",0,100) ; pc.defineDouble("xlo","BinningSpec",0,0) ; pc.defineDouble("xhi","BinningSpec",1,1) ; pc.defineObject("asymCat","Asymmetry",0) ; pc.defineObject("effCat","Efficiency",0) ; pc.defineInt("lineColor","LineColor",0,-999) ; pc.defineInt("lineStyle","LineStyle",0,-999) ; pc.defineInt("lineWidth","LineWidth",0,-999) ; pc.defineInt("markerColor","MarkerColor",0,-999) ; pc.defineInt("markerStyle","MarkerStyle",0,-999) ; pc.defineDouble("markerSize","MarkerSize",0,-999) ; pc.defineInt("fillColor","FillColor",0,-999) ; pc.defineInt("fillStyle","FillStyle",0,-999) ; pc.defineInt("errorType","DataError",0,(Int_t)RooAbsData::Auto) ; pc.defineInt("histInvisible","Invisible",0,0) ; pc.defineInt("refreshFrameNorm","RefreshNorm",0,1) ; pc.defineString("addToHistName","AddTo",0,"") ; pc.defineDouble("addToWgtSelf","AddTo",0,1.) ; pc.defineDouble("addToWgtOther","AddTo",1,1.) ; pc.defineDouble("xErrorSize","XErrorSize",0,1.) ; pc.defineDouble("scaleFactor","Rescale",0,1.) ; pc.defineMutex("DataError","Asymmetry","Efficiency") ; pc.defineMutex("Binning","BinningName","BinningSpec") ; // Process & check varargs pc.process(argList) ; if (!pc.ok(kTRUE)) { return frame ; } PlotOpt o ; // Extract values from named arguments o.drawOptions = pc.getString("drawOption") ; o.cuts = pc.getString("cutString") ; if (pc.hasProcessed("Binning")) { o.bins = (RooAbsBinning*) pc.getObject("binning") ; } else if (pc.hasProcessed("BinningName")) { o.bins = &frame->getPlotVar()->getBinning(pc.getString("binningName")) ; } else if (pc.hasProcessed("BinningSpec")) { Double_t xlo = pc.getDouble("xlo") ; Double_t xhi = pc.getDouble("xhi") ; o.bins = new RooUniformBinning((xlo==xhi)?frame->getPlotVar()->getMin():xlo, (xlo==xhi)?frame->getPlotVar()->getMax():xhi,pc.getInt("nbins")) ; } const RooAbsCategoryLValue* asymCat = (const RooAbsCategoryLValue*) pc.getObject("asymCat") ; const RooAbsCategoryLValue* effCat = (const RooAbsCategoryLValue*) pc.getObject("effCat") ; o.etype = (RooAbsData::ErrorType) pc.getInt("errorType") ; o.histInvisible = pc.getInt("histInvisible") ; o.xErrorSize = pc.getDouble("xErrorSize") ; o.cutRange = pc.getString("cutRange",0,kTRUE) ; o.histName = pc.getString("histName",0,kTRUE) ; o.addToHistName = pc.getString("addToHistName",0,kTRUE) ; o.addToWgtSelf = pc.getDouble("addToWgtSelf") ; o.addToWgtOther = pc.getDouble("addToWgtOther") ; o.refreshFrameNorm = pc.getInt("refreshFrameNorm") ; o.scaleFactor = pc.getDouble("scaleFactor") ; // Map auto error type to actual type if (o.etype == Auto) { o.etype = isNonPoissonWeighted() ? SumW2 : Poisson ; if (o.etype == SumW2) { coutI(InputArguments) << "RooAbsData::plotOn(" << GetName() << ") INFO: dataset has non-integer weights, auto-selecting SumW2 errors instead of Poisson errors" << endl ; } } if (o.addToHistName && !frame->findObject(o.addToHistName,RooHist::Class())) { coutE(InputArguments) << "RooAbsData::plotOn(" << GetName() << ") cannot find existing histogram " << o.addToHistName << " to add to in RooPlot" << endl ; return frame ; } RooPlot* ret ; if (!asymCat && !effCat) { ret = plotOn(frame,o) ; } else if (asymCat) { ret = plotAsymOn(frame,*asymCat,o) ; } else { ret = plotEffOn(frame,*effCat,o) ; } Int_t lineColor = pc.getInt("lineColor") ; Int_t lineStyle = pc.getInt("lineStyle") ; Int_t lineWidth = pc.getInt("lineWidth") ; Int_t markerColor = pc.getInt("markerColor") ; Int_t markerStyle = pc.getInt("markerStyle") ; Size_t markerSize = pc.getDouble("markerSize") ; Int_t fillColor = pc.getInt("fillColor") ; Int_t fillStyle = pc.getInt("fillStyle") ; if (lineColor!=-999) ret->getAttLine()->SetLineColor(lineColor) ; if (lineStyle!=-999) ret->getAttLine()->SetLineStyle(lineStyle) ; if (lineWidth!=-999) ret->getAttLine()->SetLineWidth(lineWidth) ; if (markerColor!=-999) ret->getAttMarker()->SetMarkerColor(markerColor) ; if (markerStyle!=-999) ret->getAttMarker()->SetMarkerStyle(markerStyle) ; if (markerSize!=-999) ret->getAttMarker()->SetMarkerSize(markerSize) ; if (fillColor!=-999) ret->getAttFill()->SetFillColor(fillColor) ; if (fillStyle!=-999) ret->getAttFill()->SetFillStyle(fillStyle) ; if (pc.hasProcessed("BinningSpec")) { delete o.bins ; } return ret ; } //////////////////////////////////////////////////////////////////////////////// /// Create and fill a histogram of the frame's variable and append it to the frame. /// The frame variable must be one of the data sets dimensions. /// /// The plot range and the number of plot bins is determined by the parameters /// of the plot variable of the frame (RooAbsReal::setPlotRange(), RooAbsReal::setPlotBins()). /// /// The optional cut string expression can be used to select the events to be plotted. /// The cut specification may refer to any variable contained in the data set. /// /// The drawOptions are passed to the TH1::Draw() method. /// \see RooAbsData::plotOn(RooPlot*,const RooLinkedList&) const RooPlot *RooAbsData::plotOn(RooPlot *frame, PlotOpt o) const { if(0 == frame) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotOn: frame is null" << endl; return 0; } RooAbsRealLValue *var= (RooAbsRealLValue*) frame->getPlotVar(); if(0 == var) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotOn: frame does not specify a plot variable" << endl; return 0; } // create and fill a temporary histogram of this variable TString histName(GetName()); histName.Append("_plot"); TH1F *hist ; if (o.bins) { hist= static_cast<TH1F*>(var->createHistogram(histName.Data(), RooFit::AxisLabel("Events"), RooFit::Binning(*o.bins))) ; } else if (!frame->getPlotVar()->getBinning().isUniform()) { hist = static_cast<TH1F*>(var->createHistogram(histName.Data(), RooFit::AxisLabel("Events"), RooFit::Binning(frame->getPlotVar()->getBinning()))); } else { hist= var->createHistogram(histName.Data(), "Events", frame->GetXaxis()->GetXmin(), frame->GetXaxis()->GetXmax(), frame->GetNbinsX()); } // Keep track of sum-of-weights error hist->Sumw2() ; if(0 == fillHistogram(hist,RooArgList(*var),o.cuts,o.cutRange)) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotOn: fillHistogram() failed" << endl; return 0; } // If frame has no predefined bin width (event density) it will be adjusted to // our histograms bin width so we should force that bin width here Double_t nomBinWidth ; if (frame->getFitRangeNEvt()==0 && o.bins) { nomBinWidth = o.bins->averageBinWidth() ; } else { nomBinWidth = o.bins ? frame->getFitRangeBinW() : 0 ; } // convert this histogram to a RooHist object on the heap RooHist *graph= new RooHist(*hist,nomBinWidth,1,o.etype,o.xErrorSize,o.correctForBinWidth,o.scaleFactor); if(0 == graph) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotOn: unable to create a RooHist object" << endl; delete hist; return 0; } // If the dataset variable has a wide range than the plot variable, // calculate the number of entries in the dataset in the plot variable fit range RooAbsRealLValue* dataVar = (RooAbsRealLValue*) _vars.find(var->GetName()) ; Double_t nEnt(sumEntries()) ; if (dataVar->getMin()<var->getMin() || dataVar->getMax()>var->getMax()) { RooAbsData* tmp = ((RooAbsData*)this)->reduce(*var) ; nEnt = tmp->sumEntries() ; delete tmp ; } // Store the number of entries before the cut, if any was made if ((o.cuts && strlen(o.cuts)) || o.cutRange) { coutI(Plotting) << "RooTreeData::plotOn: plotting " << hist->GetSum() << " events out of " << nEnt << " total events" << endl ; graph->setRawEntries(nEnt) ; } // Add self to other hist if requested if (o.addToHistName) { RooHist* otherGraph = static_cast<RooHist*>(frame->findObject(o.addToHistName,RooHist::Class())) ; if (!graph->hasIdenticalBinning(*otherGraph)) { coutE(Plotting) << "RooTreeData::plotOn: ERROR Histogram to be added to, '" << o.addToHistName << "',has different binning" << endl ; delete graph ; return frame ; } RooHist* sumGraph = new RooHist(*graph,*otherGraph,o.addToWgtSelf,o.addToWgtOther,o.etype) ; delete graph ; graph = sumGraph ; } // Rename graph if requested if (o.histName) { graph->SetName(o.histName) ; } else { TString hname(Form("h_%s",GetName())) ; if (o.cutRange && strlen(o.cutRange)>0) { hname.Append(Form("_CutRange[%s]",o.cutRange)) ; } if (o.cuts && strlen(o.cuts)>0) { hname.Append(Form("_Cut[%s]",o.cuts)) ; } graph->SetName(hname.Data()) ; } // initialize the frame's normalization setup, if necessary frame->updateNormVars(_vars); // add the RooHist to the specified plot frame->addPlotable(graph,o.drawOptions,o.histInvisible,o.refreshFrameNorm); // cleanup delete hist; return frame; } //////////////////////////////////////////////////////////////////////////////// /// Create and fill a histogram with the asymmetry N[+] - N[-] / ( N[+] + N[-] ), /// where N(+/-) is the number of data points with asymCat=+1 and asymCat=-1 /// as function of the frames variable. The asymmetry category 'asymCat' must /// have exactly 2 (or 3) states defined with index values +1,-1 (and 0) /// /// The plot range and the number of plot bins is determined by the parameters /// of the plot variable of the frame (RooAbsReal::setPlotRange(), RooAbsReal::setPlotBins()) /// /// The optional cut string expression can be used to select the events to be plotted. /// The cut specification may refer to any variable contained in the data set /// /// The drawOptions are passed to the TH1::Draw() method RooPlot* RooAbsData::plotAsymOn(RooPlot* frame, const RooAbsCategoryLValue& asymCat, PlotOpt o) const { if(0 == frame) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotAsymOn: frame is null" << endl; return 0; } RooAbsRealLValue *var= (RooAbsRealLValue*) frame->getPlotVar(); if(0 == var) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotAsymOn: frame does not specify a plot variable" << endl; return 0; } // create and fill temporary histograms of this variable for each state TString hist1Name(GetName()),hist2Name(GetName()); hist1Name.Append("_plot1"); TH1F *hist1, *hist2 ; hist2Name.Append("_plot2"); if (o.bins) { hist1= var->createHistogram(hist1Name.Data(), "Events", *o.bins) ; hist2= var->createHistogram(hist2Name.Data(), "Events", *o.bins) ; } else { hist1= var->createHistogram(hist1Name.Data(), "Events", frame->GetXaxis()->GetXmin(), frame->GetXaxis()->GetXmax(), frame->GetNbinsX()); hist2= var->createHistogram(hist2Name.Data(), "Events", frame->GetXaxis()->GetXmin(), frame->GetXaxis()->GetXmax(), frame->GetNbinsX()); } assert(0 != hist1 && 0 != hist2); TString cuts1,cuts2 ; if (o.cuts && strlen(o.cuts)) { cuts1 = Form("(%s)&&(%s>0)",o.cuts,asymCat.GetName()); cuts2 = Form("(%s)&&(%s<0)",o.cuts,asymCat.GetName()); } else { cuts1 = Form("(%s>0)",asymCat.GetName()); cuts2 = Form("(%s<0)",asymCat.GetName()); } if(0 == fillHistogram(hist1,RooArgList(*var),cuts1.Data(),o.cutRange) || 0 == fillHistogram(hist2,RooArgList(*var),cuts2.Data(),o.cutRange)) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotAsymOn: createHistogram() failed" << endl; return 0; } // convert this histogram to a RooHist object on the heap RooHist *graph= new RooHist(*hist1,*hist2,0,1,o.etype,o.xErrorSize,kFALSE,o.scaleFactor); graph->setYAxisLabel(Form("Asymmetry in %s",asymCat.GetName())) ; // initialize the frame's normalization setup, if necessary frame->updateNormVars(_vars); // Rename graph if requested if (o.histName) { graph->SetName(o.histName) ; } else { TString hname(Form("h_%s_Asym[%s]",GetName(),asymCat.GetName())) ; if (o.cutRange && strlen(o.cutRange)>0) { hname.Append(Form("_CutRange[%s]",o.cutRange)) ; } if (o.cuts && strlen(o.cuts)>0) { hname.Append(Form("_Cut[%s]",o.cuts)) ; } graph->SetName(hname.Data()) ; } // add the RooHist to the specified plot frame->addPlotable(graph,o.drawOptions,o.histInvisible,o.refreshFrameNorm); // cleanup delete hist1; delete hist2; return frame; } //////////////////////////////////////////////////////////////////////////////// /// Create and fill a histogram with the efficiency N[1] / ( N[1] + N[0] ), /// where N(1/0) is the number of data points with effCat=1 and effCat=0 /// as function of the frames variable. The efficiency category 'effCat' must /// have exactly 2 +1 and 0. /// /// The plot range and the number of plot bins is determined by the parameters /// of the plot variable of the frame (RooAbsReal::setPlotRange(), RooAbsReal::setPlotBins()) /// /// The optional cut string expression can be used to select the events to be plotted. /// The cut specification may refer to any variable contained in the data set /// /// The drawOptions are passed to the TH1::Draw() method RooPlot* RooAbsData::plotEffOn(RooPlot* frame, const RooAbsCategoryLValue& effCat, PlotOpt o) const { if(0 == frame) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotEffOn: frame is null" << endl; return 0; } RooAbsRealLValue *var= (RooAbsRealLValue*) frame->getPlotVar(); if(0 == var) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotEffOn: frame does not specify a plot variable" << endl; return 0; } // create and fill temporary histograms of this variable for each state TString hist1Name(GetName()),hist2Name(GetName()); hist1Name.Append("_plot1"); TH1F *hist1, *hist2 ; hist2Name.Append("_plot2"); if (o.bins) { hist1= var->createHistogram(hist1Name.Data(), "Events", *o.bins) ; hist2= var->createHistogram(hist2Name.Data(), "Events", *o.bins) ; } else { hist1= var->createHistogram(hist1Name.Data(), "Events", frame->GetXaxis()->GetXmin(), frame->GetXaxis()->GetXmax(), frame->GetNbinsX()); hist2= var->createHistogram(hist2Name.Data(), "Events", frame->GetXaxis()->GetXmin(), frame->GetXaxis()->GetXmax(), frame->GetNbinsX()); } assert(0 != hist1 && 0 != hist2); TString cuts1,cuts2 ; if (o.cuts && strlen(o.cuts)) { cuts1 = Form("(%s)&&(%s==1)",o.cuts,effCat.GetName()); cuts2 = Form("(%s)&&(%s==0)",o.cuts,effCat.GetName()); } else { cuts1 = Form("(%s==1)",effCat.GetName()); cuts2 = Form("(%s==0)",effCat.GetName()); } if(0 == fillHistogram(hist1,RooArgList(*var),cuts1.Data(),o.cutRange) || 0 == fillHistogram(hist2,RooArgList(*var),cuts2.Data(),o.cutRange)) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotEffOn: createHistogram() failed" << endl; return 0; } // convert this histogram to a RooHist object on the heap RooHist *graph= new RooHist(*hist1,*hist2,0,1,o.etype,o.xErrorSize,kTRUE); graph->setYAxisLabel(Form("Efficiency of %s=%s", effCat.GetName(), effCat.lookupName(1).c_str())); // initialize the frame's normalization setup, if necessary frame->updateNormVars(_vars); // Rename graph if requested if (o.histName) { graph->SetName(o.histName) ; } else { TString hname(Form("h_%s_Eff[%s]",GetName(),effCat.GetName())) ; if (o.cutRange && strlen(o.cutRange)>0) { hname.Append(Form("_CutRange[%s]",o.cutRange)) ; } if (o.cuts && strlen(o.cuts)>0) { hname.Append(Form("_Cut[%s]",o.cuts)) ; } graph->SetName(hname.Data()) ; } // add the RooHist to the specified plot frame->addPlotable(graph,o.drawOptions,o.histInvisible,o.refreshFrameNorm); // cleanup delete hist1; delete hist2; return frame; } //////////////////////////////////////////////////////////////////////////////// /// Create and fill a 1-dimensional table for given category column /// This functions is the equivalent of plotOn() for category dimensions. /// /// The optional cut string expression can be used to select the events to be tabulated /// The cut specification may refer to any variable contained in the data set /// /// The option string is currently not used Roo1DTable* RooAbsData::table(const RooAbsCategory& cat, const char* cuts, const char* /*opts*/) const { // First see if var is in data set RooAbsCategory* tableVar = (RooAbsCategory*) _vars.find(cat.GetName()) ; RooArgSet *tableSet = 0; Bool_t ownPlotVar(kFALSE) ; if (!tableVar) { if (!cat.dependsOn(_vars)) { coutE(Plotting) << "RooTreeData::Table(" << GetName() << "): Argument " << cat.GetName() << " is not in dataset and is also not dependent on data set" << endl ; return 0 ; } // Clone derived variable tableSet = (RooArgSet*) RooArgSet(cat).snapshot(kTRUE) ; if (!tableSet) { coutE(Plotting) << "RooTreeData::table(" << GetName() << ") Couldn't deep-clone table category, abort." << endl ; return 0 ; } tableVar = (RooAbsCategory*) tableSet->find(cat.GetName()) ; ownPlotVar = kTRUE ; //Redirect servers of derived clone to internal ArgSet representing the data in this set tableVar->recursiveRedirectServers(_vars) ; } TString tableName(GetName()) ; if (cuts && strlen(cuts)) { tableName.Append("(") ; tableName.Append(cuts) ; tableName.Append(")") ; } Roo1DTable* table2 = tableVar->createTable(tableName) ; // Make cut selector if cut is specified RooFormulaVar* cutVar = 0; if (cuts && strlen(cuts)) { cutVar = new RooFormulaVar("cutVar",cuts,_vars) ; } // Dump contents Int_t nevent= numEntries() ; for(Int_t i=0; i < nevent; ++i) { get(i); if (cutVar && cutVar->getVal()==0) continue ; table2->fill(*tableVar,weight()) ; } if (ownPlotVar) delete tableSet ; if (cutVar) delete cutVar ; return table2 ; } //////////////////////////////////////////////////////////////////////////////// /// Fill Doubles 'lowest' and 'highest' with the lowest and highest value of /// observable 'var' in this dataset. If the return value is kTRUE and error /// occurred Bool_t RooAbsData::getRange(const RooAbsRealLValue& var, Double_t& lowest, Double_t& highest, Double_t marginFrac, Bool_t symMode) const { // Lookup variable in dataset const auto arg = _vars.find(var.GetName()); if (!arg) { coutE(InputArguments) << "RooDataSet::getRange(" << GetName() << ") ERROR: unknown variable: " << var.GetName() << endl ; return kTRUE; } auto varPtr = dynamic_cast<const RooRealVar*>(arg); // Check if found variable is of type RooRealVar if (!varPtr) { coutE(InputArguments) << "RooDataSet::getRange(" << GetName() << ") ERROR: variable " << var.GetName() << " is not of type RooRealVar" << endl ; return kTRUE; } // Check if dataset is not empty if(sumEntries() == 0.) { coutE(InputArguments) << "RooDataSet::getRange(" << GetName() << ") WARNING: empty dataset" << endl ; return kTRUE; } // Look for highest and lowest value lowest = RooNumber::infinity() ; highest = -RooNumber::infinity() ; for (Int_t i=0 ; i<numEntries() ; i++) { get(i) ; if (varPtr->getVal()<lowest) { lowest = varPtr->getVal() ; } if (varPtr->getVal()>highest) { highest = varPtr->getVal() ; } } if (marginFrac>0) { if (symMode==kFALSE) { Double_t margin = marginFrac*(highest-lowest) ; lowest -= margin ; highest += margin ; if (lowest<var.getMin()) lowest = var.getMin() ; if (highest>var.getMax()) highest = var.getMax() ; } else { Double_t mom1 = moment(*varPtr,1) ; Double_t delta = ((highest-mom1)>(mom1-lowest)?(highest-mom1):(mom1-lowest))*(1+marginFrac) ; lowest = mom1-delta ; highest = mom1+delta ; if (lowest<var.getMin()) lowest = var.getMin() ; if (highest>var.getMax()) highest = var.getMax() ; } } return kFALSE ; } //////////////////////////////////////////////////////////////////////////////// /// Prepare dataset for use with cached constant terms listed in /// 'cacheList' of expression 'arg'. Deactivate tree branches /// for any dataset observable that is either not used at all, /// or is used exclusively by cached branch nodes. void RooAbsData::optimizeReadingWithCaching(RooAbsArg& arg, const RooArgSet& cacheList, const RooArgSet& keepObsList) { RooArgSet pruneSet ; // Add unused observables in this dataset to pruneSet pruneSet.add(*get()) ; RooArgSet* usedObs = arg.getObservables(*this) ; pruneSet.remove(*usedObs,kTRUE,kTRUE) ; // Add observables exclusively used to calculate cached observables to pruneSet TIterator* vIter = get()->createIterator() ; RooAbsArg *var ; while ((var=(RooAbsArg*) vIter->Next())) { if (allClientsCached(var,cacheList)) { pruneSet.add(*var) ; } } delete vIter ; if (pruneSet.getSize()!=0) { // Go over all used observables and check if any of them have parameterized // ranges in terms of pruned observables. If so, remove those observable // from the pruning list TIterator* uIter = usedObs->createIterator() ; RooAbsArg* obs ; while((obs=(RooAbsArg*)uIter->Next())) { RooRealVar* rrv = dynamic_cast<RooRealVar*>(obs) ; if (rrv && !rrv->getBinning().isShareable()) { RooArgSet depObs ; RooAbsReal* loFunc = rrv->getBinning().lowBoundFunc() ; RooAbsReal* hiFunc = rrv->getBinning().highBoundFunc() ; if (loFunc) { loFunc->leafNodeServerList(&depObs,0,kTRUE) ; } if (hiFunc) { hiFunc->leafNodeServerList(&depObs,0,kTRUE) ; } if (depObs.getSize()>0) { pruneSet.remove(depObs,kTRUE,kTRUE) ; } } } delete uIter ; } // Remove all observables in keep list from prune list pruneSet.remove(keepObsList,kTRUE,kTRUE) ; if (pruneSet.getSize()!=0) { // Deactivate tree branches here cxcoutI(Optimization) << "RooTreeData::optimizeReadingForTestStatistic(" << GetName() << "): Observables " << pruneSet << " in dataset are either not used at all, orserving exclusively p.d.f nodes that are now cached, disabling reading of these observables for TTree" << endl ; setArgStatus(pruneSet,kFALSE) ; } delete usedObs ; } //////////////////////////////////////////////////////////////////////////////// /// Utility function that determines if all clients of object 'var' /// appear in given list of cached nodes. Bool_t RooAbsData::allClientsCached(RooAbsArg* var, const RooArgSet& cacheList) { Bool_t ret(kTRUE), anyClient(kFALSE) ; for (const auto client : var->valueClients()) { anyClient = kTRUE ; if (!cacheList.find(client->GetName())) { // If client is not cached recurse ret &= allClientsCached(client,cacheList) ; } } return anyClient?ret:kFALSE ; } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::attachBuffers(const RooArgSet& extObs) { _dstore->attachBuffers(extObs) ; } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::resetBuffers() { _dstore->resetBuffers() ; } //////////////////////////////////////////////////////////////////////////////// Bool_t RooAbsData::canSplitFast() const { if (_ownedComponents.size()>0) { return kTRUE ; } return kFALSE ; } //////////////////////////////////////////////////////////////////////////////// RooAbsData* RooAbsData::getSimData(const char* name) { map<string,RooAbsData*>::iterator i = _ownedComponents.find(name) ; if (i==_ownedComponents.end()) return 0 ; return i->second ; } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::addOwnedComponent(const char* idxlabel, RooAbsData& data) { _ownedComponents[idxlabel]= &data ; } //////////////////////////////////////////////////////////////////////////////// /// Stream an object of class RooAbsData. void RooAbsData::Streamer(TBuffer &R__b) { if (R__b.IsReading()) { R__b.ReadClassBuffer(RooAbsData::Class(),this); // Convert on the fly to vector storage if that the current working default if (defaultStorageType==RooAbsData::Vector) { convertToVectorStore() ; } } else { R__b.WriteClassBuffer(RooAbsData::Class(),this); } } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::checkInit() const { _dstore->checkInit() ; } //////////////////////////////////////////////////////////////////////////////// /// Forward draw command to data store void RooAbsData::Draw(Option_t* option) { if (_dstore) _dstore->Draw(option) ; } //////////////////////////////////////////////////////////////////////////////// Bool_t RooAbsData::hasFilledCache() const { return _dstore->hasFilledCache() ; } //////////////////////////////////////////////////////////////////////////////// /// Return a pointer to the TTree which stores the data. Returns a nullpointer /// if vector-based storage is used. The RooAbsData remains owner of the tree. /// GetClonedTree() can be used to get a tree even if the internal storage does not use one. const TTree *RooAbsData::tree() const { if (storageType == RooAbsData::Tree) { return _dstore->tree(); } else { coutW(InputArguments) << "RooAbsData::tree(" << GetName() << ") WARNING: is not of StorageType::Tree. " << "Use GetClonedTree() instead or convert to tree storage." << endl; return (TTree *)nullptr; } } //////////////////////////////////////////////////////////////////////////////// /// Return a clone of the TTree which stores the data or create such a tree /// if vector storage is used. The user is responsible for deleting the tree TTree *RooAbsData::GetClonedTree() const { if (storageType == RooAbsData::Tree) { auto tmp = const_cast<TTree *>(_dstore->tree()); return tmp->CloneTree(); } else { RooTreeDataStore buffer(GetName(), GetTitle(), *get(), *_dstore); return buffer.tree().CloneTree(); } } //////////////////////////////////////////////////////////////////////////////// /// Convert vector-based storage to tree-based storage void RooAbsData::convertToTreeStore() { if (storageType != RooAbsData::Tree) { RooTreeDataStore *newStore = new RooTreeDataStore(GetName(), GetTitle(), _vars, *_dstore); delete _dstore; _dstore = newStore; storageType = RooAbsData::Tree; } } //////////////////////////////////////////////////////////////////////////////// /// If one of the TObject we have a referenced to is deleted, remove the /// reference. void RooAbsData::RecursiveRemove(TObject *obj) { for(auto &iter : _ownedComponents) { if (iter.second == obj) { iter.second = nullptr; } } } [RF] RooAbsData: Remove TH1F, fix memory leaks, improve string parsing. - For an unknown reason, RooAbsData was explicitly using TH1F, although none of its features/interfaces are used anywhere. - By replacing it with unique_ptr<TH1>, we are now actually including what we use, and fix memory leaks that happened when the functions return early because of an error. - Remove usage of strtok with buffer size limited to 1024 characters. /***************************************************************************** * Project: RooFit * * Package: RooFitCore * * @(#)root/roofitcore:$Id$ * Authors: * * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * * * * Copyright (c) 2000-2005, Regents of the University of California * * and Stanford University. All rights reserved. * * * * Redistribution and use in source and binary forms, * * with or without modification, are permitted according to the terms * * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ /** \file RooAbsData.cxx \class RooAbsData \ingroup Roofitcore RooAbsData is the common abstract base class for binned and unbinned datasets. The abstract interface defines plotting and tabulating entry points for its contents and provides an iterator over its elements (bins for binned data sets, data points for unbinned datasets). **/ #include "RooAbsData.h" #include "TBuffer.h" #include "TClass.h" #include "TMath.h" #include "TTree.h" #include "RooFormulaVar.h" #include "RooCmdConfig.h" #include "RooAbsRealLValue.h" #include "RooMsgService.h" #include "RooMultiCategory.h" #include "Roo1DTable.h" #include "RooAbsDataStore.h" #include "RooVectorDataStore.h" #include "RooTreeDataStore.h" #include "RooDataHist.h" #include "RooCompositeDataStore.h" #include "RooCategory.h" #include "RooTrace.h" #include "RooUniformBinning.h" #include "RooRealVar.h" #include "RooGlobalFunc.h" #include "RooPlot.h" #include "RooCurve.h" #include "RooHist.h" #include "RooHelpers.h" #include "TMatrixDSym.h" #include "TPaveText.h" #include "TH1.h" #include "TH2.h" #include "TH3.h" #include "Math/Util.h" #include <iostream> #include <memory> using namespace std; ClassImp(RooAbsData); ; static std::map<RooAbsData*,int> _dcc ; RooAbsData::StorageType RooAbsData::defaultStorageType=RooAbsData::Vector ; //////////////////////////////////////////////////////////////////////////////// void RooAbsData::setDefaultStorageType(RooAbsData::StorageType s) { if (RooAbsData::Composite == s) { cout << "Composite storage is not a valid *default* storage type." << endl; } else { defaultStorageType = s; } } //////////////////////////////////////////////////////////////////////////////// RooAbsData::StorageType RooAbsData::getDefaultStorageType( ) { return defaultStorageType; } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::claimVars(RooAbsData* data) { _dcc[data]++ ; //cout << "RooAbsData(" << data << ") claim incremented to " << _dcc[data] << endl ; } //////////////////////////////////////////////////////////////////////////////// /// If return value is true variables can be deleted Bool_t RooAbsData::releaseVars(RooAbsData* data) { if (_dcc[data]>0) { _dcc[data]-- ; } //cout << "RooAbsData(" << data << ") claim decremented to " << _dcc[data] << endl ; return (_dcc[data]==0) ; } //////////////////////////////////////////////////////////////////////////////// /// Default constructor RooAbsData::RooAbsData() { claimVars(this) ; _dstore = 0 ; storageType = defaultStorageType; RooTrace::create(this) ; } //////////////////////////////////////////////////////////////////////////////// /// Constructor from a set of variables. Only fundamental elements of vars /// (RooRealVar,RooCategory etc) are stored as part of the dataset RooAbsData::RooAbsData(const char *name, const char *title, const RooArgSet& vars, RooAbsDataStore* dstore) : TNamed(name,title), _vars("Dataset Variables"), _cachedVars("Cached Variables"), _dstore(dstore) { if (dynamic_cast<RooTreeDataStore *>(dstore)) { storageType = RooAbsData::Tree; } else if (dynamic_cast<RooVectorDataStore *>(dstore)) { storageType = RooAbsData::Vector; } else { storageType = RooAbsData::Composite; } // cout << "created dataset " << this << endl ; claimVars(this); // clone the fundamentals of the given data set into internal buffer for (const auto var : vars) { if (!var->isFundamental()) { coutE(InputArguments) << "RooAbsDataStore::initialize(" << GetName() << "): Data set cannot contain non-fundamental types, ignoring " << var->GetName() << endl; throw std::invalid_argument(std::string("Only fundamental variables can be placed into datasets. This is violated for ") + var->GetName()); } else { _vars.addClone(*var); } } // reconnect any parameterized ranges to internal dataset observables for (auto var : _vars) { var->attachDataSet(*this); } RooTrace::create(this); } //////////////////////////////////////////////////////////////////////////////// /// Copy constructor RooAbsData::RooAbsData(const RooAbsData& other, const char* newname) : TNamed(newname?newname:other.GetName(),other.GetTitle()), RooPrintable(other), _vars(), _cachedVars("Cached Variables") { //cout << "created dataset " << this << endl ; claimVars(this) ; _vars.addClone(other._vars) ; // reconnect any parameterized ranges to internal dataset observables for (const auto var : _vars) { var->attachDataSet(*this) ; } if (other._ownedComponents.size()>0) { // copy owned components here map<string,RooAbsDataStore*> smap ; for (auto& itero : other._ownedComponents) { RooAbsData* dclone = (RooAbsData*) itero.second->Clone(); _ownedComponents[itero.first] = dclone; smap[itero.first] = dclone->store(); } RooCategory* idx = (RooCategory*) _vars.find(*((RooCompositeDataStore*)other.store())->index()) ; _dstore = new RooCompositeDataStore(newname?newname:other.GetName(),other.GetTitle(),_vars,*idx,smap) ; storageType = RooAbsData::Composite; } else { // Convert to vector store if default is vector _dstore = other._dstore->clone(_vars,newname?newname:other.GetName()) ; storageType = other.storageType; } RooTrace::create(this) ; } RooAbsData& RooAbsData::operator=(const RooAbsData& other) { TNamed::operator=(other); RooPrintable::operator=(other); claimVars(this); _vars.Clear(); _vars.addClone(other._vars); // reconnect any parameterized ranges to internal dataset observables for (const auto var : _vars) { var->attachDataSet(*this) ; } if (other._ownedComponents.size()>0) { // copy owned components here map<string,RooAbsDataStore*> smap ; for (auto& itero : other._ownedComponents) { RooAbsData* dclone = (RooAbsData*) itero.second->Clone(); _ownedComponents[itero.first] = dclone; smap[itero.first] = dclone->store(); } RooCategory* idx = (RooCategory*) _vars.find(*((RooCompositeDataStore*)other.store())->index()) ; _dstore = new RooCompositeDataStore(GetName(), GetTitle(), _vars, *idx, smap); storageType = RooAbsData::Composite; } else { // Convert to vector store if default is vector _dstore = other._dstore->clone(_vars); storageType = other.storageType; } return *this; } //////////////////////////////////////////////////////////////////////////////// /// Destructor RooAbsData::~RooAbsData() { if (releaseVars(this)) { // will cause content to be deleted subsequently in dtor } else { _vars.releaseOwnership() ; } // delete owned contents. delete _dstore ; // Delete owned dataset components for(map<std::string,RooAbsData*>::iterator iter = _ownedComponents.begin() ; iter!= _ownedComponents.end() ; ++iter) { delete iter->second ; } RooTrace::destroy(this) ; } //////////////////////////////////////////////////////////////////////////////// /// Convert tree-based storage to vector-based storage void RooAbsData::convertToVectorStore() { if (storageType == RooAbsData::Tree) { RooVectorDataStore *newStore = new RooVectorDataStore(*(RooTreeDataStore *)_dstore, _vars, GetName()); delete _dstore; _dstore = newStore; storageType = RooAbsData::Vector; } } //////////////////////////////////////////////////////////////////////////////// Bool_t RooAbsData::changeObservableName(const char* from, const char* to) { Bool_t ret = _dstore->changeObservableName(from,to) ; RooAbsArg* tmp = _vars.find(from) ; if (tmp) { tmp->SetName(to) ; } return ret ; } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::fill() { _dstore->fill() ; } //////////////////////////////////////////////////////////////////////////////// Int_t RooAbsData::numEntries() const { return nullptr != _dstore ? _dstore->numEntries() : 0; } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::reset() { _dstore->reset() ; } //////////////////////////////////////////////////////////////////////////////// const RooArgSet* RooAbsData::get(Int_t index) const { checkInit() ; return _dstore->get(index) ; } //////////////////////////////////////////////////////////////////////////////// /// Internal method -- Cache given set of functions with data void RooAbsData::cacheArgs(const RooAbsArg* cacheOwner, RooArgSet& varSet, const RooArgSet* nset, Bool_t skipZeroWeights) { _dstore->cacheArgs(cacheOwner,varSet,nset,skipZeroWeights) ; } //////////////////////////////////////////////////////////////////////////////// /// Internal method -- Remove cached function values void RooAbsData::resetCache() { _dstore->resetCache() ; _cachedVars.removeAll() ; } //////////////////////////////////////////////////////////////////////////////// /// Internal method -- Attach dataset copied with cache contents to copied instances of functions void RooAbsData::attachCache(const RooAbsArg* newOwner, const RooArgSet& cachedVars) { _dstore->attachCache(newOwner, cachedVars) ; } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::setArgStatus(const RooArgSet& set, Bool_t active) { _dstore->setArgStatus(set,active) ; } //////////////////////////////////////////////////////////////////////////////// /// Control propagation of dirty flags from observables in dataset void RooAbsData::setDirtyProp(Bool_t flag) { _dstore->setDirtyProp(flag) ; } //////////////////////////////////////////////////////////////////////////////// /// Create a reduced copy of this dataset. The caller takes ownership of the returned dataset /// /// The following optional named arguments are accepted /// <table> /// <tr><td> `SelectVars(const RooArgSet& vars)` <td> Only retain the listed observables in the output dataset /// <tr><td> `Cut(const char* expression)` <td> Only retain event surviving the given cut expression /// <tr><td> `Cut(const RooFormulaVar& expr)` <td> Only retain event surviving the given cut formula /// <tr><td> `CutRange(const char* name)` <td> Only retain events inside range with given name. Multiple CutRange /// arguments may be given to select multiple ranges /// <tr><td> `EventRange(int lo, int hi)` <td> Only retain events with given sequential event numbers /// <tr><td> `Name(const char* name)` <td> Give specified name to output dataset /// <tr><td> `Title(const char* name)` <td> Give specified title to output dataset /// </table> RooAbsData* RooAbsData::reduce(const RooCmdArg& arg1,const RooCmdArg& arg2,const RooCmdArg& arg3,const RooCmdArg& arg4, const RooCmdArg& arg5,const RooCmdArg& arg6,const RooCmdArg& arg7,const RooCmdArg& arg8) { // Define configuration for this method RooCmdConfig pc(Form("RooAbsData::reduce(%s)",GetName())) ; pc.defineString("name","Name",0,"") ; pc.defineString("title","Title",0,"") ; pc.defineString("cutRange","CutRange",0,"") ; pc.defineString("cutSpec","CutSpec",0,"") ; pc.defineObject("cutVar","CutVar",0,0) ; pc.defineInt("evtStart","EventRange",0,0) ; pc.defineInt("evtStop","EventRange",1,std::numeric_limits<int>::max()) ; pc.defineObject("varSel","SelectVars",0,0) ; pc.defineMutex("CutVar","CutSpec") ; // Process & check varargs pc.process(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) ; if (!pc.ok(kTRUE)) { return 0 ; } // Extract values from named arguments const char* cutRange = pc.getString("cutRange",0,kTRUE) ; const char* cutSpec = pc.getString("cutSpec",0,kTRUE) ; RooFormulaVar* cutVar = static_cast<RooFormulaVar*>(pc.getObject("cutVar",0)) ; Int_t nStart = pc.getInt("evtStart",0) ; Int_t nStop = pc.getInt("evtStop",std::numeric_limits<int>::max()) ; RooArgSet* varSet = static_cast<RooArgSet*>(pc.getObject("varSel")) ; const char* name = pc.getString("name",0,kTRUE) ; const char* title = pc.getString("title",0,kTRUE) ; // Make sure varSubset doesn't contain any variable not in this dataset RooArgSet varSubset ; if (varSet) { varSubset.add(*varSet) ; for (const auto arg : varSubset) { if (!_vars.find(arg->GetName())) { coutW(InputArguments) << "RooAbsData::reduce(" << GetName() << ") WARNING: variable " << arg->GetName() << " not in dataset, ignored" << endl ; varSubset.remove(*arg) ; } } } else { varSubset.add(*get()) ; } RooAbsData* ret = 0 ; if (cutSpec) { RooFormulaVar cutVarTmp(cutSpec,cutSpec,*get()) ; ret = reduceEng(varSubset,&cutVarTmp,cutRange,nStart,nStop,kFALSE) ; } else if (cutVar) { ret = reduceEng(varSubset,cutVar,cutRange,nStart,nStop,kFALSE) ; } else { ret = reduceEng(varSubset,0,cutRange,nStart,nStop,kFALSE) ; } if (!ret) return 0 ; if (name) { ret->SetName(name) ; } if (title) { ret->SetTitle(title) ; } return ret ; } //////////////////////////////////////////////////////////////////////////////// /// Create a subset of the data set by applying the given cut on the data points. /// The cut expression can refer to any variable in the data set. For cuts involving /// other variables, such as intermediate formula objects, use the equivalent /// reduce method specifying the as a RooFormulVar reference. RooAbsData* RooAbsData::reduce(const char* cut) { RooFormulaVar cutVar(cut,cut,*get()) ; return reduceEng(*get(),&cutVar,0,0,std::numeric_limits<std::size_t>::max(),kFALSE) ; } //////////////////////////////////////////////////////////////////////////////// /// Create a subset of the data set by applying the given cut on the data points. /// The 'cutVar' formula variable is used to select the subset of data points to be /// retained in the reduced data collection. RooAbsData* RooAbsData::reduce(const RooFormulaVar& cutVar) { return reduceEng(*get(),&cutVar,0,0,std::numeric_limits<std::size_t>::max(),kFALSE) ; } //////////////////////////////////////////////////////////////////////////////// /// Create a subset of the data set by applying the given cut on the data points /// and reducing the dimensions to the specified set. /// /// The cut expression can refer to any variable in the data set. For cuts involving /// other variables, such as intermediate formula objects, use the equivalent /// reduce method specifying the as a RooFormulVar reference. RooAbsData* RooAbsData::reduce(const RooArgSet& varSubset, const char* cut) { // Make sure varSubset doesn't contain any variable not in this dataset RooArgSet varSubset2(varSubset) ; for (const auto arg : varSubset) { if (!_vars.find(arg->GetName())) { coutW(InputArguments) << "RooAbsData::reduce(" << GetName() << ") WARNING: variable " << arg->GetName() << " not in dataset, ignored" << endl ; varSubset2.remove(*arg) ; } } if (cut && strlen(cut)>0) { RooFormulaVar cutVar(cut, cut, *get(), false); return reduceEng(varSubset2,&cutVar,0,0,std::numeric_limits<std::size_t>::max(),kFALSE) ; } return reduceEng(varSubset2,0,0,0,std::numeric_limits<std::size_t>::max(),kFALSE) ; } //////////////////////////////////////////////////////////////////////////////// /// Create a subset of the data set by applying the given cut on the data points /// and reducing the dimensions to the specified set. /// /// The 'cutVar' formula variable is used to select the subset of data points to be /// retained in the reduced data collection. RooAbsData* RooAbsData::reduce(const RooArgSet& varSubset, const RooFormulaVar& cutVar) { // Make sure varSubset doesn't contain any variable not in this dataset RooArgSet varSubset2(varSubset) ; TIterator* iter = varSubset.createIterator() ; RooAbsArg* arg ; while((arg=(RooAbsArg*)iter->Next())) { if (!_vars.find(arg->GetName())) { coutW(InputArguments) << "RooAbsData::reduce(" << GetName() << ") WARNING: variable " << arg->GetName() << " not in dataset, ignored" << endl ; varSubset2.remove(*arg) ; } } delete iter ; return reduceEng(varSubset2,&cutVar,0,0,std::numeric_limits<std::size_t>::max(),kFALSE) ; } //////////////////////////////////////////////////////////////////////////////// /// Return error on current weight (dummy implementation returning zero) Double_t RooAbsData::weightError(ErrorType) const { return 0 ; } //////////////////////////////////////////////////////////////////////////////// /// Return asymmetric error on weight. (Dummy implementation returning zero) void RooAbsData::weightError(Double_t& lo, Double_t& hi, ErrorType) const { lo=0 ; hi=0 ; } RooPlot* RooAbsData::plotOn(RooPlot* frame, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) const { RooLinkedList l ; l.Add((TObject*)&arg1) ; l.Add((TObject*)&arg2) ; l.Add((TObject*)&arg3) ; l.Add((TObject*)&arg4) ; l.Add((TObject*)&arg5) ; l.Add((TObject*)&arg6) ; l.Add((TObject*)&arg7) ; l.Add((TObject*)&arg8) ; return plotOn(frame,l) ; } //////////////////////////////////////////////////////////////////////////////// /// Create and fill a ROOT histogram TH1,TH2 or TH3 with the values of this dataset for the variables with given names /// The range of each observable that is histogrammed is always automatically calculated from the distribution in /// the dataset. The number of bins can be controlled using the [xyz]bins parameters. For a greater degree of control /// use the createHistogram() method below with named arguments /// /// The caller takes ownership of the returned histogram TH1 *RooAbsData::createHistogram(const char* varNameList, Int_t xbins, Int_t ybins, Int_t zbins) const { // Parse list of variable names const auto varNames = RooHelpers::tokenise(varNameList, ",:"); RooLinkedList argList; RooRealVar* vars[3] = {nullptr, nullptr, nullptr}; for (unsigned int i = 0; i < varNames.size(); ++i) { if (i >= 3) { coutW(InputArguments) << "RooAbsData::createHistogram(" << GetName() << "): Can only create 3-dimensional histograms. Variable " << i << " " << varNames[i] << " unused." << std::endl; continue; } vars[i] = static_cast<RooRealVar*>( get()->find(varNames[i].data()) ); if (!vars[i]) { coutE(InputArguments) << "RooAbsData::createHistogram(" << GetName() << ") ERROR: dataset does not contain an observable named " << varNames[i] << std::endl; return nullptr; } } if (!vars[0]) { coutE(InputArguments) << "RooAbsData::createHistogram(" << GetName() << "): No variable to be histogrammed in list '" << varNameList << "'" << std::endl; return nullptr; } if (xbins<=0 || !vars[0]->hasMax() || !vars[0]->hasMin() ) { argList.Add(RooFit::AutoBinning(xbins==0?vars[0]->numBins():abs(xbins)).Clone()) ; } else { argList.Add(RooFit::Binning(xbins).Clone()) ; } if (vars[1]) { if (ybins<=0 || !vars[1]->hasMax() || !vars[1]->hasMin() ) { argList.Add(RooFit::YVar(*vars[1],RooFit::AutoBinning(ybins==0?vars[1]->numBins():abs(ybins))).Clone()) ; } else { argList.Add(RooFit::YVar(*vars[1],RooFit::Binning(ybins)).Clone()) ; } } if (vars[2]) { if (zbins<=0 || !vars[2]->hasMax() || !vars[2]->hasMin() ) { argList.Add(RooFit::ZVar(*vars[2],RooFit::AutoBinning(zbins==0?vars[2]->numBins():abs(zbins))).Clone()) ; } else { argList.Add(RooFit::ZVar(*vars[2],RooFit::Binning(zbins)).Clone()) ; } } // Call implementation function TH1* result = createHistogram(GetName(), *vars[0], argList); // Delete temporary list of RooCmdArgs argList.Delete() ; return result ; } TH1 *RooAbsData::createHistogram(const char *name, const RooAbsRealLValue& xvar, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) const { RooLinkedList l ; l.Add((TObject*)&arg1) ; l.Add((TObject*)&arg2) ; l.Add((TObject*)&arg3) ; l.Add((TObject*)&arg4) ; l.Add((TObject*)&arg5) ; l.Add((TObject*)&arg6) ; l.Add((TObject*)&arg7) ; l.Add((TObject*)&arg8) ; return createHistogram(name,xvar,l) ; } //////////////////////////////////////////////////////////////////////////////// /// /// This function accepts the following arguments /// /// \param[in] name Name of the ROOT histogram /// \param[in] xvar Observable to be mapped on x axis of ROOT histogram /// \return Histogram now owned by user. /// /// <table> /// <tr><td> `AutoBinning(Int_t nbins, Double_y margin)` <td> Automatically calculate range with given added fractional margin, set binning to nbins /// <tr><td> `AutoSymBinning(Int_t nbins, Double_y margin)` <td> Automatically calculate range with given added fractional margin, /// with additional constraint that mean of data is in center of range, set binning to nbins /// <tr><td> `Binning(const char* name)` <td> Apply binning with given name to x axis of histogram /// <tr><td> `Binning(RooAbsBinning& binning)` <td> Apply specified binning to x axis of histogram /// <tr><td> `Binning(int nbins, double lo, double hi)` <td> Apply specified binning to x axis of histogram /// /// <tr><td> `YVar(const RooAbsRealLValue& var,...)` <td> Observable to be mapped on y axis of ROOT histogram /// <tr><td> `ZVar(const RooAbsRealLValue& var,...)` <td> Observable to be mapped on z axis of ROOT histogram /// </table> /// /// The YVar() and ZVar() arguments can be supplied with optional Binning() Auto(Sym)Range() arguments to control the binning of the Y and Z axes, e.g. /// ``` /// createHistogram("histo",x,Binning(-1,1,20), YVar(y,Binning(-1,1,30)), ZVar(z,Binning("zbinning"))) /// ``` /// /// The caller takes ownership of the returned histogram TH1 *RooAbsData::createHistogram(const char *name, const RooAbsRealLValue& xvar, const RooLinkedList& argListIn) const { RooLinkedList argList(argListIn) ; // Define configuration for this method RooCmdConfig pc(Form("RooAbsData::createHistogram(%s)",GetName())) ; pc.defineString("cutRange","CutRange",0,"",kTRUE) ; pc.defineString("cutString","CutSpec",0,"") ; pc.defineObject("yvar","YVar",0,0) ; pc.defineObject("zvar","ZVar",0,0) ; pc.allowUndefined() ; // Process & check varargs pc.process(argList) ; if (!pc.ok(kTRUE)) { return 0 ; } const char* cutSpec = pc.getString("cutString",0,kTRUE) ; const char* cutRange = pc.getString("cutRange",0,kTRUE) ; RooArgList vars(xvar) ; RooAbsArg* yvar = static_cast<RooAbsArg*>(pc.getObject("yvar")) ; if (yvar) { vars.add(*yvar) ; } RooAbsArg* zvar = static_cast<RooAbsArg*>(pc.getObject("zvar")) ; if (zvar) { vars.add(*zvar) ; } pc.stripCmdList(argList,"CutRange,CutSpec") ; // Swap Auto(Sym)RangeData with a Binning command RooLinkedList ownedCmds ; RooCmdArg* autoRD = (RooCmdArg*) argList.find("AutoRangeData") ; if (autoRD) { Double_t xmin,xmax ; if (!getRange((RooRealVar&)xvar,xmin,xmax,autoRD->getDouble(0),autoRD->getInt(0))) { RooCmdArg* bincmd = (RooCmdArg*) RooFit::Binning(autoRD->getInt(1),xmin,xmax).Clone() ; ownedCmds.Add(bincmd) ; argList.Replace(autoRD,bincmd) ; } } if (yvar) { RooCmdArg* autoRDY = (RooCmdArg*) ((RooCmdArg*)argList.find("YVar"))->subArgs().find("AutoRangeData") ; if (autoRDY) { Double_t ymin,ymax ; if (!getRange((RooRealVar&)(*yvar),ymin,ymax,autoRDY->getDouble(0),autoRDY->getInt(0))) { RooCmdArg* bincmd = (RooCmdArg*) RooFit::Binning(autoRDY->getInt(1),ymin,ymax).Clone() ; //ownedCmds.Add(bincmd) ; ((RooCmdArg*)argList.find("YVar"))->subArgs().Replace(autoRDY,bincmd) ; } delete autoRDY ; } } if (zvar) { RooCmdArg* autoRDZ = (RooCmdArg*) ((RooCmdArg*)argList.find("ZVar"))->subArgs().find("AutoRangeData") ; if (autoRDZ) { Double_t zmin,zmax ; if (!getRange((RooRealVar&)(*zvar),zmin,zmax,autoRDZ->getDouble(0),autoRDZ->getInt(0))) { RooCmdArg* bincmd = (RooCmdArg*) RooFit::Binning(autoRDZ->getInt(1),zmin,zmax).Clone() ; //ownedCmds.Add(bincmd) ; ((RooCmdArg*)argList.find("ZVar"))->subArgs().Replace(autoRDZ,bincmd) ; } delete autoRDZ ; } } TH1* histo = xvar.createHistogram(name,argList) ; fillHistogram(histo,vars,cutSpec,cutRange) ; ownedCmds.Delete() ; return histo ; } //////////////////////////////////////////////////////////////////////////////// /// Construct table for product of categories in catSet Roo1DTable* RooAbsData::table(const RooArgSet& catSet, const char* cuts, const char* opts) const { RooArgSet catSet2 ; string prodName("(") ; TIterator* iter = catSet.createIterator() ; RooAbsArg* arg ; while((arg=(RooAbsArg*)iter->Next())) { if (dynamic_cast<RooAbsCategory*>(arg)) { RooAbsCategory* varsArg = dynamic_cast<RooAbsCategory*>(_vars.find(arg->GetName())) ; if (varsArg != 0) catSet2.add(*varsArg) ; else catSet2.add(*arg) ; if (prodName.length()>1) { prodName += " x " ; } prodName += arg->GetName() ; } else { coutW(InputArguments) << "RooAbsData::table(" << GetName() << ") non-RooAbsCategory input argument " << arg->GetName() << " ignored" << endl ; } } prodName += ")" ; delete iter ; RooMultiCategory tmp(prodName.c_str(),prodName.c_str(),catSet2) ; return table(tmp,cuts,opts) ; } //////////////////////////////////////////////////////////////////////////////// /// Print name of dataset void RooAbsData::printName(ostream& os) const { os << GetName() ; } //////////////////////////////////////////////////////////////////////////////// /// Print title of dataset void RooAbsData::printTitle(ostream& os) const { os << GetTitle() ; } //////////////////////////////////////////////////////////////////////////////// /// Print class name of dataset void RooAbsData::printClassName(ostream& os) const { os << IsA()->GetName() ; } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::printMultiline(ostream& os, Int_t contents, Bool_t verbose, TString indent) const { _dstore->printMultiline(os,contents,verbose,indent) ; } //////////////////////////////////////////////////////////////////////////////// /// Define default print options, for a given print style Int_t RooAbsData::defaultPrintContents(Option_t* /*opt*/) const { return kName|kClassName|kArgs|kValue ; } //////////////////////////////////////////////////////////////////////////////// /// Calculate standardized moment. /// /// \param[in] var Variable to be used for calculating the moment. /// \param[in] order Order of the moment. /// \param[in] cutSpec If specified, the moment is calculated on the subset of the data which pass the C++ cut specification expression 'cutSpec' /// \param[in] cutRange If specified, calculate inside the range named 'cutRange' (also applies cut spec) /// \return \f$ \frac{\left< \left( X - \left< X \right> \right)^n \right>}{\sigma^n} \f$, where n = order. Double_t RooAbsData::standMoment(const RooRealVar &var, Double_t order, const char* cutSpec, const char* cutRange) const { // Hardwire invariant answer for first and second moment if (order==1) return 0 ; if (order==2) return 1 ; return moment(var,order,cutSpec,cutRange) / TMath::Power(sigma(var,cutSpec,cutRange),order) ; } //////////////////////////////////////////////////////////////////////////////// /// Calculate moment of requested order. /// /// \param[in] var Variable to be used for calculating the moment. /// \param[in] order Order of the moment. /// \param[in] cutSpec If specified, the moment is calculated on the subset of the data which pass the C++ cut specification expression 'cutSpec' /// \param[in] cutRange If specified, calculate inside the range named 'cutRange' (also applies cut spec) /// \return \f$ \left< \left( X - \left< X \right> \right)^n \right> \f$ of order \f$n\f$. /// Double_t RooAbsData::moment(const RooRealVar& var, Double_t order, const char* cutSpec, const char* cutRange) const { Double_t offset = order>1 ? moment(var,1,cutSpec,cutRange) : 0 ; return moment(var,order,offset,cutSpec,cutRange) ; } //////////////////////////////////////////////////////////////////////////////// /// Return the 'order'-ed moment of observable 'var' in this dataset. If offset is non-zero it is subtracted /// from the values of 'var' prior to the moment calculation. If cutSpec and/or cutRange are specified /// the moment is calculated on the subset of the data which pass the C++ cut specification expression 'cutSpec' /// and/or are inside the range named 'cutRange' Double_t RooAbsData::moment(const RooRealVar& var, Double_t order, Double_t offset, const char* cutSpec, const char* cutRange) const { // Lookup variable in dataset auto arg = _vars.find(var.GetName()); if (!arg) { coutE(InputArguments) << "RooDataSet::moment(" << GetName() << ") ERROR: unknown variable: " << var.GetName() << endl ; return 0; } auto varPtr = dynamic_cast<const RooRealVar*>(arg); // Check if found variable is of type RooRealVar if (!varPtr) { coutE(InputArguments) << "RooDataSet::moment(" << GetName() << ") ERROR: variable " << var.GetName() << " is not of type RooRealVar" << endl ; return 0; } // Check if dataset is not empty if(sumEntries(cutSpec, cutRange) == 0.) { coutE(InputArguments) << "RooDataSet::moment(" << GetName() << ") WARNING: empty dataset" << endl ; return 0; } // Setup RooFormulaVar for cutSpec if it is present std::unique_ptr<RooFormula> select; if (cutSpec) { select.reset(new RooFormula("select",cutSpec,*get())); } // Calculate requested moment ROOT::Math::KahanSum<double> sum; for(Int_t index= 0; index < numEntries(); index++) { const RooArgSet* vars = get(index) ; if (select && select->eval()==0) continue ; if (cutRange && vars->allInRange(cutRange)) continue ; sum += weight() * TMath::Power(varPtr->getVal() - offset,order); } return sum/sumEntries(cutSpec, cutRange); } //////////////////////////////////////////////////////////////////////////////// /// Internal method to check if given RooRealVar maps to a RooRealVar in this dataset RooRealVar* RooAbsData::dataRealVar(const char* methodname, const RooRealVar& extVar) const { // Lookup variable in dataset RooRealVar *xdata = (RooRealVar*) _vars.find(extVar.GetName()); if(!xdata) { coutE(InputArguments) << "RooDataSet::" << methodname << "(" << GetName() << ") ERROR: variable : " << extVar.GetName() << " is not in data" << endl ; return 0; } // Check if found variable is of type RooRealVar if (!dynamic_cast<RooRealVar*>(xdata)) { coutE(InputArguments) << "RooDataSet::" << methodname << "(" << GetName() << ") ERROR: variable : " << extVar.GetName() << " is not of type RooRealVar in data" << endl ; return 0; } return xdata; } //////////////////////////////////////////////////////////////////////////////// /// Internal method to calculate single correlation and covariance elements Double_t RooAbsData::corrcov(const RooRealVar &x, const RooRealVar &y, const char* cutSpec, const char* cutRange, Bool_t corr) const { // Lookup variable in dataset RooRealVar *xdata = dataRealVar(corr?"correlation":"covariance",x) ; RooRealVar *ydata = dataRealVar(corr?"correlation":"covariance",y) ; if (!xdata||!ydata) return 0 ; // Check if dataset is not empty if(sumEntries(cutSpec, cutRange) == 0.) { coutW(InputArguments) << "RooDataSet::" << (corr?"correlation":"covariance") << "(" << GetName() << ") WARNING: empty dataset, returning zero" << endl ; return 0; } // Setup RooFormulaVar for cutSpec if it is present RooFormula* select = cutSpec ? new RooFormula("select",cutSpec,*get()) : 0 ; // Calculate requested moment Double_t xysum(0),xsum(0),ysum(0),x2sum(0),y2sum(0); const RooArgSet* vars ; for(Int_t index= 0; index < numEntries(); index++) { vars = get(index) ; if (select && select->eval()==0) continue ; if (cutRange && vars->allInRange(cutRange)) continue ; xysum += weight()*xdata->getVal()*ydata->getVal() ; xsum += weight()*xdata->getVal() ; ysum += weight()*ydata->getVal() ; if (corr) { x2sum += weight()*xdata->getVal()*xdata->getVal() ; y2sum += weight()*ydata->getVal()*ydata->getVal() ; } } // Normalize entries xysum/=sumEntries(cutSpec, cutRange) ; xsum/=sumEntries(cutSpec, cutRange) ; ysum/=sumEntries(cutSpec, cutRange) ; if (corr) { x2sum/=sumEntries(cutSpec, cutRange) ; y2sum/=sumEntries(cutSpec, cutRange) ; } // Cleanup if (select) delete select ; // Return covariance or correlation as requested if (corr) { return (xysum-xsum*ysum)/(sqrt(x2sum-(xsum*xsum))*sqrt(y2sum-(ysum*ysum))) ; } else { return (xysum-xsum*ysum); } } //////////////////////////////////////////////////////////////////////////////// /// Return covariance matrix from data for given list of observables TMatrixDSym* RooAbsData::corrcovMatrix(const RooArgList& vars, const char* cutSpec, const char* cutRange, Bool_t corr) const { RooArgList varList ; TIterator* iter = vars.createIterator() ; RooRealVar* var ; while((var=(RooRealVar*)iter->Next())) { RooRealVar* datavar = dataRealVar("covarianceMatrix",*var) ; if (!datavar) { delete iter ; return 0 ; } varList.add(*datavar) ; } delete iter ; // Check if dataset is not empty if(sumEntries(cutSpec, cutRange) == 0.) { coutW(InputArguments) << "RooDataSet::covariance(" << GetName() << ") WARNING: empty dataset, returning zero" << endl ; return 0; } // Setup RooFormulaVar for cutSpec if it is present RooFormula* select = cutSpec ? new RooFormula("select",cutSpec,*get()) : 0 ; iter = varList.createIterator() ; TIterator* iter2 = varList.createIterator() ; TMatrixDSym xysum(varList.getSize()) ; vector<double> xsum(varList.getSize()) ; vector<double> x2sum(varList.getSize()) ; // Calculate <x_i> and <x_i y_j> for(Int_t index= 0; index < numEntries(); index++) { const RooArgSet* dvars = get(index) ; if (select && select->eval()==0) continue ; if (cutRange && dvars->allInRange(cutRange)) continue ; RooRealVar* varx, *vary ; iter->Reset() ; Int_t ix=0,iy=0 ; while((varx=(RooRealVar*)iter->Next())) { xsum[ix] += weight()*varx->getVal() ; if (corr) { x2sum[ix] += weight()*varx->getVal()*varx->getVal() ; } *iter2=*iter ; iy=ix ; vary=varx ; while(vary) { xysum(ix,iy) += weight()*varx->getVal()*vary->getVal() ; xysum(iy,ix) = xysum(ix,iy) ; iy++ ; vary=(RooRealVar*)iter2->Next() ; } ix++ ; } } // Normalize sums for (Int_t ix=0 ; ix<varList.getSize() ; ix++) { xsum[ix] /= sumEntries(cutSpec, cutRange) ; if (corr) { x2sum[ix] /= sumEntries(cutSpec, cutRange) ; } for (Int_t iy=0 ; iy<varList.getSize() ; iy++) { xysum(ix,iy) /= sumEntries(cutSpec, cutRange) ; } } // Calculate covariance matrix TMatrixDSym* C = new TMatrixDSym(varList.getSize()) ; for (Int_t ix=0 ; ix<varList.getSize() ; ix++) { for (Int_t iy=0 ; iy<varList.getSize() ; iy++) { (*C)(ix,iy) = xysum(ix,iy)-xsum[ix]*xsum[iy] ; if (corr) { (*C)(ix,iy) /= sqrt((x2sum[ix]-(xsum[ix]*xsum[ix]))*(x2sum[iy]-(xsum[iy]*xsum[iy]))) ; } } } if (select) delete select ; delete iter ; delete iter2 ; return C ; } //////////////////////////////////////////////////////////////////////////////// /// Create a RooRealVar containing the mean of observable 'var' in /// this dataset. If cutSpec and/or cutRange are specified the /// moment is calculated on the subset of the data which pass the C++ /// cut specification expression 'cutSpec' and/or are inside the /// range named 'cutRange' RooRealVar* RooAbsData::meanVar(const RooRealVar &var, const char* cutSpec, const char* cutRange) const { // Create a new variable with appropriate strings. The error is calculated as // RMS/Sqrt(N) which is generally valid. // Create holder variable for mean TString name(var.GetName()),title("Mean of ") ; name.Append("Mean"); title.Append(var.GetTitle()); RooRealVar *meanv= new RooRealVar(name,title,0) ; meanv->setConstant(kFALSE) ; // Adjust plot label TString label("<") ; label.Append(var.getPlotLabel()); label.Append(">"); meanv->setPlotLabel(label.Data()); // fill in this variable's value and error Double_t meanVal=moment(var,1,0,cutSpec,cutRange) ; Double_t N(sumEntries(cutSpec,cutRange)) ; Double_t rmsVal= sqrt(moment(var,2,meanVal,cutSpec,cutRange)*N/(N-1)); meanv->setVal(meanVal) ; meanv->setError(N > 0 ? rmsVal/sqrt(N) : 0); return meanv; } //////////////////////////////////////////////////////////////////////////////// /// Create a RooRealVar containing the RMS of observable 'var' in /// this dataset. If cutSpec and/or cutRange are specified the /// moment is calculated on the subset of the data which pass the C++ /// cut specification expression 'cutSpec' and/or are inside the /// range named 'cutRange' RooRealVar* RooAbsData::rmsVar(const RooRealVar &var, const char* cutSpec, const char* cutRange) const { // Create a new variable with appropriate strings. The error is calculated as // RMS/(2*Sqrt(N)) which is only valid if the variable has a Gaussian distribution. // Create RMS value holder TString name(var.GetName()),title("RMS of ") ; name.Append("RMS"); title.Append(var.GetTitle()); RooRealVar *rms= new RooRealVar(name,title,0) ; rms->setConstant(kFALSE) ; // Adjust plot label TString label(var.getPlotLabel()); label.Append("_{RMS}"); rms->setPlotLabel(label); // Fill in this variable's value and error Double_t meanVal(moment(var,1,0,cutSpec,cutRange)) ; Double_t N(sumEntries(cutSpec, cutRange)); Double_t rmsVal= sqrt(moment(var,2,meanVal,cutSpec,cutRange)*N/(N-1)); rms->setVal(rmsVal) ; rms->setError(rmsVal/sqrt(2*N)); return rms; } //////////////////////////////////////////////////////////////////////////////// /// Add a box with statistics information to the specified frame. By default a box with the /// event count, mean and rms of the plotted variable is added. /// /// The following optional named arguments are accepted /// <table> /// <tr><td> `What(const char* whatstr)` <td> Controls what is printed: "N" = count, "M" is mean, "R" is RMS. /// <tr><td> `Format(const char* optStr)` <td> \deprecated Classing parameter formatting options, provided for backward compatibility /// /// <tr><td> `Format(const char* what,...)` <td> Parameter formatting options. /// <table> /// <tr><td> const char* what <td> Controls what is shown: /// - "N" adds name /// - "E" adds error /// - "A" shows asymmetric error /// - "U" shows unit /// - "H" hides the value /// <tr><td> `FixedPrecision(int n)` <td> Controls precision, set fixed number of digits /// <tr><td> `AutoPrecision(int n)` <td> Controls precision. Number of shown digits is calculated from error + n specified additional digits (1 is sensible default) /// <tr><td> `VerbatimName(Bool_t flag)` <td> Put variable name in a \\verb+ + clause. /// </table> /// <tr><td> `Label(const chat* label)` <td> Add header label to parameter box /// <tr><td> `Layout(Double_t xmin, Double_t xmax, Double_t ymax)` <td> Specify relative position of left,right side of box and top of box. Position of /// bottom of box is calculated automatically from number lines in box /// <tr><td> `Cut(const char* expression)` <td> Apply given cut expression to data when calculating statistics /// <tr><td> `CutRange(const char* rangeName)` <td> Only consider events within given range when calculating statistics. Multiple /// CutRange() argument may be specified to combine ranges. /// /// </table> RooPlot* RooAbsData::statOn(RooPlot* frame, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) { // Stuff all arguments in a list RooLinkedList cmdList; cmdList.Add(const_cast<RooCmdArg*>(&arg1)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg2)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg3)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg4)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg5)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg6)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg7)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg8)) ; // Select the pdf-specific commands RooCmdConfig pc(Form("RooTreeData::statOn(%s)",GetName())) ; pc.defineString("what","What",0,"MNR") ; pc.defineString("label","Label",0,"") ; pc.defineDouble("xmin","Layout",0,0.65) ; pc.defineDouble("xmax","Layout",1,0.99) ; pc.defineInt("ymaxi","Layout",0,Int_t(0.95*10000)) ; pc.defineString("formatStr","Format",0,"NELU") ; pc.defineInt("sigDigit","Format",0,2) ; pc.defineInt("dummy","FormatArgs",0,0) ; pc.defineString("cutRange","CutRange",0,"",kTRUE) ; pc.defineString("cutString","CutSpec",0,"") ; pc.defineMutex("Format","FormatArgs") ; // Process and check varargs pc.process(cmdList) ; if (!pc.ok(kTRUE)) { return frame ; } const char* label = pc.getString("label") ; Double_t xmin = pc.getDouble("xmin") ; Double_t xmax = pc.getDouble("xmax") ; Double_t ymax = pc.getInt("ymaxi") / 10000. ; const char* formatStr = pc.getString("formatStr") ; Int_t sigDigit = pc.getInt("sigDigit") ; const char* what = pc.getString("what") ; const char* cutSpec = pc.getString("cutString",0,kTRUE) ; const char* cutRange = pc.getString("cutRange",0,kTRUE) ; if (pc.hasProcessed("FormatArgs")) { RooCmdArg* formatCmd = static_cast<RooCmdArg*>(cmdList.FindObject("FormatArgs")) ; return statOn(frame,what,label,0,0,xmin,xmax,ymax,cutSpec,cutRange,formatCmd) ; } else { return statOn(frame,what,label,sigDigit,formatStr,xmin,xmax,ymax,cutSpec,cutRange) ; } } //////////////////////////////////////////////////////////////////////////////// /// Implementation back-end of statOn() method with named arguments RooPlot* RooAbsData::statOn(RooPlot* frame, const char* what, const char *label, Int_t sigDigits, Option_t *options, Double_t xmin, Double_t xmax, Double_t ymax, const char* cutSpec, const char* cutRange, const RooCmdArg* formatCmd) { Bool_t showLabel= (label != 0 && strlen(label) > 0); TString whatStr(what) ; whatStr.ToUpper() ; Bool_t showN = whatStr.Contains("N") ; Bool_t showR = whatStr.Contains("R") ; Bool_t showM = whatStr.Contains("M") ; Int_t nPar= 0; if (showN) nPar++ ; if (showR) nPar++ ; if (showM) nPar++ ; // calculate the box's size Double_t dy(0.06), ymin(ymax-nPar*dy); if(showLabel) ymin-= dy; // create the box and set its options TPaveText *box= new TPaveText(xmin,ymax,xmax,ymin,"BRNDC"); if(!box) return 0; box->SetName(Form("%s_statBox",GetName())) ; box->SetFillColor(0); box->SetBorderSize(1); box->SetTextAlign(12); box->SetTextSize(0.04F); box->SetFillStyle(1001); // add formatted text for each statistic RooRealVar N("N","Number of Events",sumEntries(cutSpec,cutRange)); N.setPlotLabel("Entries") ; RooRealVar *meanv= meanVar(*(RooRealVar*)frame->getPlotVar(),cutSpec,cutRange); meanv->setPlotLabel("Mean") ; RooRealVar *rms= rmsVar(*(RooRealVar*)frame->getPlotVar(),cutSpec,cutRange); rms->setPlotLabel("RMS") ; TString *rmsText, *meanText, *NText ; if (options) { rmsText= rms->format(sigDigits,options); meanText= meanv->format(sigDigits,options); NText= N.format(sigDigits,options); } else { rmsText= rms->format(*formatCmd); meanText= meanv->format(*formatCmd); NText= N.format(*formatCmd); } if (showR) box->AddText(rmsText->Data()); if (showM) box->AddText(meanText->Data()); if (showN) box->AddText(NText->Data()); // cleanup heap memory delete NText; delete meanText; delete rmsText; delete meanv; delete rms; // add the optional label if specified if(showLabel) box->AddText(label); frame->addObject(box) ; return frame ; } //////////////////////////////////////////////////////////////////////////////// /// Loop over columns of our tree data and fill the input histogram. Returns a pointer to the /// input histogram, or zero in case of an error. The input histogram can be any TH1 subclass, and /// therefore of arbitrary dimension. Variables are matched with the (x,y,...) dimensions of the input /// histogram according to the order in which they appear in the input plotVars list. TH1 *RooAbsData::fillHistogram(TH1 *hist, const RooArgList &plotVars, const char *cuts, const char* cutRange) const { // Do we have a valid histogram to use? if(0 == hist) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: no valid histogram to fill" << endl; return 0; } // Check that the number of plotVars matches the input histogram's dimension Int_t hdim= hist->GetDimension(); if(hdim != plotVars.getSize()) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: plotVars has the wrong dimension" << endl; return 0; } // Check that the plot variables are all actually RooAbsReal's and print a warning if we do not // explicitly depend on one of them. Clone any variables that we do not contain directly and // redirect them to use our event data. RooArgSet plotClones,localVars; for(Int_t index= 0; index < plotVars.getSize(); index++) { const RooAbsArg *var= plotVars.at(index); const RooAbsReal *realVar= dynamic_cast<const RooAbsReal*>(var); if(0 == realVar) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: cannot plot variable \"" << var->GetName() << "\" of type " << var->ClassName() << endl; return 0; } RooAbsArg *found= _vars.find(realVar->GetName()); if(!found) { RooAbsArg *clone= plotClones.addClone(*realVar,kTRUE); // do not complain about duplicates assert(0 != clone); if(!clone->dependsOn(_vars)) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: Data does not contain the variable '" << realVar->GetName() << "'." << endl; return nullptr; } else { clone->recursiveRedirectServers(_vars); } localVars.add(*clone); } else { localVars.add(*found); } } // Create selection formula if selection cuts are specified std::unique_ptr<RooFormula> select; if (cuts != nullptr && strlen(cuts) > 0) { select.reset(new RooFormula(cuts, cuts, _vars, false)); if (!select || !select->ok()) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: invalid cuts \"" << cuts << "\"" << endl; return 0 ; } } // Lookup each of the variables we are binning in our tree variables const RooAbsReal *xvar = 0; const RooAbsReal *yvar = 0; const RooAbsReal *zvar = 0; switch(hdim) { case 3: zvar= dynamic_cast<RooAbsReal*>(localVars.find(plotVars.at(2)->GetName())); assert(0 != zvar); // fall through to next case... case 2: yvar= dynamic_cast<RooAbsReal*>(localVars.find(plotVars.at(1)->GetName())); assert(0 != yvar); // fall through to next case... case 1: xvar= dynamic_cast<RooAbsReal*>(localVars.find(plotVars.at(0)->GetName())); assert(0 != xvar); break; default: coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: cannot fill histogram with " << hdim << " dimensions" << endl; break; } // Parse cutRange specification vector<string> cutVec ; if (cutRange && strlen(cutRange)>0) { if (strchr(cutRange,',')==0) { cutVec.push_back(cutRange) ; } else { const size_t bufSize = strlen(cutRange)+1; char* buf = new char[bufSize] ; strlcpy(buf,cutRange,bufSize) ; const char* oneRange = strtok(buf,",") ; while(oneRange) { cutVec.push_back(oneRange) ; oneRange = strtok(0,",") ; } delete[] buf ; } } // Loop over events and fill the histogram if (hist->GetSumw2()->fN==0) { hist->Sumw2() ; } Int_t nevent= numEntries() ; //(Int_t)_tree->GetEntries(); for(Int_t i=0; i < nevent; ++i) { //Int_t entryNumber= _tree->GetEntryNumber(i); //if (entryNumber<0) break; get(i); // Apply expression based selection criteria if (select && select->eval()==0) { continue ; } // Apply range based selection criteria Bool_t selectByRange = kTRUE ; if (cutRange) { for (const auto arg : _vars) { Bool_t selectThisArg = kFALSE ; UInt_t icut ; for (icut=0 ; icut<cutVec.size() ; icut++) { if (arg->inRange(cutVec[icut].c_str())) { selectThisArg = kTRUE ; break ; } } if (!selectThisArg) { selectByRange = kFALSE ; break ; } } } if (!selectByRange) { // Go to next event in loop over events continue ; } Int_t bin(0); switch(hdim) { case 1: bin= hist->FindBin(xvar->getVal()); hist->Fill(xvar->getVal(),weight()) ; break; case 2: bin= hist->FindBin(xvar->getVal(),yvar->getVal()); static_cast<TH2*>(hist)->Fill(xvar->getVal(),yvar->getVal(),weight()) ; break; case 3: bin= hist->FindBin(xvar->getVal(),yvar->getVal(),zvar->getVal()); static_cast<TH3*>(hist)->Fill(xvar->getVal(),yvar->getVal(),zvar->getVal(),weight()) ; break; default: assert(hdim < 3); break; } Double_t error2 = TMath::Power(hist->GetBinError(bin),2)-TMath::Power(weight(),2) ; Double_t we = weightError(RooAbsData::SumW2) ; if (we==0) we = weight() ; error2 += TMath::Power(we,2) ; // Double_t we = weightError(RooAbsData::SumW2) ; // Double_t error2(0) ; // if (we==0) { // we = weight() ; //sqrt(weight()) ; // error2 = TMath::Power(hist->GetBinError(bin),2)-TMath::Power(weight(),2) + TMath::Power(we,2) ; // } else { // error2 = TMath::Power(hist->GetBinError(bin),2)-TMath::Power(weight(),2) + TMath::Power(we,2) ; // } //hist->AddBinContent(bin,weight()); hist->SetBinError(bin,sqrt(error2)) ; //cout << "RooTreeData::fillHistogram() bin = " << bin << " weight() = " << weight() << " we = " << we << endl ; } return hist; } //////////////////////////////////////////////////////////////////////////////// /// Split dataset into subsets based on states of given splitCat in this dataset. /// A TList of RooDataSets is returned in which each RooDataSet is named /// after the state name of splitCat of which it contains the dataset subset. /// The observables splitCat itself is no longer present in the sub datasets. /// If createEmptyDataSets is kFALSE (default) this method only creates datasets for states /// which have at least one entry The caller takes ownership of the returned list and its contents TList* RooAbsData::split(const RooAbsCategory& splitCat, Bool_t createEmptyDataSets) const { // Sanity check if (!splitCat.dependsOn(*get())) { coutE(InputArguments) << "RooTreeData::split(" << GetName() << ") ERROR category " << splitCat.GetName() << " doesn't depend on any variable in this dataset" << endl ; return 0 ; } // Clone splitting category and attach to self RooAbsCategory* cloneCat =0; RooArgSet* cloneSet = 0; if (splitCat.isDerived()) { cloneSet = (RooArgSet*) RooArgSet(splitCat).snapshot(kTRUE) ; if (!cloneSet) { coutE(InputArguments) << "RooTreeData::split(" << GetName() << ") Couldn't deep-clone splitting category, abort." << endl ; return 0 ; } cloneCat = (RooAbsCategory*) cloneSet->find(splitCat.GetName()) ; cloneCat->attachDataSet(*this) ; } else { cloneCat = dynamic_cast<RooAbsCategory*>(get()->find(splitCat.GetName())) ; if (!cloneCat) { coutE(InputArguments) << "RooTreeData::split(" << GetName() << ") ERROR category " << splitCat.GetName() << " is fundamental and does not appear in this dataset" << endl ; return 0 ; } } // Split a dataset in a series of subsets, each corresponding // to a state of splitCat TList* dsetList = new TList ; // Construct set of variables to be included in split sets = full set - split category RooArgSet subsetVars(*get()) ; if (splitCat.isDerived()) { RooArgSet* vars = splitCat.getVariables() ; subsetVars.remove(*vars,kTRUE,kTRUE) ; delete vars ; } else { subsetVars.remove(splitCat,kTRUE,kTRUE) ; } // Add weight variable explicitly if dataset has weights, but no top-level weight // variable exists (can happen with composite datastores) Bool_t addWV(kFALSE) ; RooRealVar newweight("weight","weight",-1e9,1e9) ; if (isWeighted() && !IsA()->InheritsFrom(RooDataHist::Class())) { subsetVars.add(newweight) ; addWV = kTRUE ; } // If createEmptyDataSets is true, prepopulate with empty sets corresponding to all states if (createEmptyDataSets) { for (const auto& nameIdx : *cloneCat) { RooAbsData* subset = emptyClone(nameIdx.first.c_str(), nameIdx.first.c_str(), &subsetVars,(addWV?"weight":0)) ; dsetList->Add((RooAbsArg*)subset) ; } } // Loop over dataset and copy event to matching subset const bool propWeightSquared = isWeighted(); for (Int_t i = 0; i < numEntries(); ++i) { const RooArgSet* row = get(i); RooAbsData* subset = (RooAbsData*) dsetList->FindObject(cloneCat->getCurrentLabel()); if (!subset) { subset = emptyClone(cloneCat->getCurrentLabel(),cloneCat->getCurrentLabel(),&subsetVars,(addWV?"weight":0)); dsetList->Add((RooAbsArg*)subset); } if (!propWeightSquared) { subset->add(*row, weight()); } else { subset->add(*row, weight(), weightSquared()); } } delete cloneSet; return dsetList; } //////////////////////////////////////////////////////////////////////////////// /// Plot dataset on specified frame. /// /// By default: /// - An unbinned dataset will use the default binning of the target frame. /// - A binned dataset will retain its intrinsic binning. /// /// The following optional named arguments can be used to modify the behaviour: /// /// <table> /// <tr><th> <th> Data representation options /// <tr><td> `Asymmetry(const RooCategory& c)` <td> Show the asymmetry of the data in given two-state category [F(+)-F(-)] / [F(+)+F(-)]. /// Category must have two states with indices -1 and +1 or three states with indices -1,0 and +1. /// <tr><td> `Efficiency(const RooCategory& c)` <td> Show the efficiency F(acc)/[F(acc)+F(rej)]. Category must have two states with indices 0 and 1 /// <tr><td> `DataError(RooAbsData::EType)` <td> Select the type of error drawn: /// - `Auto(default)` results in Poisson for unweighted data and SumW2 for weighted data /// - `Poisson` draws asymmetric Poisson confidence intervals. /// - `SumW2` draws symmetric sum-of-weights error ( \f$ \left( \sum w \right)^2 / \sum\left(w^2\right) \f$ ) /// - `None` draws no error bars /// <tr><td> `Binning(int nbins, double xlo, double xhi)` <td> Use specified binning to draw dataset /// <tr><td> `Binning(const RooAbsBinning&)` <td> Use specified binning to draw dataset /// <tr><td> `Binning(const char* name)` <td> Use binning with specified name to draw dataset /// <tr><td> `RefreshNorm(Bool_t flag)` <td> Force refreshing for PDF normalization information in frame. /// If set, any subsequent PDF will normalize to this dataset, even if it is /// not the first one added to the frame. By default only the 1st dataset /// added to a frame will update the normalization information /// <tr><td> `Rescale(Double_t f)` <td> Rescale drawn histogram by given factor. /// <tr><td> `Cut(const char*)` <td> Only plot entries that pass the given cut. /// Apart from cutting in continuous variables `Cut("x>5")`, this can also be used to plot a specific /// category state. Use something like `Cut("myCategory == myCategory::stateA")`, where /// `myCategory` resolves to the state number for a given entry and /// `myCategory::stateA` resolves to the state number of the state named "stateA". /// /// <tr><td> `CutRange(const char*)` <td> Only plot data from given range. Separate multiple ranges with ",". /// \note This often requires passing the normalisation when plotting the PDF because RooFit does not save /// how many events were being plotted (it will only work for cutting slices out of uniformly distributed variables). /// ``` /// data->plotOn(frame01, CutRange("SB1")); /// const double nData = data->sumEntries("", "SB1"); /// // Make clear that the target normalisation is nData. The enumerator NumEvent /// // is needed to switch between relative and absolute scaling. /// model.plotOn(frame01, Normalization(nData, RooAbsReal::NumEvent), /// ProjectionRange("SB1")); /// ``` /// /// <tr><th> <th> Histogram drawing options /// <tr><td> `DrawOption(const char* opt)` <td> Select ROOT draw option for resulting TGraph object /// <tr><td> `LineStyle(Int_t style)` <td> Select line style by ROOT line style code, default is solid /// <tr><td> `LineColor(Int_t color)` <td> Select line color by ROOT color code, default is black /// <tr><td> `LineWidth(Int_t width)` <td> Select line with in pixels, default is 3 /// <tr><td> `MarkerStyle(Int_t style)` <td> Select the ROOT marker style, default is 21 /// <tr><td> `MarkerColor(Int_t color)` <td> Select the ROOT marker color, default is black /// <tr><td> `MarkerSize(Double_t size)` <td> Select the ROOT marker size /// <tr><td> `FillStyle(Int_t style)` <td> Select fill style, default is filled. /// <tr><td> `FillColor(Int_t color)` <td> Select fill color by ROOT color code /// <tr><td> `XErrorSize(Double_t frac)` <td> Select size of X error bar as fraction of the bin width, default is 1 /// /// /// <tr><th> <th> Misc. other options /// <tr><td> `Name(const chat* name)` <td> Give curve specified name in frame. Useful if curve is to be referenced later /// <tr><td> `Invisible()` <td> Add curve to frame, but do not display. Useful in combination AddTo() /// <tr><td> `AddTo(const char* name, double_t wgtSelf, double_t wgtOther)` <td> Add constructed histogram to already existing histogram with given name and relative weight factors /// </table> RooPlot* RooAbsData::plotOn(RooPlot* frame, const RooLinkedList& argList) const { // New experimental plotOn() with varargs... // Define configuration for this method RooCmdConfig pc(Form("RooAbsData::plotOn(%s)",GetName())) ; pc.defineString("drawOption","DrawOption",0,"P") ; pc.defineString("cutRange","CutRange",0,"",kTRUE) ; pc.defineString("cutString","CutSpec",0,"") ; pc.defineString("histName","Name",0,"") ; pc.defineObject("cutVar","CutVar",0) ; pc.defineObject("binning","Binning",0) ; pc.defineString("binningName","BinningName",0,"") ; pc.defineInt("nbins","BinningSpec",0,100) ; pc.defineDouble("xlo","BinningSpec",0,0) ; pc.defineDouble("xhi","BinningSpec",1,1) ; pc.defineObject("asymCat","Asymmetry",0) ; pc.defineObject("effCat","Efficiency",0) ; pc.defineInt("lineColor","LineColor",0,-999) ; pc.defineInt("lineStyle","LineStyle",0,-999) ; pc.defineInt("lineWidth","LineWidth",0,-999) ; pc.defineInt("markerColor","MarkerColor",0,-999) ; pc.defineInt("markerStyle","MarkerStyle",0,-999) ; pc.defineDouble("markerSize","MarkerSize",0,-999) ; pc.defineInt("fillColor","FillColor",0,-999) ; pc.defineInt("fillStyle","FillStyle",0,-999) ; pc.defineInt("errorType","DataError",0,(Int_t)RooAbsData::Auto) ; pc.defineInt("histInvisible","Invisible",0,0) ; pc.defineInt("refreshFrameNorm","RefreshNorm",0,1) ; pc.defineString("addToHistName","AddTo",0,"") ; pc.defineDouble("addToWgtSelf","AddTo",0,1.) ; pc.defineDouble("addToWgtOther","AddTo",1,1.) ; pc.defineDouble("xErrorSize","XErrorSize",0,1.) ; pc.defineDouble("scaleFactor","Rescale",0,1.) ; pc.defineMutex("DataError","Asymmetry","Efficiency") ; pc.defineMutex("Binning","BinningName","BinningSpec") ; // Process & check varargs pc.process(argList) ; if (!pc.ok(kTRUE)) { return frame ; } PlotOpt o ; // Extract values from named arguments o.drawOptions = pc.getString("drawOption") ; o.cuts = pc.getString("cutString") ; if (pc.hasProcessed("Binning")) { o.bins = (RooAbsBinning*) pc.getObject("binning") ; } else if (pc.hasProcessed("BinningName")) { o.bins = &frame->getPlotVar()->getBinning(pc.getString("binningName")) ; } else if (pc.hasProcessed("BinningSpec")) { Double_t xlo = pc.getDouble("xlo") ; Double_t xhi = pc.getDouble("xhi") ; o.bins = new RooUniformBinning((xlo==xhi)?frame->getPlotVar()->getMin():xlo, (xlo==xhi)?frame->getPlotVar()->getMax():xhi,pc.getInt("nbins")) ; } const RooAbsCategoryLValue* asymCat = (const RooAbsCategoryLValue*) pc.getObject("asymCat") ; const RooAbsCategoryLValue* effCat = (const RooAbsCategoryLValue*) pc.getObject("effCat") ; o.etype = (RooAbsData::ErrorType) pc.getInt("errorType") ; o.histInvisible = pc.getInt("histInvisible") ; o.xErrorSize = pc.getDouble("xErrorSize") ; o.cutRange = pc.getString("cutRange",0,kTRUE) ; o.histName = pc.getString("histName",0,kTRUE) ; o.addToHistName = pc.getString("addToHistName",0,kTRUE) ; o.addToWgtSelf = pc.getDouble("addToWgtSelf") ; o.addToWgtOther = pc.getDouble("addToWgtOther") ; o.refreshFrameNorm = pc.getInt("refreshFrameNorm") ; o.scaleFactor = pc.getDouble("scaleFactor") ; // Map auto error type to actual type if (o.etype == Auto) { o.etype = isNonPoissonWeighted() ? SumW2 : Poisson ; if (o.etype == SumW2) { coutI(InputArguments) << "RooAbsData::plotOn(" << GetName() << ") INFO: dataset has non-integer weights, auto-selecting SumW2 errors instead of Poisson errors" << endl ; } } if (o.addToHistName && !frame->findObject(o.addToHistName,RooHist::Class())) { coutE(InputArguments) << "RooAbsData::plotOn(" << GetName() << ") cannot find existing histogram " << o.addToHistName << " to add to in RooPlot" << endl ; return frame ; } RooPlot* ret ; if (!asymCat && !effCat) { ret = plotOn(frame,o) ; } else if (asymCat) { ret = plotAsymOn(frame,*asymCat,o) ; } else { ret = plotEffOn(frame,*effCat,o) ; } Int_t lineColor = pc.getInt("lineColor") ; Int_t lineStyle = pc.getInt("lineStyle") ; Int_t lineWidth = pc.getInt("lineWidth") ; Int_t markerColor = pc.getInt("markerColor") ; Int_t markerStyle = pc.getInt("markerStyle") ; Size_t markerSize = pc.getDouble("markerSize") ; Int_t fillColor = pc.getInt("fillColor") ; Int_t fillStyle = pc.getInt("fillStyle") ; if (lineColor!=-999) ret->getAttLine()->SetLineColor(lineColor) ; if (lineStyle!=-999) ret->getAttLine()->SetLineStyle(lineStyle) ; if (lineWidth!=-999) ret->getAttLine()->SetLineWidth(lineWidth) ; if (markerColor!=-999) ret->getAttMarker()->SetMarkerColor(markerColor) ; if (markerStyle!=-999) ret->getAttMarker()->SetMarkerStyle(markerStyle) ; if (markerSize!=-999) ret->getAttMarker()->SetMarkerSize(markerSize) ; if (fillColor!=-999) ret->getAttFill()->SetFillColor(fillColor) ; if (fillStyle!=-999) ret->getAttFill()->SetFillStyle(fillStyle) ; if (pc.hasProcessed("BinningSpec")) { delete o.bins ; } return ret ; } //////////////////////////////////////////////////////////////////////////////// /// Create and fill a histogram of the frame's variable and append it to the frame. /// The frame variable must be one of the data sets dimensions. /// /// The plot range and the number of plot bins is determined by the parameters /// of the plot variable of the frame (RooAbsReal::setPlotRange(), RooAbsReal::setPlotBins()). /// /// The optional cut string expression can be used to select the events to be plotted. /// The cut specification may refer to any variable contained in the data set. /// /// The drawOptions are passed to the TH1::Draw() method. /// \see RooAbsData::plotOn(RooPlot*,const RooLinkedList&) const RooPlot *RooAbsData::plotOn(RooPlot *frame, PlotOpt o) const { if(0 == frame) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotOn: frame is null" << endl; return 0; } RooAbsRealLValue *var= (RooAbsRealLValue*) frame->getPlotVar(); if(0 == var) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotOn: frame does not specify a plot variable" << endl; return 0; } // create and fill a temporary histogram of this variable TString histName(GetName()); histName.Append("_plot"); std::unique_ptr<TH1> hist; if (o.bins) { hist.reset( var->createHistogram(histName.Data(), RooFit::AxisLabel("Events"), RooFit::Binning(*o.bins)) ); } else if (!frame->getPlotVar()->getBinning().isUniform()) { hist.reset( var->createHistogram(histName.Data(), RooFit::AxisLabel("Events"), RooFit::Binning(frame->getPlotVar()->getBinning())) ); } else { hist.reset( var->createHistogram(histName.Data(), "Events", frame->GetXaxis()->GetXmin(), frame->GetXaxis()->GetXmax(), frame->GetNbinsX()) ); } // Keep track of sum-of-weights error hist->Sumw2() ; if(0 == fillHistogram(hist.get(), RooArgList(*var),o.cuts,o.cutRange)) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotOn: fillHistogram() failed" << endl; return 0; } // If frame has no predefined bin width (event density) it will be adjusted to // our histograms bin width so we should force that bin width here Double_t nomBinWidth ; if (frame->getFitRangeNEvt()==0 && o.bins) { nomBinWidth = o.bins->averageBinWidth() ; } else { nomBinWidth = o.bins ? frame->getFitRangeBinW() : 0 ; } // convert this histogram to a RooHist object on the heap RooHist *graph= new RooHist(*hist,nomBinWidth,1,o.etype,o.xErrorSize,o.correctForBinWidth,o.scaleFactor); if(0 == graph) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotOn: unable to create a RooHist object" << endl; return 0; } // If the dataset variable has a wide range than the plot variable, // calculate the number of entries in the dataset in the plot variable fit range RooAbsRealLValue* dataVar = (RooAbsRealLValue*) _vars.find(var->GetName()) ; Double_t nEnt(sumEntries()) ; if (dataVar->getMin()<var->getMin() || dataVar->getMax()>var->getMax()) { RooAbsData* tmp = ((RooAbsData*)this)->reduce(*var) ; nEnt = tmp->sumEntries() ; delete tmp ; } // Store the number of entries before the cut, if any was made if ((o.cuts && strlen(o.cuts)) || o.cutRange) { coutI(Plotting) << "RooTreeData::plotOn: plotting " << hist->GetSumOfWeights() << " events out of " << nEnt << " total events" << endl ; graph->setRawEntries(nEnt) ; } // Add self to other hist if requested if (o.addToHistName) { RooHist* otherGraph = static_cast<RooHist*>(frame->findObject(o.addToHistName,RooHist::Class())) ; if (!graph->hasIdenticalBinning(*otherGraph)) { coutE(Plotting) << "RooTreeData::plotOn: ERROR Histogram to be added to, '" << o.addToHistName << "',has different binning" << endl ; delete graph ; return frame ; } RooHist* sumGraph = new RooHist(*graph,*otherGraph,o.addToWgtSelf,o.addToWgtOther,o.etype) ; delete graph ; graph = sumGraph ; } // Rename graph if requested if (o.histName) { graph->SetName(o.histName) ; } else { TString hname(Form("h_%s",GetName())) ; if (o.cutRange && strlen(o.cutRange)>0) { hname.Append(Form("_CutRange[%s]",o.cutRange)) ; } if (o.cuts && strlen(o.cuts)>0) { hname.Append(Form("_Cut[%s]",o.cuts)) ; } graph->SetName(hname.Data()) ; } // initialize the frame's normalization setup, if necessary frame->updateNormVars(_vars); // add the RooHist to the specified plot frame->addPlotable(graph,o.drawOptions,o.histInvisible,o.refreshFrameNorm); return frame; } //////////////////////////////////////////////////////////////////////////////// /// Create and fill a histogram with the asymmetry N[+] - N[-] / ( N[+] + N[-] ), /// where N(+/-) is the number of data points with asymCat=+1 and asymCat=-1 /// as function of the frames variable. The asymmetry category 'asymCat' must /// have exactly 2 (or 3) states defined with index values +1,-1 (and 0) /// /// The plot range and the number of plot bins is determined by the parameters /// of the plot variable of the frame (RooAbsReal::setPlotRange(), RooAbsReal::setPlotBins()) /// /// The optional cut string expression can be used to select the events to be plotted. /// The cut specification may refer to any variable contained in the data set /// /// The drawOptions are passed to the TH1::Draw() method RooPlot* RooAbsData::plotAsymOn(RooPlot* frame, const RooAbsCategoryLValue& asymCat, PlotOpt o) const { if(0 == frame) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotAsymOn: frame is null" << endl; return 0; } RooAbsRealLValue *var= (RooAbsRealLValue*) frame->getPlotVar(); if(0 == var) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotAsymOn: frame does not specify a plot variable" << endl; return 0; } // create and fill temporary histograms of this variable for each state TString hist1Name(GetName()),hist2Name(GetName()); hist1Name.Append("_plot1"); std::unique_ptr<TH1> hist1, hist2; hist2Name.Append("_plot2"); if (o.bins) { hist1.reset( var->createHistogram(hist1Name.Data(), "Events", *o.bins) ); hist2.reset( var->createHistogram(hist2Name.Data(), "Events", *o.bins) ); } else { hist1.reset( var->createHistogram(hist1Name.Data(), "Events", frame->GetXaxis()->GetXmin(), frame->GetXaxis()->GetXmax(), frame->GetNbinsX()) ); hist2.reset( var->createHistogram(hist2Name.Data(), "Events", frame->GetXaxis()->GetXmin(), frame->GetXaxis()->GetXmax(), frame->GetNbinsX()) ); } assert(hist1 && hist2); TString cuts1,cuts2 ; if (o.cuts && strlen(o.cuts)) { cuts1 = Form("(%s)&&(%s>0)",o.cuts,asymCat.GetName()); cuts2 = Form("(%s)&&(%s<0)",o.cuts,asymCat.GetName()); } else { cuts1 = Form("(%s>0)",asymCat.GetName()); cuts2 = Form("(%s<0)",asymCat.GetName()); } if(! fillHistogram(hist1.get(), RooArgList(*var),cuts1.Data(),o.cutRange) || ! fillHistogram(hist2.get(), RooArgList(*var),cuts2.Data(),o.cutRange)) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotAsymOn: createHistogram() failed" << endl; return 0; } // convert this histogram to a RooHist object on the heap RooHist *graph= new RooHist(*hist1,*hist2,0,1,o.etype,o.xErrorSize,kFALSE,o.scaleFactor); graph->setYAxisLabel(Form("Asymmetry in %s",asymCat.GetName())) ; // initialize the frame's normalization setup, if necessary frame->updateNormVars(_vars); // Rename graph if requested if (o.histName) { graph->SetName(o.histName) ; } else { TString hname(Form("h_%s_Asym[%s]",GetName(),asymCat.GetName())) ; if (o.cutRange && strlen(o.cutRange)>0) { hname.Append(Form("_CutRange[%s]",o.cutRange)) ; } if (o.cuts && strlen(o.cuts)>0) { hname.Append(Form("_Cut[%s]",o.cuts)) ; } graph->SetName(hname.Data()) ; } // add the RooHist to the specified plot frame->addPlotable(graph,o.drawOptions,o.histInvisible,o.refreshFrameNorm); return frame; } //////////////////////////////////////////////////////////////////////////////// /// Create and fill a histogram with the efficiency N[1] / ( N[1] + N[0] ), /// where N(1/0) is the number of data points with effCat=1 and effCat=0 /// as function of the frames variable. The efficiency category 'effCat' must /// have exactly 2 +1 and 0. /// /// The plot range and the number of plot bins is determined by the parameters /// of the plot variable of the frame (RooAbsReal::setPlotRange(), RooAbsReal::setPlotBins()) /// /// The optional cut string expression can be used to select the events to be plotted. /// The cut specification may refer to any variable contained in the data set /// /// The drawOptions are passed to the TH1::Draw() method RooPlot* RooAbsData::plotEffOn(RooPlot* frame, const RooAbsCategoryLValue& effCat, PlotOpt o) const { if(0 == frame) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotEffOn: frame is null" << endl; return 0; } RooAbsRealLValue *var= (RooAbsRealLValue*) frame->getPlotVar(); if(0 == var) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotEffOn: frame does not specify a plot variable" << endl; return 0; } // create and fill temporary histograms of this variable for each state TString hist1Name(GetName()),hist2Name(GetName()); hist1Name.Append("_plot1"); std::unique_ptr<TH1> hist1, hist2; hist2Name.Append("_plot2"); if (o.bins) { hist1.reset( var->createHistogram(hist1Name.Data(), "Events", *o.bins) ); hist2.reset( var->createHistogram(hist2Name.Data(), "Events", *o.bins) ); } else { hist1.reset( var->createHistogram(hist1Name.Data(), "Events", frame->GetXaxis()->GetXmin(), frame->GetXaxis()->GetXmax(), frame->GetNbinsX()) ); hist2.reset( var->createHistogram(hist2Name.Data(), "Events", frame->GetXaxis()->GetXmin(), frame->GetXaxis()->GetXmax(), frame->GetNbinsX()) ); } assert(hist1 && hist2); TString cuts1,cuts2 ; if (o.cuts && strlen(o.cuts)) { cuts1 = Form("(%s)&&(%s==1)",o.cuts,effCat.GetName()); cuts2 = Form("(%s)&&(%s==0)",o.cuts,effCat.GetName()); } else { cuts1 = Form("(%s==1)",effCat.GetName()); cuts2 = Form("(%s==0)",effCat.GetName()); } if(! fillHistogram(hist1.get(), RooArgList(*var),cuts1.Data(),o.cutRange) || ! fillHistogram(hist2.get(), RooArgList(*var),cuts2.Data(),o.cutRange)) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotEffOn: createHistogram() failed" << endl; return 0; } // convert this histogram to a RooHist object on the heap RooHist *graph= new RooHist(*hist1,*hist2,0,1,o.etype,o.xErrorSize,kTRUE); graph->setYAxisLabel(Form("Efficiency of %s=%s", effCat.GetName(), effCat.lookupName(1).c_str())); // initialize the frame's normalization setup, if necessary frame->updateNormVars(_vars); // Rename graph if requested if (o.histName) { graph->SetName(o.histName) ; } else { TString hname(Form("h_%s_Eff[%s]",GetName(),effCat.GetName())) ; if (o.cutRange && strlen(o.cutRange)>0) { hname.Append(Form("_CutRange[%s]",o.cutRange)) ; } if (o.cuts && strlen(o.cuts)>0) { hname.Append(Form("_Cut[%s]",o.cuts)) ; } graph->SetName(hname.Data()) ; } // add the RooHist to the specified plot frame->addPlotable(graph,o.drawOptions,o.histInvisible,o.refreshFrameNorm); return frame; } //////////////////////////////////////////////////////////////////////////////// /// Create and fill a 1-dimensional table for given category column /// This functions is the equivalent of plotOn() for category dimensions. /// /// The optional cut string expression can be used to select the events to be tabulated /// The cut specification may refer to any variable contained in the data set /// /// The option string is currently not used Roo1DTable* RooAbsData::table(const RooAbsCategory& cat, const char* cuts, const char* /*opts*/) const { // First see if var is in data set RooAbsCategory* tableVar = (RooAbsCategory*) _vars.find(cat.GetName()) ; RooArgSet *tableSet = 0; Bool_t ownPlotVar(kFALSE) ; if (!tableVar) { if (!cat.dependsOn(_vars)) { coutE(Plotting) << "RooTreeData::Table(" << GetName() << "): Argument " << cat.GetName() << " is not in dataset and is also not dependent on data set" << endl ; return 0 ; } // Clone derived variable tableSet = (RooArgSet*) RooArgSet(cat).snapshot(kTRUE) ; if (!tableSet) { coutE(Plotting) << "RooTreeData::table(" << GetName() << ") Couldn't deep-clone table category, abort." << endl ; return 0 ; } tableVar = (RooAbsCategory*) tableSet->find(cat.GetName()) ; ownPlotVar = kTRUE ; //Redirect servers of derived clone to internal ArgSet representing the data in this set tableVar->recursiveRedirectServers(_vars) ; } TString tableName(GetName()) ; if (cuts && strlen(cuts)) { tableName.Append("(") ; tableName.Append(cuts) ; tableName.Append(")") ; } Roo1DTable* table2 = tableVar->createTable(tableName) ; // Make cut selector if cut is specified RooFormulaVar* cutVar = 0; if (cuts && strlen(cuts)) { cutVar = new RooFormulaVar("cutVar",cuts,_vars) ; } // Dump contents Int_t nevent= numEntries() ; for(Int_t i=0; i < nevent; ++i) { get(i); if (cutVar && cutVar->getVal()==0) continue ; table2->fill(*tableVar,weight()) ; } if (ownPlotVar) delete tableSet ; if (cutVar) delete cutVar ; return table2 ; } //////////////////////////////////////////////////////////////////////////////// /// Fill Doubles 'lowest' and 'highest' with the lowest and highest value of /// observable 'var' in this dataset. If the return value is kTRUE and error /// occurred Bool_t RooAbsData::getRange(const RooAbsRealLValue& var, Double_t& lowest, Double_t& highest, Double_t marginFrac, Bool_t symMode) const { // Lookup variable in dataset const auto arg = _vars.find(var.GetName()); if (!arg) { coutE(InputArguments) << "RooDataSet::getRange(" << GetName() << ") ERROR: unknown variable: " << var.GetName() << endl ; return kTRUE; } auto varPtr = dynamic_cast<const RooRealVar*>(arg); // Check if found variable is of type RooRealVar if (!varPtr) { coutE(InputArguments) << "RooDataSet::getRange(" << GetName() << ") ERROR: variable " << var.GetName() << " is not of type RooRealVar" << endl ; return kTRUE; } // Check if dataset is not empty if(sumEntries() == 0.) { coutE(InputArguments) << "RooDataSet::getRange(" << GetName() << ") WARNING: empty dataset" << endl ; return kTRUE; } // Look for highest and lowest value lowest = RooNumber::infinity() ; highest = -RooNumber::infinity() ; for (Int_t i=0 ; i<numEntries() ; i++) { get(i) ; if (varPtr->getVal()<lowest) { lowest = varPtr->getVal() ; } if (varPtr->getVal()>highest) { highest = varPtr->getVal() ; } } if (marginFrac>0) { if (symMode==kFALSE) { Double_t margin = marginFrac*(highest-lowest) ; lowest -= margin ; highest += margin ; if (lowest<var.getMin()) lowest = var.getMin() ; if (highest>var.getMax()) highest = var.getMax() ; } else { Double_t mom1 = moment(*varPtr,1) ; Double_t delta = ((highest-mom1)>(mom1-lowest)?(highest-mom1):(mom1-lowest))*(1+marginFrac) ; lowest = mom1-delta ; highest = mom1+delta ; if (lowest<var.getMin()) lowest = var.getMin() ; if (highest>var.getMax()) highest = var.getMax() ; } } return kFALSE ; } //////////////////////////////////////////////////////////////////////////////// /// Prepare dataset for use with cached constant terms listed in /// 'cacheList' of expression 'arg'. Deactivate tree branches /// for any dataset observable that is either not used at all, /// or is used exclusively by cached branch nodes. void RooAbsData::optimizeReadingWithCaching(RooAbsArg& arg, const RooArgSet& cacheList, const RooArgSet& keepObsList) { RooArgSet pruneSet ; // Add unused observables in this dataset to pruneSet pruneSet.add(*get()) ; RooArgSet* usedObs = arg.getObservables(*this) ; pruneSet.remove(*usedObs,kTRUE,kTRUE) ; // Add observables exclusively used to calculate cached observables to pruneSet TIterator* vIter = get()->createIterator() ; RooAbsArg *var ; while ((var=(RooAbsArg*) vIter->Next())) { if (allClientsCached(var,cacheList)) { pruneSet.add(*var) ; } } delete vIter ; if (pruneSet.getSize()!=0) { // Go over all used observables and check if any of them have parameterized // ranges in terms of pruned observables. If so, remove those observable // from the pruning list TIterator* uIter = usedObs->createIterator() ; RooAbsArg* obs ; while((obs=(RooAbsArg*)uIter->Next())) { RooRealVar* rrv = dynamic_cast<RooRealVar*>(obs) ; if (rrv && !rrv->getBinning().isShareable()) { RooArgSet depObs ; RooAbsReal* loFunc = rrv->getBinning().lowBoundFunc() ; RooAbsReal* hiFunc = rrv->getBinning().highBoundFunc() ; if (loFunc) { loFunc->leafNodeServerList(&depObs,0,kTRUE) ; } if (hiFunc) { hiFunc->leafNodeServerList(&depObs,0,kTRUE) ; } if (depObs.getSize()>0) { pruneSet.remove(depObs,kTRUE,kTRUE) ; } } } delete uIter ; } // Remove all observables in keep list from prune list pruneSet.remove(keepObsList,kTRUE,kTRUE) ; if (pruneSet.getSize()!=0) { // Deactivate tree branches here cxcoutI(Optimization) << "RooTreeData::optimizeReadingForTestStatistic(" << GetName() << "): Observables " << pruneSet << " in dataset are either not used at all, orserving exclusively p.d.f nodes that are now cached, disabling reading of these observables for TTree" << endl ; setArgStatus(pruneSet,kFALSE) ; } delete usedObs ; } //////////////////////////////////////////////////////////////////////////////// /// Utility function that determines if all clients of object 'var' /// appear in given list of cached nodes. Bool_t RooAbsData::allClientsCached(RooAbsArg* var, const RooArgSet& cacheList) { Bool_t ret(kTRUE), anyClient(kFALSE) ; for (const auto client : var->valueClients()) { anyClient = kTRUE ; if (!cacheList.find(client->GetName())) { // If client is not cached recurse ret &= allClientsCached(client,cacheList) ; } } return anyClient?ret:kFALSE ; } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::attachBuffers(const RooArgSet& extObs) { _dstore->attachBuffers(extObs) ; } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::resetBuffers() { _dstore->resetBuffers() ; } //////////////////////////////////////////////////////////////////////////////// Bool_t RooAbsData::canSplitFast() const { if (_ownedComponents.size()>0) { return kTRUE ; } return kFALSE ; } //////////////////////////////////////////////////////////////////////////////// RooAbsData* RooAbsData::getSimData(const char* name) { map<string,RooAbsData*>::iterator i = _ownedComponents.find(name) ; if (i==_ownedComponents.end()) return 0 ; return i->second ; } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::addOwnedComponent(const char* idxlabel, RooAbsData& data) { _ownedComponents[idxlabel]= &data ; } //////////////////////////////////////////////////////////////////////////////// /// Stream an object of class RooAbsData. void RooAbsData::Streamer(TBuffer &R__b) { if (R__b.IsReading()) { R__b.ReadClassBuffer(RooAbsData::Class(),this); // Convert on the fly to vector storage if that the current working default if (defaultStorageType==RooAbsData::Vector) { convertToVectorStore() ; } } else { R__b.WriteClassBuffer(RooAbsData::Class(),this); } } //////////////////////////////////////////////////////////////////////////////// void RooAbsData::checkInit() const { _dstore->checkInit() ; } //////////////////////////////////////////////////////////////////////////////// /// Forward draw command to data store void RooAbsData::Draw(Option_t* option) { if (_dstore) _dstore->Draw(option) ; } //////////////////////////////////////////////////////////////////////////////// Bool_t RooAbsData::hasFilledCache() const { return _dstore->hasFilledCache() ; } //////////////////////////////////////////////////////////////////////////////// /// Return a pointer to the TTree which stores the data. Returns a nullpointer /// if vector-based storage is used. The RooAbsData remains owner of the tree. /// GetClonedTree() can be used to get a tree even if the internal storage does not use one. const TTree *RooAbsData::tree() const { if (storageType == RooAbsData::Tree) { return _dstore->tree(); } else { coutW(InputArguments) << "RooAbsData::tree(" << GetName() << ") WARNING: is not of StorageType::Tree. " << "Use GetClonedTree() instead or convert to tree storage." << endl; return (TTree *)nullptr; } } //////////////////////////////////////////////////////////////////////////////// /// Return a clone of the TTree which stores the data or create such a tree /// if vector storage is used. The user is responsible for deleting the tree TTree *RooAbsData::GetClonedTree() const { if (storageType == RooAbsData::Tree) { auto tmp = const_cast<TTree *>(_dstore->tree()); return tmp->CloneTree(); } else { RooTreeDataStore buffer(GetName(), GetTitle(), *get(), *_dstore); return buffer.tree().CloneTree(); } } //////////////////////////////////////////////////////////////////////////////// /// Convert vector-based storage to tree-based storage void RooAbsData::convertToTreeStore() { if (storageType != RooAbsData::Tree) { RooTreeDataStore *newStore = new RooTreeDataStore(GetName(), GetTitle(), _vars, *_dstore); delete _dstore; _dstore = newStore; storageType = RooAbsData::Tree; } } //////////////////////////////////////////////////////////////////////////////// /// If one of the TObject we have a referenced to is deleted, remove the /// reference. void RooAbsData::RecursiveRemove(TObject *obj) { for(auto &iter : _ownedComponents) { if (iter.second == obj) { iter.second = nullptr; } } }
#pragma once #include "spinner/misc.hpp" #include "spinner/resmgr.hpp" #include "spinner/dir.hpp" #ifdef WIN32 #include <intrin.h> #include <windows.h> #endif #include <SDL.h> #include <SDL_atomic.h> #include <SDL_thread.h> #include <SDL_events.h> #include <SDL_image.h> #include <exception> #include <stdexcept> #include "spinner/error.hpp" #include "spinner/size.hpp" #include <boost/serialization/access.hpp> #include <boost/variant.hpp> #include "spinner/ziptree.hpp" #include "handle.hpp" #include "sdlformat.hpp" #define SDLEC_Base(flag, act, ...) ::spn::EChk_memory##flag<::spn::none_t>(AAct_##act<std::runtime_error>(), ::rs::SDLError(), SOURCEPOS, __VA_ARGS__) #define SDLEC_Base0(flag, act) ::spn::EChk##flag(AAct_##act<std::runtime_error>(), ::rs::SDLError(), SOURCEPOS); #define SDLEC(...) SDLEC_Base(_a, __VA_ARGS__) #define SDLEC_Chk(act) SDLEC_Base0(_a, act) #define SDLEC_D(...) SDLEC_Base(_d, __VA_ARGS__) #define SDLEC_Chk_D(act) SDLEC_Base0(_d, act) #define IMGEC_Base(flag, act, ...) ::spn::EChk_memory##flag<::spn::none_t>(AAct_##act<std::runtime_error>(), ::rs::IMGError(), SOURCEPOS, __VA_ARGS__) #define IMGEC_Base0(flag, act) ::spn::EChk##flag(AAct_##act<std::runtime_error>(), ::rs::IMGError(), SOURCEPOS) #define IMGEC(act, ...) IMGEC_Base(_a, act, __VA_ARGS__) #define IMGEC_Chk(act) IMGEC_Base0(_a, act) #define IMGEC_D(act, ...) IMGEC_Base(_d, act, __VA_ARGS__) #define IMGEC_Chk_D(act) IMGEC_Base0(_d, act) namespace rs { //! RAII形式でSDLの初期化 (for spn::MInitializer) struct SDLInitializer { SDLInitializer(uint32_t flag); ~SDLInitializer(); }; struct IMGInitializer { IMGInitializer(uint32_t flag); ~IMGInitializer(); }; struct SDLErrorI { static const char* Get(); static void Reset(); static const char *const c_apiName; }; struct IMGErrorI { static const char* Get(); static void Reset(); static const char *const c_apiName; }; template <class I> struct ErrorT { std::string _errMsg; const char* errorDesc() { const char* err = I::Get(); if(*err != '\0') { _errMsg = err; I::Reset(); return _errMsg.c_str(); } return nullptr; } void reset() const { I::Reset(); } const char* getAPIName() const { return I::c_apiName; } }; using SDLError = ErrorT<SDLErrorI>; using IMGError = ErrorT<IMGErrorI>; template <class T> class TLS; extern TLS<SDL_threadID> tls_threadID; extern TLS<std::string> tls_threadName; //! 実行環境に関する情報を取得 class Spec : public spn::Singleton<Spec> { public: enum Feature : uint32_t { F_3DNow = 0x01, F_AltiVec = 0x02, F_MMX = 0x04, F_RDTSC = 0x08, F_SSE = 0x10, F_SSE2 = 0x11, F_SSE3 = 0x12, F_SSE41 = 0x14, F_SSE42 = 0x18 }; enum class PStatN { Unknown, OnBattery, NoBattery, Charging, Charged }; struct PStat { PStatN state; int seconds, percentage; void output(std::ostream& os) const; }; private: uint32_t _feature; std::string _platform; int _nCacheLine, _nCpu; public: Spec(); const std::string& getPlatform() const; int cpuCacheLineSize() const; int cpuCount() const; bool hasFuture(uint32_t flag) const; PStat powerStatus() const; }; //! SDLのMutexラッパ class Mutex { SDL_mutex* _mutex; public: Mutex(); Mutex(Mutex&& m); Mutex(const Mutex&) = delete; Mutex& operator = (const Mutex&) = delete; ~Mutex(); bool lock(); bool try_lock(); void unlock(); SDL_mutex* getMutex(); }; class UniLock { Mutex* _mutex; bool _bLocked; public: static struct DeferLock_t {} DeferLock; static struct AdoptLock_t {} AdoptLock; static struct TryLock_t {} TryLock; UniLock() = delete; UniLock(const UniLock&) = delete; void operator = (const UniLock& u) = delete; UniLock(Mutex& m, DeferLock_t); UniLock(Mutex& m, AdoptLock_t); UniLock(Mutex& m, TryLock_t); UniLock(Mutex& m); ~UniLock(); UniLock(UniLock&& u); void lock(); void unlock(); bool tryLock(); bool isLocked() const; explicit operator bool () const; SDL_mutex* getMutex(); }; class CondV { SDL_cond* _cond; public: CondV(); ~CondV(); void wait(UniLock& u); bool wait_for(UniLock& u, uint32_t msec); void signal(); void signal_all(); }; //! thread local storage (with SDL) template <class T> class TLS { SDL_TLSID _tlsID; static void Dtor(void* p) { delete reinterpret_cast<T*>(p); } T* _getPtr() { return reinterpret_cast<T*>(SDL_TLSGet(_tlsID)); } const T* _getPtr() const { return reinterpret_cast<const T*>(SDL_TLSGet(_tlsID)); } public: TLS() { _tlsID = SDLEC_D(Trap, SDL_TLSCreate); } template <class... Args> TLS(Args&&... args): TLS() { *this = T(std::forward<Args>(args)...); } template <class TA> TLS& operator = (TA&& t) { T* p = _getPtr(); if(!p) SDL_TLSSet(_tlsID, new T(std::forward<TA>(t)), Dtor); else *p = std::forward<TA>(t); return *this; } bool valid() const { return _getPtr(); } T& operator * () { return *_getPtr(); } const T& operator * () const { return *_getPtr(); } T& get() { return this->operator*(); } const T& get() const { return this->operator*(); } explicit operator bool() const { return _getPtr() != nullptr; } bool initialized() const { return _getPtr() != nullptr; } void terminate() { SDL_TLSSet(_tlsID, nullptr, nullptr); } }; namespace detail { struct CallUnlockR { template <class T> void operator()(T& t) const { return t._unlockR(); } }; struct CallUnlock { template <class T> void operator()(T& t) const { return t._unlock(); } }; template <class SP, class T, class UnlockT> class SpinInner { private: SP& _src; T* _data; public: SpinInner(const SpinInner&) = delete; SpinInner& operator = (const SpinInner&) = delete; SpinInner(SpinInner&& n): _src(n._src), _data(n._data) { n._data = nullptr; } SpinInner(SP& src, T* data): _src(src), _data(data) {} ~SpinInner() { unlock(); } T& operator * () { return *_data; } T* operator -> () { return _data; } bool valid() const { return _data != nullptr; } explicit operator bool () const { return valid(); } void unlock() { if(_data) { UnlockT()(_src); _data = nullptr; } } template <class T2> auto castAndMove() { SpinInner<SP, T2, UnlockT> ret(_src, reinterpret_cast<T2*>(_data)); _data = nullptr; return ret; } template <class T2> auto castAndMoveDeRef() { SpinInner<SP, T2, UnlockT> ret(_src, reinterpret_cast<T2*>(*_data)); _data = nullptr; return ret; } }; } //! 再帰対応のスピンロック template <class T> class SpinLock { using Inner = detail::SpinInner<SpinLock<T>, T, detail::CallUnlock>; using CInner = detail::SpinInner<SpinLock<T>, const T, detail::CallUnlock>; friend struct detail::CallUnlock; SDL_atomic_t _atmLock, _atmCount; void _unlock() { if(SDL_AtomicDecRef(&_atmCount) == SDL_TRUE) SDL_AtomicSet(&_atmLock, 0); } T _data; template <class I> I _lock(bool bBlock) { do { bool bSuccess = false; if(SDL_AtomicCAS(&_atmLock, 0, *tls_threadID) == SDL_TRUE) bSuccess = true; else if(SDL_AtomicGet(&_atmLock) == static_cast<decltype(SDL_AtomicGet(&_atmLock))>(*tls_threadID)) { // 同じスレッドからのロック bSuccess = true; } if(bSuccess) { // ロック成功 SDL_AtomicAdd(&_atmCount, 1); return I(*this, &_data); } } while(bBlock); return I(*this, nullptr); } public: SpinLock() { SDL_AtomicSet(&_atmLock, 0); SDL_AtomicSet(&_atmCount, 0); } Inner lock() { return _lock<Inner>(true); } CInner lockC() const { return const_cast<SpinLock*>(this)->_lock<CInner>(true); } Inner try_lock() { return _lock<Inner>(false); } CInner try_lockC() const { return const_cast<SpinLock*>(this)->_lock<CInner>(false); } }; template <class T> class SpinLockP { struct InnerP { SpinLockP& _s; bool _bLocked; InnerP(InnerP&& p): _s(p._s), _bLocked(p._bLocked) { p._bLocked = false; } InnerP(SpinLockP& s): _s(s) { _bLocked = _s._put(); } ~InnerP() { if(_bLocked) _s._put_reset(); } }; using Inner = detail::SpinInner<SpinLockP<T>, T, detail::CallUnlock>; using CInner = detail::SpinInner<SpinLockP<T>, const T, detail::CallUnlock>; friend struct detail::CallUnlock; TLS<int> _tlsCount; SDL_threadID _lockID; int _lockCount; Mutex _mutex; T _data; void _unlock() { AssertP(Trap, _lockID == *tls_threadID) AssertP(Trap, _lockCount >= 1) if(--_lockCount == 0) _lockID = 0; _mutex.unlock(); } template <class I> I _lock(bool bBlock) { if(bBlock) _mutex.lock(); if(bBlock || _mutex.try_lock()) { if(_lockID == 0) { _lockCount = 1; _lockID = *tls_threadID; } else { AssertP(Trap, _lockID == *tls_threadID) ++_lockCount; } return I(*this, &_data); } return I(*this, nullptr); } void _put_reset() { _mutex.lock(); _lockID = *tls_threadID; _lockCount = _tlsCount.get()-1; *_tlsCount = -1; int tmp = _lockCount; while(--tmp != 0) _mutex.lock(); } bool _put() { // 自スレッドがロックしてたらカウンタを退避して一旦解放 if(_mutex.try_lock()) { if(_lockCount > 0) { ++_lockCount; *_tlsCount = _lockCount; int tmp = _lockCount; _lockCount = 0; _lockID = 0; while(tmp-- != 0) _mutex.unlock(); return true; } _mutex.unlock(); } return false; } public: SpinLockP(): _lockID(0), _lockCount(0) { _tlsCount = -1; } Inner lock() { return _lock<Inner>(true); } CInner lockC() const { return const_cast<SpinLockP*>(this)->_lock<CInner>(true); } Inner try_lock() { return _lock<Inner>(false); } CInner try_lockC() const { return const_cast<SpinLockP*>(this)->_lock<CInner>(false); } InnerP put() { return InnerP(*this); } }; // SIG = スレッドに関するシグニチャ template <class DER, class RET, class... Args> class _Thread { using This = _Thread<DER, RET, Args...>; SDL_atomic_t _atmInt; SDL_Thread* _thread; using Holder = spn::ArgHolder<Args...>; using OPHolder = spn::Optional<Holder>; OPHolder _holder; enum Stat { Idle, //!< スレッド開始前 Running, //!< スレッド実行中 Interrupted, //!< 中断要求がされたが、まだスレッドが終了していない Interrupted_End,//!< 中断要求によりスレッドが終了した Error_End, //!< 例外による異常終了 Finished //!< 正常終了 }; SDL_atomic_t _atmStat; SDL_cond *_condC, //!< 子スレッドが開始された事を示す *_condP; //!< 親スレッドがクラス変数にスレッドポインタを格納した事を示す Mutex _mtxC, _mtxP; std::string _name; static int ThreadFunc(void* p) { DER* ths = reinterpret_cast<DER*>(p); ths->_mtxC.lock(); ths->_mtxP.lock(); SDL_CondBroadcast(ths->_condC); ths->_mtxC.unlock(); // 親スレッドが子スレッド変数をセットするまで待つ SDL_CondWait(ths->_condP, ths->_mtxP.getMutex()); ths->_mtxP.unlock(); // この時点でスレッドのポインタは有効な筈 tls_threadID = SDL_GetThreadID(ths->_thread); tls_threadName = ths->_name; Stat stat; try { ths->_holder->inorder([ths](Args&&... args){ ths->runIt(std::forward<Args>(args)...); }); stat = (ths->isInterrupted()) ? Interrupted_End : Finished; } catch(...) { Assert(Warn, false, "thread is finished unexpectedly") #ifdef NO_EXCEPTION_PTR ths->_bException = true; #else ths->_eptr = std::current_exception(); #endif stat = Error_End; } SDL_AtomicSet(&ths->_atmStat, stat); SDL_CondBroadcast(ths->_condP); // SDLの戻り値は使わない return 0; } //! move-ctorの後に値を掃除する void _clean() { _thread = nullptr; _holder = spn::none; _condC = _condP = nullptr; } protected: #ifdef NO_EXCEPTION_PTR bool _bException = false; #else std::exception_ptr _eptr = nullptr; #endif virtual RET run(Args...) = 0; public: _Thread(_Thread&& th): _atmInt(std::move(th._atmInt)), _thread(th._thread), _holder(std::move(th._holder)), _atmStat(std::move(th._atmStat)), _condC(th._condC), _condP(th._condP), _mtxC(std::move(th._mtxC)), _mtxP(std::move(th._mtxP)), _name(std::move(th._name)) { th._clean(); } _Thread(const _Thread& t) = delete; _Thread& operator = (const _Thread& t) = delete; _Thread(const std::string& name): _thread(nullptr), _name(name) { _condC = SDL_CreateCond(); _condP = SDL_CreateCond(); // 中断フラグに0をセット SDL_AtomicSet(&_atmInt, 0); SDL_AtomicSet(&_atmStat, Idle); } ~_Thread() { if(_thread) { // スレッド実行中だったらエラーを出す Assert(Trap, !isRunning()) SDL_DestroyCond(_condC); SDL_DestroyCond(_condP); } } template <class... Args0> void start(Args0&&... args0) { _holder = Holder(std::forward<Args0>(args0)...); // 2回以上呼ぶとエラー Assert(Trap, SDL_AtomicGet(&_atmStat) == Idle) SDL_AtomicSet(&_atmStat, Running); _mtxC.lock(); // 一旦クラス内部に変数を参照で取っておく SDL_Thread* th = SDL_CreateThread(ThreadFunc, _name.c_str(), this); // 子スレッドが開始されるまで待つ SDL_CondWait(_condC, _mtxC.getMutex()); _mtxC.unlock(); _mtxP.lock(); _thread = th; SDL_CondBroadcast(_condP); _mtxP.unlock(); } Stat getStatus() { return static_cast<Stat>(SDL_AtomicGet(&_atmStat)); } bool isRunning() { Stat stat = getStatus(); return stat==Running || stat==Interrupted; } //! 中断を指示する virtual bool interrupt() { auto ret = SDL_AtomicCAS(&_atmStat, Running, Interrupted); SDL_AtomicSet(&_atmInt, 1); return ret == SDL_TRUE; } //! スレッド内部で中断指示がされているかを確認 bool isInterrupted() { return SDL_AtomicGet(&_atmInt) == 1; } void join() { Assert(Trap, getStatus() != Stat::Idle) _mtxP.lock(); if(_thread) { _mtxP.unlock(); SDL_WaitThread(_thread, nullptr); _thread = nullptr; SDL_DestroyCond(_condP); SDL_DestroyCond(_condC); _condP = _condC = nullptr; } else _mtxP.unlock(); } bool try_join(uint32_t ms) { Assert(Trap, getStatus() != Stat::Idle) _mtxP.lock(); if(_thread) { int res = SDL_CondWaitTimeout(_condP, _mtxP.getMutex(), ms); _mtxP.unlock(); SDLEC_Chk(Trap) if(res == 0 || !isRunning()) { SDL_WaitThread(_thread, nullptr); _thread = nullptr; return true; } return false; } _mtxP.unlock(); return true; } void getResult() { // まだスレッドが終了して無い時の為にjoinを呼ぶ join(); rethrowIfException(); } void rethrowIfException() { #ifdef NO_EXCEPTION_PTR if(_bException) throw std::runtime_error("exception catched in thread"); #else if(_eptr) std::rethrow_exception(_eptr); #endif } const std::string& getName() const { return _name; } }; template <class SIG> class Thread; template <class RET, class... Args> class Thread<RET (Args...)> : public _Thread<Thread<RET (Args...)>, RET, Args...> { using base_type = _Thread<Thread<RET (Args...)>, RET, Args...>; spn::Optional<RET> _retVal; protected: virtual RET run(Args...) = 0; public: using base_type::base_type; void runIt(Args... args) { _retVal = run(std::forward<Args>(args)...); } RET&& getResult() { // まだスレッドが終了して無い時の為にjoinを呼ぶ base_type::join(); base_type::rethrowIfException(); return std::move(*_retVal); } }; template <class... Args> class Thread<void (Args...)> : public _Thread<Thread<void (Args...)>, void, Args...> { using base_type = _Thread<Thread<void (Args...)>, void, Args...>; protected: virtual void run(Args...) = 0; public: using base_type::base_type; void runIt(Args... args) { run(std::forward<Args>(args)...); } void getResult() { // まだスレッドが終了して無い時の為にjoinを呼ぶ base_type::join(); base_type::rethrowIfException(); } }; class Window; using SPWindow = std::shared_ptr<Window>; class Window { public: enum class Stat { Minimized, Maximized, Hidden, Fullscreen, Shown }; //! OpenGL初期化パラメータ struct GLParam { int verMajor, verMinor; //!< OpenGLバージョン(メジャー & マイナー) int red, green, blue, depth; //!< 色深度(RGB + Depth) int doublebuffer; //!< ダブルバッファフラグ GLParam(); void setStdAttributes() const; void getStdAttributes(); }; //! Window初期化パラメータ struct Param { std::string title; //!< ウィンドウタイトル int posx, posy, //!< ウィンドウ位置 width, height; //!< ウィンドウサイズ uint32_t flag; //!< その他のフラグ Param(); }; private: SDL_Window* _window; Stat _stat; Window(SDL_Window* w); void _checkState(); public: static void SetGLAttributes() {} // SDL_GLパラメータ設定(可変引数バージョン) template <class... Ts> static void SetGLAttributes(SDL_GLattr attr, int value, Ts... ts) { SDL_GL_SetAttribute(attr, value); SetGLAttributes(ts...); } static void GetGLAttributes() {} // SDL_GLパラメータ取得(可変引数バージョン) template <class... Ts> static void GetGLAttributes(SDL_GLattr attr, int& dst, Ts&&... ts) { SDL_GL_GetAttribute(attr, &dst); GetGLAttributes(std::forward<Ts>(ts)...); } static SPWindow Create(const Param& p); static SPWindow Create(const std::string& title, int w, int h, uint32_t flag=0); static SPWindow Create(const std::string& title, int x, int y, int w, int h, uint32_t flag=0); ~Window(); void setFullscreen(bool bFull); void setGrab(bool bGrab); void setMaximumSize(int w, int h); void setMinimumSize(int w, int h); void setSize(int w, int h); void setTitle(const std::string& title); void show(bool bShow); void maximize(); void minimize(); void restore(); void setPosition(int x, int y); void raise(); // for logging uint32_t getID() const; Stat getState() const; bool isGrabbed() const; bool isResizable() const; bool hasInputFocus() const; bool hasMouseFocus() const; spn::Size getSize() const; spn::Size getMaximumSize() const; spn::Size getMinimumSize() const; uint32_t getSDLFlag() const; SDL_Window* getWindow() const; static void EnableScreenSaver(bool bEnable); }; class GLContext; using SPGLContext = std::shared_ptr<GLContext>; class GLContext { //! makeCurrentした時に指定したウィンドウ SPWindow _spWindow; SDL_GLContext _ctx; GLContext(const SPWindow& w); public: static SPGLContext CreateContext(const SPWindow& w, bool bShare=false); ~GLContext(); void makeCurrent(const SPWindow& w); void makeCurrent(); void swapWindow(); static int SetSwapInterval(int n); }; class RWops { public: struct Callback : boost::serialization::traits<Callback, boost::serialization::object_serializable, boost::serialization::track_never> { virtual void onRelease(RWops& rw) = 0; template <class Archive> void serialize(Archive&, const unsigned int) {} }; enum Hence : int { Begin = RW_SEEK_SET, Current = RW_SEEK_CUR, End = RW_SEEK_END }; // 管轄外メモリであってもシリアライズ時にはデータ保存する enum Type { ConstMem, //!< 外部Constメモリ (管轄外) Mem, //!< 外部メモリ (管轄外) ConstVector, //!< 管轄Constメモリ Vector, //!< 管轄メモリ File }; enum Access : int { Read = 0x01, Write = 0x02, Binary = 0x04 }; //! 外部バッファ struct ExtBuff { void* ptr; size_t size; template <class Archive> void serialize(Archive& /*ar*/, const unsigned int /*ver*/) { AssertP(Trap, false, "this object cannot serialize") } }; //! RWopsエラー基底 struct RWE_Error : std::runtime_error { const std::string _title; RWE_Error(const std::string& title); void setMessage(const std::string& msg); }; //! ファイル開けないエラー struct RWE_File : RWE_Error { const std::string _path; RWE_File(const std::string& path); }; //! 範囲外アクセス struct RWE_OutOfRange : RWE_Error { const Hence _hence; const int64_t _pos, _size; RWE_OutOfRange(int64_t pos, Hence hence, int64_t size); }; //! アクセス権限違反(読み取り専用ファイルに書き込みなど) struct RWE_Permission : RWE_Error { const Access _have, _try; RWE_Permission(Access have, Access tr); }; //! メモリ確保エラー struct RWE_Memory : RWE_Error { const size_t _size; RWE_Memory(size_t size); }; //! ぬるぽ指定 struct RWE_NullMemory : RWE_Error { RWE_NullMemory(); }; private: using Data = boost::variant<boost::blank, std::string, spn::URI, ExtBuff, spn::ByteBuff>; SDL_RWops* _ops; int _access; Type _type; Data _data; //! RWopsが解放される直前に呼ばれる関数 using UPCallback = std::unique_ptr<Callback>; UPCallback _endCB; void _deserializeFromMember(); void _clear(); friend class boost::serialization::access; BOOST_SERIALIZATION_SPLIT_MEMBER(); template <class Archive> void save(Archive& ar, const unsigned int) const { ar & _access; if(isMemory()) { Type type; if(_type == Type::ConstMem || _type == Type::ConstVector) type = Type::ConstVector; else type = Type::Vector; ar & type; auto dat = getMemoryPtrC(); spn::ByteBuff buff(dat.second); std::memcpy(&buff[0], dat.first, dat.second); Data data(std::move(buff)); ar & data; } else ar & _type & _data; int64_t pos = tell(); ar & pos & _endCB; } template <class Archive> void load(Archive& ar, const unsigned int) { int64_t pos; ar & _access & _type & _data & pos & _endCB; _deserializeFromType(pos); } void _deserializeFromType(int64_t pos); friend spn::ResWrap<RWops, spn::String<std::string>>; RWops() = default; template <class T> RWops(SDL_RWops* ops, Type type, int access, T&& data, Callback* cb=nullptr) { AssertT(Trap, ops, (RWE_Error)(const char*), "unknown error") _ops = ops; _type = type; _access = access; _data = std::forward<T>(data); _endCB.reset(cb); } static RWops _FromVector(spn::ByteBuff&& buff, Callback* cb, std::false_type); static RWops _FromVector(spn::ByteBuff&& buff, Callback* cb, std::true_type); public: static int ReadMode(const char* mode); static std::string ReadModeStr(int mode); static RWops FromConstMem(const void* mem, size_t size, Callback* cb=nullptr); template <class T> static RWops FromVector(T&& buff, Callback* cb=nullptr) { spn::ByteBuff tbuff(std::forward<T>(buff)); return _FromVector(std::move(tbuff), cb, typename std::is_const<T>::type()); } static RWops FromMem(void* mem, size_t size, Callback* cb=nullptr); static RWops FromFile(const std::string& path, int access); static RWops FromURI(SDL_RWops* ops, const spn::URI& uri, int access); RWops(RWops&& ops); RWops& operator = (RWops&& ops); ~RWops(); void close(); int getAccessFlag() const; size_t read(void* dst, size_t blockSize, size_t nblock); size_t write(const void* src, size_t blockSize, size_t nblock); int64_t size(); int64_t seek(int64_t offset, Hence hence); int64_t tell() const; uint16_t readBE16(); uint32_t readBE32(); uint64_t readBE64(); uint16_t readLE16(); uint32_t readLE32(); uint64_t readLE64(); bool writeBE(uint16_t value); bool writeBE(uint32_t value); bool writeBE(uint64_t value); bool writeLE(uint16_t value); bool writeLE(uint32_t value); bool writeLE(uint64_t value); SDL_RWops* getOps(); spn::ByteBuff readAll(); Type getType() const; bool isMemory() const; //! isMemory()==trueの時だけ有効 std::pair<const void*, size_t> getMemoryPtrC() const; //! Type::Vector時のみ有効 std::pair<void*, size_t> getMemoryPtr(); }; struct UriHandler : spn::IURIOpener { virtual HLRW openURI_RW(const spn::URI& uri, int access) = 0; }; using SPUriHandler = std::shared_ptr<UriHandler>; #define mgr_rw (::rs::RWMgr::_ref()) class RWMgr : public spn::ResMgrA<RWops, RWMgr> { struct HChk { HLRW operator()(UriHandler& h, const spn::URI& uri, int access) const; }; using UriHandlerV = spn::HandlerV<UriHandler, HChk>; UriHandlerV _handlerV; std::string _orgName, _appName; //! 一時ファイルディレクトリのファイルを全て削除 void _cleanupTemporaryFile(); public: RWMgr(const std::string& org_name, const std::string& app_name); UriHandlerV& getHandler(); using base_type = spn::ResMgrA<RWops, RWMgr>; using LHdl = AnotherLHandle<RWops, true>; // ---- RWopsへ中継するだけの関数 ---- //! 任意のURIからハンドル作成(ReadOnly) LHdl fromURI(const spn::URI& uri, int access); LHdl fromFile(const std::string& path, int access); template <class T> LHdl fromVector(T&& t) { return base_type::acquire(RWops::FromVector(std::forward<T>(t))); } LHdl fromConstMem(const void* p, int size, typename RWops::Callback* cb=nullptr); LHdl fromMem(void* p, int size, typename RWops::Callback* cb=nullptr); //! ランダムな名前の一時ファイルを作ってそのハンドルとファイルパスを返す std::pair<LHdl, std::string> createTemporaryFile(); //! OrgNameとAppNameからなるプライベートなディレクトリパス std::string makeFilePath(const std::string& dirName) const; }; //! ファイルシステムに置かれたZipからのファイル読み込み class UriH_PackedZip : public UriHandler { spn::UP_Adapt _stream; spn::zip::ZipTree _ztree; static bool Capable(const spn::URI& uri); public: UriH_PackedZip(spn::ToPathStr zippath); // --- from UriHandler --- HLRW openURI_RW(const spn::URI& uri, int access) override; // --- from IURIOpener --- spn::UP_Adapt openURI(const spn::URI& uri) override; }; //! アセットZipからのファイル読み込み (Android only) class UriH_AssetZip : public UriH_PackedZip { public: // Asset中のZipファイルのパスを指定 UriH_AssetZip(spn::ToPathStr zippath); }; //! ファイルシステムからのファイル読み込み class UriH_File : public UriHandler { spn::PathStr _basePath; public: UriH_File(spn::ToPathStr path); static bool Capable(const spn::URI& uri, int access); // --- from UriHandler --- HLRW openURI_RW(const spn::URI& uri, int access) override; // --- from IURIOpener --- spn::UP_Adapt openURI(const spn::URI& uri) override; }; struct RGB { union { uint8_t ar[3]; struct { uint8_t r,g,b; }; }; RGB() = default; RGB(int r, int g, int b): ar{uint8_t(r), uint8_t(g), uint8_t(b)} {} }; struct RGBA { union { uint8_t ar[4]; struct { uint8_t r,g,b,a; }; }; RGBA() = default; RGBA(RGB rgb, int a): ar{rgb.r, rgb.g, rgb.b, static_cast<uint8_t>(a)} {} }; using UPSDLFormat = std::unique_ptr<SDL_PixelFormat, decltype(&SDL_FreeFormat)>; UPSDLFormat MakeUPFormat(uint32_t fmt); class Surface; using SPSurface = std::shared_ptr<Surface>; class Surface { SDL_Surface* _sfc; mutable Mutex _mutex; spn::AB_Byte _buff; class LockObj { const Surface& _sfc; void* _bits; int _pitch; public: LockObj(LockObj&& lk); LockObj(const Surface& sfc, void* bits, int pitch); ~LockObj(); void* getBits(); int getPitch() const; operator bool () const; }; void _unlock() const; Surface(SDL_Surface* sfc); Surface(SDL_Surface* sfc, spn::ByteBuff&& buff); public: static uint32_t Map(uint32_t format, RGB rgb); //! RGBA値をSDLのピクセルフォーマット形式にパックする static uint32_t Map(uint32_t format, RGBA rgba); //! SDLのピクセルフォーマットからRGB値を取り出す static RGBA Get(uint32_t format, uint32_t pixel); //! SDLのピクセルフォーマット名を表す文字列を取得 static const std::string& GetFormatString(uint32_t format); //! 任意のフォーマットの画像を読み込む static SPSurface Load(HRW hRW); //! 空のサーフェス作成 static SPSurface Create(int w, int h, uint32_t format); //! ピクセルデータを元にサーフェス作成 static SPSurface Create(const spn::ByteBuff& src, int pitch, int w, int h, uint32_t format); static SPSurface Create(spn::ByteBuff&& src, int pitch, int w, int h, uint32_t format); ~Surface(); void saveAsBMP(HRW hDst) const; void saveAsPNG(HRW hDst) const; LockObj lock() const; LockObj try_lock() const; const SDL_PixelFormat& getFormat() const; uint32_t getFormatEnum() const; spn::Size getSize() const; int width() const; int height() const; //! 同サイズのサーフェスを作成 SPSurface makeBlank() const; SPSurface duplicate() const; SPSurface flipHorizontal() const; SPSurface flipVertical() const; //! ピクセルフォーマット変換 SPSurface convert(uint32_t fmt) const; SPSurface convert(const SDL_PixelFormat& fmt) const; //! ピクセルデータがデータ配列先頭から隙間なく詰められているか bool isContinuous() const; //! Continuousな状態でピクセルデータを抽出 spn::ByteBuff extractAsContinuous(uint32_t dstFmt=0) const; //! ビットブロック転送 void blit(const SPSurface& sfc, const spn::Rect& srcRect, int dstX, int dstY) const; //! スケーリング有りのビットブロック転送 void blitScaled(const SPSurface& sfc, const spn::Rect& srcRect, const spn::Rect& dstRect) const; //! 単色での矩形塗りつぶし void fillRect(const spn::Rect& rect, uint32_t color); SDL_Surface* getSurface(); SPSurface resize(const spn::Size& s) const; void setEnableColorKey(uint32_t key); void setDisableColorKey(); spn::Optional<uint32_t> getColorKey() const; void setBlendMode(SDL_BlendMode mode); SDL_BlendMode getBlendMode() const; }; } SpinLockP: 一部変数で無効な値を0としてたのをoptionalに変更 #pragma once #include "spinner/misc.hpp" #include "spinner/resmgr.hpp" #include "spinner/dir.hpp" #ifdef WIN32 #include <intrin.h> #include <windows.h> #endif #include <SDL.h> #include <SDL_atomic.h> #include <SDL_thread.h> #include <SDL_events.h> #include <SDL_image.h> #include <exception> #include <stdexcept> #include "spinner/error.hpp" #include "spinner/size.hpp" #include <boost/serialization/access.hpp> #include <boost/variant.hpp> #include "spinner/ziptree.hpp" #include "handle.hpp" #include "sdlformat.hpp" #define SDLEC_Base(flag, act, ...) ::spn::EChk_memory##flag<::spn::none_t>(AAct_##act<std::runtime_error>(), ::rs::SDLError(), SOURCEPOS, __VA_ARGS__) #define SDLEC_Base0(flag, act) ::spn::EChk##flag(AAct_##act<std::runtime_error>(), ::rs::SDLError(), SOURCEPOS); #define SDLEC(...) SDLEC_Base(_a, __VA_ARGS__) #define SDLEC_Chk(act) SDLEC_Base0(_a, act) #define SDLEC_D(...) SDLEC_Base(_d, __VA_ARGS__) #define SDLEC_Chk_D(act) SDLEC_Base0(_d, act) #define IMGEC_Base(flag, act, ...) ::spn::EChk_memory##flag<::spn::none_t>(AAct_##act<std::runtime_error>(), ::rs::IMGError(), SOURCEPOS, __VA_ARGS__) #define IMGEC_Base0(flag, act) ::spn::EChk##flag(AAct_##act<std::runtime_error>(), ::rs::IMGError(), SOURCEPOS) #define IMGEC(act, ...) IMGEC_Base(_a, act, __VA_ARGS__) #define IMGEC_Chk(act) IMGEC_Base0(_a, act) #define IMGEC_D(act, ...) IMGEC_Base(_d, act, __VA_ARGS__) #define IMGEC_Chk_D(act) IMGEC_Base0(_d, act) namespace rs { //! RAII形式でSDLの初期化 (for spn::MInitializer) struct SDLInitializer { SDLInitializer(uint32_t flag); ~SDLInitializer(); }; struct IMGInitializer { IMGInitializer(uint32_t flag); ~IMGInitializer(); }; struct SDLErrorI { static const char* Get(); static void Reset(); static const char *const c_apiName; }; struct IMGErrorI { static const char* Get(); static void Reset(); static const char *const c_apiName; }; template <class I> struct ErrorT { std::string _errMsg; const char* errorDesc() { const char* err = I::Get(); if(*err != '\0') { _errMsg = err; I::Reset(); return _errMsg.c_str(); } return nullptr; } void reset() const { I::Reset(); } const char* getAPIName() const { return I::c_apiName; } }; using SDLError = ErrorT<SDLErrorI>; using IMGError = ErrorT<IMGErrorI>; template <class T> class TLS; extern TLS<SDL_threadID> tls_threadID; extern TLS<std::string> tls_threadName; //! 実行環境に関する情報を取得 class Spec : public spn::Singleton<Spec> { public: enum Feature : uint32_t { F_3DNow = 0x01, F_AltiVec = 0x02, F_MMX = 0x04, F_RDTSC = 0x08, F_SSE = 0x10, F_SSE2 = 0x11, F_SSE3 = 0x12, F_SSE41 = 0x14, F_SSE42 = 0x18 }; enum class PStatN { Unknown, OnBattery, NoBattery, Charging, Charged }; struct PStat { PStatN state; int seconds, percentage; void output(std::ostream& os) const; }; private: uint32_t _feature; std::string _platform; int _nCacheLine, _nCpu; public: Spec(); const std::string& getPlatform() const; int cpuCacheLineSize() const; int cpuCount() const; bool hasFuture(uint32_t flag) const; PStat powerStatus() const; }; //! SDLのMutexラッパ class Mutex { SDL_mutex* _mutex; public: Mutex(); Mutex(Mutex&& m); Mutex(const Mutex&) = delete; Mutex& operator = (const Mutex&) = delete; ~Mutex(); bool lock(); bool try_lock(); void unlock(); SDL_mutex* getMutex(); }; class UniLock { Mutex* _mutex; bool _bLocked; public: static struct DeferLock_t {} DeferLock; static struct AdoptLock_t {} AdoptLock; static struct TryLock_t {} TryLock; UniLock() = delete; UniLock(const UniLock&) = delete; void operator = (const UniLock& u) = delete; UniLock(Mutex& m, DeferLock_t); UniLock(Mutex& m, AdoptLock_t); UniLock(Mutex& m, TryLock_t); UniLock(Mutex& m); ~UniLock(); UniLock(UniLock&& u); void lock(); void unlock(); bool tryLock(); bool isLocked() const; explicit operator bool () const; SDL_mutex* getMutex(); }; class CondV { SDL_cond* _cond; public: CondV(); ~CondV(); void wait(UniLock& u); bool wait_for(UniLock& u, uint32_t msec); void signal(); void signal_all(); }; //! thread local storage (with SDL) template <class T> class TLS { SDL_TLSID _tlsID; static void Dtor(void* p) { delete reinterpret_cast<T*>(p); } T* _getPtr() { return reinterpret_cast<T*>(SDL_TLSGet(_tlsID)); } const T* _getPtr() const { return reinterpret_cast<const T*>(SDL_TLSGet(_tlsID)); } public: TLS() { _tlsID = SDLEC_D(Trap, SDL_TLSCreate); } template <class... Args> TLS(Args&&... args): TLS() { *this = T(std::forward<Args>(args)...); } template <class TA> TLS& operator = (TA&& t) { T* p = _getPtr(); if(!p) SDL_TLSSet(_tlsID, new T(std::forward<TA>(t)), Dtor); else *p = std::forward<TA>(t); return *this; } bool valid() const { return _getPtr(); } T& operator * () { return *_getPtr(); } const T& operator * () const { return *_getPtr(); } T& get() { return this->operator*(); } const T& get() const { return this->operator*(); } explicit operator bool() const { return _getPtr() != nullptr; } bool initialized() const { return _getPtr() != nullptr; } void terminate() { SDL_TLSSet(_tlsID, nullptr, nullptr); } }; namespace detail { struct CallUnlockR { template <class T> void operator()(T& t) const { return t._unlockR(); } }; struct CallUnlock { template <class T> void operator()(T& t) const { return t._unlock(); } }; template <class SP, class T, class UnlockT> class SpinInner { private: SP& _src; T* _data; public: SpinInner(const SpinInner&) = delete; SpinInner& operator = (const SpinInner&) = delete; SpinInner(SpinInner&& n): _src(n._src), _data(n._data) { n._data = nullptr; } SpinInner(SP& src, T* data): _src(src), _data(data) {} ~SpinInner() { unlock(); } T& operator * () { return *_data; } T* operator -> () { return _data; } bool valid() const { return _data != nullptr; } explicit operator bool () const { return valid(); } void unlock() { if(_data) { UnlockT()(_src); _data = nullptr; } } template <class T2> auto castAndMove() { SpinInner<SP, T2, UnlockT> ret(_src, reinterpret_cast<T2*>(_data)); _data = nullptr; return ret; } template <class T2> auto castAndMoveDeRef() { SpinInner<SP, T2, UnlockT> ret(_src, reinterpret_cast<T2*>(*_data)); _data = nullptr; return ret; } }; } //! 再帰対応のスピンロック template <class T> class SpinLock { using Inner = detail::SpinInner<SpinLock<T>, T, detail::CallUnlock>; using CInner = detail::SpinInner<SpinLock<T>, const T, detail::CallUnlock>; friend struct detail::CallUnlock; SDL_atomic_t _atmLock, _atmCount; void _unlock() { if(SDL_AtomicDecRef(&_atmCount) == SDL_TRUE) SDL_AtomicSet(&_atmLock, 0); } T _data; template <class I> I _lock(bool bBlock) { do { bool bSuccess = false; if(SDL_AtomicCAS(&_atmLock, 0, *tls_threadID) == SDL_TRUE) bSuccess = true; else if(SDL_AtomicGet(&_atmLock) == static_cast<decltype(SDL_AtomicGet(&_atmLock))>(*tls_threadID)) { // 同じスレッドからのロック bSuccess = true; } if(bSuccess) { // ロック成功 SDL_AtomicAdd(&_atmCount, 1); return I(*this, &_data); } } while(bBlock); return I(*this, nullptr); } public: SpinLock() { SDL_AtomicSet(&_atmLock, 0); SDL_AtomicSet(&_atmCount, 0); } Inner lock() { return _lock<Inner>(true); } CInner lockC() const { return const_cast<SpinLock*>(this)->_lock<CInner>(true); } Inner try_lock() { return _lock<Inner>(false); } CInner try_lockC() const { return const_cast<SpinLock*>(this)->_lock<CInner>(false); } }; //! 一時的なロック解除機能を備えたSpinLock /*! あるスレッドがロック中でも一旦アンロックし、別のスレッドがロックできるようにする */ template <class T> class SpinLockP { struct InnerP { SpinLockP& _s; bool _bLocked; InnerP(InnerP&& p): _s(p._s), _bLocked(p._bLocked) { p._bLocked = false; } InnerP(SpinLockP& s): _s(s) { _bLocked = _s._put(); } ~InnerP() { if(_bLocked) _s._put_reset(); } }; using Inner = detail::SpinInner<SpinLockP<T>, T, detail::CallUnlock>; using CInner = detail::SpinInner<SpinLockP<T>, const T, detail::CallUnlock>; friend struct detail::CallUnlock; using ThreadID_OP = spn::Optional<SDL_threadID>; TLS<int> _tlsCount; ThreadID_OP _lockID; int _lockCount; Mutex _mutex; T _data; void _unlock() { AssertP(Trap, _lockID && *_lockID == *tls_threadID) AssertP(Trap, _lockCount >= 1) if(--_lockCount == 0) _lockID = spn::none; _mutex.unlock(); } template <class I> I _lock(bool bBlock) { if(bBlock) _mutex.lock(); if(bBlock || _mutex.try_lock()) { if(!_lockID) { _lockCount = 1; _lockID = *tls_threadID; } else { AssertP(Trap, *_lockID == *tls_threadID) ++_lockCount; } return I(*this, &_data); } return I(*this, nullptr); } void _put_reset() { _mutex.lock(); // TLS変数に対比してた回数分、再度MutexのLock関数を呼ぶ _lockID = *tls_threadID; _lockCount = _tlsCount.get()-1; *_tlsCount = -1; int tmp = _lockCount; while(--tmp != 0) _mutex.lock(); } bool _put() { // 自スレッドがロックしてたらカウンタを退避して一旦解放 if(_mutex.try_lock()) { if(_lockCount > 0) { ++_lockCount; *_tlsCount = _lockCount; // ロックしてた回数をTLS変数に退避 int tmp = _lockCount; _lockCount = 0; _lockID = spn::none; // 今までロックしてた回数分、MutexのUnlock回数を呼ぶ while(tmp-- != 0) _mutex.unlock(); return true; } _mutex.unlock(); } return false; } public: SpinLockP(): _lockCount(0) { _tlsCount = -1; } Inner lock() { return _lock<Inner>(true); } CInner lockC() const { return const_cast<SpinLockP*>(this)->_lock<CInner>(true); } Inner try_lock() { return _lock<Inner>(false); } CInner try_lockC() const { return const_cast<SpinLockP*>(this)->_lock<CInner>(false); } InnerP put() { return InnerP(*this); } }; // SIG = スレッドに関するシグニチャ template <class DER, class RET, class... Args> class _Thread { using This = _Thread<DER, RET, Args...>; SDL_atomic_t _atmInt; SDL_Thread* _thread; using Holder = spn::ArgHolder<Args...>; using OPHolder = spn::Optional<Holder>; OPHolder _holder; enum Stat { Idle, //!< スレッド開始前 Running, //!< スレッド実行中 Interrupted, //!< 中断要求がされたが、まだスレッドが終了していない Interrupted_End,//!< 中断要求によりスレッドが終了した Error_End, //!< 例外による異常終了 Finished //!< 正常終了 }; SDL_atomic_t _atmStat; SDL_cond *_condC, //!< 子スレッドが開始された事を示す *_condP; //!< 親スレッドがクラス変数にスレッドポインタを格納した事を示す Mutex _mtxC, _mtxP; std::string _name; static int ThreadFunc(void* p) { DER* ths = reinterpret_cast<DER*>(p); ths->_mtxC.lock(); ths->_mtxP.lock(); SDL_CondBroadcast(ths->_condC); ths->_mtxC.unlock(); // 親スレッドが子スレッド変数をセットするまで待つ SDL_CondWait(ths->_condP, ths->_mtxP.getMutex()); ths->_mtxP.unlock(); // この時点でスレッドのポインタは有効な筈 tls_threadID = SDL_GetThreadID(ths->_thread); tls_threadName = ths->_name; Stat stat; try { ths->_holder->inorder([ths](Args&&... args){ ths->runIt(std::forward<Args>(args)...); }); stat = (ths->isInterrupted()) ? Interrupted_End : Finished; } catch(...) { Assert(Warn, false, "thread is finished unexpectedly") #ifdef NO_EXCEPTION_PTR ths->_bException = true; #else ths->_eptr = std::current_exception(); #endif stat = Error_End; } SDL_AtomicSet(&ths->_atmStat, stat); SDL_CondBroadcast(ths->_condP); // SDLの戻り値は使わない return 0; } //! move-ctorの後に値を掃除する void _clean() { _thread = nullptr; _holder = spn::none; _condC = _condP = nullptr; } protected: #ifdef NO_EXCEPTION_PTR bool _bException = false; #else std::exception_ptr _eptr = nullptr; #endif virtual RET run(Args...) = 0; public: _Thread(_Thread&& th): _atmInt(std::move(th._atmInt)), _thread(th._thread), _holder(std::move(th._holder)), _atmStat(std::move(th._atmStat)), _condC(th._condC), _condP(th._condP), _mtxC(std::move(th._mtxC)), _mtxP(std::move(th._mtxP)), _name(std::move(th._name)) { th._clean(); } _Thread(const _Thread& t) = delete; _Thread& operator = (const _Thread& t) = delete; _Thread(const std::string& name): _thread(nullptr), _name(name) { _condC = SDL_CreateCond(); _condP = SDL_CreateCond(); // 中断フラグに0をセット SDL_AtomicSet(&_atmInt, 0); SDL_AtomicSet(&_atmStat, Idle); } ~_Thread() { if(_thread) { // スレッド実行中だったらエラーを出す Assert(Trap, !isRunning()) SDL_DestroyCond(_condC); SDL_DestroyCond(_condP); } } template <class... Args0> void start(Args0&&... args0) { _holder = Holder(std::forward<Args0>(args0)...); // 2回以上呼ぶとエラー Assert(Trap, SDL_AtomicGet(&_atmStat) == Idle) SDL_AtomicSet(&_atmStat, Running); _mtxC.lock(); // 一旦クラス内部に変数を参照で取っておく SDL_Thread* th = SDL_CreateThread(ThreadFunc, _name.c_str(), this); // 子スレッドが開始されるまで待つ SDL_CondWait(_condC, _mtxC.getMutex()); _mtxC.unlock(); _mtxP.lock(); _thread = th; SDL_CondBroadcast(_condP); _mtxP.unlock(); } Stat getStatus() { return static_cast<Stat>(SDL_AtomicGet(&_atmStat)); } bool isRunning() { Stat stat = getStatus(); return stat==Running || stat==Interrupted; } //! 中断を指示する virtual bool interrupt() { auto ret = SDL_AtomicCAS(&_atmStat, Running, Interrupted); SDL_AtomicSet(&_atmInt, 1); return ret == SDL_TRUE; } //! スレッド内部で中断指示がされているかを確認 bool isInterrupted() { return SDL_AtomicGet(&_atmInt) == 1; } void join() { Assert(Trap, getStatus() != Stat::Idle) _mtxP.lock(); if(_thread) { _mtxP.unlock(); SDL_WaitThread(_thread, nullptr); _thread = nullptr; SDL_DestroyCond(_condP); SDL_DestroyCond(_condC); _condP = _condC = nullptr; } else _mtxP.unlock(); } bool try_join(uint32_t ms) { Assert(Trap, getStatus() != Stat::Idle) _mtxP.lock(); if(_thread) { int res = SDL_CondWaitTimeout(_condP, _mtxP.getMutex(), ms); _mtxP.unlock(); SDLEC_Chk(Trap) if(res == 0 || !isRunning()) { SDL_WaitThread(_thread, nullptr); _thread = nullptr; return true; } return false; } _mtxP.unlock(); return true; } void getResult() { // まだスレッドが終了して無い時の為にjoinを呼ぶ join(); rethrowIfException(); } void rethrowIfException() { #ifdef NO_EXCEPTION_PTR if(_bException) throw std::runtime_error("exception catched in thread"); #else if(_eptr) std::rethrow_exception(_eptr); #endif } const std::string& getName() const { return _name; } }; template <class SIG> class Thread; template <class RET, class... Args> class Thread<RET (Args...)> : public _Thread<Thread<RET (Args...)>, RET, Args...> { using base_type = _Thread<Thread<RET (Args...)>, RET, Args...>; spn::Optional<RET> _retVal; protected: virtual RET run(Args...) = 0; public: using base_type::base_type; void runIt(Args... args) { _retVal = run(std::forward<Args>(args)...); } RET&& getResult() { // まだスレッドが終了して無い時の為にjoinを呼ぶ base_type::join(); base_type::rethrowIfException(); return std::move(*_retVal); } }; template <class... Args> class Thread<void (Args...)> : public _Thread<Thread<void (Args...)>, void, Args...> { using base_type = _Thread<Thread<void (Args...)>, void, Args...>; protected: virtual void run(Args...) = 0; public: using base_type::base_type; void runIt(Args... args) { run(std::forward<Args>(args)...); } void getResult() { // まだスレッドが終了して無い時の為にjoinを呼ぶ base_type::join(); base_type::rethrowIfException(); } }; class Window; using SPWindow = std::shared_ptr<Window>; class Window { public: enum class Stat { Minimized, Maximized, Hidden, Fullscreen, Shown }; //! OpenGL初期化パラメータ struct GLParam { int verMajor, verMinor; //!< OpenGLバージョン(メジャー & マイナー) int red, green, blue, depth; //!< 色深度(RGB + Depth) int doublebuffer; //!< ダブルバッファフラグ GLParam(); void setStdAttributes() const; void getStdAttributes(); }; //! Window初期化パラメータ struct Param { std::string title; //!< ウィンドウタイトル int posx, posy, //!< ウィンドウ位置 width, height; //!< ウィンドウサイズ uint32_t flag; //!< その他のフラグ Param(); }; private: SDL_Window* _window; Stat _stat; Window(SDL_Window* w); void _checkState(); public: static void SetGLAttributes() {} // SDL_GLパラメータ設定(可変引数バージョン) template <class... Ts> static void SetGLAttributes(SDL_GLattr attr, int value, Ts... ts) { SDL_GL_SetAttribute(attr, value); SetGLAttributes(ts...); } static void GetGLAttributes() {} // SDL_GLパラメータ取得(可変引数バージョン) template <class... Ts> static void GetGLAttributes(SDL_GLattr attr, int& dst, Ts&&... ts) { SDL_GL_GetAttribute(attr, &dst); GetGLAttributes(std::forward<Ts>(ts)...); } static SPWindow Create(const Param& p); static SPWindow Create(const std::string& title, int w, int h, uint32_t flag=0); static SPWindow Create(const std::string& title, int x, int y, int w, int h, uint32_t flag=0); ~Window(); void setFullscreen(bool bFull); void setGrab(bool bGrab); void setMaximumSize(int w, int h); void setMinimumSize(int w, int h); void setSize(int w, int h); void setTitle(const std::string& title); void show(bool bShow); void maximize(); void minimize(); void restore(); void setPosition(int x, int y); void raise(); // for logging uint32_t getID() const; Stat getState() const; bool isGrabbed() const; bool isResizable() const; bool hasInputFocus() const; bool hasMouseFocus() const; spn::Size getSize() const; spn::Size getMaximumSize() const; spn::Size getMinimumSize() const; uint32_t getSDLFlag() const; SDL_Window* getWindow() const; static void EnableScreenSaver(bool bEnable); }; class GLContext; using SPGLContext = std::shared_ptr<GLContext>; class GLContext { //! makeCurrentした時に指定したウィンドウ SPWindow _spWindow; SDL_GLContext _ctx; GLContext(const SPWindow& w); public: static SPGLContext CreateContext(const SPWindow& w, bool bShare=false); ~GLContext(); void makeCurrent(const SPWindow& w); void makeCurrent(); void swapWindow(); static int SetSwapInterval(int n); }; class RWops { public: struct Callback : boost::serialization::traits<Callback, boost::serialization::object_serializable, boost::serialization::track_never> { virtual void onRelease(RWops& rw) = 0; template <class Archive> void serialize(Archive&, const unsigned int) {} }; enum Hence : int { Begin = RW_SEEK_SET, Current = RW_SEEK_CUR, End = RW_SEEK_END }; // 管轄外メモリであってもシリアライズ時にはデータ保存する enum Type { ConstMem, //!< 外部Constメモリ (管轄外) Mem, //!< 外部メモリ (管轄外) ConstVector, //!< 管轄Constメモリ Vector, //!< 管轄メモリ File }; enum Access : int { Read = 0x01, Write = 0x02, Binary = 0x04 }; //! 外部バッファ struct ExtBuff { void* ptr; size_t size; template <class Archive> void serialize(Archive& /*ar*/, const unsigned int /*ver*/) { AssertP(Trap, false, "this object cannot serialize") } }; //! RWopsエラー基底 struct RWE_Error : std::runtime_error { const std::string _title; RWE_Error(const std::string& title); void setMessage(const std::string& msg); }; //! ファイル開けないエラー struct RWE_File : RWE_Error { const std::string _path; RWE_File(const std::string& path); }; //! 範囲外アクセス struct RWE_OutOfRange : RWE_Error { const Hence _hence; const int64_t _pos, _size; RWE_OutOfRange(int64_t pos, Hence hence, int64_t size); }; //! アクセス権限違反(読み取り専用ファイルに書き込みなど) struct RWE_Permission : RWE_Error { const Access _have, _try; RWE_Permission(Access have, Access tr); }; //! メモリ確保エラー struct RWE_Memory : RWE_Error { const size_t _size; RWE_Memory(size_t size); }; //! ぬるぽ指定 struct RWE_NullMemory : RWE_Error { RWE_NullMemory(); }; private: using Data = boost::variant<boost::blank, std::string, spn::URI, ExtBuff, spn::ByteBuff>; SDL_RWops* _ops; int _access; Type _type; Data _data; //! RWopsが解放される直前に呼ばれる関数 using UPCallback = std::unique_ptr<Callback>; UPCallback _endCB; void _deserializeFromMember(); void _clear(); friend class boost::serialization::access; BOOST_SERIALIZATION_SPLIT_MEMBER(); template <class Archive> void save(Archive& ar, const unsigned int) const { ar & _access; if(isMemory()) { Type type; if(_type == Type::ConstMem || _type == Type::ConstVector) type = Type::ConstVector; else type = Type::Vector; ar & type; auto dat = getMemoryPtrC(); spn::ByteBuff buff(dat.second); std::memcpy(&buff[0], dat.first, dat.second); Data data(std::move(buff)); ar & data; } else ar & _type & _data; int64_t pos = tell(); ar & pos & _endCB; } template <class Archive> void load(Archive& ar, const unsigned int) { int64_t pos; ar & _access & _type & _data & pos & _endCB; _deserializeFromType(pos); } void _deserializeFromType(int64_t pos); friend spn::ResWrap<RWops, spn::String<std::string>>; RWops() = default; template <class T> RWops(SDL_RWops* ops, Type type, int access, T&& data, Callback* cb=nullptr) { AssertT(Trap, ops, (RWE_Error)(const char*), "unknown error") _ops = ops; _type = type; _access = access; _data = std::forward<T>(data); _endCB.reset(cb); } static RWops _FromVector(spn::ByteBuff&& buff, Callback* cb, std::false_type); static RWops _FromVector(spn::ByteBuff&& buff, Callback* cb, std::true_type); public: static int ReadMode(const char* mode); static std::string ReadModeStr(int mode); static RWops FromConstMem(const void* mem, size_t size, Callback* cb=nullptr); template <class T> static RWops FromVector(T&& buff, Callback* cb=nullptr) { spn::ByteBuff tbuff(std::forward<T>(buff)); return _FromVector(std::move(tbuff), cb, typename std::is_const<T>::type()); } static RWops FromMem(void* mem, size_t size, Callback* cb=nullptr); static RWops FromFile(const std::string& path, int access); static RWops FromURI(SDL_RWops* ops, const spn::URI& uri, int access); RWops(RWops&& ops); RWops& operator = (RWops&& ops); ~RWops(); void close(); int getAccessFlag() const; size_t read(void* dst, size_t blockSize, size_t nblock); size_t write(const void* src, size_t blockSize, size_t nblock); int64_t size(); int64_t seek(int64_t offset, Hence hence); int64_t tell() const; uint16_t readBE16(); uint32_t readBE32(); uint64_t readBE64(); uint16_t readLE16(); uint32_t readLE32(); uint64_t readLE64(); bool writeBE(uint16_t value); bool writeBE(uint32_t value); bool writeBE(uint64_t value); bool writeLE(uint16_t value); bool writeLE(uint32_t value); bool writeLE(uint64_t value); SDL_RWops* getOps(); spn::ByteBuff readAll(); Type getType() const; bool isMemory() const; //! isMemory()==trueの時だけ有効 std::pair<const void*, size_t> getMemoryPtrC() const; //! Type::Vector時のみ有効 std::pair<void*, size_t> getMemoryPtr(); }; struct UriHandler : spn::IURIOpener { virtual HLRW openURI_RW(const spn::URI& uri, int access) = 0; }; using SPUriHandler = std::shared_ptr<UriHandler>; #define mgr_rw (::rs::RWMgr::_ref()) class RWMgr : public spn::ResMgrA<RWops, RWMgr> { struct HChk { HLRW operator()(UriHandler& h, const spn::URI& uri, int access) const; }; using UriHandlerV = spn::HandlerV<UriHandler, HChk>; UriHandlerV _handlerV; std::string _orgName, _appName; //! 一時ファイルディレクトリのファイルを全て削除 void _cleanupTemporaryFile(); public: RWMgr(const std::string& org_name, const std::string& app_name); UriHandlerV& getHandler(); using base_type = spn::ResMgrA<RWops, RWMgr>; using LHdl = AnotherLHandle<RWops, true>; // ---- RWopsへ中継するだけの関数 ---- //! 任意のURIからハンドル作成(ReadOnly) LHdl fromURI(const spn::URI& uri, int access); LHdl fromFile(const std::string& path, int access); template <class T> LHdl fromVector(T&& t) { return base_type::acquire(RWops::FromVector(std::forward<T>(t))); } LHdl fromConstMem(const void* p, int size, typename RWops::Callback* cb=nullptr); LHdl fromMem(void* p, int size, typename RWops::Callback* cb=nullptr); //! ランダムな名前の一時ファイルを作ってそのハンドルとファイルパスを返す std::pair<LHdl, std::string> createTemporaryFile(); //! OrgNameとAppNameからなるプライベートなディレクトリパス std::string makeFilePath(const std::string& dirName) const; }; //! ファイルシステムに置かれたZipからのファイル読み込み class UriH_PackedZip : public UriHandler { spn::UP_Adapt _stream; spn::zip::ZipTree _ztree; static bool Capable(const spn::URI& uri); public: UriH_PackedZip(spn::ToPathStr zippath); // --- from UriHandler --- HLRW openURI_RW(const spn::URI& uri, int access) override; // --- from IURIOpener --- spn::UP_Adapt openURI(const spn::URI& uri) override; }; //! アセットZipからのファイル読み込み (Android only) class UriH_AssetZip : public UriH_PackedZip { public: // Asset中のZipファイルのパスを指定 UriH_AssetZip(spn::ToPathStr zippath); }; //! ファイルシステムからのファイル読み込み class UriH_File : public UriHandler { spn::PathStr _basePath; public: UriH_File(spn::ToPathStr path); static bool Capable(const spn::URI& uri, int access); // --- from UriHandler --- HLRW openURI_RW(const spn::URI& uri, int access) override; // --- from IURIOpener --- spn::UP_Adapt openURI(const spn::URI& uri) override; }; struct RGB { union { uint8_t ar[3]; struct { uint8_t r,g,b; }; }; RGB() = default; RGB(int r, int g, int b): ar{uint8_t(r), uint8_t(g), uint8_t(b)} {} }; struct RGBA { union { uint8_t ar[4]; struct { uint8_t r,g,b,a; }; }; RGBA() = default; RGBA(RGB rgb, int a): ar{rgb.r, rgb.g, rgb.b, static_cast<uint8_t>(a)} {} }; using UPSDLFormat = std::unique_ptr<SDL_PixelFormat, decltype(&SDL_FreeFormat)>; UPSDLFormat MakeUPFormat(uint32_t fmt); class Surface; using SPSurface = std::shared_ptr<Surface>; class Surface { SDL_Surface* _sfc; mutable Mutex _mutex; spn::AB_Byte _buff; class LockObj { const Surface& _sfc; void* _bits; int _pitch; public: LockObj(LockObj&& lk); LockObj(const Surface& sfc, void* bits, int pitch); ~LockObj(); void* getBits(); int getPitch() const; operator bool () const; }; void _unlock() const; Surface(SDL_Surface* sfc); Surface(SDL_Surface* sfc, spn::ByteBuff&& buff); public: static uint32_t Map(uint32_t format, RGB rgb); //! RGBA値をSDLのピクセルフォーマット形式にパックする static uint32_t Map(uint32_t format, RGBA rgba); //! SDLのピクセルフォーマットからRGB値を取り出す static RGBA Get(uint32_t format, uint32_t pixel); //! SDLのピクセルフォーマット名を表す文字列を取得 static const std::string& GetFormatString(uint32_t format); //! 任意のフォーマットの画像を読み込む static SPSurface Load(HRW hRW); //! 空のサーフェス作成 static SPSurface Create(int w, int h, uint32_t format); //! ピクセルデータを元にサーフェス作成 static SPSurface Create(const spn::ByteBuff& src, int pitch, int w, int h, uint32_t format); static SPSurface Create(spn::ByteBuff&& src, int pitch, int w, int h, uint32_t format); ~Surface(); void saveAsBMP(HRW hDst) const; void saveAsPNG(HRW hDst) const; LockObj lock() const; LockObj try_lock() const; const SDL_PixelFormat& getFormat() const; uint32_t getFormatEnum() const; spn::Size getSize() const; int width() const; int height() const; //! 同サイズのサーフェスを作成 SPSurface makeBlank() const; SPSurface duplicate() const; SPSurface flipHorizontal() const; SPSurface flipVertical() const; //! ピクセルフォーマット変換 SPSurface convert(uint32_t fmt) const; SPSurface convert(const SDL_PixelFormat& fmt) const; //! ピクセルデータがデータ配列先頭から隙間なく詰められているか bool isContinuous() const; //! Continuousな状態でピクセルデータを抽出 spn::ByteBuff extractAsContinuous(uint32_t dstFmt=0) const; //! ビットブロック転送 void blit(const SPSurface& sfc, const spn::Rect& srcRect, int dstX, int dstY) const; //! スケーリング有りのビットブロック転送 void blitScaled(const SPSurface& sfc, const spn::Rect& srcRect, const spn::Rect& dstRect) const; //! 単色での矩形塗りつぶし void fillRect(const spn::Rect& rect, uint32_t color); SDL_Surface* getSurface(); SPSurface resize(const spn::Size& s) const; void setEnableColorKey(uint32_t key); void setDisableColorKey(); spn::Optional<uint32_t> getColorKey() const; void setBlendMode(SDL_BlendMode mode); SDL_BlendMode getBlendMode() const; }; }
//****************************************************************************** /// /// @file base/image/hdr.cpp /// /// Implementation of Radiance RGBE High Dynamic Range (HDR) image file /// handling. /// /// @author Christopher Cason /// @author Christoph Lipka /// @author Based on MegaPOV HDR code written by Mael and Christoph Hormann /// /// @copyright /// @parblock /// /// Persistence of Vision Ray Tracer ('POV-Ray') version 3.7. /// Copyright 1991-2016 Persistence of Vision Raytracer Pty. Ltd. /// /// POV-Ray is free software: you can redistribute it and/or modify /// it under the terms of the GNU Affero General Public License as /// published by the Free Software Foundation, either version 3 of the /// License, or (at your option) any later version. /// /// POV-Ray is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU Affero General Public License for more details. /// /// You should have received a copy of the GNU Affero General Public License /// along with this program. If not, see <http://www.gnu.org/licenses/>. /// /// ---------------------------------------------------------------------------- /// /// POV-Ray is based on the popular DKB raytracer version 2.12. /// DKBTrace was originally written by David K. Buck. /// DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins. /// /// @endparblock /// //****************************************************************************** // Unit header file must be the first file included within POV-Ray *.cpp files (pulls in config) #include "base/image/hdr.h" // Standard C++ header files #include <string> // Boost header files #include <boost/scoped_ptr.hpp> #include <boost/scoped_array.hpp> // POV-Ray base header files #include "base/fileinputoutput.h" #include "base/types.h" #include "base/image/metadata.h" // this must be the last file included #include "base/povdebug.h" namespace pov_base { namespace HDR { /***************************************************************************** * Local preprocessor defines ******************************************************************************/ #define MINELEN 8 /* minimum scanline length for encoding */ #define MAXELEN 0x7fff /* maximum scanline length for encoding */ #define MINRUN 4 /* minimum run length */ /***************************************************************************** * Local typedefs ******************************************************************************/ struct Messages { vector<string> warnings; string error; }; typedef unsigned char RGBE[4]; // red, green, blue, exponent void GetRGBE(RGBE rgbe, const Image *image, int col, int row, const GammaCurvePtr& gamma, DitherHandler* dither); void SetRGBE(const unsigned char *scanline, Image *image, int row, int width, const GammaCurvePtr& gamma); void ReadOldLine(unsigned char *scanline, int width, IStream *file); /***************************************************************************** * Code ******************************************************************************/ void GetRGBE(RGBE rgbe, const Image *image, int col, int row, const GammaCurvePtr& gamma, DitherHandler* dh) { DitherHandler::OffsetInfo linOff, encOff; dh->getOffset(col,row,linOff,encOff); RGBColour rgbColour; GetEncodedRGBValue(image, col, row, gamma, rgbColour); rgbColour += linOff.getRGB(); RadianceHDRColour rgbeColour(rgbColour,encOff.getRGB()); for (int i = 0; i < 4; i ++) rgbe[i] = (*rgbeColour)[i]; rgbColour -= RGBColour(rgbeColour); linOff.setRGB(rgbColour); dh->setError(col,row,linOff); } void SetRGBE(const unsigned char *scanline, Image *image, int row, int width, const GammaCurvePtr& gamma) { for(int i = 0; i < width; i++) { RadianceHDRColour rgbeColour; for (int j = 0; j < 4; j ++) (*rgbeColour)[j] = scanline[j]; SetEncodedRGBValue(image, i, row, gamma, RGBColour(rgbeColour)); scanline += 4; } } void ReadOldLine(unsigned char *scanline, int width, IStream *file) { int rshift = 0; unsigned char b; while(width > 0) { scanline[0] = file->Read_Byte(); scanline[1] = file->Read_Byte(); scanline[2] = file->Read_Byte(); // NB EOF won't be set at this point even if the last read obtained the // final byte in the file (we need to read another byte for that to happen). if(*file == false) throw POV_EXCEPTION(kFileDataErr, "Invalid HDR file (unexpected EOF)"); if(!file->Read_Byte(b)) return; scanline[3] = b; if((scanline[0] == 1) && (scanline[1] == 1) && (scanline[2] == 1)) { for(int i = scanline[3] << rshift; i > 0; i--) { memcpy(scanline, scanline - 4, 4); scanline += 4; width--; } rshift += 8; } else { scanline += 4; width--; rshift = 0; } } } Image *Read(IStream *file, const Image::ReadOptions& options) { char line[2048]; char *s; char s1[3]; char s2[3]; unsigned char b; unsigned char val; float e; float exposure = 1.0; unsigned int width; unsigned int height; Image *image = NULL; Image::ImageDataType imagetype = options.itype; // Radiance HDR files store linear color values by default, so never convert unless the user overrides // (e.g. to handle a non-compliant file). GammaCurvePtr gamma; if (options.gammacorrect) { if (options.gammaOverride) gamma = TranscodingGammaCurve::Get(options.workingGamma, options.defaultGamma); else gamma = TranscodingGammaCurve::Get(options.workingGamma, NeutralGammaCurve::Get()); } while(*file) { if((file->getline(line, sizeof(line)) == false) || (line[0] == '-') || (line[0] == '+')) break; // TODO: what do we do with exposure? if(strncmp(line, "EXPOSURE", 8) == 0) { if((s = strchr(line, '=')) != NULL) { if(sscanf(s + 1, "%f", &e) == 1) exposure *= e; } } } if(sscanf(line, "%2[+-XY] %u %2[+-XY] %u\n", s1, &height, s2, &width) != 4) throw POV_EXCEPTION(kFileDataErr, "Bad HDR file header"); if(imagetype == Image::Undefined) imagetype = Image::RGBFT_Float; image = Image::Create(width, height, imagetype); // NB: HDR files don't use alpha, so premultiplied vs. non-premultiplied is not an issue boost::scoped_array<unsigned char> scanline(new unsigned char[4 * width]); for(int row = 0; row < height; row++) { // determine scanline type if((width < MINELEN) | (width > MAXELEN)) { ReadOldLine(scanline.get(), width, file); SetRGBE(scanline.get(), image, row, width, gamma); continue; } if(file->Read_Byte(b) == false) throw POV_EXCEPTION(kFileDataErr, "Incomplete HDR file"); if(b != 2) { file->UnRead_Byte(b); ReadOldLine(scanline.get(), width, file); SetRGBE(scanline.get(), image, row, width, gamma); continue; } scanline[1] = file->Read_Byte(); scanline[2] = file->Read_Byte(); if(file->Read_Byte(b) == false) throw POV_EXCEPTION(kFileDataErr, "Incomplete or invalid HDR file"); if((scanline[1] != 2) || ((scanline[2] & 128) != 0)) { scanline[0] = 2; scanline[3] = b; ReadOldLine(scanline.get() + 4, width - 1, file); SetRGBE(scanline.get(), image, row, width, gamma); continue; } if((((int) scanline[2] << 8) | b) != width) throw POV_EXCEPTION(kFileDataErr, "Invalid HDR file (length mismatch)"); for(int i = 0; i < 4; i++) { for(int j = 0; j < width; ) { if(file->Read_Byte(b) == false) throw POV_EXCEPTION(kFileDataErr, "Invalid HDR file (unexpected EOF)"); if(b > 128) { // run b &= 127; if(file->Read_Byte(val) == false) throw POV_EXCEPTION(kFileDataErr, "Invalid HDR file (unexpected EOF)"); while(b--) scanline[j++ * 4 + i] = (unsigned char) val; } else { while(b--) { if(file->Read_Byte(val) == false) throw POV_EXCEPTION(kFileDataErr, "Invalid HDR file (unexpected EOF)"); scanline[j++ * 4 + i] = (unsigned char) val; } } } } SetRGBE(scanline.get(), image, row, width, gamma); } return image; } void Write(OStream *file, const Image *image, const Image::WriteOptions& options) { int width = image->GetWidth(); int height = image->GetHeight(); int cnt = 1; int c2; RGBE rgbe; GammaCurvePtr gamma = TranscodingGammaCurve::Get(options.workingGamma, NeutralGammaCurve::Get()); DitherHandler* dither = options.dither.get(); Metadata meta; file->printf("#?RADIANCE\n"); file->printf("SOFTWARE=%s\n", meta.getSoftware().c_str()); file->printf("CREATION_TIME=%s\n" ,meta.getDateTime().c_str()); if (!meta.getComment1().empty()) file->printf("COMMENT=%s\n", meta.getComment1().c_str()); if (!meta.getComment2().empty()) file->printf("COMMENT=%s\n", meta.getComment2().c_str()); if (!meta.getComment3().empty()) file->printf("COMMENT=%s\n", meta.getComment3().c_str()); if (!meta.getComment4().empty()) file->printf("COMMENT=%s\n", meta.getComment4().c_str()); file->printf("FORMAT=32-bit_rle_rgbe\n"); file->printf("\n"); file->printf("-Y %d +X %d\n", height, width); boost::scoped_array<RGBE> scanline(new RGBE[width]); for(int row = 0; row < height; row++) { if((width < MINELEN) | (width > MAXELEN)) { for(int col = 0; col < width; col++) { GetRGBE(rgbe, image, col, row, gamma, dither); if(file->write(&rgbe, sizeof(RGBE)) == false) throw POV_EXCEPTION(kFileDataErr, "Failed to write data to HDR file"); } } else { // put magic header file->Write_Byte(2); file->Write_Byte(2); file->Write_Byte(width >> 8); file->Write_Byte(width & 255); // convert pixels for(int col = 0; col < width; col++) GetRGBE(scanline[col], image, col, row, gamma, dither); // put components seperately for(int i = 0; i < 4; i++) { for(int col = 0; col < width; col += cnt) { int beg = 0; // find next run for(beg = col; beg < width; beg += cnt) { cnt = 1; while((cnt < 127) && (beg + cnt < width) && (scanline[beg + cnt][i] == scanline[beg][i])) cnt++; // long enough ? if(cnt >= MINRUN) break; } if(beg - col > 1 && beg - col < MINRUN) { c2 = col + 1; while(scanline[c2++][i] == scanline[col][i]) { if(c2 == beg) { // short run file->Write_Byte(128 + beg - col); if(file->Write_Byte(scanline[col][i]) == false) throw POV_EXCEPTION(kFileDataErr, "Failed to write data to HDR file"); col = beg; break; } } } while(col < beg) { // write non-run if((c2 = beg - col) > 128) c2 = 128; file->Write_Byte(c2); while(c2--) { if(file->Write_Byte(scanline[col++][i]) == false) throw POV_EXCEPTION(kFileDataErr, "Failed to write data to HDR file"); } } if(cnt >= MINRUN) { // write run file->Write_Byte(128 + cnt); if(file->Write_Byte(scanline[beg][i]) == false) throw POV_EXCEPTION(kFileDataErr, "Failed to write data to HDR file"); } else cnt = 0; } } } } } } // end of namespace HDR } // end of namespace pov_base Replaced broken comparison in hdr.cpp Replaced invalid comparison of IStream to bool. //****************************************************************************** /// /// @file base/image/hdr.cpp /// /// Implementation of Radiance RGBE High Dynamic Range (HDR) image file /// handling. /// /// @author Christopher Cason /// @author Christoph Lipka /// @author Based on MegaPOV HDR code written by Mael and Christoph Hormann /// /// @copyright /// @parblock /// /// Persistence of Vision Ray Tracer ('POV-Ray') version 3.7. /// Copyright 1991-2016 Persistence of Vision Raytracer Pty. Ltd. /// /// POV-Ray is free software: you can redistribute it and/or modify /// it under the terms of the GNU Affero General Public License as /// published by the Free Software Foundation, either version 3 of the /// License, or (at your option) any later version. /// /// POV-Ray is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU Affero General Public License for more details. /// /// You should have received a copy of the GNU Affero General Public License /// along with this program. If not, see <http://www.gnu.org/licenses/>. /// /// ---------------------------------------------------------------------------- /// /// POV-Ray is based on the popular DKB raytracer version 2.12. /// DKBTrace was originally written by David K. Buck. /// DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins. /// /// @endparblock /// //****************************************************************************** // Unit header file must be the first file included within POV-Ray *.cpp files (pulls in config) #include "base/image/hdr.h" // Standard C++ header files #include <string> // Boost header files #include <boost/scoped_ptr.hpp> #include <boost/scoped_array.hpp> // POV-Ray base header files #include "base/fileinputoutput.h" #include "base/types.h" #include "base/image/metadata.h" // this must be the last file included #include "base/povdebug.h" namespace pov_base { namespace HDR { /***************************************************************************** * Local preprocessor defines ******************************************************************************/ #define MINELEN 8 /* minimum scanline length for encoding */ #define MAXELEN 0x7fff /* maximum scanline length for encoding */ #define MINRUN 4 /* minimum run length */ /***************************************************************************** * Local typedefs ******************************************************************************/ struct Messages { vector<string> warnings; string error; }; typedef unsigned char RGBE[4]; // red, green, blue, exponent void GetRGBE(RGBE rgbe, const Image *image, int col, int row, const GammaCurvePtr& gamma, DitherHandler* dither); void SetRGBE(const unsigned char *scanline, Image *image, int row, int width, const GammaCurvePtr& gamma); void ReadOldLine(unsigned char *scanline, int width, IStream *file); /***************************************************************************** * Code ******************************************************************************/ void GetRGBE(RGBE rgbe, const Image *image, int col, int row, const GammaCurvePtr& gamma, DitherHandler* dh) { DitherHandler::OffsetInfo linOff, encOff; dh->getOffset(col,row,linOff,encOff); RGBColour rgbColour; GetEncodedRGBValue(image, col, row, gamma, rgbColour); rgbColour += linOff.getRGB(); RadianceHDRColour rgbeColour(rgbColour,encOff.getRGB()); for (int i = 0; i < 4; i ++) rgbe[i] = (*rgbeColour)[i]; rgbColour -= RGBColour(rgbeColour); linOff.setRGB(rgbColour); dh->setError(col,row,linOff); } void SetRGBE(const unsigned char *scanline, Image *image, int row, int width, const GammaCurvePtr& gamma) { for(int i = 0; i < width; i++) { RadianceHDRColour rgbeColour; for (int j = 0; j < 4; j ++) (*rgbeColour)[j] = scanline[j]; SetEncodedRGBValue(image, i, row, gamma, RGBColour(rgbeColour)); scanline += 4; } } void ReadOldLine(unsigned char *scanline, int width, IStream *file) { int rshift = 0; unsigned char b; while(width > 0) { scanline[0] = file->Read_Byte(); scanline[1] = file->Read_Byte(); scanline[2] = file->Read_Byte(); // NB EOF won't be set at this point even if the last read obtained the // final byte in the file (we need to read another byte for that to happen). if(!*file) throw POV_EXCEPTION(kFileDataErr, "Invalid HDR file (unexpected EOF)"); if(!file->Read_Byte(b)) return; scanline[3] = b; if((scanline[0] == 1) && (scanline[1] == 1) && (scanline[2] == 1)) { for(int i = scanline[3] << rshift; i > 0; i--) { memcpy(scanline, scanline - 4, 4); scanline += 4; width--; } rshift += 8; } else { scanline += 4; width--; rshift = 0; } } } Image *Read(IStream *file, const Image::ReadOptions& options) { char line[2048]; char *s; char s1[3]; char s2[3]; unsigned char b; unsigned char val; float e; float exposure = 1.0; unsigned int width; unsigned int height; Image *image = NULL; Image::ImageDataType imagetype = options.itype; // Radiance HDR files store linear color values by default, so never convert unless the user overrides // (e.g. to handle a non-compliant file). GammaCurvePtr gamma; if (options.gammacorrect) { if (options.gammaOverride) gamma = TranscodingGammaCurve::Get(options.workingGamma, options.defaultGamma); else gamma = TranscodingGammaCurve::Get(options.workingGamma, NeutralGammaCurve::Get()); } while(*file) { if((file->getline(line, sizeof(line)) == false) || (line[0] == '-') || (line[0] == '+')) break; // TODO: what do we do with exposure? if(strncmp(line, "EXPOSURE", 8) == 0) { if((s = strchr(line, '=')) != NULL) { if(sscanf(s + 1, "%f", &e) == 1) exposure *= e; } } } if(sscanf(line, "%2[+-XY] %u %2[+-XY] %u\n", s1, &height, s2, &width) != 4) throw POV_EXCEPTION(kFileDataErr, "Bad HDR file header"); if(imagetype == Image::Undefined) imagetype = Image::RGBFT_Float; image = Image::Create(width, height, imagetype); // NB: HDR files don't use alpha, so premultiplied vs. non-premultiplied is not an issue boost::scoped_array<unsigned char> scanline(new unsigned char[4 * width]); for(int row = 0; row < height; row++) { // determine scanline type if((width < MINELEN) | (width > MAXELEN)) { ReadOldLine(scanline.get(), width, file); SetRGBE(scanline.get(), image, row, width, gamma); continue; } if(file->Read_Byte(b) == false) throw POV_EXCEPTION(kFileDataErr, "Incomplete HDR file"); if(b != 2) { file->UnRead_Byte(b); ReadOldLine(scanline.get(), width, file); SetRGBE(scanline.get(), image, row, width, gamma); continue; } scanline[1] = file->Read_Byte(); scanline[2] = file->Read_Byte(); if(file->Read_Byte(b) == false) throw POV_EXCEPTION(kFileDataErr, "Incomplete or invalid HDR file"); if((scanline[1] != 2) || ((scanline[2] & 128) != 0)) { scanline[0] = 2; scanline[3] = b; ReadOldLine(scanline.get() + 4, width - 1, file); SetRGBE(scanline.get(), image, row, width, gamma); continue; } if((((int) scanline[2] << 8) | b) != width) throw POV_EXCEPTION(kFileDataErr, "Invalid HDR file (length mismatch)"); for(int i = 0; i < 4; i++) { for(int j = 0; j < width; ) { if(file->Read_Byte(b) == false) throw POV_EXCEPTION(kFileDataErr, "Invalid HDR file (unexpected EOF)"); if(b > 128) { // run b &= 127; if(file->Read_Byte(val) == false) throw POV_EXCEPTION(kFileDataErr, "Invalid HDR file (unexpected EOF)"); while(b--) scanline[j++ * 4 + i] = (unsigned char) val; } else { while(b--) { if(file->Read_Byte(val) == false) throw POV_EXCEPTION(kFileDataErr, "Invalid HDR file (unexpected EOF)"); scanline[j++ * 4 + i] = (unsigned char) val; } } } } SetRGBE(scanline.get(), image, row, width, gamma); } return image; } void Write(OStream *file, const Image *image, const Image::WriteOptions& options) { int width = image->GetWidth(); int height = image->GetHeight(); int cnt = 1; int c2; RGBE rgbe; GammaCurvePtr gamma = TranscodingGammaCurve::Get(options.workingGamma, NeutralGammaCurve::Get()); DitherHandler* dither = options.dither.get(); Metadata meta; file->printf("#?RADIANCE\n"); file->printf("SOFTWARE=%s\n", meta.getSoftware().c_str()); file->printf("CREATION_TIME=%s\n" ,meta.getDateTime().c_str()); if (!meta.getComment1().empty()) file->printf("COMMENT=%s\n", meta.getComment1().c_str()); if (!meta.getComment2().empty()) file->printf("COMMENT=%s\n", meta.getComment2().c_str()); if (!meta.getComment3().empty()) file->printf("COMMENT=%s\n", meta.getComment3().c_str()); if (!meta.getComment4().empty()) file->printf("COMMENT=%s\n", meta.getComment4().c_str()); file->printf("FORMAT=32-bit_rle_rgbe\n"); file->printf("\n"); file->printf("-Y %d +X %d\n", height, width); boost::scoped_array<RGBE> scanline(new RGBE[width]); for(int row = 0; row < height; row++) { if((width < MINELEN) | (width > MAXELEN)) { for(int col = 0; col < width; col++) { GetRGBE(rgbe, image, col, row, gamma, dither); if(file->write(&rgbe, sizeof(RGBE)) == false) throw POV_EXCEPTION(kFileDataErr, "Failed to write data to HDR file"); } } else { // put magic header file->Write_Byte(2); file->Write_Byte(2); file->Write_Byte(width >> 8); file->Write_Byte(width & 255); // convert pixels for(int col = 0; col < width; col++) GetRGBE(scanline[col], image, col, row, gamma, dither); // put components seperately for(int i = 0; i < 4; i++) { for(int col = 0; col < width; col += cnt) { int beg = 0; // find next run for(beg = col; beg < width; beg += cnt) { cnt = 1; while((cnt < 127) && (beg + cnt < width) && (scanline[beg + cnt][i] == scanline[beg][i])) cnt++; // long enough ? if(cnt >= MINRUN) break; } if(beg - col > 1 && beg - col < MINRUN) { c2 = col + 1; while(scanline[c2++][i] == scanline[col][i]) { if(c2 == beg) { // short run file->Write_Byte(128 + beg - col); if(file->Write_Byte(scanline[col][i]) == false) throw POV_EXCEPTION(kFileDataErr, "Failed to write data to HDR file"); col = beg; break; } } } while(col < beg) { // write non-run if((c2 = beg - col) > 128) c2 = 128; file->Write_Byte(c2); while(c2--) { if(file->Write_Byte(scanline[col++][i]) == false) throw POV_EXCEPTION(kFileDataErr, "Failed to write data to HDR file"); } } if(cnt >= MINRUN) { // write run file->Write_Byte(128 + cnt); if(file->Write_Byte(scanline[beg][i]) == false) throw POV_EXCEPTION(kFileDataErr, "Failed to write data to HDR file"); } else cnt = 0; } } } } } } // end of namespace HDR } // end of namespace pov_base
#ifndef _UNTOOLS_UCBLOCKBYTES_HXX #define _UNTOOLS_UCBLOCKBYTES_HXX #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_ #include <com/sun/star/io/XOutputStream.hpp> #endif #ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_ #include <com/sun/star/io/XStream.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_ #include <com/sun/star/ucb/XContent.hpp> #endif #ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_ #include <com/sun/star/io/XSeekable.hpp> #endif #include <vos/thread.hxx> #include <vos/conditn.hxx> #include <vos/mutex.hxx> #include <tools/stream.hxx> #include <tools/link.hxx> #include <tools/errcode.hxx> #include <tools/datetime.hxx> namespace utl { SV_DECL_REF( UcbLockBytes ) class UcbLockBytesHandler : public SvRefBase { sal_Bool m_bActive; public: enum LoadHandlerItem { BEFOREWAIT, AFTERWAIT, DATA_AVAILABLE, DONE, CANCEL }; UcbLockBytesHandler() : m_bActive( sal_True ) {} virtual void Handle( LoadHandlerItem nWhich, UcbLockBytesRef xLockBytes ) = 0; void Activate( BOOL bActivate = sal_True ) { m_bActive = bActivate; } sal_Bool IsActive() const { return m_bActive; } }; SV_DECL_IMPL_REF( UcbLockBytesHandler ) #define NS_UNO ::com::sun::star::uno #define NS_IO ::com::sun::star::io #define NS_UCB ::com::sun::star::ucb class CommandThread_Impl; class UcbLockBytes : public virtual SvLockBytes { vos::OCondition m_aInitialized; vos::OCondition m_aTerminated; vos::OMutex m_aMutex; String m_aContentType; String m_aRealURL; DateTime m_aExpireDate; NS_UNO::Reference < NS_IO::XInputStream > m_xInputStream; NS_UNO::Reference < NS_IO::XOutputStream > m_xOutputStream; NS_UNO::Reference < NS_IO::XSeekable > m_xSeekable; CommandThread_Impl* m_pCommandThread; UcbLockBytesHandlerRef m_xHandler; sal_uInt32 m_nRead; sal_uInt32 m_nSize; ErrCode m_nError; sal_Bool m_bTerminated : 1; sal_Bool m_bDontClose : 1; sal_Bool m_bStreamValid : 1; DECL_LINK( DataAvailHdl, void * ); UcbLockBytes( UcbLockBytesHandler* pHandler=NULL ); protected: virtual ~UcbLockBytes (void); public: static UcbLockBytesRef CreateLockBytes( const NS_UNO::Reference < NS_UCB::XContent > xContent, StreamMode eMode, UcbLockBytesHandler* pHandler=0 ); static UcbLockBytesRef CreateInputLockBytes( const NS_UNO::Reference < NS_IO::XInputStream > xContent ); // SvLockBytes virtual void SetSynchronMode (BOOL bSynchron); virtual ErrCode ReadAt ( ULONG nPos, void *pBuffer, ULONG nCount, ULONG *pRead) const; virtual ErrCode WriteAt ( ULONG, const void*, ULONG, ULONG *pWritten); virtual ErrCode Flush (void) const; virtual ErrCode SetSize (ULONG); virtual ErrCode Stat ( SvLockBytesStat *pStat, SvLockBytesStatFlag) const; void SetError( ErrCode nError ) { m_nError = nError; } ErrCode GetError() const { return m_nError; } void Cancel(); // the following properties are available when and after the first DataAvailable callback has been executed String GetContentType() const; String GetRealURL() const; DateTime GetExpireDate() const; #if __PRIVATE sal_Bool setInputStream_Impl( const NS_UNO::Reference < NS_IO::XInputStream > &rxInputStream ); sal_Bool setStream_Impl( const NS_UNO::Reference < NS_IO::XStream > &rxStream ); void terminate_Impl (void); NS_UNO::Reference < NS_IO::XInputStream > getInputStream_Impl() const { vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex ); return m_xInputStream; } NS_UNO::Reference < NS_IO::XOutputStream > getOutputStream_Impl() const { vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex ); return m_xOutputStream; } NS_UNO::Reference < NS_IO::XSeekable > getSeekable_Impl() const { vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex ); return m_xSeekable; } sal_Bool hasInputStream_Impl() const { vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex ); return m_xInputStream.is(); } void setCommandThread_Impl( CommandThread_Impl* pThread ) { m_pCommandThread = pThread; } void setDontClose_Impl() { m_bDontClose = sal_True; } void SetContentType_Impl( const String& rType ) { m_aContentType = rType; } void SetRealURL_Impl( const String& rURL ) { m_aRealURL = rURL; } void SetExpireDate_Impl( const DateTime& rDateTime ) { m_aExpireDate = rDateTime; } void SetStreamValid_Impl(); #endif }; SV_IMPL_REF( UcbLockBytes ); }; #endif #58628#,#65293# __PRIVATE -> _SOLAR__PRIVATE #ifndef _UNTOOLS_UCBLOCKBYTES_HXX #define _UNTOOLS_UCBLOCKBYTES_HXX #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_ #include <com/sun/star/io/XOutputStream.hpp> #endif #ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_ #include <com/sun/star/io/XStream.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_ #include <com/sun/star/ucb/XContent.hpp> #endif #ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_ #include <com/sun/star/io/XSeekable.hpp> #endif #include <vos/thread.hxx> #include <vos/conditn.hxx> #include <vos/mutex.hxx> #include <tools/stream.hxx> #include <tools/link.hxx> #include <tools/errcode.hxx> #include <tools/datetime.hxx> namespace utl { SV_DECL_REF( UcbLockBytes ) class UcbLockBytesHandler : public SvRefBase { sal_Bool m_bActive; public: enum LoadHandlerItem { BEFOREWAIT, AFTERWAIT, DATA_AVAILABLE, DONE, CANCEL }; UcbLockBytesHandler() : m_bActive( sal_True ) {} virtual void Handle( LoadHandlerItem nWhich, UcbLockBytesRef xLockBytes ) = 0; void Activate( BOOL bActivate = sal_True ) { m_bActive = bActivate; } sal_Bool IsActive() const { return m_bActive; } }; SV_DECL_IMPL_REF( UcbLockBytesHandler ) #define NS_UNO ::com::sun::star::uno #define NS_IO ::com::sun::star::io #define NS_UCB ::com::sun::star::ucb class CommandThread_Impl; class UcbLockBytes : public virtual SvLockBytes { vos::OCondition m_aInitialized; vos::OCondition m_aTerminated; vos::OMutex m_aMutex; String m_aContentType; String m_aRealURL; DateTime m_aExpireDate; NS_UNO::Reference < NS_IO::XInputStream > m_xInputStream; NS_UNO::Reference < NS_IO::XOutputStream > m_xOutputStream; NS_UNO::Reference < NS_IO::XSeekable > m_xSeekable; CommandThread_Impl* m_pCommandThread; UcbLockBytesHandlerRef m_xHandler; sal_uInt32 m_nRead; sal_uInt32 m_nSize; ErrCode m_nError; sal_Bool m_bTerminated : 1; sal_Bool m_bDontClose : 1; sal_Bool m_bStreamValid : 1; DECL_LINK( DataAvailHdl, void * ); UcbLockBytes( UcbLockBytesHandler* pHandler=NULL ); protected: virtual ~UcbLockBytes (void); public: static UcbLockBytesRef CreateLockBytes( const NS_UNO::Reference < NS_UCB::XContent > xContent, StreamMode eMode, UcbLockBytesHandler* pHandler=0 ); static UcbLockBytesRef CreateInputLockBytes( const NS_UNO::Reference < NS_IO::XInputStream > xContent ); // SvLockBytes virtual void SetSynchronMode (BOOL bSynchron); virtual ErrCode ReadAt ( ULONG nPos, void *pBuffer, ULONG nCount, ULONG *pRead) const; virtual ErrCode WriteAt ( ULONG, const void*, ULONG, ULONG *pWritten); virtual ErrCode Flush (void) const; virtual ErrCode SetSize (ULONG); virtual ErrCode Stat ( SvLockBytesStat *pStat, SvLockBytesStatFlag) const; void SetError( ErrCode nError ) { m_nError = nError; } ErrCode GetError() const { return m_nError; } void Cancel(); // the following properties are available when and after the first DataAvailable callback has been executed String GetContentType() const; String GetRealURL() const; DateTime GetExpireDate() const; #if _SOLAR__PRIVATE sal_Bool setInputStream_Impl( const NS_UNO::Reference < NS_IO::XInputStream > &rxInputStream ); sal_Bool setStream_Impl( const NS_UNO::Reference < NS_IO::XStream > &rxStream ); void terminate_Impl (void); NS_UNO::Reference < NS_IO::XInputStream > getInputStream_Impl() const { vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex ); return m_xInputStream; } NS_UNO::Reference < NS_IO::XOutputStream > getOutputStream_Impl() const { vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex ); return m_xOutputStream; } NS_UNO::Reference < NS_IO::XSeekable > getSeekable_Impl() const { vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex ); return m_xSeekable; } sal_Bool hasInputStream_Impl() const { vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex ); return m_xInputStream.is(); } void setCommandThread_Impl( CommandThread_Impl* pThread ) { m_pCommandThread = pThread; } void setDontClose_Impl() { m_bDontClose = sal_True; } void SetContentType_Impl( const String& rType ) { m_aContentType = rType; } void SetRealURL_Impl( const String& rURL ) { m_aRealURL = rURL; } void SetExpireDate_Impl( const DateTime& rDateTime ) { m_aExpireDate = rDateTime; } void SetStreamValid_Impl(); #endif }; SV_IMPL_REF( UcbLockBytes ); }; #endif
/* * SessionBreakpoints.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "environment/EnvironmentUtils.hpp" #include <algorithm> #include <boost/bind.hpp> #include <boost/format.hpp> #include <boost/utility.hpp> #include <boost/foreach.hpp> #include <core/Error.hpp> #include <core/Log.hpp> #include <core/Exec.hpp> #include <core/FilePath.hpp> #include <core/json/JsonRpc.hpp> #include <r/RExec.hpp> #include <r/RRoutines.hpp> #include <r/RErrorCategory.hpp> #include <r/RUtil.hpp> #include <r/session/RSession.hpp> #include <r/session/RClientState.hpp> #include <r/Rinternals.h> #include <session/SessionModuleContext.hpp> #include <session/SessionUserSettings.hpp> #include <session/projects/SessionProjects.hpp> using namespace core; using namespace r::sexp; using namespace r::exec; namespace session { namespace modules { namespace breakpoints { namespace { int s_maxShinyFunctionId = 0; // Represents a currently running Shiny function. class ShinyFunction : boost::noncopyable { public: ShinyFunction(SEXP expr, const std::string& name, SEXP where): id_(s_maxShinyFunctionId++), firstLine_(0), lastLine_(0), name_(name), where_(where) { // If the srcref attribute is present on the expression, use it to // compute the first and last lines of the function in the original // source file. SEXP srcref = r::sexp::getAttrib(expr, "srcref"); if (srcref != NULL && TYPEOF(srcref) != NILSXP) { SEXP firstRef = VECTOR_ELT(srcref, 0); firstLine_ = INTEGER(firstRef)[0]; SEXP lastRef = VECTOR_ELT(srcref, r::sexp::length(srcref) - 1); lastLine_ = INTEGER(lastRef)[2]; } // If the srcfile attribute is present, extract it SEXP srcfile = r::sexp::getAttrib(expr, "srcfile"); if (srcfile != NULL && TYPEOF(srcfile) != NILSXP) { SEXP file = r::sexp::findVar("filename", srcfile); r::sexp::extract(file, &srcfilename_); } } bool contains(std::string filename, int line) const { if (!(line >= firstLine_ && line <= lastLine_)) return false; return module_context::resolveAliasedPath(srcfilename_) == module_context::resolveAliasedPath(filename); } int getId() { return id_; } int getSize() { return lastLine_ - firstLine_; } std::string getName() { return name_; } SEXP getWhere() { return where_; } private: int id_; int firstLine_; int lastLine_; std::string name_; std::string srcfilename_; SEXP where_; }; // A list of the Shiny functions we know about (see notes in // rs_registerShinyFunction for an explanation of how this memory is managed) std::vector<boost::shared_ptr<ShinyFunction> > s_shinyFunctions; class Breakpoint : boost::noncopyable { public: int type; int lineNumber; int id; std::string path; Breakpoint(int typeIn, int lineNumberIn, int idIn, std::string pathIn): type(typeIn), lineNumber(lineNumberIn), id(idIn), path(pathIn) {} }; // A list of the breakpoints we know about. Note that this is a slave list; // the client maintains the master copy and is responsible for synchronizing // with this list. This list is maintained so we can inject breakpoints // synchronously when Shiny creates an anonymous function object. std::vector<boost::shared_ptr<Breakpoint> > s_breakpoints; // Returns the Shiny function that contains the given line, if any. // Finds the smallest (innermost) function in the case where more than one // expression encloses the line. boost::shared_ptr<ShinyFunction> findShinyFunction(std::string filename, int line) { boost::shared_ptr<ShinyFunction> bestPsf; int bestSize = INT_MAX; BOOST_FOREACH(boost::shared_ptr<ShinyFunction> psf, s_shinyFunctions) { if (psf->contains(filename, line) && psf->getSize() < bestSize) { bestSize = psf->getSize(); bestPsf = psf; } } return bestPsf; } boost::shared_ptr<Breakpoint> breakpointFromJson(json::Object& obj) { return boost::make_shared<Breakpoint>(obj["type"].get_int(), obj["line_number"].get_int(), obj["id"].get_int(), obj["path"].get_str()); } std::vector<int> getShinyBreakpointLines(const ShinyFunction& sf) { std::vector<int> lines; BOOST_FOREACH(boost::shared_ptr<Breakpoint> pbp, s_breakpoints) { if (sf.contains(pbp->path, pbp->lineNumber)) lines.push_back(pbp->lineNumber); } return lines; } // Runs a series of pre-flight checks to determine whether we can set a // breakpoint at the given location, and, if we can, what kind of breakpoint // we should set. Error getFunctionState(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { json::Object response; std::string functionName, fileName, packageName; int lineNumber = 0; bool inSync = false; Error error = json::readParams( request.params, &functionName, &fileName, &lineNumber); if (error) { return error; } // check whether the function is in a package packageName = module_context::packageNameForSourceFile( module_context::resolveAliasedPath(fileName)); // get the source refs and code for the function SEXP srcRefs = NULL; Protect protect; std::string functionCode; error = r::exec::RFunction(".rs.getFunctionSourceRefs", functionName, fileName, packageName) .call(&srcRefs, &protect); if (!error) { error = r::exec::RFunction(".rs.getFunctionSourceCode", functionName, fileName, packageName) .call(&functionCode); } // compare with the disk if we were able to get the source code; // otherwise, assume it's out of sync if (!error) inSync = !environment::functionDiffersFromSource(srcRefs, functionCode); response["sync_state"] = inSync; response["package_name"] = packageName; response["is_package_function"] = packageName.length() > 0; pResponse->setResult(response); return Success(); } // Sets a breakpoint on a single copy of a function. Invoked several times to // look for function copies in alternate environemnts. Returns true if a // breakpoint was set; false otherwise. bool setBreakpoint(const std::string& functionName, const std::string& fileName, const std::string& packageName, const json::Array& steps) { SEXP env = NULL; Protect protect; Error error = r::exec::RFunction(".rs.getEnvironmentOfFunction", functionName, fileName, packageName) .call(&env, &protect); if (error) { LOG_ERROR(error); return false; } // if we found a function in the requested environment, set the breakpoint if (TYPEOF(env) == ENVSXP) { error = r::exec::RFunction(".rs.setFunctionBreakpoints", functionName, env, steps).call(); if (error) { LOG_ERROR(error); return false; } // successfully set a breakpoint return true; } // did not find the function in the environment return false; } // Set a breakpoint on a function, potentially on multiple copies: // 1. The private copy of the function inside the package under development // (even if from another package; it may be an imported copy) // 2. The private copy of the function inside its own package (if from a // package) // 3. The copy of the function on the global search path // // Note that this is not guaranteed to find ALL copies of the function in ANY // environment--at most, three breakpoints are set. Error setBreakpoints(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string functionName, fileName, packageName; json::Array steps; bool set = false; Error error = json::readParams(request.params, &functionName, &fileName, &packageName, &steps); if (error) return error; // If we're in package development mode, try to set a breakpoint in the // package's namespace first. const projects::ProjectContext& projectContext = projects::projectContext(); if (projectContext.config().buildType == r_util::kBuildTypePackage) { set |= setBreakpoint( functionName, fileName, projectContext.packageInfo().name(), steps); } // If a package name was specified, try to set a breakpoint in that package's // namespace, too. if (packageName.length() > 0) { set |= setBreakpoint(functionName, fileName, packageName, steps); } // Always search the global namespace. set |= setBreakpoint(functionName, fileName, "", steps); // Couldn't find a function to set a breakpoint on--maybe a bad parameter? if (!set) { return Error(json::errc::ParamInvalid, ERROR_LOCATION); } return Success(); } std::vector<boost::shared_ptr<Breakpoint> >::iterator posOfBreakpointId(int id) { std::vector<boost::shared_ptr<Breakpoint> >::iterator psbi; for (psbi = s_breakpoints.begin(); psbi != s_breakpoints.end(); psbi++) { if ((*psbi)->id == id) break; } return psbi; } // Called by the R garbage collector when a Shiny function is cleaned up; // we use this as a trigger to clean up our own references to the function. void unregisterShinyFunction(SEXP ptr) { // Extract the cached pointer ShinyFunction* psf = static_cast<ShinyFunction*> (r::sexp::getExternalPtrAddr(ptr)); if (psf == NULL) return; // Look over each Shiny function we know about; if this was a function // we were tracking, release it. for (std::vector<boost::shared_ptr<ShinyFunction> >::iterator psfi = s_shinyFunctions.begin(); psfi != s_shinyFunctions.end(); psfi++) { if (psfi->get() == psf) { s_shinyFunctions.erase(psfi); break; } } r::sexp::clearExternalPtr(ptr); } // Called by Shiny (through a debug hook set up in tools:rstudio) to register // a Shiny function for debugging. // // 'params' is an ENVSXP expected to contain the following contents: // expr - The original expression from which the Shiny function was generated // fun - The function generated from that expression // name - The name of the variable or field containing the object // where - The environment or reference object containing the object // label - The name to be shown for the object in the debugger // // Sets up a data structure and attaches it to the function as an EXTPTRSXP // attribute; unregistration is performed when R garbage-collects this pointer. void rs_registerShinyFunction(SEXP params) { Protect protect; SEXP expr = r::sexp::findVar("expr", params); SEXP fun = r::sexp::findVar("fun", params); SEXP name = r::sexp::findVar("name", params); SEXP where = r::sexp::findVar("where", params); // Get the name of the object we're about to attach. std::string objName; Error error = r::sexp::extract(name, &objName); if (error) return; boost::shared_ptr<ShinyFunction> psf = boost::make_shared<ShinyFunction>(expr, objName, where); // The Shiny server function itself is always the first one registered when // a Shiny session starts. If we had other functions "running", they // likely simply haven't been GC'ed yet--forcefully clean them up. SEXP isShinyServer = r::sexp::getAttrib(fun, "shinyServerFunction"); if (isShinyServer != NULL && TYPEOF(isShinyServer) != NILSXP) { s_shinyFunctions.clear(); } s_shinyFunctions.push_back(psf); // Attach the information we just created to the Shiny function. SEXP sid = r::sexp::create(psf->getId(), &protect); r::sexp::setAttrib(fun, "_rs_shinyDebugPtr", r::sexp::makeExternalPtr(psf.get(), unregisterShinyFunction, &protect)); r::sexp::setAttrib(fun, "_rs_shinyDebugId", sid); r::sexp::setAttrib(fun, "_rs_shinyDebugLabel", r::sexp::findVar("label", params)); r::exec::RFunction(".rs.setShinyFunction", name, where, fun).call(); // If we found breakpoint lines in this Shiny function, set breakpoints // on it. std::vector<int> lines = getShinyBreakpointLines(*psf); if (lines.size() > 0) { // Copy the function into the Shiny object first r::exec::RFunction(".rs.setShinyBreakpoints", name, where, lines).call(); } } // Initializes the set of breakpoints the server knows about by populating it // from client state (any of these may become a Shiny breakpoint at app boot); // registers the callback from Shiny into RStudio to register a running function Error initBreakpoints() { // Register rs_registerShinyFunction; called from registerShinyDebugHook R_CallMethodDef registerShiny; registerShiny.name = "rs_registerShinyFunction" ; registerShiny.fun = (DL_FUNC)rs_registerShinyFunction; registerShiny.numArgs = 1; r::routines::addCallMethod(registerShiny); // Load breakpoints from client state json::Value breakpointStateValue = r::session::clientState().getProjectPersistent("debug-breakpoints", "debugBreakpointsState"); if (!breakpointStateValue.is_null() && json::isType<core::json::Object>(breakpointStateValue)) { json::Object breakpointState = breakpointStateValue.get_obj(); json::Array breakpointArray = breakpointState["breakpoints"].get_array(); s_breakpoints.clear(); BOOST_FOREACH(json::Value bp, breakpointArray) { if (json::isType<core::json::Object>(bp)) { s_breakpoints.push_back(breakpointFromJson(bp.get_obj())); } } } return Success(); } // Called by the client whenever a top-level breakpoint is set or cleared; // updates breakpoints on the corresponding Shiny functions, if any. Error updateShinyBreakpoints(const json::JsonRpcRequest& request, json::JsonRpcResponse*) { json::Array breakpointArr; bool set = false; Error error = json::readParams(request.params, &breakpointArr, &set); if (error) return error; BOOST_FOREACH(json::Value bp, breakpointArr) { boost::shared_ptr<Breakpoint> breakpoint (breakpointFromJson(bp.get_obj())); std::vector<boost::shared_ptr<Breakpoint> >::iterator psbi = posOfBreakpointId(breakpoint->id); // Erase anything we already know about this breakpoint if (psbi != s_breakpoints.end()) s_breakpoints.erase(psbi); // If setting or updating the brekapoint, reintroduce it if (set) s_breakpoints.push_back(breakpoint); // Is this breakpoint associated with a running Shiny function? boost::shared_ptr<ShinyFunction> psf = findShinyFunction(breakpoint->path, breakpoint->lineNumber); if (psf) { // Collect all the breakpoints associated with this function and // update the function's state std::vector<int> lines = getShinyBreakpointLines(*psf); r::exec::RFunction(".rs.setShinyBreakpoints", psf->getName(), psf->getWhere(), lines).call(); } } return Success(); } } // anonymous namespace json::Value debugStateAsJson() { json::Object state; // look for the debug state environment created by debugSource; if // it exists, emit the pieces the client cares about. SEXP debugState = r::sexp::findVar(".rs.topDebugState"); if (TYPEOF(debugState) == ENVSXP) { state["top_level_debug"] = true; state["debug_step"] = r::sexp::asInteger(r::sexp::findVar("currentDebugStep", debugState)); state["debug_file"] = r::sexp::asString(r::sexp::findVar("currentDebugFile", debugState)); SEXP srcref = r::sexp::findVar("currentDebugSrcref", debugState); environment::sourceRefToJson(srcref, &state); } else { state["top_level_debug"] = json::Value(false); } return state; } bool haveSrcrefAttribute() { // check whether this is R 2.14 or greater bool haveSrcref = false; Error error = r::exec::evaluateString("getRversion() >= '2.14.0'", &haveSrcref); if (error) LOG_ERROR(error); return haveSrcref; } Error initialize() { using boost::bind; using namespace module_context; ExecBlock initBlock ; initBlock.addFunctions() (bind(registerRpcMethod, "get_function_state", getFunctionState)) (bind(registerRpcMethod, "set_function_breakpoints", setBreakpoints)) (bind(registerRpcMethod, "update_shiny_breakpoints", updateShinyBreakpoints)) (bind(sourceModuleRFile, "SessionBreakpoints.R")) (bind(initBreakpoints)); return initBlock.execute(); } } // namepsace breakpoints } // namespace modules } // namesapce session fix build breakage /* * SessionBreakpoints.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "environment/EnvironmentUtils.hpp" #include <algorithm> #include <boost/bind.hpp> #include <boost/format.hpp> #include <boost/utility.hpp> #include <boost/foreach.hpp> #include <core/Error.hpp> #include <core/Log.hpp> #include <core/Exec.hpp> #include <core/FilePath.hpp> #include <core/json/JsonRpc.hpp> #include <r/RExec.hpp> #include <r/RRoutines.hpp> #include <r/RErrorCategory.hpp> #include <r/RUtil.hpp> #include <r/session/RSession.hpp> #include <r/session/RClientState.hpp> #include <r/RInternal.hpp> #include <session/SessionModuleContext.hpp> #include <session/SessionUserSettings.hpp> #include <session/projects/SessionProjects.hpp> using namespace core; using namespace r::sexp; using namespace r::exec; namespace session { namespace modules { namespace breakpoints { namespace { int s_maxShinyFunctionId = 0; // Represents a currently running Shiny function. class ShinyFunction : boost::noncopyable { public: ShinyFunction(SEXP expr, const std::string& name, SEXP where): id_(s_maxShinyFunctionId++), firstLine_(0), lastLine_(0), name_(name), where_(where) { // If the srcref attribute is present on the expression, use it to // compute the first and last lines of the function in the original // source file. SEXP srcref = r::sexp::getAttrib(expr, "srcref"); if (srcref != NULL && TYPEOF(srcref) != NILSXP) { SEXP firstRef = VECTOR_ELT(srcref, 0); firstLine_ = INTEGER(firstRef)[0]; SEXP lastRef = VECTOR_ELT(srcref, r::sexp::length(srcref) - 1); lastLine_ = INTEGER(lastRef)[2]; } // If the srcfile attribute is present, extract it SEXP srcfile = r::sexp::getAttrib(expr, "srcfile"); if (srcfile != NULL && TYPEOF(srcfile) != NILSXP) { SEXP file = r::sexp::findVar("filename", srcfile); r::sexp::extract(file, &srcfilename_); } } bool contains(std::string filename, int line) const { if (!(line >= firstLine_ && line <= lastLine_)) return false; return module_context::resolveAliasedPath(srcfilename_) == module_context::resolveAliasedPath(filename); } int getId() { return id_; } int getSize() { return lastLine_ - firstLine_; } std::string getName() { return name_; } SEXP getWhere() { return where_; } private: int id_; int firstLine_; int lastLine_; std::string name_; std::string srcfilename_; SEXP where_; }; // A list of the Shiny functions we know about (see notes in // rs_registerShinyFunction for an explanation of how this memory is managed) std::vector<boost::shared_ptr<ShinyFunction> > s_shinyFunctions; class Breakpoint : boost::noncopyable { public: int type; int lineNumber; int id; std::string path; Breakpoint(int typeIn, int lineNumberIn, int idIn, std::string pathIn): type(typeIn), lineNumber(lineNumberIn), id(idIn), path(pathIn) {} }; // A list of the breakpoints we know about. Note that this is a slave list; // the client maintains the master copy and is responsible for synchronizing // with this list. This list is maintained so we can inject breakpoints // synchronously when Shiny creates an anonymous function object. std::vector<boost::shared_ptr<Breakpoint> > s_breakpoints; // Returns the Shiny function that contains the given line, if any. // Finds the smallest (innermost) function in the case where more than one // expression encloses the line. boost::shared_ptr<ShinyFunction> findShinyFunction(std::string filename, int line) { boost::shared_ptr<ShinyFunction> bestPsf; int bestSize = INT_MAX; BOOST_FOREACH(boost::shared_ptr<ShinyFunction> psf, s_shinyFunctions) { if (psf->contains(filename, line) && psf->getSize() < bestSize) { bestSize = psf->getSize(); bestPsf = psf; } } return bestPsf; } boost::shared_ptr<Breakpoint> breakpointFromJson(json::Object& obj) { return boost::make_shared<Breakpoint>(obj["type"].get_int(), obj["line_number"].get_int(), obj["id"].get_int(), obj["path"].get_str()); } std::vector<int> getShinyBreakpointLines(const ShinyFunction& sf) { std::vector<int> lines; BOOST_FOREACH(boost::shared_ptr<Breakpoint> pbp, s_breakpoints) { if (sf.contains(pbp->path, pbp->lineNumber)) lines.push_back(pbp->lineNumber); } return lines; } // Runs a series of pre-flight checks to determine whether we can set a // breakpoint at the given location, and, if we can, what kind of breakpoint // we should set. Error getFunctionState(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { json::Object response; std::string functionName, fileName, packageName; int lineNumber = 0; bool inSync = false; Error error = json::readParams( request.params, &functionName, &fileName, &lineNumber); if (error) { return error; } // check whether the function is in a package packageName = module_context::packageNameForSourceFile( module_context::resolveAliasedPath(fileName)); // get the source refs and code for the function SEXP srcRefs = NULL; Protect protect; std::string functionCode; error = r::exec::RFunction(".rs.getFunctionSourceRefs", functionName, fileName, packageName) .call(&srcRefs, &protect); if (!error) { error = r::exec::RFunction(".rs.getFunctionSourceCode", functionName, fileName, packageName) .call(&functionCode); } // compare with the disk if we were able to get the source code; // otherwise, assume it's out of sync if (!error) inSync = !environment::functionDiffersFromSource(srcRefs, functionCode); response["sync_state"] = inSync; response["package_name"] = packageName; response["is_package_function"] = packageName.length() > 0; pResponse->setResult(response); return Success(); } // Sets a breakpoint on a single copy of a function. Invoked several times to // look for function copies in alternate environemnts. Returns true if a // breakpoint was set; false otherwise. bool setBreakpoint(const std::string& functionName, const std::string& fileName, const std::string& packageName, const json::Array& steps) { SEXP env = NULL; Protect protect; Error error = r::exec::RFunction(".rs.getEnvironmentOfFunction", functionName, fileName, packageName) .call(&env, &protect); if (error) { LOG_ERROR(error); return false; } // if we found a function in the requested environment, set the breakpoint if (TYPEOF(env) == ENVSXP) { error = r::exec::RFunction(".rs.setFunctionBreakpoints", functionName, env, steps).call(); if (error) { LOG_ERROR(error); return false; } // successfully set a breakpoint return true; } // did not find the function in the environment return false; } // Set a breakpoint on a function, potentially on multiple copies: // 1. The private copy of the function inside the package under development // (even if from another package; it may be an imported copy) // 2. The private copy of the function inside its own package (if from a // package) // 3. The copy of the function on the global search path // // Note that this is not guaranteed to find ALL copies of the function in ANY // environment--at most, three breakpoints are set. Error setBreakpoints(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string functionName, fileName, packageName; json::Array steps; bool set = false; Error error = json::readParams(request.params, &functionName, &fileName, &packageName, &steps); if (error) return error; // If we're in package development mode, try to set a breakpoint in the // package's namespace first. const projects::ProjectContext& projectContext = projects::projectContext(); if (projectContext.config().buildType == r_util::kBuildTypePackage) { set |= setBreakpoint( functionName, fileName, projectContext.packageInfo().name(), steps); } // If a package name was specified, try to set a breakpoint in that package's // namespace, too. if (packageName.length() > 0) { set |= setBreakpoint(functionName, fileName, packageName, steps); } // Always search the global namespace. set |= setBreakpoint(functionName, fileName, "", steps); // Couldn't find a function to set a breakpoint on--maybe a bad parameter? if (!set) { return Error(json::errc::ParamInvalid, ERROR_LOCATION); } return Success(); } std::vector<boost::shared_ptr<Breakpoint> >::iterator posOfBreakpointId(int id) { std::vector<boost::shared_ptr<Breakpoint> >::iterator psbi; for (psbi = s_breakpoints.begin(); psbi != s_breakpoints.end(); psbi++) { if ((*psbi)->id == id) break; } return psbi; } // Called by the R garbage collector when a Shiny function is cleaned up; // we use this as a trigger to clean up our own references to the function. void unregisterShinyFunction(SEXP ptr) { // Extract the cached pointer ShinyFunction* psf = static_cast<ShinyFunction*> (r::sexp::getExternalPtrAddr(ptr)); if (psf == NULL) return; // Look over each Shiny function we know about; if this was a function // we were tracking, release it. for (std::vector<boost::shared_ptr<ShinyFunction> >::iterator psfi = s_shinyFunctions.begin(); psfi != s_shinyFunctions.end(); psfi++) { if (psfi->get() == psf) { s_shinyFunctions.erase(psfi); break; } } r::sexp::clearExternalPtr(ptr); } // Called by Shiny (through a debug hook set up in tools:rstudio) to register // a Shiny function for debugging. // // 'params' is an ENVSXP expected to contain the following contents: // expr - The original expression from which the Shiny function was generated // fun - The function generated from that expression // name - The name of the variable or field containing the object // where - The environment or reference object containing the object // label - The name to be shown for the object in the debugger // // Sets up a data structure and attaches it to the function as an EXTPTRSXP // attribute; unregistration is performed when R garbage-collects this pointer. void rs_registerShinyFunction(SEXP params) { Protect protect; SEXP expr = r::sexp::findVar("expr", params); SEXP fun = r::sexp::findVar("fun", params); SEXP name = r::sexp::findVar("name", params); SEXP where = r::sexp::findVar("where", params); // Get the name of the object we're about to attach. std::string objName; Error error = r::sexp::extract(name, &objName); if (error) return; boost::shared_ptr<ShinyFunction> psf = boost::make_shared<ShinyFunction>(expr, objName, where); // The Shiny server function itself is always the first one registered when // a Shiny session starts. If we had other functions "running", they // likely simply haven't been GC'ed yet--forcefully clean them up. SEXP isShinyServer = r::sexp::getAttrib(fun, "shinyServerFunction"); if (isShinyServer != NULL && TYPEOF(isShinyServer) != NILSXP) { s_shinyFunctions.clear(); } s_shinyFunctions.push_back(psf); // Attach the information we just created to the Shiny function. SEXP sid = r::sexp::create(psf->getId(), &protect); r::sexp::setAttrib(fun, "_rs_shinyDebugPtr", r::sexp::makeExternalPtr(psf.get(), unregisterShinyFunction, &protect)); r::sexp::setAttrib(fun, "_rs_shinyDebugId", sid); r::sexp::setAttrib(fun, "_rs_shinyDebugLabel", r::sexp::findVar("label", params)); r::exec::RFunction(".rs.setShinyFunction", name, where, fun).call(); // If we found breakpoint lines in this Shiny function, set breakpoints // on it. std::vector<int> lines = getShinyBreakpointLines(*psf); if (lines.size() > 0) { // Copy the function into the Shiny object first r::exec::RFunction(".rs.setShinyBreakpoints", name, where, lines).call(); } } // Initializes the set of breakpoints the server knows about by populating it // from client state (any of these may become a Shiny breakpoint at app boot); // registers the callback from Shiny into RStudio to register a running function Error initBreakpoints() { // Register rs_registerShinyFunction; called from registerShinyDebugHook R_CallMethodDef registerShiny; registerShiny.name = "rs_registerShinyFunction" ; registerShiny.fun = (DL_FUNC)rs_registerShinyFunction; registerShiny.numArgs = 1; r::routines::addCallMethod(registerShiny); // Load breakpoints from client state json::Value breakpointStateValue = r::session::clientState().getProjectPersistent("debug-breakpoints", "debugBreakpointsState"); if (!breakpointStateValue.is_null() && json::isType<core::json::Object>(breakpointStateValue)) { json::Object breakpointState = breakpointStateValue.get_obj(); json::Array breakpointArray = breakpointState["breakpoints"].get_array(); s_breakpoints.clear(); BOOST_FOREACH(json::Value bp, breakpointArray) { if (json::isType<core::json::Object>(bp)) { s_breakpoints.push_back(breakpointFromJson(bp.get_obj())); } } } return Success(); } // Called by the client whenever a top-level breakpoint is set or cleared; // updates breakpoints on the corresponding Shiny functions, if any. Error updateShinyBreakpoints(const json::JsonRpcRequest& request, json::JsonRpcResponse*) { json::Array breakpointArr; bool set = false; Error error = json::readParams(request.params, &breakpointArr, &set); if (error) return error; BOOST_FOREACH(json::Value bp, breakpointArr) { boost::shared_ptr<Breakpoint> breakpoint (breakpointFromJson(bp.get_obj())); std::vector<boost::shared_ptr<Breakpoint> >::iterator psbi = posOfBreakpointId(breakpoint->id); // Erase anything we already know about this breakpoint if (psbi != s_breakpoints.end()) s_breakpoints.erase(psbi); // If setting or updating the brekapoint, reintroduce it if (set) s_breakpoints.push_back(breakpoint); // Is this breakpoint associated with a running Shiny function? boost::shared_ptr<ShinyFunction> psf = findShinyFunction(breakpoint->path, breakpoint->lineNumber); if (psf) { // Collect all the breakpoints associated with this function and // update the function's state std::vector<int> lines = getShinyBreakpointLines(*psf); r::exec::RFunction(".rs.setShinyBreakpoints", psf->getName(), psf->getWhere(), lines).call(); } } return Success(); } } // anonymous namespace json::Value debugStateAsJson() { json::Object state; // look for the debug state environment created by debugSource; if // it exists, emit the pieces the client cares about. SEXP debugState = r::sexp::findVar(".rs.topDebugState"); if (TYPEOF(debugState) == ENVSXP) { state["top_level_debug"] = true; state["debug_step"] = r::sexp::asInteger(r::sexp::findVar("currentDebugStep", debugState)); state["debug_file"] = r::sexp::asString(r::sexp::findVar("currentDebugFile", debugState)); SEXP srcref = r::sexp::findVar("currentDebugSrcref", debugState); environment::sourceRefToJson(srcref, &state); } else { state["top_level_debug"] = json::Value(false); } return state; } bool haveSrcrefAttribute() { // check whether this is R 2.14 or greater bool haveSrcref = false; Error error = r::exec::evaluateString("getRversion() >= '2.14.0'", &haveSrcref); if (error) LOG_ERROR(error); return haveSrcref; } Error initialize() { using boost::bind; using namespace module_context; ExecBlock initBlock ; initBlock.addFunctions() (bind(registerRpcMethod, "get_function_state", getFunctionState)) (bind(registerRpcMethod, "set_function_breakpoints", setBreakpoints)) (bind(registerRpcMethod, "update_shiny_breakpoints", updateShinyBreakpoints)) (bind(sourceModuleRFile, "SessionBreakpoints.R")) (bind(initBreakpoints)); return initBlock.execute(); } } // namepsace breakpoints } // namespace modules } // namesapce session
#include <iostream> #include "vtrc-client-base/vtrc-client.h" #include "vtrc-common/vtrc-pool-pair.h" #include "vtrc-common/vtrc-exception.h" #include "protocol/calculator.pb.h" #include "calculator-iface.h" #include "vtrc-condition-variable.h" #include "vtrc-bind.h" #include "vtrc-ref.h" #include "vtrc-thread.h" #include "vtrc-chrono.h" using namespace vtrc::client; using namespace vtrc::common; void usage( ) { std::cout << "Usage: \n\tcalculator_client <server ip> <server port>\n" << "or:\n\tcalculator_client <localname>\n" << "examples:\n" << "\tfor tcp: calculator_client 127.0.0.1 55555\n" << "\tfor unix: calculator_client /tmp/calculator.sock\n" << "\tfor win pipe: calculator_client \\\\.\\pipe\\calculator_pipe\n"; } struct work_time { typedef vtrc::chrono::high_resolution_clock::time_point time_point; time_point start_; work_time( ) :start_(vtrc::chrono::high_resolution_clock::now( )) {} ~work_time( ) { time_point::duration stop( vtrc::chrono::high_resolution_clock::now( ) - start_); std::cout << "Call time: " << stop << "\n"; } }; class variable_pool: public vtrc_example::variable_pool { std::map<std::string, double> variables_; unsigned server_calback_count_; void set_variable(::google::protobuf::RpcController* controller, const ::vtrc_example::number* request, ::vtrc_example::number* response, ::google::protobuf::Closure* done) { ++server_calback_count_; closure_holder done_holder(done); std::string n(request->name( )); std::cout << "Server sets variable: '" << n << "'" << " = " << request->value( ) << " thread id: " << vtrc::this_thread::get_id( ) << "\n"; variables_[n] = request->value( ); } void get_variable(::google::protobuf::RpcController* controller, const ::vtrc_example::number* request, ::vtrc_example::number* response, ::google::protobuf::Closure* done) { ++server_calback_count_; closure_holder done_holder(done); std::string n(request->name( )); std::cout << "Server wants variable: '" << n << "'" << "; thread id: " << vtrc::this_thread::get_id( ) << "\n"; std::map<std::string, double>::const_iterator f(variables_.find(n)); if( f == variables_.end( ) ) { std::cout << "Client sends exception to server...\n"; std::ostringstream oss; oss << "Variable is not found: '" << n << "'"; throw std::runtime_error( oss.str( ) ); } response->set_value( f->second ); } public: variable_pool( ) :server_calback_count_(0) {} unsigned calls_count( ) const { return server_calback_count_; } void set( std::string const &name, double value ) { /// don't need lock this calls; variables_[name] = value; } }; void tests( vtrc::shared_ptr<vtrc_client> client, vtrc::shared_ptr<variable_pool> vars ) { work_time wt; /// create calculator client interface vtrc::unique_ptr<interfaces::calculator> calc(interfaces::create_calculator( client )); std::string test_name; /// first: simple sum, mul, div, pow std::string splitter( 80, '=' ); splitter += "\n"; std::cout << "My thread id: " << vtrc::this_thread::get_id( ) << "\n"; /** * ======================== FIRST ================================== **/ test_name = "first"; std::cout << splitter << test_name << ":\n"; try { double res = calc->mul( "pi", "e" ); /// CALL std::cout << "\tpi * e = " << res << "\n"; vars->set( test_name, res ); /// now we can use old result } catch( const vtrc::common::exception& ex ) { std::cout << "call '"<< test_name << "' failed: " << ex.what( ) << "; " << ex.additional( ) << "\n"; } /** * ======================== SECOND ================================= **/ test_name = "second"; std::cout << splitter << test_name << ":\n"; try { double res = calc->sum( 17, calc->mul( 3, 5 )); /// CALL std::cout << "\t17 + 3 * 5 = " << res << "\n"; vars->set( test_name, res ); } catch( const vtrc::common::exception& ex ) { std::cout << "call '"<< test_name << "' failed: " << ex.what( ) << "; " << ex.additional( ) << "\n"; } /** * ======================== THRID ================================== **/ test_name = "third"; std::cout << splitter << test_name << ":\n"; try { std::cout << "\tnow we take first and seconds results " << "and make pow(firts, second)\n"; double res = calc->pow( "first", "second" ); /// CALL std::cout << "\tpow(first, second) = " << res << "\n"; vars->set( test_name, res ); } catch( const vtrc::common::exception& ex ) { std::cout << "call '"<< test_name << "' failed: " << ex.what( ) << "; " << ex.additional( ) << "\n"; } /** * ======================== THE TEST THAT FAILED =================== **/ test_name = "failed"; std::cout << splitter << test_name << ":\n"; try { std::cout << "\tDivision by zero\n"; double res = calc->div( "first", 0); /// CALL std::cout << "\tfirst/0 = " << res << "\n"; /// we don't see this out vars->set( test_name, res ); } catch( const vtrc::common::exception& ex ) { /// but see this std::cout << "call '"<< test_name << "' failed: " << ex.what( ) << "; " << ex.additional( ) << "\n"; } /** * ======================== THE TEST THAT FAILED 2 ================= **/ test_name = "failed2"; std::cout << splitter << test_name << ":\n"; try { std::cout << "\tRequesting invalid variabe 'invalid'" << " and make 'invalid' * 1\n"; double res = calc->mul( "invalid", 1 ); /// CALL std::cout << "\t'invalid' * 1 = " << res << "\n"; /// we don't see this out vars->set( test_name, res ); } catch( const vtrc::common::exception& ex ) { /// but see this std::cout << "call '"<< test_name << "' failed: " << ex.what( ) << "; " << ex.additional( ) << "\n"; } std::cout << splitter; std::cout << "Total RPC was made: " << calc->calls_count( ) << "\n"; } void on_client_ready( vtrc::condition_variable &cond ) { cond.notify_all( ); } int main( int argc, char **argv ) try { if( argc < 2 ) { usage( ); return 1; } /// one thread for transport io, and one for calls pool_pair pp(1, 1); /// create client vtrc::shared_ptr<vtrc_client> client(vtrc_client::create(pp)); /// connect slot to 'on_ready' client->get_on_ready( ).connect( vtrc::bind( on_client_ready, vtrc::ref( ready_cond ) ) ); /// connecting client to server if( argc < 3 ) { std::cout << "connecting to '" << argv[1] << "'..."; client->connect( argv[1] ); std::cout << "success\n"; } else { std::cout << "connecting to '" << argv[1] << ":" << argv[2] << "'..."; client->connect( argv[1], argv[2] ); std::cout << "success\n"; } /// set rpc handler for local variable vtrc::shared_ptr<variable_pool> vars(vtrc::make_shared<variable_pool>()); client->assign_weak_rpc_handler( vtrc::weak_ptr<variable_pool>(vars) ); /// wait for client ready; There must be a better way. But anyway ... :))) vtrc::mutex ready_mutex; vtrc::condition_variable ready_cond; vtrc::unique_lock<vtrc::mutex> ready_lock(ready_mutex); ready_cond.wait( ready_lock, vtrc::bind( &vtrc_client::ready, client ) ); /// add some variables vars->set( "pi", 3.1415926 ); vars->set( "e", 2.7182818 ); /// we call 'tests' in another thread, for example vtrc::thread(tests, client, vars).join( ); /// and wait it std::cout << "Server callbacks count: " << vars->calls_count( ) << "\n"; std::cout << "\n\nFINISH\n\n"; return 0; } catch( const std::exception &ex ) { std::cout << "General client error: " << ex.what( ) << "\n"; return 2; } examples #include <iostream> #include "vtrc-client-base/vtrc-client.h" #include "vtrc-common/vtrc-pool-pair.h" #include "vtrc-common/vtrc-exception.h" #include "protocol/calculator.pb.h" #include "calculator-iface.h" #include "vtrc-condition-variable.h" #include "vtrc-bind.h" #include "vtrc-ref.h" #include "vtrc-thread.h" #include "vtrc-chrono.h" using namespace vtrc::client; using namespace vtrc::common; void usage( ) { std::cout << "Usage: \n\tcalculator_client <server ip> <server port>\n" << "or:\n\tcalculator_client <localname>\n" << "examples:\n" << "\tfor tcp: calculator_client 127.0.0.1 55555\n" << "\tfor unix: calculator_client /tmp/calculator.sock\n" << "\tfor win pipe: calculator_client \\\\.\\pipe\\calculator_pipe\n"; } struct work_time { typedef vtrc::chrono::high_resolution_clock::time_point time_point; time_point start_; work_time( ) :start_(vtrc::chrono::high_resolution_clock::now( )) {} ~work_time( ) { time_point::duration stop( vtrc::chrono::high_resolution_clock::now( ) - start_); std::cout << "Call time: " << stop << "\n"; } }; class variable_pool: public vtrc_example::variable_pool { std::map<std::string, double> variables_; unsigned server_calback_count_; void set_variable(::google::protobuf::RpcController* controller, const ::vtrc_example::number* request, ::vtrc_example::number* response, ::google::protobuf::Closure* done) { ++server_calback_count_; closure_holder done_holder(done); std::string n(request->name( )); std::cout << "Server sets variable: '" << n << "'" << " = " << request->value( ) << " thread id: " << vtrc::this_thread::get_id( ) << "\n"; variables_[n] = request->value( ); } void get_variable(::google::protobuf::RpcController* controller, const ::vtrc_example::number* request, ::vtrc_example::number* response, ::google::protobuf::Closure* done) { ++server_calback_count_; closure_holder done_holder(done); std::string n(request->name( )); std::cout << "Server wants variable: '" << n << "'" << "; thread id: " << vtrc::this_thread::get_id( ) << "\n"; std::map<std::string, double>::const_iterator f(variables_.find(n)); if( f == variables_.end( ) ) { std::cout << "Client sends exception to server...\n"; std::ostringstream oss; oss << "Variable is not found: '" << n << "'"; throw std::runtime_error( oss.str( ) ); } response->set_value( f->second ); } public: variable_pool( ) :server_calback_count_(0) {} unsigned calls_count( ) const { return server_calback_count_; } void set( std::string const &name, double value ) { /// don't need lock this calls; variables_[name] = value; } }; void tests( vtrc::shared_ptr<vtrc_client> client, vtrc::shared_ptr<variable_pool> vars ) { work_time wt; /// create calculator client interface vtrc::unique_ptr<interfaces::calculator> calc(interfaces::create_calculator( client )); std::string test_name; /// first: simple sum, mul, div, pow std::string splitter( 80, '=' ); splitter += "\n"; std::cout << "My thread id: " << vtrc::this_thread::get_id( ) << "\n"; /** * ======================== FIRST ================================== **/ test_name = "first"; std::cout << splitter << test_name << ":\n"; try { double res = calc->mul( "pi", "e" ); /// CALL std::cout << "\tpi * e = " << res << "\n"; vars->set( test_name, res ); /// now we can use old result } catch( const vtrc::common::exception& ex ) { std::cout << "call '"<< test_name << "' failed: " << ex.what( ) << "; " << ex.additional( ) << "\n"; } /** * ======================== SECOND ================================= **/ test_name = "second"; std::cout << splitter << test_name << ":\n"; try { double res = calc->sum( 17, calc->mul( 3, 5 )); /// CALL std::cout << "\t17 + 3 * 5 = " << res << "\n"; vars->set( test_name, res ); } catch( const vtrc::common::exception& ex ) { std::cout << "call '"<< test_name << "' failed: " << ex.what( ) << "; " << ex.additional( ) << "\n"; } /** * ======================== THRID ================================== **/ test_name = "third"; std::cout << splitter << test_name << ":\n"; try { std::cout << "\tnow we take first and seconds results " << "and make pow(firts, second)\n"; double res = calc->pow( "first", "second" ); /// CALL std::cout << "\tpow(first, second) = " << res << "\n"; vars->set( test_name, res ); } catch( const vtrc::common::exception& ex ) { std::cout << "call '"<< test_name << "' failed: " << ex.what( ) << "; " << ex.additional( ) << "\n"; } /** * ======================== THE TEST THAT FAILED =================== **/ test_name = "failed"; std::cout << splitter << test_name << ":\n"; try { std::cout << "\tDivision by zero\n"; double res = calc->div( "first", 0); /// CALL std::cout << "\tfirst/0 = " << res << "\n"; /// we don't see this out vars->set( test_name, res ); } catch( const vtrc::common::exception& ex ) { /// but see this std::cout << "call '"<< test_name << "' failed: " << ex.what( ) << "; " << ex.additional( ) << "\n"; } /** * ======================== THE TEST THAT FAILED 2 ================= **/ test_name = "failed2"; std::cout << splitter << test_name << ":\n"; try { std::cout << "\tRequesting invalid variabe 'invalid'" << " and make 'invalid' * 1\n"; double res = calc->mul( "invalid", 1 ); /// CALL std::cout << "\t'invalid' * 1 = " << res << "\n"; /// we don't see this out vars->set( test_name, res ); } catch( const vtrc::common::exception& ex ) { /// but see this std::cout << "call '"<< test_name << "' failed: " << ex.what( ) << "; " << ex.additional( ) << "\n"; } std::cout << splitter; std::cout << "Total RPC was made: " << calc->calls_count( ) << "\n"; } void on_client_ready( vtrc::condition_variable &cond ) { cond.notify_all( ); } int main( int argc, char **argv ) try { if( argc < 2 ) { usage( ); return 1; } /// one thread for transport io, and one for calls pool_pair pp(1, 1); /// create client vtrc::shared_ptr<vtrc_client> client(vtrc_client::create(pp)); /// connect slot to 'on_ready' vtrc::condition_variable ready_cond; client->get_on_ready( ).connect( vtrc::bind( on_client_ready, vtrc::ref( ready_cond ) ) ); /// connecting client to server if( argc < 3 ) { std::cout << "connecting to '" << argv[1] << "'..."; client->connect( argv[1] ); std::cout << "success\n"; } else { std::cout << "connecting to '" << argv[1] << ":" << argv[2] << "'..."; client->connect( argv[1], argv[2] ); std::cout << "success\n"; } /// set rpc handler for local variable vtrc::shared_ptr<variable_pool> vars(vtrc::make_shared<variable_pool>()); client->assign_weak_rpc_handler( vtrc::weak_ptr<variable_pool>(vars) ); /// wait for client ready; There must be a better way. But anyway ... :))) vtrc::mutex ready_mutex; vtrc::unique_lock<vtrc::mutex> ready_lock(ready_mutex); ready_cond.wait( ready_lock, vtrc::bind( &vtrc_client::ready, client ) ); /// add some variables vars->set( "pi", 3.1415926 ); vars->set( "e", 2.7182818 ); /// we call 'tests' in another thread, for example vtrc::thread(tests, client, vars).join( ); /// and wait it std::cout << "Server callbacks count: " << vars->calls_count( ) << "\n"; std::cout << "\n\nFINISH\n\n"; return 0; } catch( const std::exception &ex ) { std::cout << "General client error: " << ex.what( ) << "\n"; return 2; }
// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com> // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #include <string.h> // memcpy #include <nvcore/Containers.h> // nextPowerOfTwo #include <nvcore/Memory.h> #include "nvtt.h" #include "InputOptions.h" using namespace nv; using namespace nvtt; namespace { static uint countMipmaps(int w, int h, int d) { uint mipmap = 0; while (w != 1 || h != 1 || d != 1) { w = max(1, w / 2); h = max(1, h / 2); d = max(1, d / 2); mipmap++; } return mipmap + 1; } // 1 -> 1, 2 -> 2, 3 -> 2, 4 -> 4, 5 -> 4, ... static uint previousPowerOfTwo(const uint v) { return nextPowerOfTwo(v + 1) / 2; } static uint nearestPowerOfTwo(const uint v) { const uint np2 = nextPowerOfTwo(v); const uint pp2 = previousPowerOfTwo(v); if (np2 - v <= v - pp2) { return np2; } else { return pp2; } } } // namespace /// Constructor. InputOptions::InputOptions() : m(*new InputOptions::Private()) { reset(); } // Delete images. InputOptions::~InputOptions() { resetTextureLayout(); delete &m; } // Reset input options. void InputOptions::reset() { m.wrapMode = WrapMode_Mirror; m.textureType = TextureType_2D; m.inputFormat = InputFormat_BGRA_8UB; m.alphaMode = AlphaMode_Transparency; m.inputGamma = 2.2f; m.outputGamma = 2.2f; m.colorTransform = ColorTransform_None; m.linearTransform = Matrix(identity); for (int i = 0; i < 4; i++) m.colorOffsets[i] = 0; for (int i = 0; i < 4; i++) m.swizzleTransform[i] = i; m.generateMipmaps = true; m.maxLevel = -1; m.mipmapFilter = MipmapFilter_Box; m.kaiserWidth = 3; m.kaiserAlpha = 4.0f; m.kaiserStretch = 1.0f; m.isNormalMap = false; m.normalizeMipmaps = true; m.convertToNormalMap = false; m.heightFactors.set(0.0f, 0.0f, 0.0f, 1.0f); m.bumpFrequencyScale = Vector4(1.0f, 0.5f, 0.25f, 0.125f) / (1.0f + 0.5f + 0.25f + 0.125f); m.maxExtent = 0; m.roundMode = RoundMode_None; m.premultiplyAlpha = false; } // Setup the input image. void InputOptions::setTextureLayout(TextureType type, int width, int height, int depth /*= 1*/) { // Validate arguments. nvCheck(width >= 0); nvCheck(height >= 0); nvCheck(depth >= 0); // Correct arguments. if (width == 0) width = 1; if (height == 0) height = 1; if (depth == 0) depth = 1; // Delete previous images. resetTextureLayout(); m.textureType = type; // Allocate images. m.mipmapCount = countMipmaps(width, height, depth); m.faceCount = (type == TextureType_Cube) ? 6 : 1; m.imageCount = m.mipmapCount * m.faceCount; m.images = new Private::InputImage[m.imageCount]; for(uint f = 0; f < m.faceCount; f++) { uint w = width; uint h = height; uint d = depth; for (uint mipLevel = 0; mipLevel < m.mipmapCount; mipLevel++) { Private::InputImage & img = m.images[f * m.mipmapCount + mipLevel]; img.width = w; img.height = h; img.depth = d; img.mipLevel = mipLevel; img.face = f; img.uint8data = NULL; img.floatdata = NULL; w = max(1U, w / 2); h = max(1U, h / 2); d = max(1U, d / 2); } } } void InputOptions::resetTextureLayout() { if (m.images != NULL) { // Delete image array. delete [] m.images; m.images = NULL; m.faceCount = 0; m.mipmapCount = 0; m.imageCount = 0; } } // Copies the data to our internal structures. bool InputOptions::setMipmapData(const void * data, int width, int height, int depth /*= 1*/, int face /*= 0*/, int mipLevel /*= 0*/) { nvCheck(depth == 1); const int idx = face * m.mipmapCount + mipLevel; if (m.images[idx].width != width || m.images[idx].height != height || m.images[idx].depth != depth || m.images[idx].mipLevel != mipLevel || m.images[idx].face != face) { // Invalid dimension or index. return false; } switch(m.inputFormat) { case InputFormat_BGRA_8UB: if (Image * image = new nv::Image()) { image->allocate(width, height); memcpy(image->pixels(), data, width * height * 4); m.images[idx].uint8data = image; } else { // @@ Out of memory error. return false; } break; case InputFormat_RGBA_32F: if (FloatImage * image = new nv::FloatImage()) { const float * floatData = (const float *)data; image->allocate(4, width, height); for (int c = 0; c < 4; c++) { float * channel = image->channel(c); for (int i = 0; i < width * height; i++) { channel[i] = floatData[i*4 + c]; } } m.images[idx].floatdata = image; } else { // @@ Out of memory error. return false; } break; default: return false; } return true; } /// Describe the format of the input. void InputOptions::setFormat(InputFormat format) { m.inputFormat = format; } /// Set the way the input alpha channel is interpreted. void InputOptions::setAlphaMode(AlphaMode alphaMode) { m.alphaMode = alphaMode; } /// Set gamma settings. void InputOptions::setGamma(float inputGamma, float outputGamma) { m.inputGamma = inputGamma; m.outputGamma = outputGamma; } /// Set texture wrappign mode. void InputOptions::setWrapMode(WrapMode mode) { m.wrapMode = mode; } /// Set mipmap filter. void InputOptions::setMipmapFilter(MipmapFilter filter) { m.mipmapFilter = filter; } /// Set mipmap generation. void InputOptions::setMipmapGeneration(bool enabled, int maxLevel/*= -1*/) { m.generateMipmaps = enabled; m.maxLevel = maxLevel; } /// Set Kaiser filter parameters. void InputOptions::setKaiserParameters(float width, float alpha, float stretch) { m.kaiserWidth = width; m.kaiserAlpha = alpha; m.kaiserStretch = stretch; } /// Indicate whether input is a normal map or not. void InputOptions::setNormalMap(bool b) { m.isNormalMap = b; } /// Enable normal map conversion. void InputOptions::setConvertToNormalMap(bool convert) { m.convertToNormalMap = convert; } /// Set height evaluation factors. void InputOptions::setHeightEvaluation(float redScale, float greenScale, float blueScale, float alphaScale) { // Do not normalize height factors. // float total = redScale + greenScale + blueScale + alphaScale; m.heightFactors = Vector4(redScale, greenScale, blueScale, alphaScale); } /// Set normal map conversion filter. void InputOptions::setNormalFilter(float small, float medium, float big, float large) { float total = small + medium + big + large; m.bumpFrequencyScale = Vector4(small, medium, big, large) / total; } /// Enable mipmap normalization. void InputOptions::setNormalizeMipmaps(bool normalize) { m.normalizeMipmaps = normalize; } /// Set color transform. void InputOptions::setColorTransform(ColorTransform t) { m.colorTransform = t; } // Set linear transform for the given channel. void InputOptions::setLinearTransform(int channel, float w0, float w1, float w2, float w3) { nvCheck(channel >= 0 && channel < 4); m.linearTransform(0, channel) = w0; m.linearTransform(1, channel) = w1; m.linearTransform(2, channel) = w2; m.linearTransform(3, channel) = w3; } void InputOptions::setLinearTransform(int channel, float w0, float w1, float w2, float w3, float offset) { nvCheck(channel >= 0 && channel < 4); setLinearTransform(channel, w0, w1, w2, w3); m.colorOffsets[channel] = offset; } void InputOptions::setSwizzleTransform(int x, int y, int z, int w) { nvCheck(x >= 0 && x <= 6); nvCheck(y >= 0 && y <= 6); nvCheck(z >= 0 && z <= 6); nvCheck(w >= 0 && w <= 6); m.swizzleTransform[0] = x; m.swizzleTransform[1] = y; m.swizzleTransform[2] = z; m.swizzleTransform[3] = w; } void InputOptions::setMaxExtents(int e) { nvDebugCheck(e > 0); m.maxExtent = e; } void InputOptions::setRoundMode(RoundMode mode) { m.roundMode = mode; } void InputOptions::setPremultiplyAlpha(bool b) { m.premultiplyAlpha = b; } void InputOptions::Private::computeTargetExtents() const { nvCheck(images != NULL); uint maxExtent = this->maxExtent; if (roundMode != RoundMode_None) { // rounded max extent should never be higher than original max extent. maxExtent = previousPowerOfTwo(maxExtent); } uint w = images->width; uint h = images->height; uint d = images->depth; nvDebugCheck(w > 0); nvDebugCheck(h > 0); nvDebugCheck(d > 0); // Scale extents without changing aspect ratio. uint maxwhd = max(max(w, h), d); if (maxExtent != 0 && maxwhd > maxExtent) { w = max((w * maxExtent) / maxwhd, 1U); h = max((h * maxExtent) / maxwhd, 1U); d = max((d * maxExtent) / maxwhd, 1U); } // Round to power of two. if (roundMode == RoundMode_ToNextPowerOfTwo) { w = nextPowerOfTwo(w); h = nextPowerOfTwo(h); d = nextPowerOfTwo(d); } else if (roundMode == RoundMode_ToNearestPowerOfTwo) { w = nearestPowerOfTwo(w); h = nearestPowerOfTwo(h); d = nearestPowerOfTwo(d); } else if (roundMode == RoundMode_ToPreviousPowerOfTwo) { w = previousPowerOfTwo(w); h = previousPowerOfTwo(h); d = previousPowerOfTwo(d); } this->targetWidth = w; this->targetHeight = h; this->targetDepth = d; this->targetMipmapCount = countMipmaps(w, h, d); } // Return real number of mipmaps, including first level. // computeTargetExtents should have been called before. int InputOptions::Private::realMipmapCount() const { int mipmapCount = targetMipmapCount; if (!generateMipmaps) mipmapCount = 1; else if (maxLevel != -1 && maxLevel < mipmapCount - 1) mipmapCount = maxLevel + 1; return mipmapCount; } const Image * InputOptions::Private::image(uint face, uint mipmap) const { nvDebugCheck(face < faceCount); nvDebugCheck(mipmap < mipmapCount); const InputImage & image = this->images[face * mipmapCount + mipmap]; nvDebugCheck(image.face == face); nvDebugCheck(image.mipLevel == mipmap); return image.uint8data.ptr(); } const Image * InputOptions::Private::image(uint idx) const { nvDebugCheck(idx < faceCount * mipmapCount); const InputImage & image = this->images[idx]; return image.uint8data.ptr(); } const FloatImage * InputOptions::Private::floatImage(uint idx) const { nvDebugCheck(idx < faceCount * mipmapCount); const InputImage & image = this->images[idx]; return image.floatdata.ptr(); } Fix color transforms. // Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com> // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #include <string.h> // memcpy #include <nvcore/Containers.h> // nextPowerOfTwo #include <nvcore/Memory.h> #include "nvtt.h" #include "InputOptions.h" using namespace nv; using namespace nvtt; namespace { static uint countMipmaps(int w, int h, int d) { uint mipmap = 0; while (w != 1 || h != 1 || d != 1) { w = max(1, w / 2); h = max(1, h / 2); d = max(1, d / 2); mipmap++; } return mipmap + 1; } // 1 -> 1, 2 -> 2, 3 -> 2, 4 -> 4, 5 -> 4, ... static uint previousPowerOfTwo(const uint v) { return nextPowerOfTwo(v + 1) / 2; } static uint nearestPowerOfTwo(const uint v) { const uint np2 = nextPowerOfTwo(v); const uint pp2 = previousPowerOfTwo(v); if (np2 - v <= v - pp2) { return np2; } else { return pp2; } } } // namespace /// Constructor. InputOptions::InputOptions() : m(*new InputOptions::Private()) { reset(); } // Delete images. InputOptions::~InputOptions() { resetTextureLayout(); delete &m; } // Reset input options. void InputOptions::reset() { m.wrapMode = WrapMode_Mirror; m.textureType = TextureType_2D; m.inputFormat = InputFormat_BGRA_8UB; m.alphaMode = AlphaMode_Transparency; m.inputGamma = 2.2f; m.outputGamma = 2.2f; m.colorTransform = ColorTransform_None; m.linearTransform = Matrix(identity); for (int i = 0; i < 4; i++) m.colorOffsets[i] = 0; for (int i = 0; i < 4; i++) m.swizzleTransform[i] = i; m.generateMipmaps = true; m.maxLevel = -1; m.mipmapFilter = MipmapFilter_Box; m.kaiserWidth = 3; m.kaiserAlpha = 4.0f; m.kaiserStretch = 1.0f; m.isNormalMap = false; m.normalizeMipmaps = true; m.convertToNormalMap = false; m.heightFactors.set(0.0f, 0.0f, 0.0f, 1.0f); m.bumpFrequencyScale = Vector4(1.0f, 0.5f, 0.25f, 0.125f) / (1.0f + 0.5f + 0.25f + 0.125f); m.maxExtent = 0; m.roundMode = RoundMode_None; m.premultiplyAlpha = false; } // Setup the input image. void InputOptions::setTextureLayout(TextureType type, int width, int height, int depth /*= 1*/) { // Validate arguments. nvCheck(width >= 0); nvCheck(height >= 0); nvCheck(depth >= 0); // Correct arguments. if (width == 0) width = 1; if (height == 0) height = 1; if (depth == 0) depth = 1; // Delete previous images. resetTextureLayout(); m.textureType = type; // Allocate images. m.mipmapCount = countMipmaps(width, height, depth); m.faceCount = (type == TextureType_Cube) ? 6 : 1; m.imageCount = m.mipmapCount * m.faceCount; m.images = new Private::InputImage[m.imageCount]; for(uint f = 0; f < m.faceCount; f++) { uint w = width; uint h = height; uint d = depth; for (uint mipLevel = 0; mipLevel < m.mipmapCount; mipLevel++) { Private::InputImage & img = m.images[f * m.mipmapCount + mipLevel]; img.width = w; img.height = h; img.depth = d; img.mipLevel = mipLevel; img.face = f; img.uint8data = NULL; img.floatdata = NULL; w = max(1U, w / 2); h = max(1U, h / 2); d = max(1U, d / 2); } } } void InputOptions::resetTextureLayout() { if (m.images != NULL) { // Delete image array. delete [] m.images; m.images = NULL; m.faceCount = 0; m.mipmapCount = 0; m.imageCount = 0; } } // Copies the data to our internal structures. bool InputOptions::setMipmapData(const void * data, int width, int height, int depth /*= 1*/, int face /*= 0*/, int mipLevel /*= 0*/) { nvCheck(depth == 1); const int idx = face * m.mipmapCount + mipLevel; if (m.images[idx].width != width || m.images[idx].height != height || m.images[idx].depth != depth || m.images[idx].mipLevel != mipLevel || m.images[idx].face != face) { // Invalid dimension or index. return false; } switch(m.inputFormat) { case InputFormat_BGRA_8UB: if (Image * image = new nv::Image()) { image->allocate(width, height); memcpy(image->pixels(), data, width * height * 4); m.images[idx].uint8data = image; } else { // @@ Out of memory error. return false; } break; case InputFormat_RGBA_32F: if (FloatImage * image = new nv::FloatImage()) { const float * floatData = (const float *)data; image->allocate(4, width, height); for (int c = 0; c < 4; c++) { float * channel = image->channel(c); for (int i = 0; i < width * height; i++) { channel[i] = floatData[i*4 + c]; } } m.images[idx].floatdata = image; } else { // @@ Out of memory error. return false; } break; default: return false; } return true; } /// Describe the format of the input. void InputOptions::setFormat(InputFormat format) { m.inputFormat = format; } /// Set the way the input alpha channel is interpreted. void InputOptions::setAlphaMode(AlphaMode alphaMode) { m.alphaMode = alphaMode; } /// Set gamma settings. void InputOptions::setGamma(float inputGamma, float outputGamma) { m.inputGamma = inputGamma; m.outputGamma = outputGamma; } /// Set texture wrappign mode. void InputOptions::setWrapMode(WrapMode mode) { m.wrapMode = mode; } /// Set mipmap filter. void InputOptions::setMipmapFilter(MipmapFilter filter) { m.mipmapFilter = filter; } /// Set mipmap generation. void InputOptions::setMipmapGeneration(bool enabled, int maxLevel/*= -1*/) { m.generateMipmaps = enabled; m.maxLevel = maxLevel; } /// Set Kaiser filter parameters. void InputOptions::setKaiserParameters(float width, float alpha, float stretch) { m.kaiserWidth = width; m.kaiserAlpha = alpha; m.kaiserStretch = stretch; } /// Indicate whether input is a normal map or not. void InputOptions::setNormalMap(bool b) { m.isNormalMap = b; } /// Enable normal map conversion. void InputOptions::setConvertToNormalMap(bool convert) { m.convertToNormalMap = convert; } /// Set height evaluation factors. void InputOptions::setHeightEvaluation(float redScale, float greenScale, float blueScale, float alphaScale) { // Do not normalize height factors. // float total = redScale + greenScale + blueScale + alphaScale; m.heightFactors = Vector4(redScale, greenScale, blueScale, alphaScale); } /// Set normal map conversion filter. void InputOptions::setNormalFilter(float small, float medium, float big, float large) { float total = small + medium + big + large; m.bumpFrequencyScale = Vector4(small, medium, big, large) / total; } /// Enable mipmap normalization. void InputOptions::setNormalizeMipmaps(bool normalize) { m.normalizeMipmaps = normalize; } /// Set color transform. void InputOptions::setColorTransform(ColorTransform t) { m.colorTransform = t; } // Set linear transform for the given channel. void InputOptions::setLinearTransform(int channel, float w0, float w1, float w2, float w3) { nvCheck(channel >= 0 && channel < 4); m.linearTransform(channel, 0) = w0; m.linearTransform(channel, 1) = w1; m.linearTransform(channel, 2) = w2; m.linearTransform(channel, 3) = w3; } void InputOptions::setLinearTransform(int channel, float w0, float w1, float w2, float w3, float offset) { nvCheck(channel >= 0 && channel < 4); setLinearTransform(channel, w0, w1, w2, w3); m.colorOffsets[channel] = offset; } void InputOptions::setSwizzleTransform(int x, int y, int z, int w) { nvCheck(x >= 0 && x <= 6); nvCheck(y >= 0 && y <= 6); nvCheck(z >= 0 && z <= 6); nvCheck(w >= 0 && w <= 6); m.swizzleTransform[0] = x; m.swizzleTransform[1] = y; m.swizzleTransform[2] = z; m.swizzleTransform[3] = w; } void InputOptions::setMaxExtents(int e) { nvDebugCheck(e > 0); m.maxExtent = e; } void InputOptions::setRoundMode(RoundMode mode) { m.roundMode = mode; } void InputOptions::setPremultiplyAlpha(bool b) { m.premultiplyAlpha = b; } void InputOptions::Private::computeTargetExtents() const { nvCheck(images != NULL); uint maxExtent = this->maxExtent; if (roundMode != RoundMode_None) { // rounded max extent should never be higher than original max extent. maxExtent = previousPowerOfTwo(maxExtent); } uint w = images->width; uint h = images->height; uint d = images->depth; nvDebugCheck(w > 0); nvDebugCheck(h > 0); nvDebugCheck(d > 0); // Scale extents without changing aspect ratio. uint maxwhd = max(max(w, h), d); if (maxExtent != 0 && maxwhd > maxExtent) { w = max((w * maxExtent) / maxwhd, 1U); h = max((h * maxExtent) / maxwhd, 1U); d = max((d * maxExtent) / maxwhd, 1U); } // Round to power of two. if (roundMode == RoundMode_ToNextPowerOfTwo) { w = nextPowerOfTwo(w); h = nextPowerOfTwo(h); d = nextPowerOfTwo(d); } else if (roundMode == RoundMode_ToNearestPowerOfTwo) { w = nearestPowerOfTwo(w); h = nearestPowerOfTwo(h); d = nearestPowerOfTwo(d); } else if (roundMode == RoundMode_ToPreviousPowerOfTwo) { w = previousPowerOfTwo(w); h = previousPowerOfTwo(h); d = previousPowerOfTwo(d); } this->targetWidth = w; this->targetHeight = h; this->targetDepth = d; this->targetMipmapCount = countMipmaps(w, h, d); } // Return real number of mipmaps, including first level. // computeTargetExtents should have been called before. int InputOptions::Private::realMipmapCount() const { int mipmapCount = targetMipmapCount; if (!generateMipmaps) mipmapCount = 1; else if (maxLevel != -1 && maxLevel < mipmapCount - 1) mipmapCount = maxLevel + 1; return mipmapCount; } const Image * InputOptions::Private::image(uint face, uint mipmap) const { nvDebugCheck(face < faceCount); nvDebugCheck(mipmap < mipmapCount); const InputImage & image = this->images[face * mipmapCount + mipmap]; nvDebugCheck(image.face == face); nvDebugCheck(image.mipLevel == mipmap); return image.uint8data.ptr(); } const Image * InputOptions::Private::image(uint idx) const { nvDebugCheck(idx < faceCount * mipmapCount); const InputImage & image = this->images[idx]; return image.uint8data.ptr(); } const FloatImage * InputOptions::Private::floatImage(uint idx) const { nvDebugCheck(idx < faceCount * mipmapCount); const InputImage & image = this->images[idx]; return image.floatdata.ptr(); }
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include <comphelper/propertysequence.hxx> #include <cppuhelper/implbase.hxx> #include <cppuhelper/supportsservice.hxx> #include <cppuhelper/weakref.hxx> #include <framework/imageproducer.hxx> #include <svtools/toolboxcontroller.hxx> #include <toolkit/helper/vclunohelper.hxx> #include <tools/gen.hxx> #include <vcl/svapp.hxx> #include <vcl/toolbox.hxx> #include <com/sun/star/awt/XDockableWindow.hpp> #include <com/sun/star/frame/XSubToolbarController.hpp> #include <com/sun/star/frame/status/ItemStatus.hpp> #include <com/sun/star/frame/status/Visibility.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/ui/theUIElementFactoryManager.hpp> typedef cppu::ImplInheritanceHelper< svt::ToolboxController, css::frame::XSubToolbarController, css::awt::XDockableWindowListener, css::lang::XServiceInfo > ToolBarBase; class SubToolBarController : public ToolBarBase { OUString m_aSubTbName; OUString m_aLastCommand; css::uno::Reference< css::ui::XUIElement > m_xUIElement; void disposeUIElement(); public: explicit SubToolBarController( const css::uno::Sequence< css::uno::Any >& rxArgs ); virtual ~SubToolBarController(); // XStatusListener virtual void SAL_CALL statusChanged( const css::frame::FeatureStateEvent& Event ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XToolbarController virtual void SAL_CALL execute( sal_Int16 nKeyModifier ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual css::uno::Reference< css::awt::XWindow > SAL_CALL createPopupWindow() throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XSubToolbarController virtual sal_Bool SAL_CALL opensSubToolbar() throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual OUString SAL_CALL getSubToolbarName() throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual void SAL_CALL functionSelected( const OUString& rCommand ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual void SAL_CALL updateImage() throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XDockableWindowListener virtual void SAL_CALL startDocking( const css::awt::DockingEvent& e ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual css::awt::DockingData SAL_CALL docking( const css::awt::DockingEvent& e ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual void SAL_CALL endDocking( const css::awt::EndDockingEvent& e ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual sal_Bool SAL_CALL prepareToggleFloatingMode( const css::lang::EventObject& e ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual void SAL_CALL toggleFloatingMode( const css::lang::EventObject& e ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual void SAL_CALL closed( const css::lang::EventObject& e ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual void SAL_CALL endPopupMode( const css::awt::EndPopupModeEvent& e ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XEventListener virtual void SAL_CALL disposing( const css::lang::EventObject& e ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XUpdatable virtual void SAL_CALL update() throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XComponent virtual void SAL_CALL dispose() throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw ( css::uno::RuntimeException ) SAL_OVERRIDE; virtual sal_Bool SAL_CALL supportsService( const OUString& rServiceName ) throw ( css::uno::RuntimeException ) SAL_OVERRIDE; virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() throw ( css::uno::RuntimeException ) SAL_OVERRIDE; }; SubToolBarController::SubToolBarController( const css::uno::Sequence< css::uno::Any >& rxArgs ) { css::beans::PropertyValue aPropValue; for ( sal_Int32 i = 0; i < rxArgs.getLength(); ++i ) { rxArgs[i] >>= aPropValue; if ( aPropValue.Name == "Value" ) { OUString aValue; aPropValue.Value >>= aValue; m_aSubTbName = aValue.getToken(0, ';'); m_aLastCommand = aValue.getToken(1, ';'); break; } } if ( !m_aLastCommand.isEmpty() ) addStatusListener( m_aLastCommand ); } SubToolBarController::~SubToolBarController() { disposeUIElement(); m_xUIElement = 0; } void SubToolBarController::disposeUIElement() { if ( m_xUIElement.is() ) { css::uno::Reference< css::lang::XComponent > xComponent( m_xUIElement, css::uno::UNO_QUERY ); xComponent->dispose(); } } void SubToolBarController::statusChanged( const css::frame::FeatureStateEvent& Event ) throw ( css::uno::RuntimeException, std::exception ) { SolarMutexGuard aSolarMutexGuard; if ( m_bDisposed ) return; ToolBox* pToolBox = 0; sal_uInt16 nId = 0; if ( getToolboxId( nId, &pToolBox ) ) { ToolBoxItemBits nItemBits = pToolBox->GetItemBits( nId ); nItemBits &= ~ToolBoxItemBits::CHECKABLE; TriState eTri = TRISTATE_FALSE; if ( Event.FeatureURL.Complete == m_aCommandURL ) { pToolBox->EnableItem( nId, Event.IsEnabled ); OUString aStrValue; css::frame::status::Visibility aItemVisibility; if ( Event.State >>= aStrValue ) { // Enum command, such as the current custom shape, // toggle checked state. if ( m_aLastCommand == OUString( m_aCommandURL + "." + aStrValue ) ) { eTri = TRISTATE_TRUE; nItemBits |= ToolBoxItemBits::CHECKABLE; } } else if ( Event.State >>= aItemVisibility ) { pToolBox->ShowItem( nId, aItemVisibility.bVisible ); } } else { bool bValue; if ( Event.State >>= bValue ) { // Boolean, treat it as checked/unchecked if ( bValue ) eTri = TRISTATE_TRUE; nItemBits |= ToolBoxItemBits::CHECKABLE; } } pToolBox->SetItemState( nId, eTri ); pToolBox->SetItemBits( nId, nItemBits ); } } void SubToolBarController::execute( sal_Int16 nKeyModifier ) throw ( css::uno::RuntimeException, std::exception ) { if ( !m_aLastCommand.isEmpty() ) { auto aArgs( comphelper::InitPropertySequence( { { "KeyModifier", css::uno::makeAny( nKeyModifier ) } } ) ); dispatchCommand( m_aLastCommand, aArgs ); } } css::uno::Reference< css::awt::XWindow > SubToolBarController::createPopupWindow() throw ( css::uno::RuntimeException, std::exception ) { SolarMutexGuard aGuard; ToolBox* pToolBox = 0; sal_uInt16 nId = 0; if ( getToolboxId( nId, &pToolBox ) ) { css::uno::Reference< css::frame::XFrame > xFrame ( getFrameInterface() ); // create element with factory static css::uno::WeakReference< css::ui::XUIElementFactoryManager > xWeakUIElementFactory; css::uno::Reference< css::ui::XUIElement > xUIElement; css::uno::Reference< css::ui::XUIElementFactoryManager > xUIElementFactory; xUIElementFactory = xWeakUIElementFactory; if ( !xUIElementFactory.is() ) { xUIElementFactory = css::ui::theUIElementFactoryManager::get( m_xContext ); xWeakUIElementFactory = xUIElementFactory; } auto aPropSeq( comphelper::InitPropertySequence( { { "Frame", css::uno::makeAny( xFrame ) }, { "Persistent", css::uno::makeAny( false ) }, { "PopupMode", css::uno::makeAny( true ) } } ) ); try { xUIElement = xUIElementFactory->createUIElement( "private:resource/toolbar/" + m_aSubTbName, aPropSeq ); } catch ( css::container::NoSuchElementException& ) {} catch ( css::lang::IllegalArgumentException& ) {} if ( xUIElement.is() ) { css::uno::Reference< css::awt::XWindow > xParent = xFrame->getContainerWindow(); css::uno::Reference< css::awt::XWindow > xSubToolBar( xUIElement->getRealInterface(), css::uno::UNO_QUERY ); if ( xSubToolBar.is() ) { css::uno::Reference< css::awt::XDockableWindow > xDockWindow( xSubToolBar, css::uno::UNO_QUERY ); xDockWindow->addDockableWindowListener( css::uno::Reference< css::awt::XDockableWindowListener >( static_cast< OWeakObject * >( this ), css::uno::UNO_QUERY ) ); xDockWindow->enableDocking( sal_True ); // keep reference to UIElement to avoid its destruction disposeUIElement(); m_xUIElement = xUIElement; vcl::Window* pTbxWindow = VCLUnoHelper::GetWindow( xSubToolBar ); if ( pTbxWindow && pTbxWindow->GetType() == WINDOW_TOOLBOX ) { ToolBox* pToolBar = static_cast< ToolBox* >( pTbxWindow ); pToolBar->SetParent( pToolBox ); // calc and set size for popup mode Size aSize = pToolBar->CalcPopupWindowSizePixel(); pToolBar->SetSizePixel( aSize ); // open subtoolbox in popup mode vcl::Window::GetDockingManager()->StartPopupMode( pToolBox, pToolBar ); } } } } return css::uno::Reference< css::awt::XWindow >(); } sal_Bool SubToolBarController::opensSubToolbar() throw ( css::uno::RuntimeException, std::exception ) { return sal_True; } OUString SubToolBarController::getSubToolbarName() throw ( css::uno::RuntimeException, std::exception ) { return m_aSubTbName; } void SubToolBarController::functionSelected( const OUString& rCommand ) throw ( css::uno::RuntimeException, std::exception ) { if ( !m_aLastCommand.isEmpty() && m_aLastCommand != rCommand ) { removeStatusListener( m_aLastCommand ); m_aLastCommand = rCommand; addStatusListener( m_aLastCommand ); updateImage(); } } void SubToolBarController::updateImage() throw ( css::uno::RuntimeException, std::exception ) { SolarMutexGuard aGuard; if ( !m_aLastCommand.isEmpty() ) { ToolBox* pToolBox = 0; sal_uInt16 nId = 0; if ( getToolboxId( nId, &pToolBox ) ) { Image aImage = framework::GetImageFromURL( getFrameInterface(), m_aLastCommand, pToolBox->GetToolboxButtonSize() == TOOLBOX_BUTTONSIZE_LARGE ); if ( !!aImage ) pToolBox->SetItemImage( nId, aImage ); } } } void SubToolBarController::startDocking( const css::awt::DockingEvent& ) throw ( css::uno::RuntimeException, std::exception ) { } css::awt::DockingData SubToolBarController::docking( const css::awt::DockingEvent& ) throw ( css::uno::RuntimeException, std::exception ) { return css::awt::DockingData(); } void SubToolBarController::endDocking( const css::awt::EndDockingEvent& ) throw ( css::uno::RuntimeException, std::exception ) { } sal_Bool SubToolBarController::prepareToggleFloatingMode( const css::lang::EventObject& ) throw ( css::uno::RuntimeException, std::exception ) { return sal_False; } void SubToolBarController::toggleFloatingMode( const css::lang::EventObject& ) throw ( css::uno::RuntimeException, std::exception ) { } void SubToolBarController::closed( const css::lang::EventObject& ) throw ( css::uno::RuntimeException, std::exception ) { } void SubToolBarController::endPopupMode( const css::awt::EndPopupModeEvent& e ) throw ( css::uno::RuntimeException, std::exception ) { SolarMutexGuard aGuard; OUString aSubToolBarResName; if ( m_xUIElement.is() ) { css::uno::Reference< css::beans::XPropertySet > xPropSet( m_xUIElement, css::uno::UNO_QUERY ); if ( xPropSet.is() ) { try { xPropSet->getPropertyValue("ResourceURL") >>= aSubToolBarResName; } catch ( css::beans::UnknownPropertyException& ) {} catch ( css::lang::WrappedTargetException& ) {} } disposeUIElement(); } m_xUIElement = 0; // if the toolbar was teared-off recreate it and place it at the given position if( e.bTearoff ) { css::uno::Reference< css::ui::XUIElement > xUIElement; css::uno::Reference< css::frame::XLayoutManager > xLayoutManager = getLayoutManager(); if ( !xLayoutManager.is() ) return; xLayoutManager->createElement( aSubToolBarResName ); xUIElement = xLayoutManager->getElement( aSubToolBarResName ); if ( xUIElement.is() ) { css::uno::Reference< css::awt::XWindow > xParent = getFrameInterface()->getContainerWindow(); css::uno::Reference< css::awt::XWindow > xSubToolBar( xUIElement->getRealInterface(), css::uno::UNO_QUERY ); css::uno::Reference< css::beans::XPropertySet > xProp( xUIElement, css::uno::UNO_QUERY ); if ( xSubToolBar.is() && xProp.is() ) { OUString aPersistentString( "Persistent" ); try { vcl::Window* pTbxWindow = VCLUnoHelper::GetWindow( xSubToolBar ); if ( pTbxWindow && pTbxWindow->GetType() == WINDOW_TOOLBOX ) { css::uno::Any a = xProp->getPropertyValue( aPersistentString ); xProp->setPropertyValue( aPersistentString, css::uno::makeAny( false ) ); xLayoutManager->hideElement( aSubToolBarResName ); xLayoutManager->floatWindow( aSubToolBarResName ); xLayoutManager->setElementPos( aSubToolBarResName, e.FloatingPosition ); xLayoutManager->showElement( aSubToolBarResName ); xProp->setPropertyValue("Persistent", a ); } } catch ( css::uno::RuntimeException& ) { throw; } catch ( css::uno::Exception& ) {} } } } } void SubToolBarController::disposing( const css::lang::EventObject& e ) throw ( css::uno::RuntimeException, std::exception ) { svt::ToolboxController::disposing( e ); } void SubToolBarController::update() throw ( css::uno::RuntimeException, std::exception ) { svt::ToolboxController::update(); ToolBox* pToolBox = 0; sal_uInt16 nId = 0; if ( getToolboxId( nId, &pToolBox ) ) { if ( m_aLastCommand.isEmpty() ) pToolBox->SetItemBits( nId, pToolBox->GetItemBits( nId ) | ToolBoxItemBits::DROPDOWNONLY ); else pToolBox->SetItemBits( nId, pToolBox->GetItemBits( nId ) | ToolBoxItemBits::DROPDOWN ); } updateImage(); } void SubToolBarController::dispose() throw ( css::uno::RuntimeException, std::exception ) { if ( m_bDisposed ) return; svt::ToolboxController::dispose(); disposeUIElement(); m_xUIElement = 0; } OUString SubToolBarController::getImplementationName() throw ( css::uno::RuntimeException ) { return OUString( "com.sun.star.comp.framework.SubToolBarController" ); } sal_Bool SubToolBarController::supportsService( const OUString& rServiceName ) throw ( css::uno::RuntimeException ) { return cppu::supportsService( this, rServiceName ); } css::uno::Sequence< OUString > SubToolBarController::getSupportedServiceNames() throw ( css::uno::RuntimeException ) { css::uno::Sequence< OUString > aRet( 1 ); aRet[0] = "com.sun.star.frame.ToolbarController"; return aRet; } extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface * SAL_CALL com_sun_star_comp_framework_SubToolBarController_get_implementation( css::uno::XComponentContext*, css::uno::Sequence<css::uno::Any> const & rxArgs ) { return cppu::acquire( new SubToolBarController( rxArgs ) ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ Fix image update of DROPDOWNONLY buttons Change-Id: I787878d6ac02d15286a405ccfcc1f09f04c39501 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include <comphelper/propertysequence.hxx> #include <cppuhelper/implbase.hxx> #include <cppuhelper/supportsservice.hxx> #include <cppuhelper/weakref.hxx> #include <framework/imageproducer.hxx> #include <svtools/toolboxcontroller.hxx> #include <toolkit/helper/vclunohelper.hxx> #include <tools/gen.hxx> #include <vcl/svapp.hxx> #include <vcl/toolbox.hxx> #include <com/sun/star/awt/XDockableWindow.hpp> #include <com/sun/star/frame/XSubToolbarController.hpp> #include <com/sun/star/frame/status/ItemStatus.hpp> #include <com/sun/star/frame/status/Visibility.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/ui/theUIElementFactoryManager.hpp> typedef cppu::ImplInheritanceHelper< svt::ToolboxController, css::frame::XSubToolbarController, css::awt::XDockableWindowListener, css::lang::XServiceInfo > ToolBarBase; class SubToolBarController : public ToolBarBase { OUString m_aSubTbName; OUString m_aLastCommand; css::uno::Reference< css::ui::XUIElement > m_xUIElement; void disposeUIElement(); public: explicit SubToolBarController( const css::uno::Sequence< css::uno::Any >& rxArgs ); virtual ~SubToolBarController(); // XStatusListener virtual void SAL_CALL statusChanged( const css::frame::FeatureStateEvent& Event ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XToolbarController virtual void SAL_CALL execute( sal_Int16 nKeyModifier ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual css::uno::Reference< css::awt::XWindow > SAL_CALL createPopupWindow() throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XSubToolbarController virtual sal_Bool SAL_CALL opensSubToolbar() throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual OUString SAL_CALL getSubToolbarName() throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual void SAL_CALL functionSelected( const OUString& rCommand ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual void SAL_CALL updateImage() throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XDockableWindowListener virtual void SAL_CALL startDocking( const css::awt::DockingEvent& e ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual css::awt::DockingData SAL_CALL docking( const css::awt::DockingEvent& e ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual void SAL_CALL endDocking( const css::awt::EndDockingEvent& e ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual sal_Bool SAL_CALL prepareToggleFloatingMode( const css::lang::EventObject& e ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual void SAL_CALL toggleFloatingMode( const css::lang::EventObject& e ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual void SAL_CALL closed( const css::lang::EventObject& e ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; virtual void SAL_CALL endPopupMode( const css::awt::EndPopupModeEvent& e ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XEventListener virtual void SAL_CALL disposing( const css::lang::EventObject& e ) throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XUpdatable virtual void SAL_CALL update() throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XComponent virtual void SAL_CALL dispose() throw ( css::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw ( css::uno::RuntimeException ) SAL_OVERRIDE; virtual sal_Bool SAL_CALL supportsService( const OUString& rServiceName ) throw ( css::uno::RuntimeException ) SAL_OVERRIDE; virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() throw ( css::uno::RuntimeException ) SAL_OVERRIDE; }; SubToolBarController::SubToolBarController( const css::uno::Sequence< css::uno::Any >& rxArgs ) { css::beans::PropertyValue aPropValue; for ( sal_Int32 i = 0; i < rxArgs.getLength(); ++i ) { rxArgs[i] >>= aPropValue; if ( aPropValue.Name == "Value" ) { OUString aValue; aPropValue.Value >>= aValue; m_aSubTbName = aValue.getToken(0, ';'); m_aLastCommand = aValue.getToken(1, ';'); break; } } if ( !m_aLastCommand.isEmpty() ) addStatusListener( m_aLastCommand ); } SubToolBarController::~SubToolBarController() { disposeUIElement(); m_xUIElement = 0; } void SubToolBarController::disposeUIElement() { if ( m_xUIElement.is() ) { css::uno::Reference< css::lang::XComponent > xComponent( m_xUIElement, css::uno::UNO_QUERY ); xComponent->dispose(); } } void SubToolBarController::statusChanged( const css::frame::FeatureStateEvent& Event ) throw ( css::uno::RuntimeException, std::exception ) { SolarMutexGuard aSolarMutexGuard; if ( m_bDisposed ) return; ToolBox* pToolBox = 0; sal_uInt16 nId = 0; if ( getToolboxId( nId, &pToolBox ) ) { ToolBoxItemBits nItemBits = pToolBox->GetItemBits( nId ); nItemBits &= ~ToolBoxItemBits::CHECKABLE; TriState eTri = TRISTATE_FALSE; if ( Event.FeatureURL.Complete == m_aCommandURL ) { pToolBox->EnableItem( nId, Event.IsEnabled ); OUString aStrValue; css::frame::status::Visibility aItemVisibility; if ( Event.State >>= aStrValue ) { // Enum command, such as the current custom shape, // toggle checked state. if ( m_aLastCommand == OUString( m_aCommandURL + "." + aStrValue ) ) { eTri = TRISTATE_TRUE; nItemBits |= ToolBoxItemBits::CHECKABLE; } } else if ( Event.State >>= aItemVisibility ) { pToolBox->ShowItem( nId, aItemVisibility.bVisible ); } } else { bool bValue; if ( Event.State >>= bValue ) { // Boolean, treat it as checked/unchecked if ( bValue ) eTri = TRISTATE_TRUE; nItemBits |= ToolBoxItemBits::CHECKABLE; } } pToolBox->SetItemState( nId, eTri ); pToolBox->SetItemBits( nId, nItemBits ); } } void SubToolBarController::execute( sal_Int16 nKeyModifier ) throw ( css::uno::RuntimeException, std::exception ) { if ( !m_aLastCommand.isEmpty() ) { auto aArgs( comphelper::InitPropertySequence( { { "KeyModifier", css::uno::makeAny( nKeyModifier ) } } ) ); dispatchCommand( m_aLastCommand, aArgs ); } } css::uno::Reference< css::awt::XWindow > SubToolBarController::createPopupWindow() throw ( css::uno::RuntimeException, std::exception ) { SolarMutexGuard aGuard; ToolBox* pToolBox = 0; sal_uInt16 nId = 0; if ( getToolboxId( nId, &pToolBox ) ) { css::uno::Reference< css::frame::XFrame > xFrame ( getFrameInterface() ); // create element with factory static css::uno::WeakReference< css::ui::XUIElementFactoryManager > xWeakUIElementFactory; css::uno::Reference< css::ui::XUIElement > xUIElement; css::uno::Reference< css::ui::XUIElementFactoryManager > xUIElementFactory; xUIElementFactory = xWeakUIElementFactory; if ( !xUIElementFactory.is() ) { xUIElementFactory = css::ui::theUIElementFactoryManager::get( m_xContext ); xWeakUIElementFactory = xUIElementFactory; } auto aPropSeq( comphelper::InitPropertySequence( { { "Frame", css::uno::makeAny( xFrame ) }, { "Persistent", css::uno::makeAny( false ) }, { "PopupMode", css::uno::makeAny( true ) } } ) ); try { xUIElement = xUIElementFactory->createUIElement( "private:resource/toolbar/" + m_aSubTbName, aPropSeq ); } catch ( css::container::NoSuchElementException& ) {} catch ( css::lang::IllegalArgumentException& ) {} if ( xUIElement.is() ) { css::uno::Reference< css::awt::XWindow > xParent = xFrame->getContainerWindow(); css::uno::Reference< css::awt::XWindow > xSubToolBar( xUIElement->getRealInterface(), css::uno::UNO_QUERY ); if ( xSubToolBar.is() ) { css::uno::Reference< css::awt::XDockableWindow > xDockWindow( xSubToolBar, css::uno::UNO_QUERY ); xDockWindow->addDockableWindowListener( css::uno::Reference< css::awt::XDockableWindowListener >( static_cast< OWeakObject * >( this ), css::uno::UNO_QUERY ) ); xDockWindow->enableDocking( sal_True ); // keep reference to UIElement to avoid its destruction disposeUIElement(); m_xUIElement = xUIElement; vcl::Window* pTbxWindow = VCLUnoHelper::GetWindow( xSubToolBar ); if ( pTbxWindow && pTbxWindow->GetType() == WINDOW_TOOLBOX ) { ToolBox* pToolBar = static_cast< ToolBox* >( pTbxWindow ); pToolBar->SetParent( pToolBox ); // calc and set size for popup mode Size aSize = pToolBar->CalcPopupWindowSizePixel(); pToolBar->SetSizePixel( aSize ); // open subtoolbox in popup mode vcl::Window::GetDockingManager()->StartPopupMode( pToolBox, pToolBar ); } } } } return css::uno::Reference< css::awt::XWindow >(); } sal_Bool SubToolBarController::opensSubToolbar() throw ( css::uno::RuntimeException, std::exception ) { return !m_aLastCommand.isEmpty(); } OUString SubToolBarController::getSubToolbarName() throw ( css::uno::RuntimeException, std::exception ) { return m_aSubTbName; } void SubToolBarController::functionSelected( const OUString& rCommand ) throw ( css::uno::RuntimeException, std::exception ) { if ( !m_aLastCommand.isEmpty() && m_aLastCommand != rCommand ) { removeStatusListener( m_aLastCommand ); m_aLastCommand = rCommand; addStatusListener( m_aLastCommand ); updateImage(); } } void SubToolBarController::updateImage() throw ( css::uno::RuntimeException, std::exception ) { SolarMutexGuard aGuard; if ( !m_aLastCommand.isEmpty() ) { ToolBox* pToolBox = 0; sal_uInt16 nId = 0; if ( getToolboxId( nId, &pToolBox ) ) { Image aImage = framework::GetImageFromURL( getFrameInterface(), m_aLastCommand, pToolBox->GetToolboxButtonSize() == TOOLBOX_BUTTONSIZE_LARGE ); if ( !!aImage ) pToolBox->SetItemImage( nId, aImage ); } } } void SubToolBarController::startDocking( const css::awt::DockingEvent& ) throw ( css::uno::RuntimeException, std::exception ) { } css::awt::DockingData SubToolBarController::docking( const css::awt::DockingEvent& ) throw ( css::uno::RuntimeException, std::exception ) { return css::awt::DockingData(); } void SubToolBarController::endDocking( const css::awt::EndDockingEvent& ) throw ( css::uno::RuntimeException, std::exception ) { } sal_Bool SubToolBarController::prepareToggleFloatingMode( const css::lang::EventObject& ) throw ( css::uno::RuntimeException, std::exception ) { return sal_False; } void SubToolBarController::toggleFloatingMode( const css::lang::EventObject& ) throw ( css::uno::RuntimeException, std::exception ) { } void SubToolBarController::closed( const css::lang::EventObject& ) throw ( css::uno::RuntimeException, std::exception ) { } void SubToolBarController::endPopupMode( const css::awt::EndPopupModeEvent& e ) throw ( css::uno::RuntimeException, std::exception ) { SolarMutexGuard aGuard; OUString aSubToolBarResName; if ( m_xUIElement.is() ) { css::uno::Reference< css::beans::XPropertySet > xPropSet( m_xUIElement, css::uno::UNO_QUERY ); if ( xPropSet.is() ) { try { xPropSet->getPropertyValue("ResourceURL") >>= aSubToolBarResName; } catch ( css::beans::UnknownPropertyException& ) {} catch ( css::lang::WrappedTargetException& ) {} } disposeUIElement(); } m_xUIElement = 0; // if the toolbar was teared-off recreate it and place it at the given position if( e.bTearoff ) { css::uno::Reference< css::ui::XUIElement > xUIElement; css::uno::Reference< css::frame::XLayoutManager > xLayoutManager = getLayoutManager(); if ( !xLayoutManager.is() ) return; xLayoutManager->createElement( aSubToolBarResName ); xUIElement = xLayoutManager->getElement( aSubToolBarResName ); if ( xUIElement.is() ) { css::uno::Reference< css::awt::XWindow > xParent = getFrameInterface()->getContainerWindow(); css::uno::Reference< css::awt::XWindow > xSubToolBar( xUIElement->getRealInterface(), css::uno::UNO_QUERY ); css::uno::Reference< css::beans::XPropertySet > xProp( xUIElement, css::uno::UNO_QUERY ); if ( xSubToolBar.is() && xProp.is() ) { OUString aPersistentString( "Persistent" ); try { vcl::Window* pTbxWindow = VCLUnoHelper::GetWindow( xSubToolBar ); if ( pTbxWindow && pTbxWindow->GetType() == WINDOW_TOOLBOX ) { css::uno::Any a = xProp->getPropertyValue( aPersistentString ); xProp->setPropertyValue( aPersistentString, css::uno::makeAny( false ) ); xLayoutManager->hideElement( aSubToolBarResName ); xLayoutManager->floatWindow( aSubToolBarResName ); xLayoutManager->setElementPos( aSubToolBarResName, e.FloatingPosition ); xLayoutManager->showElement( aSubToolBarResName ); xProp->setPropertyValue("Persistent", a ); } } catch ( css::uno::RuntimeException& ) { throw; } catch ( css::uno::Exception& ) {} } } } } void SubToolBarController::disposing( const css::lang::EventObject& e ) throw ( css::uno::RuntimeException, std::exception ) { svt::ToolboxController::disposing( e ); } void SubToolBarController::update() throw ( css::uno::RuntimeException, std::exception ) { svt::ToolboxController::update(); ToolBox* pToolBox = 0; sal_uInt16 nId = 0; if ( getToolboxId( nId, &pToolBox ) ) { if ( m_aLastCommand.isEmpty() ) pToolBox->SetItemBits( nId, pToolBox->GetItemBits( nId ) | ToolBoxItemBits::DROPDOWNONLY ); else pToolBox->SetItemBits( nId, pToolBox->GetItemBits( nId ) | ToolBoxItemBits::DROPDOWN ); } updateImage(); } void SubToolBarController::dispose() throw ( css::uno::RuntimeException, std::exception ) { if ( m_bDisposed ) return; svt::ToolboxController::dispose(); disposeUIElement(); m_xUIElement = 0; } OUString SubToolBarController::getImplementationName() throw ( css::uno::RuntimeException ) { return OUString( "com.sun.star.comp.framework.SubToolBarController" ); } sal_Bool SubToolBarController::supportsService( const OUString& rServiceName ) throw ( css::uno::RuntimeException ) { return cppu::supportsService( this, rServiceName ); } css::uno::Sequence< OUString > SubToolBarController::getSupportedServiceNames() throw ( css::uno::RuntimeException ) { css::uno::Sequence< OUString > aRet( 1 ); aRet[0] = "com.sun.star.frame.ToolbarController"; return aRet; } extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface * SAL_CALL com_sun_star_comp_framework_SubToolBarController_get_implementation( css::uno::XComponentContext*, css::uno::Sequence<css::uno::Any> const & rxArgs ) { return cppu::acquire( new SubToolBarController( rxArgs ) ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/*************************************************************************/ /* scene_tree_dock.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "scene_tree_dock.h" #include "core/io/resource_saver.h" #include "core/os/keyboard.h" #include "core/project_settings.h" #include "editor/animation_editor.h" #include "editor/editor_node.h" #include "editor/editor_settings.h" #include "editor/multi_node_edit.h" #include "editor/plugins/animation_player_editor_plugin.h" #include "editor/plugins/canvas_item_editor_plugin.h" #include "editor/plugins/script_editor_plugin.h" #include "editor/plugins/spatial_editor_plugin.h" #include "editor/script_editor_debugger.h" #include "scene/main/viewport.h" #include "scene/resources/packed_scene.h" void SceneTreeDock::_nodes_drag_begin() { if (restore_script_editor_on_drag) { EditorNode::get_singleton()->set_visible_editor(EditorNode::EDITOR_SCRIPT); restore_script_editor_on_drag = false; } } void SceneTreeDock::_input(Ref<InputEvent> p_event) { Ref<InputEventMouseButton> mb = p_event; if (mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) { restore_script_editor_on_drag = false; //lost chance } } void SceneTreeDock::_unhandled_key_input(Ref<InputEvent> p_event) { if (get_viewport()->get_modal_stack_top()) return; //ignore because of modal window if (get_focus_owner() && get_focus_owner()->is_text_field()) return; if (!p_event->is_pressed() || p_event->is_echo()) return; if (ED_IS_SHORTCUT("scene_tree/add_child_node", p_event)) { _tool_selected(TOOL_NEW); } else if (ED_IS_SHORTCUT("scene_tree/instance_scene", p_event)) { _tool_selected(TOOL_INSTANCE); } else if (ED_IS_SHORTCUT("scene_tree/change_node_type", p_event)) { _tool_selected(TOOL_REPLACE); } else if (ED_IS_SHORTCUT("scene_tree/duplicate", p_event)) { _tool_selected(TOOL_DUPLICATE); } else if (ED_IS_SHORTCUT("scene_tree/attach_script", p_event)) { _tool_selected(TOOL_ATTACH_SCRIPT); } else if (ED_IS_SHORTCUT("scene_tree/clear_script", p_event)) { _tool_selected(TOOL_CLEAR_SCRIPT); } else if (ED_IS_SHORTCUT("scene_tree/move_up", p_event)) { _tool_selected(TOOL_MOVE_UP); } else if (ED_IS_SHORTCUT("scene_tree/move_down", p_event)) { _tool_selected(TOOL_MOVE_DOWN); } else if (ED_IS_SHORTCUT("scene_tree/reparent", p_event)) { _tool_selected(TOOL_REPARENT); } else if (ED_IS_SHORTCUT("scene_tree/merge_from_scene", p_event)) { _tool_selected(TOOL_MERGE_FROM_SCENE); } else if (ED_IS_SHORTCUT("scene_tree/save_branch_as_scene", p_event)) { _tool_selected(TOOL_NEW_SCENE_FROM); } else if (ED_IS_SHORTCUT("scene_tree/delete_no_confirm", p_event)) { _tool_selected(TOOL_ERASE, true); } else if (ED_IS_SHORTCUT("scene_tree/copy_node_path", p_event)) { _tool_selected(TOOL_COPY_NODE_PATH); } else if (ED_IS_SHORTCUT("scene_tree/delete", p_event)) { _tool_selected(TOOL_ERASE); } } void SceneTreeDock::instance(const String &p_file) { Node *parent = scene_tree->get_selected(); if (!parent || !edited_scene) { current_option = -1; accept->get_ok()->set_text(TTR("OK :(")); accept->set_text(TTR("No parent to instance a child at.")); accept->popup_centered_minsize(); return; }; ERR_FAIL_COND(!parent); Vector<String> scenes; scenes.push_back(p_file); _perform_instance_scenes(scenes, parent, -1); } void SceneTreeDock::instance_scenes(const Vector<String> &p_files, Node *p_parent) { Node *parent = p_parent; if (!parent) { parent = scene_tree->get_selected(); } if (!parent || !edited_scene) { accept->get_ok()->set_text(TTR("OK")); accept->set_text(TTR("No parent to instance the scenes at.")); accept->popup_centered_minsize(); return; }; _perform_instance_scenes(p_files, parent, -1); } void SceneTreeDock::_perform_instance_scenes(const Vector<String> &p_files, Node *parent, int p_pos) { ERR_FAIL_COND(!parent); Vector<Node *> instances; bool error = false; for (int i = 0; i < p_files.size(); i++) { Ref<PackedScene> sdata = ResourceLoader::load(p_files[i]); if (!sdata.is_valid()) { current_option = -1; accept->get_ok()->set_text(TTR("Ugh")); accept->set_text(vformat(TTR("Error loading scene from %s"), p_files[i])); accept->popup_centered_minsize(); error = true; break; } Node *instanced_scene = sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE); if (!instanced_scene) { current_option = -1; accept->get_ok()->set_text(TTR("Ugh")); accept->set_text(vformat(TTR("Error instancing scene from %s"), p_files[i])); accept->popup_centered_minsize(); error = true; break; } if (edited_scene->get_filename() != "") { if (_cyclical_dependency_exists(edited_scene->get_filename(), instanced_scene)) { accept->get_ok()->set_text(TTR("Ok")); accept->set_text(vformat(TTR("Cannot instance the scene '%s' because the current scene exists within one of its nodes."), p_files[i])); accept->popup_centered_minsize(); error = true; break; } } instanced_scene->set_filename(ProjectSettings::get_singleton()->localize_path(p_files[i])); instances.push_back(instanced_scene); } if (error) { for (int i = 0; i < instances.size(); i++) { memdelete(instances[i]); } return; } editor_data->get_undo_redo().create_action(TTR("Instance Scene(s)")); for (int i = 0; i < instances.size(); i++) { Node *instanced_scene = instances[i]; editor_data->get_undo_redo().add_do_method(parent, "add_child", instanced_scene); if (p_pos >= 0) { editor_data->get_undo_redo().add_do_method(parent, "move_child", instanced_scene, p_pos + i); } editor_data->get_undo_redo().add_do_method(instanced_scene, "set_owner", edited_scene); editor_data->get_undo_redo().add_do_method(editor_selection, "clear"); editor_data->get_undo_redo().add_do_method(editor_selection, "add_node", instanced_scene); editor_data->get_undo_redo().add_do_reference(instanced_scene); editor_data->get_undo_redo().add_undo_method(parent, "remove_child", instanced_scene); String new_name = parent->validate_child_name(instanced_scene); ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger(); editor_data->get_undo_redo().add_do_method(sed, "live_debug_instance_node", edited_scene->get_path_to(parent), p_files[i], new_name); editor_data->get_undo_redo().add_undo_method(sed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)) + "/" + new_name)); } editor_data->get_undo_redo().commit_action(); } void SceneTreeDock::_replace_with_branch_scene(const String &p_file, Node *base) { Ref<PackedScene> sdata = ResourceLoader::load(p_file); if (!sdata.is_valid()) { accept->get_ok()->set_text(TTR("Ugh")); accept->set_text(vformat(TTR("Error loading scene from %s"), p_file)); accept->popup_centered_minsize(); return; } Node *instanced_scene = sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE); if (!instanced_scene) { accept->get_ok()->set_text(TTR("Ugh")); accept->set_text(vformat(TTR("Error instancing scene from %s"), p_file)); accept->popup_centered_minsize(); return; } Node *parent = base->get_parent(); int pos = base->get_index(); parent->remove_child(base); parent->add_child(instanced_scene); parent->move_child(instanced_scene, pos); instanced_scene->set_owner(edited_scene); editor_selection->clear(); editor_selection->add_node(instanced_scene); scene_tree->set_selected(instanced_scene); // Delete the node as late as possible because before another one is selected // an editor plugin could be referencing it to do something with it before // switching to another (or to none); and since some steps of changing the // editor state are deferred, the safest thing is to do this is as the last // step of this function and also by enqueing instead of memdelete()-ing it here base->queue_delete(); } bool SceneTreeDock::_cyclical_dependency_exists(const String &p_target_scene_path, Node *p_desired_node) { int childCount = p_desired_node->get_child_count(); if (p_desired_node->get_filename() == p_target_scene_path) { return true; } for (int i = 0; i < childCount; i++) { Node *child = p_desired_node->get_child(i); if (_cyclical_dependency_exists(p_target_scene_path, child)) { return true; } } return false; } void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) { current_option = p_tool; switch (p_tool) { case TOOL_NEW: { String preferred = ""; Node *current_edited_scene_root = EditorNode::get_singleton()->get_edited_scene(); if (current_edited_scene_root) { if (ClassDB::is_parent_class(current_edited_scene_root->get_class_name(), "Node2D")) preferred = "Node2D"; else if (ClassDB::is_parent_class(current_edited_scene_root->get_class_name(), "Spatial")) preferred = "Spatial"; } create_dialog->set_preferred_search_result_type(preferred); create_dialog->popup_create(true); } break; case TOOL_INSTANCE: { Node *scene = edited_scene; if (!scene) { EditorNode::get_singleton()->new_inherited_scene(); break; } file->set_mode(EditorFileDialog::MODE_OPEN_FILE); List<String> extensions; ResourceLoader::get_recognized_extensions_for_type("PackedScene", &extensions); file->clear_filters(); for (int i = 0; i < extensions.size(); i++) { file->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper()); } file->popup_centered_ratio(); } break; case TOOL_REPLACE: { create_dialog->popup_create(false, true); } break; case TOOL_ATTACH_SCRIPT: { Node *selected = scene_tree->get_selected(); if (!selected) break; Ref<Script> existing = selected->get_script(); if (existing.is_valid()) editor->push_item(existing.ptr()); else { String path = selected->get_filename(); if (path == "") { String root_path = editor_data->get_edited_scene_root()->get_filename(); if (root_path == "") { path = "res://" + selected->get_name(); } else { path = root_path.get_base_dir() + "/" + selected->get_name(); } } script_create_dialog->config(selected->get_class(), path); script_create_dialog->popup_centered(); } } break; case TOOL_CLEAR_SCRIPT: { Node *selected = scene_tree->get_selected(); if (!selected) break; Ref<Script> existing = selected->get_script(); if (existing.is_valid()) { const RefPtr empty; selected->set_script(empty); _update_script_button(); } } break; case TOOL_MOVE_UP: case TOOL_MOVE_DOWN: { if (!scene_tree->get_selected()) break; if (scene_tree->get_selected() == edited_scene) { current_option = -1; accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("This operation can't be done on the tree root.")); accept->popup_centered_minsize(); break; } if (!_validate_no_foreign()) break; bool MOVING_DOWN = (p_tool == TOOL_MOVE_DOWN); bool MOVING_UP = !MOVING_DOWN; Node *common_parent = scene_tree->get_selected()->get_parent(); List<Node *> selection = editor_selection->get_selected_node_list(); selection.sort_custom<Node::Comparator>(); // sort by index if (MOVING_DOWN) selection.invert(); int lowest_id = common_parent->get_child_count() - 1; int highest_id = 0; for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { int index = E->get()->get_index(); if (index > highest_id) highest_id = index; if (index < lowest_id) lowest_id = index; if (E->get()->get_parent() != common_parent) common_parent = NULL; } if (!common_parent || (MOVING_DOWN && highest_id >= common_parent->get_child_count() - MOVING_DOWN) || (MOVING_UP && lowest_id == 0)) break; // one or more nodes can not be moved if (selection.size() == 1) editor_data->get_undo_redo().create_action(TTR("Move Node In Parent")); if (selection.size() > 1) editor_data->get_undo_redo().create_action(TTR("Move Nodes In Parent")); for (int i = 0; i < selection.size(); i++) { Node *top_node = selection[i]; Node *bottom_node = selection[selection.size() - 1 - i]; ERR_FAIL_COND(!top_node->get_parent()); ERR_FAIL_COND(!bottom_node->get_parent()); int bottom_node_pos = bottom_node->get_index(); int top_node_pos_next = top_node->get_index() + (MOVING_DOWN ? 1 : -1); editor_data->get_undo_redo().add_do_method(top_node->get_parent(), "move_child", top_node, top_node_pos_next); editor_data->get_undo_redo().add_undo_method(bottom_node->get_parent(), "move_child", bottom_node, bottom_node_pos); } editor_data->get_undo_redo().commit_action(); } break; case TOOL_DUPLICATE: { if (!edited_scene) break; if (editor_selection->is_selected(edited_scene)) { current_option = -1; accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("This operation can't be done on the tree root.")); accept->popup_centered_minsize(); break; } if (!_validate_no_foreign()) break; List<Node *> selection = editor_selection->get_selected_node_list(); if (selection.size() == 0) break; editor_data->get_undo_redo().create_action(TTR("Duplicate Node(s)")); editor_data->get_undo_redo().add_do_method(editor_selection, "clear"); Node *dupsingle = NULL; for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { Node *node = E->get(); Node *parent = node->get_parent(); List<Node *> owned; node->get_owned_by(node->get_owner(), &owned); Map<const Node *, Node *> duplimap; Node *dup = node->duplicate_from_editor(duplimap); ERR_CONTINUE(!dup); if (selection.size() == 1) dupsingle = dup; dup->set_name(parent->validate_child_name(dup)); editor_data->get_undo_redo().add_do_method(parent, "add_child_below_node", node, dup); for (List<Node *>::Element *F = owned.front(); F; F = F->next()) { if (!duplimap.has(F->get())) { continue; } Node *d = duplimap[F->get()]; editor_data->get_undo_redo().add_do_method(d, "set_owner", node->get_owner()); } editor_data->get_undo_redo().add_do_method(editor_selection, "add_node", dup); editor_data->get_undo_redo().add_undo_method(parent, "remove_child", dup); editor_data->get_undo_redo().add_do_reference(dup); ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger(); editor_data->get_undo_redo().add_do_method(sed, "live_debug_duplicate_node", edited_scene->get_path_to(node), dup->get_name()); editor_data->get_undo_redo().add_undo_method(sed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)) + "/" + dup->get_name())); } editor_data->get_undo_redo().commit_action(); if (dupsingle) editor->push_item(dupsingle); } break; case TOOL_REPARENT: { if (!scene_tree->get_selected()) break; if (editor_selection->is_selected(edited_scene)) { current_option = -1; accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("This operation can't be done on the tree root.")); accept->popup_centered_minsize(); break; } if (!_validate_no_foreign()) break; List<Node *> nodes = editor_selection->get_selected_node_list(); Set<Node *> nodeset; for (List<Node *>::Element *E = nodes.front(); E; E = E->next()) { nodeset.insert(E->get()); } reparent_dialog->popup_centered_ratio(); reparent_dialog->set_current(nodeset); } break; case TOOL_MULTI_EDIT: { Node *root = EditorNode::get_singleton()->get_edited_scene(); if (!root) break; Ref<MultiNodeEdit> mne = memnew(MultiNodeEdit); for (const Map<Node *, Object *>::Element *E = EditorNode::get_singleton()->get_editor_selection()->get_selection().front(); E; E = E->next()) { mne->add_node(root->get_path_to(E->key())); } EditorNode::get_singleton()->push_item(mne.ptr()); } break; case TOOL_ERASE: { List<Node *> remove_list = editor_selection->get_selected_node_list(); if (remove_list.empty()) return; if (!_validate_no_foreign()) break; if (p_confirm_override) { _delete_confirm(); } else { delete_dialog->set_text(TTR("Delete Node(s)?")); delete_dialog->popup_centered_minsize(); } } break; case TOOL_MERGE_FROM_SCENE: { EditorNode::get_singleton()->merge_from_scene(); } break; case TOOL_NEW_SCENE_FROM: { Node *scene = editor_data->get_edited_scene_root(); if (!scene) { accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("This operation can't be done without a scene.")); accept->popup_centered_minsize(); break; } List<Node *> selection = editor_selection->get_selected_node_list(); if (selection.size() != 1) { accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("This operation requires a single selected node.")); accept->popup_centered_minsize(); break; } Node *tocopy = selection.front()->get(); if (tocopy == scene) { accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("Can not perform with the root node.")); accept->popup_centered_minsize(); break; } if (tocopy != editor_data->get_edited_scene_root() && tocopy->get_filename() != "") { accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("This operation can't be done on instanced scenes.")); accept->popup_centered_minsize(); break; } new_scene_from_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE); List<String> extensions; Ref<PackedScene> sd = memnew(PackedScene); ResourceSaver::get_recognized_extensions(sd, &extensions); new_scene_from_dialog->clear_filters(); for (int i = 0; i < extensions.size(); i++) { new_scene_from_dialog->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper()); } String existing; if (extensions.size()) { String root_name(tocopy->get_name()); existing = root_name + "." + extensions.front()->get().to_lower(); } new_scene_from_dialog->set_current_path(existing); new_scene_from_dialog->popup_centered_ratio(); new_scene_from_dialog->set_title(TTR("Save New Scene As..")); } break; case TOOL_COPY_NODE_PATH: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { Node *root = EditorNode::get_singleton()->get_edited_scene(); NodePath path = root->get_path().rel_path_to(node->get_path()); OS::get_singleton()->set_clipboard(path); } } } break; case TOOL_SCENE_EDITABLE_CHILDREN: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { bool editable = EditorNode::get_singleton()->get_edited_scene()->is_editable_instance(node); int editable_item_idx = menu->get_item_idx_from_text(TTR("Editable Children")); int placeholder_item_idx = menu->get_item_idx_from_text(TTR("Load As Placeholder")); editable = !editable; EditorNode::get_singleton()->get_edited_scene()->set_editable_instance(node, editable); menu->set_item_checked(editable_item_idx, editable); if (editable) { node->set_scene_instance_load_placeholder(false); menu->set_item_checked(placeholder_item_idx, false); } scene_tree->update_tree(); } } } break; case TOOL_SCENE_USE_PLACEHOLDER: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { bool placeholder = node->get_scene_instance_load_placeholder(); placeholder = !placeholder; int editable_item_idx = menu->get_item_idx_from_text(TTR("Editable Children")); int placeholder_item_idx = menu->get_item_idx_from_text(TTR("Load As Placeholder")); if (placeholder) EditorNode::get_singleton()->get_edited_scene()->set_editable_instance(node, false); node->set_scene_instance_load_placeholder(placeholder); menu->set_item_checked(editable_item_idx, false); menu->set_item_checked(placeholder_item_idx, placeholder); scene_tree->update_tree(); } } } break; case TOOL_SCENE_CLEAR_INSTANCING: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { Node *root = EditorNode::get_singleton()->get_edited_scene(); UndoRedo *undo_redo = &editor_data->get_undo_redo(); if (!root) break; ERR_FAIL_COND(node->get_filename() == String()); undo_redo->create_action(TTR("Discard Instancing")); undo_redo->add_do_method(node, "set_filename", ""); undo_redo->add_undo_method(node, "set_filename", node->get_filename()); _node_replace_owner(node, node, root); undo_redo->add_do_method(scene_tree, "update_tree"); undo_redo->add_undo_method(scene_tree, "update_tree"); undo_redo->commit_action(); } } } break; case TOOL_SCENE_OPEN: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { scene_tree->emit_signal("open", node->get_filename()); } } } break; case TOOL_SCENE_CLEAR_INHERITANCE: { clear_inherit_confirm->popup_centered_minsize(); } break; case TOOL_SCENE_CLEAR_INHERITANCE_CONFIRM: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { node->set_scene_inherited_state(Ref<SceneState>()); scene_tree->update_tree(); EditorNode::get_singleton()->get_property_editor()->update_tree(); } } } break; case TOOL_SCENE_OPEN_INHERITED: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { if (node && node->get_scene_inherited_state().is_valid()) { scene_tree->emit_signal("open", node->get_scene_inherited_state()->get_path()); } } } } break; default: { if (p_tool >= EDIT_SUBRESOURCE_BASE) { int idx = p_tool - EDIT_SUBRESOURCE_BASE; ERR_FAIL_INDEX(idx, subresources.size()); Object *obj = ObjectDB::get_instance(subresources[idx]); ERR_FAIL_COND(!obj); editor->push_item(obj); } } } } void SceneTreeDock::_notification(int p_what) { switch (p_what) { case NOTIFICATION_READY: { if (!first_enter) break; first_enter = false; CanvasItemEditorPlugin *canvas_item_plugin = Object::cast_to<CanvasItemEditorPlugin>(editor_data->get_editor("2D")); if (canvas_item_plugin) { canvas_item_plugin->get_canvas_item_editor()->connect("item_lock_status_changed", scene_tree, "_update_tree"); canvas_item_plugin->get_canvas_item_editor()->connect("item_group_status_changed", scene_tree, "_update_tree"); scene_tree->connect("node_changed", canvas_item_plugin->get_canvas_item_editor()->get_viewport_control(), "update"); } SpatialEditorPlugin *spatial_editor_plugin = Object::cast_to<SpatialEditorPlugin>(editor_data->get_editor("3D")); spatial_editor_plugin->get_spatial_editor()->connect("item_lock_status_changed", scene_tree, "_update_tree"); button_add->set_icon(get_icon("Add", "EditorIcons")); button_instance->set_icon(get_icon("Instance", "EditorIcons")); button_create_script->set_icon(get_icon("ScriptCreate", "EditorIcons")); button_clear_script->set_icon(get_icon("ScriptRemove", "EditorIcons")); filter->add_icon_override("right_icon", get_icon("Search", "EditorIcons")); EditorNode::get_singleton()->get_editor_selection()->connect("selection_changed", this, "_selection_changed"); } break; case NOTIFICATION_ENTER_TREE: { clear_inherit_confirm->connect("confirmed", this, "_tool_selected", varray(TOOL_SCENE_CLEAR_INHERITANCE_CONFIRM)); } break; case NOTIFICATION_EXIT_TREE: { clear_inherit_confirm->disconnect("confirmed", this, "_tool_selected"); } break; case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { button_add->set_icon(get_icon("Add", "EditorIcons")); button_instance->set_icon(get_icon("Instance", "EditorIcons")); button_create_script->set_icon(get_icon("ScriptCreate", "EditorIcons")); button_clear_script->set_icon(get_icon("ScriptRemove", "EditorIcons")); filter->add_icon_override("right_icon", get_icon("Search", "EditorIcons")); } break; } } void SceneTreeDock::_node_replace_owner(Node *p_base, Node *p_node, Node *p_root) { if (p_base != p_node) { if (p_node->get_owner() == p_base) { UndoRedo *undo_redo = &editor_data->get_undo_redo(); undo_redo->add_do_method(p_node, "set_owner", p_root); undo_redo->add_undo_method(p_node, "set_owner", p_base); } } for (int i = 0; i < p_node->get_child_count(); i++) { _node_replace_owner(p_base, p_node->get_child(i), p_root); } } void SceneTreeDock::_load_request(const String &p_path) { editor->open_request(p_path); } void SceneTreeDock::_script_open_request(const Ref<Script> &p_script) { editor->edit_resource(p_script); } void SceneTreeDock::_node_selected() { Node *node = scene_tree->get_selected(); if (!node) { editor->push_item(NULL); return; } if (ScriptEditor::get_singleton()->is_visible_in_tree()) { restore_script_editor_on_drag = true; } editor->push_item(node); } void SceneTreeDock::_node_renamed() { _node_selected(); } void SceneTreeDock::_set_owners(Node *p_owner, const Array &p_nodes) { for (int i = 0; i < p_nodes.size(); i++) { Node *n = Object::cast_to<Node>(p_nodes[i]); if (!n) continue; n->set_owner(p_owner); } } void SceneTreeDock::_fill_path_renames(Vector<StringName> base_path, Vector<StringName> new_base_path, Node *p_node, List<Pair<NodePath, NodePath> > *p_renames) { base_path.push_back(p_node->get_name()); if (new_base_path.size()) new_base_path.push_back(p_node->get_name()); NodePath from(base_path, true); NodePath to; if (new_base_path.size()) to = NodePath(new_base_path, true); Pair<NodePath, NodePath> npp; npp.first = from; npp.second = to; p_renames->push_back(npp); for (int i = 0; i < p_node->get_child_count(); i++) { _fill_path_renames(base_path, new_base_path, p_node->get_child(i), p_renames); } } void SceneTreeDock::fill_path_renames(Node *p_node, Node *p_new_parent, List<Pair<NodePath, NodePath> > *p_renames) { if (!bool(EDITOR_DEF("editors/animation/autorename_animation_tracks", true))) return; Vector<StringName> base_path; Node *n = p_node->get_parent(); while (n) { base_path.push_back(n->get_name()); n = n->get_parent(); } base_path.invert(); Vector<StringName> new_base_path; if (p_new_parent) { n = p_new_parent; while (n) { new_base_path.push_back(n->get_name()); n = n->get_parent(); } new_base_path.invert(); } _fill_path_renames(base_path, new_base_path, p_node, p_renames); } void SceneTreeDock::perform_node_renames(Node *p_base, List<Pair<NodePath, NodePath> > *p_renames, Map<Ref<Animation>, Set<int> > *r_rem_anims) { Map<Ref<Animation>, Set<int> > rem_anims; if (!r_rem_anims) r_rem_anims = &rem_anims; if (!bool(EDITOR_DEF("editors/animation/autorename_animation_tracks", true))) return; if (!p_base) { p_base = edited_scene; } if (!p_base) return; if (Object::cast_to<AnimationPlayer>(p_base)) { AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_base); List<StringName> anims; ap->get_animation_list(&anims); Node *root = ap->get_node(ap->get_root()); if (root) { NodePath root_path = root->get_path(); NodePath new_root_path = root_path; for (List<Pair<NodePath, NodePath> >::Element *E = p_renames->front(); E; E = E->next()) { if (E->get().first == root_path) { new_root_path = E->get().second; break; } } if (new_root_path != NodePath()) { //will not be erased for (List<StringName>::Element *E = anims.front(); E; E = E->next()) { Ref<Animation> anim = ap->get_animation(E->get()); if (!r_rem_anims->has(anim)) { r_rem_anims->insert(anim, Set<int>()); Set<int> &ran = r_rem_anims->find(anim)->get(); for (int i = 0; i < anim->get_track_count(); i++) ran.insert(i); } Set<int> &ran = r_rem_anims->find(anim)->get(); if (anim.is_null()) continue; for (int i = 0; i < anim->get_track_count(); i++) { NodePath track_np = anim->track_get_path(i); Node *n = root->get_node(track_np); if (!n) { continue; } NodePath old_np = n->get_path(); if (!ran.has(i)) continue; //channel was removed for (List<Pair<NodePath, NodePath> >::Element *E = p_renames->front(); E; E = E->next()) { if (E->get().first == old_np) { if (E->get().second == NodePath()) { //will be erased int idx = 0; Set<int>::Element *EI = ran.front(); ERR_FAIL_COND(!EI); //bug while (EI->get() != i) { idx++; EI = EI->next(); ERR_FAIL_COND(!EI); //another bug } editor_data->get_undo_redo().add_do_method(anim.ptr(), "remove_track", idx); editor_data->get_undo_redo().add_undo_method(anim.ptr(), "add_track", anim->track_get_type(i), idx); editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_set_path", idx, track_np); editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_set_interpolation_type", idx, anim->track_get_interpolation_type(i)); for (int j = 0; j < anim->track_get_key_count(i); j++) { editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_insert_key", idx, anim->track_get_key_time(i, j), anim->track_get_key_value(i, j), anim->track_get_key_transition(i, j)); } ran.erase(i); //byebye channel } else { //will be renamed NodePath rel_path = new_root_path.rel_path_to(E->get().second); NodePath new_path = NodePath(rel_path.get_names(), track_np.get_subnames(), false); if (new_path == track_np) continue; //bleh editor_data->get_undo_redo().add_do_method(anim.ptr(), "track_set_path", i, new_path); editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_set_path", i, track_np); } } } } } } } } for (int i = 0; i < p_base->get_child_count(); i++) perform_node_renames(p_base->get_child(i), p_renames, r_rem_anims); } void SceneTreeDock::_node_prerenamed(Node *p_node, const String &p_new_name) { List<Pair<NodePath, NodePath> > path_renames; Vector<StringName> base_path; Node *n = p_node->get_parent(); while (n) { base_path.push_back(n->get_name()); n = n->get_parent(); } base_path.invert(); Vector<StringName> new_base_path = base_path; base_path.push_back(p_node->get_name()); new_base_path.push_back(p_new_name); Pair<NodePath, NodePath> npp; npp.first = NodePath(base_path, true); npp.second = NodePath(new_base_path, true); path_renames.push_back(npp); for (int i = 0; i < p_node->get_child_count(); i++) _fill_path_renames(base_path, new_base_path, p_node->get_child(i), &path_renames); perform_node_renames(NULL, &path_renames); } bool SceneTreeDock::_validate_no_foreign() { List<Node *> selection = editor_selection->get_selected_node_list(); for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { if (E->get() != edited_scene && E->get()->get_owner() != edited_scene) { accept->get_ok()->set_text(TTR("Makes Sense!")); accept->set_text(TTR("Can't operate on nodes from a foreign scene!")); accept->popup_centered_minsize(); return false; } if (edited_scene->get_scene_inherited_state().is_valid() && edited_scene->get_scene_inherited_state()->find_node_by_path(edited_scene->get_path_to(E->get())) >= 0) { accept->get_ok()->set_text(TTR("Makes Sense!")); accept->set_text(TTR("Can't operate on nodes the current scene inherits from!")); accept->popup_centered_minsize(); return false; } } return true; } void SceneTreeDock::_node_reparent(NodePath p_path, bool p_keep_global_xform) { Node *new_parent = scene_root->get_node(p_path); ERR_FAIL_COND(!new_parent); List<Node *> selection = editor_selection->get_selected_node_list(); if (selection.empty()) return; //nothing to reparent Vector<Node *> nodes; for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { nodes.push_back(E->get()); } _do_reparent(new_parent, -1, nodes, p_keep_global_xform); } void SceneTreeDock::_do_reparent(Node *p_new_parent, int p_position_in_parent, Vector<Node *> p_nodes, bool p_keep_global_xform) { Node *new_parent = p_new_parent; ERR_FAIL_COND(!new_parent); Node *validate = new_parent; while (validate) { if (p_nodes.find(validate) != -1) { ERR_EXPLAIN("Selection changed at some point.. can't reparent"); ERR_FAIL(); return; } validate = validate->get_parent(); } //ok all valid if (p_nodes.size() == 0) return; //nothing to reparent //sort by tree order, so re-adding is easy p_nodes.sort_custom<Node::Comparator>(); editor_data->get_undo_redo().create_action(TTR("Reparent Node")); List<Pair<NodePath, NodePath> > path_renames; Vector<StringName> former_names; int inc = 0; for (int ni = 0; ni < p_nodes.size(); ni++) { //no undo for now, sorry Node *node = p_nodes[ni]; fill_path_renames(node, new_parent, &path_renames); former_names.push_back(node->get_name()); List<Node *> owned; node->get_owned_by(node->get_owner(), &owned); Array owners; for (List<Node *>::Element *E = owned.front(); E; E = E->next()) { owners.push_back(E->get()); } if (new_parent == node->get_parent() && node->get_index() < p_position_in_parent + ni) { //if child will generate a gap when moved, adjust inc--; } editor_data->get_undo_redo().add_do_method(node->get_parent(), "remove_child", node); editor_data->get_undo_redo().add_do_method(new_parent, "add_child", node); if (p_position_in_parent >= 0) editor_data->get_undo_redo().add_do_method(new_parent, "move_child", node, p_position_in_parent + inc); ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger(); String new_name = new_parent->validate_child_name(node); editor_data->get_undo_redo().add_do_method(sed, "live_debug_reparent_node", edited_scene->get_path_to(node), edited_scene->get_path_to(new_parent), new_name, -1); editor_data->get_undo_redo().add_undo_method(sed, "live_debug_reparent_node", NodePath(String(edited_scene->get_path_to(new_parent)) + "/" + new_name), edited_scene->get_path_to(node->get_parent()), node->get_name(), node->get_index()); if (p_keep_global_xform) { if (Object::cast_to<Node2D>(node)) editor_data->get_undo_redo().add_do_method(node, "set_global_transform", Object::cast_to<Node2D>(node)->get_global_transform()); if (Object::cast_to<Spatial>(node)) editor_data->get_undo_redo().add_do_method(node, "set_global_transform", Object::cast_to<Spatial>(node)->get_global_transform()); if (Object::cast_to<Control>(node)) editor_data->get_undo_redo().add_do_method(node, "set_global_position", Object::cast_to<Control>(node)->get_global_position()); } editor_data->get_undo_redo().add_do_method(this, "_set_owners", edited_scene, owners); if (AnimationPlayerEditor::singleton->get_key_editor()->get_root() == node) editor_data->get_undo_redo().add_do_method(AnimationPlayerEditor::singleton->get_key_editor(), "set_root", node); editor_data->get_undo_redo().add_undo_method(new_parent, "remove_child", node); editor_data->get_undo_redo().add_undo_method(node, "set_name", former_names[ni]); inc++; } //add and move in a second step.. (so old order is preserved) for (int ni = 0; ni < p_nodes.size(); ni++) { Node *node = p_nodes[ni]; List<Node *> owned; node->get_owned_by(node->get_owner(), &owned); Array owners; for (List<Node *>::Element *E = owned.front(); E; E = E->next()) { owners.push_back(E->get()); } int child_pos = node->get_position_in_parent(); editor_data->get_undo_redo().add_undo_method(node->get_parent(), "add_child", node); editor_data->get_undo_redo().add_undo_method(node->get_parent(), "move_child", node, child_pos); editor_data->get_undo_redo().add_undo_method(this, "_set_owners", edited_scene, owners); if (AnimationPlayerEditor::singleton->get_key_editor()->get_root() == node) editor_data->get_undo_redo().add_undo_method(AnimationPlayerEditor::singleton->get_key_editor(), "set_root", node); if (p_keep_global_xform) { if (Object::cast_to<Node2D>(node)) editor_data->get_undo_redo().add_undo_method(node, "set_transform", Object::cast_to<Node2D>(node)->get_transform()); if (Object::cast_to<Spatial>(node)) editor_data->get_undo_redo().add_undo_method(node, "set_transform", Object::cast_to<Spatial>(node)->get_transform()); if (Object::cast_to<Control>(node)) editor_data->get_undo_redo().add_undo_method(node, "set_position", Object::cast_to<Control>(node)->get_position()); } } perform_node_renames(NULL, &path_renames); editor_data->get_undo_redo().commit_action(); } void SceneTreeDock::_script_created(Ref<Script> p_script) { Node *selected = scene_tree->get_selected(); if (!selected) return; selected->set_script(p_script.get_ref_ptr()); editor->push_item(p_script.operator->()); _update_script_button(); } void SceneTreeDock::_delete_confirm() { List<Node *> remove_list = editor_selection->get_selected_node_list(); if (remove_list.empty()) return; editor->get_editor_plugins_over()->make_visible(false); editor_data->get_undo_redo().create_action(TTR("Remove Node(s)")); bool entire_scene = false; for (List<Node *>::Element *E = remove_list.front(); E; E = E->next()) { if (E->get() == edited_scene) { entire_scene = true; } } if (entire_scene) { editor_data->get_undo_redo().add_do_method(editor, "set_edited_scene", (Object *)NULL); editor_data->get_undo_redo().add_undo_method(editor, "set_edited_scene", edited_scene); editor_data->get_undo_redo().add_undo_method(edited_scene, "set_owner", edited_scene->get_owner()); editor_data->get_undo_redo().add_undo_method(scene_tree, "update_tree"); editor_data->get_undo_redo().add_undo_reference(edited_scene); } else { remove_list.sort_custom<Node::Comparator>(); //sort nodes to keep positions List<Pair<NodePath, NodePath> > path_renames; //delete from animation for (List<Node *>::Element *E = remove_list.front(); E; E = E->next()) { Node *n = E->get(); if (!n->is_inside_tree() || !n->get_parent()) continue; fill_path_renames(n, NULL, &path_renames); } perform_node_renames(NULL, &path_renames); //delete for read for (List<Node *>::Element *E = remove_list.front(); E; E = E->next()) { Node *n = E->get(); if (!n->is_inside_tree() || !n->get_parent()) continue; List<Node *> owned; n->get_owned_by(n->get_owner(), &owned); Array owners; for (List<Node *>::Element *E = owned.front(); E; E = E->next()) { owners.push_back(E->get()); } editor_data->get_undo_redo().add_do_method(n->get_parent(), "remove_child", n); editor_data->get_undo_redo().add_undo_method(n->get_parent(), "add_child", n); editor_data->get_undo_redo().add_undo_method(n->get_parent(), "move_child", n, n->get_index()); if (AnimationPlayerEditor::singleton->get_key_editor()->get_root() == n) editor_data->get_undo_redo().add_undo_method(AnimationPlayerEditor::singleton->get_key_editor(), "set_root", n); editor_data->get_undo_redo().add_undo_method(this, "_set_owners", edited_scene, owners); editor_data->get_undo_redo().add_undo_reference(n); ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger(); editor_data->get_undo_redo().add_do_method(sed, "live_debug_remove_and_keep_node", edited_scene->get_path_to(n), n->get_instance_id()); editor_data->get_undo_redo().add_undo_method(sed, "live_debug_restore_node", n->get_instance_id(), edited_scene->get_path_to(n->get_parent()), n->get_index()); } } editor_data->get_undo_redo().commit_action(); // hack, force 2d editor viewport to refresh after deletion if (CanvasItemEditor *editor = CanvasItemEditor::get_singleton()) editor->get_viewport_control()->update(); editor->push_item(NULL); // Fixes the EditorHistory from still offering deleted notes EditorHistory *editor_history = EditorNode::get_singleton()->get_editor_history(); editor_history->cleanup_history(); EditorNode::get_singleton()->call("_prepare_history"); } void SceneTreeDock::_update_script_button() { if (EditorNode::get_singleton()->get_editor_selection()->get_selection().size() == 1) { if (EditorNode::get_singleton()->get_editor_selection()->get_selection().front()->key()->get_script().is_null()) { button_create_script->show(); button_clear_script->hide(); } else { button_create_script->hide(); button_clear_script->show(); } } else { button_create_script->hide(); button_clear_script->hide(); } } void SceneTreeDock::_selection_changed() { int selection_size = EditorNode::get_singleton()->get_editor_selection()->get_selection().size(); if (selection_size > 1) { //automatically turn on multi-edit _tool_selected(TOOL_MULTI_EDIT); } _update_script_button(); } void SceneTreeDock::_create() { if (current_option == TOOL_NEW) { Node *parent = NULL; if (edited_scene) { // If root exists in edited scene parent = scene_tree->get_selected(); if (!parent) parent = edited_scene; } else { // If no root exist in edited scene parent = scene_root; ERR_FAIL_COND(!parent); } Object *c = create_dialog->instance_selected(); ERR_FAIL_COND(!c); Node *child = Object::cast_to<Node>(c); ERR_FAIL_COND(!child); editor_data->get_undo_redo().create_action(TTR("Create Node")); if (edited_scene) { editor_data->get_undo_redo().add_do_method(parent, "add_child", child); editor_data->get_undo_redo().add_do_method(child, "set_owner", edited_scene); editor_data->get_undo_redo().add_do_method(editor_selection, "clear"); editor_data->get_undo_redo().add_do_method(editor_selection, "add_node", child); editor_data->get_undo_redo().add_do_reference(child); editor_data->get_undo_redo().add_undo_method(parent, "remove_child", child); String new_name = parent->validate_child_name(child); ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger(); editor_data->get_undo_redo().add_do_method(sed, "live_debug_create_node", edited_scene->get_path_to(parent), child->get_class(), new_name); editor_data->get_undo_redo().add_undo_method(sed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)) + "/" + new_name)); } else { editor_data->get_undo_redo().add_do_method(editor, "set_edited_scene", child); editor_data->get_undo_redo().add_do_method(scene_tree, "update_tree"); editor_data->get_undo_redo().add_do_reference(child); editor_data->get_undo_redo().add_undo_method(editor, "set_edited_scene", (Object *)NULL); } editor_data->get_undo_redo().commit_action(); editor->push_item(c); editor_selection->clear(); editor_selection->add_node(child); if (Object::cast_to<Control>(c)) { //make editor more comfortable, so some controls don't appear super shrunk Control *ct = Object::cast_to<Control>(c); Size2 ms = ct->get_minimum_size(); if (ms.width < 4) ms.width = 40; if (ms.height < 4) ms.height = 40; ct->set_size(ms); } } else if (current_option == TOOL_REPLACE) { List<Node *> selection = editor_selection->get_selected_node_list(); ERR_FAIL_COND(selection.size() <= 0); for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { Node *n = E->get(); ERR_FAIL_COND(!n); Object *c = create_dialog->instance_selected(); ERR_FAIL_COND(!c); Node *newnode = Object::cast_to<Node>(c); ERR_FAIL_COND(!newnode); replace_node(n, newnode); } } } void SceneTreeDock::replace_node(Node *p_node, Node *p_by_node) { Node *n = p_node; Node *newnode = p_by_node; List<PropertyInfo> pinfo; n->get_property_list(&pinfo); for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { if (!(E->get().usage & PROPERTY_USAGE_STORAGE)) continue; if (E->get().name == "__meta__") continue; newnode->set(E->get().name, n->get(E->get().name)); } editor->push_item(NULL); //reconnect signals List<MethodInfo> sl; n->get_signal_list(&sl); for (List<MethodInfo>::Element *E = sl.front(); E; E = E->next()) { List<Object::Connection> cl; n->get_signal_connection_list(E->get().name, &cl); for (List<Object::Connection>::Element *F = cl.front(); F; F = F->next()) { Object::Connection &c = F->get(); if (!(c.flags & Object::CONNECT_PERSIST)) continue; newnode->connect(c.signal, c.target, c.method, varray(), Object::CONNECT_PERSIST); } } String newname = n->get_name(); List<Node *> to_erase; for (int i = 0; i < n->get_child_count(); i++) { if (n->get_child(i)->get_owner() == NULL && n->is_owned_by_parent()) { to_erase.push_back(n->get_child(i)); } } n->replace_by(newnode, true); if (n == edited_scene) { edited_scene = newnode; editor->set_edited_scene(newnode); newnode->set_editable_instances(n->get_editable_instances()); } //small hack to make collisionshapes and other kind of nodes to work for (int i = 0; i < newnode->get_child_count(); i++) { Node *c = newnode->get_child(i); c->call("set_transform", c->call("get_transform")); } editor_data->get_undo_redo().clear_history(); newnode->set_name(newname); editor->push_item(newnode); memdelete(n); while (to_erase.front()) { memdelete(to_erase.front()->get()); to_erase.pop_front(); } } void SceneTreeDock::set_edited_scene(Node *p_scene) { edited_scene = p_scene; } void SceneTreeDock::set_selected(Node *p_node, bool p_emit_selected) { scene_tree->set_selected(p_node, p_emit_selected); } void SceneTreeDock::import_subscene() { import_subscene_dialog->popup_centered_ratio(); } void SceneTreeDock::_import_subscene() { Node *parent = scene_tree->get_selected(); if (!parent) { parent = editor_data->get_edited_scene_root(); ERR_FAIL_COND(!parent); } import_subscene_dialog->move(parent, edited_scene); editor_data->get_undo_redo().clear_history(); //no undo for now.. } void SceneTreeDock::_new_scene_from(String p_file) { List<Node *> selection = editor_selection->get_selected_node_list(); if (selection.size() != 1) { accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("This operation requires a single selected node.")); accept->popup_centered_minsize(); return; } Node *base = selection.front()->get(); Map<Node *, Node *> reown; reown[editor_data->get_edited_scene_root()] = base; Node *copy = base->duplicate_and_reown(reown); if (copy) { Ref<PackedScene> sdata = memnew(PackedScene); Error err = sdata->pack(copy); memdelete(copy); if (err != OK) { accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("Couldn't save new scene. Likely dependencies (instances) couldn't be satisfied.")); accept->popup_centered_minsize(); return; } int flg = 0; if (EditorSettings::get_singleton()->get("filesystem/on_save/compress_binary_resources")) flg |= ResourceSaver::FLAG_COMPRESS; err = ResourceSaver::save(p_file, sdata, flg); if (err != OK) { accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("Error saving scene.")); accept->popup_centered_minsize(); return; } _replace_with_branch_scene(p_file, base); } else { accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("Error duplicating scene to save it.")); accept->popup_centered_minsize(); return; } } static bool _is_node_visible(Node *p_node) { if (!p_node->get_owner()) return false; if (p_node->get_owner() != EditorNode::get_singleton()->get_edited_scene() && !EditorNode::get_singleton()->get_edited_scene()->is_editable_instance(p_node->get_owner())) return false; return true; } static bool _has_visible_children(Node *p_node) { bool collapsed = p_node->is_displayed_folded(); if (collapsed) return false; for (int i = 0; i < p_node->get_child_count(); i++) { Node *child = p_node->get_child(i); if (!_is_node_visible(child)) continue; return true; } return false; } static Node *_find_last_visible(Node *p_node) { Node *last = NULL; bool collapsed = p_node->is_displayed_folded(); if (!collapsed) { for (int i = 0; i < p_node->get_child_count(); i++) { if (_is_node_visible(p_node->get_child(i))) { last = p_node->get_child(i); } } } if (last) { Node *lastc = _find_last_visible(last); if (lastc) last = lastc; } else { last = p_node; } return last; } void SceneTreeDock::_normalize_drop(Node *&to_node, int &to_pos, int p_type) { to_pos = -1; if (p_type == -1) { //drop at above selected node if (to_node == EditorNode::get_singleton()->get_edited_scene()) { to_node = NULL; ERR_EXPLAIN("Cannot perform drop above the root node!"); ERR_FAIL(); } to_pos = to_node->get_index(); to_node = to_node->get_parent(); } else if (p_type == 1) { //drop at below selected node if (to_node == EditorNode::get_singleton()->get_edited_scene()) { //if at lower sibling of root node to_pos = 0; //just insert at beginning of root node return; } Node *lower_sibling = NULL; if (_has_visible_children(to_node)) { to_pos = 0; } else { for (int i = to_node->get_index() + 1; i < to_node->get_parent()->get_child_count(); i++) { Node *c = to_node->get_parent()->get_child(i); if (_is_node_visible(c)) { lower_sibling = c; break; } } if (lower_sibling) { to_pos = lower_sibling->get_index(); } to_node = to_node->get_parent(); } } } void SceneTreeDock::_files_dropped(Vector<String> p_files, NodePath p_to, int p_type) { Node *node = get_node(p_to); ERR_FAIL_COND(!node); int to_pos = -1; _normalize_drop(node, to_pos, p_type); _perform_instance_scenes(p_files, node, to_pos); } void SceneTreeDock::_script_dropped(String p_file, NodePath p_to) { Ref<Script> scr = ResourceLoader::load(p_file); ERR_FAIL_COND(!scr.is_valid()); Node *n = get_node(p_to); if (n) { n->set_script(scr.get_ref_ptr()); _update_script_button(); } } void SceneTreeDock::_nodes_dragged(Array p_nodes, NodePath p_to, int p_type) { Vector<Node *> nodes; Node *to_node; for (int i = 0; i < p_nodes.size(); i++) { Node *n = get_node((p_nodes[i])); if (n) { nodes.push_back(n); } } if (nodes.size() == 0) return; to_node = get_node(p_to); if (!to_node) return; int to_pos = -1; _normalize_drop(to_node, to_pos, p_type); _do_reparent(to_node, to_pos, nodes, true); } void SceneTreeDock::_add_children_to_popup(Object *p_obj, int p_depth) { if (p_depth > 8) return; List<PropertyInfo> pinfo; p_obj->get_property_list(&pinfo); for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { if (!(E->get().usage & PROPERTY_USAGE_EDITOR)) continue; if (E->get().hint != PROPERTY_HINT_RESOURCE_TYPE) continue; Variant value = p_obj->get(E->get().name); if (value.get_type() != Variant::OBJECT) continue; Object *obj = value; if (!obj) continue; Ref<Texture> icon; if (has_icon(obj->get_class(), "EditorIcons")) icon = get_icon(obj->get_class(), "EditorIcons"); else icon = get_icon("Object", "EditorIcons"); if (menu->get_item_count() == 0) { menu->add_submenu_item(TTR("Sub-Resources"), "Sub-Resources"); } int index = menu_subresources->get_item_count(); menu_subresources->add_icon_item(icon, E->get().name.capitalize(), EDIT_SUBRESOURCE_BASE + subresources.size()); menu_subresources->set_item_h_offset(index, p_depth * 10 * EDSCALE); subresources.push_back(obj->get_instance_id()); _add_children_to_popup(obj, p_depth + 1); } } void SceneTreeDock::_tree_rmb(const Vector2 &p_menu_pos) { if (!EditorNode::get_singleton()->get_edited_scene()) { menu->clear(); menu->add_icon_shortcut(get_icon("Add", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/add_child_node"), TOOL_NEW); menu->add_icon_shortcut(get_icon("Instance", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/instance_scene"), TOOL_INSTANCE); menu->set_size(Size2(1, 1)); menu->set_position(p_menu_pos); menu->popup(); return; } List<Node *> selection = editor_selection->get_selected_node_list(); if (selection.size() == 0) return; menu->clear(); if (selection.size() == 1) { subresources.clear(); menu_subresources->clear(); _add_children_to_popup(selection.front()->get(), 0); if (menu->get_item_count() > 0) menu->add_separator(); menu->add_icon_shortcut(get_icon("Add", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/add_child_node"), TOOL_NEW); menu->add_icon_shortcut(get_icon("Instance", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/instance_scene"), TOOL_INSTANCE); menu->add_separator(); menu->add_icon_shortcut(get_icon("ScriptCreate", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/attach_script"), TOOL_ATTACH_SCRIPT); menu->add_icon_shortcut(get_icon("ScriptRemove", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/clear_script"), TOOL_CLEAR_SCRIPT); menu->add_separator(); } menu->add_icon_shortcut(get_icon("Reload", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/change_node_type"), TOOL_REPLACE); menu->add_separator(); menu->add_icon_shortcut(get_icon("MoveUp", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/move_up"), TOOL_MOVE_UP); menu->add_icon_shortcut(get_icon("MoveDown", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/move_down"), TOOL_MOVE_DOWN); menu->add_icon_shortcut(get_icon("Duplicate", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/duplicate"), TOOL_DUPLICATE); menu->add_icon_shortcut(get_icon("Reparent", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/reparent"), TOOL_REPARENT); if (selection.size() == 1) { menu->add_separator(); menu->add_icon_shortcut(get_icon("Blend", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/merge_from_scene"), TOOL_MERGE_FROM_SCENE); menu->add_icon_shortcut(get_icon("CreateNewSceneFrom", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/save_branch_as_scene"), TOOL_NEW_SCENE_FROM); menu->add_separator(); menu->add_icon_shortcut(get_icon("CopyNodePath", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/copy_node_path"), TOOL_COPY_NODE_PATH); bool is_external = (selection[0]->get_filename() != ""); if (is_external) { bool is_inherited = selection[0]->get_scene_inherited_state() != NULL; bool is_top_level = selection[0]->get_owner() == NULL; if (is_inherited && is_top_level) { menu->add_separator(); menu->add_item(TTR("Clear Inheritance"), TOOL_SCENE_CLEAR_INHERITANCE); menu->add_icon_item(get_icon("Load", "EditorIcons"), TTR("Open in Editor"), TOOL_SCENE_OPEN_INHERITED); } else if (!is_top_level) { menu->add_separator(); bool editable = EditorNode::get_singleton()->get_edited_scene()->is_editable_instance(selection[0]); bool placeholder = selection[0]->get_scene_instance_load_placeholder(); menu->add_check_item(TTR("Editable Children"), TOOL_SCENE_EDITABLE_CHILDREN); menu->add_check_item(TTR("Load As Placeholder"), TOOL_SCENE_USE_PLACEHOLDER); menu->add_item(TTR("Discard Instancing"), TOOL_SCENE_CLEAR_INSTANCING); menu->add_icon_item(get_icon("Load", "EditorIcons"), TTR("Open in Editor"), TOOL_SCENE_OPEN); menu->set_item_checked(menu->get_item_idx_from_text(TTR("Editable Children")), editable); menu->set_item_checked(menu->get_item_idx_from_text(TTR("Load As Placeholder")), placeholder); } } } menu->add_separator(); menu->add_icon_shortcut(get_icon("Remove", "EditorIcons"), ED_SHORTCUT("scene_tree/delete", TTR("Delete Node(s)"), KEY_DELETE), TOOL_ERASE); menu->set_size(Size2(1, 1)); menu->set_position(p_menu_pos); menu->popup(); } void SceneTreeDock::_filter_changed(const String &p_filter) { scene_tree->set_filter(p_filter); } String SceneTreeDock::get_filter() { return filter->get_text(); } void SceneTreeDock::set_filter(const String &p_filter) { filter->set_text(p_filter); scene_tree->set_filter(p_filter); } void SceneTreeDock::_focus_node() { Node *node = scene_tree->get_selected(); ERR_FAIL_COND(!node); if (node->is_class("CanvasItem")) { CanvasItemEditorPlugin *editor = Object::cast_to<CanvasItemEditorPlugin>(editor_data->get_editor("2D")); editor->get_canvas_item_editor()->focus_selection(); } else { SpatialEditorPlugin *editor = Object::cast_to<SpatialEditorPlugin>(editor_data->get_editor("3D")); editor->get_spatial_editor()->get_editor_viewport(0)->focus_selection(); } } void SceneTreeDock::open_script_dialog(Node *p_for_node) { scene_tree->set_selected(p_for_node, false); _tool_selected(TOOL_ATTACH_SCRIPT); } void SceneTreeDock::add_remote_tree_editor(Control *p_remote) { ERR_FAIL_COND(remote_tree != NULL); add_child(p_remote); remote_tree = p_remote; remote_tree->hide(); } void SceneTreeDock::show_remote_tree() { _remote_tree_selected(); } void SceneTreeDock::hide_remote_tree() { _local_tree_selected(); } void SceneTreeDock::show_tab_buttons() { button_hb->show(); } void SceneTreeDock::hide_tab_buttons() { button_hb->hide(); } void SceneTreeDock::_remote_tree_selected() { scene_tree->hide(); if (remote_tree) remote_tree->show(); edit_remote->set_pressed(true); edit_local->set_pressed(false); emit_signal("remote_tree_selected"); } void SceneTreeDock::_local_tree_selected() { scene_tree->show(); if (remote_tree) remote_tree->hide(); edit_remote->set_pressed(false); edit_local->set_pressed(true); } void SceneTreeDock::_bind_methods() { ClassDB::bind_method(D_METHOD("_tool_selected"), &SceneTreeDock::_tool_selected, DEFVAL(false)); ClassDB::bind_method(D_METHOD("_create"), &SceneTreeDock::_create); ClassDB::bind_method(D_METHOD("_node_reparent"), &SceneTreeDock::_node_reparent); ClassDB::bind_method(D_METHOD("_set_owners"), &SceneTreeDock::_set_owners); ClassDB::bind_method(D_METHOD("_node_selected"), &SceneTreeDock::_node_selected); ClassDB::bind_method(D_METHOD("_node_renamed"), &SceneTreeDock::_node_renamed); ClassDB::bind_method(D_METHOD("_script_created"), &SceneTreeDock::_script_created); ClassDB::bind_method(D_METHOD("_load_request"), &SceneTreeDock::_load_request); ClassDB::bind_method(D_METHOD("_script_open_request"), &SceneTreeDock::_script_open_request); ClassDB::bind_method(D_METHOD("_unhandled_key_input"), &SceneTreeDock::_unhandled_key_input); ClassDB::bind_method(D_METHOD("_input"), &SceneTreeDock::_input); ClassDB::bind_method(D_METHOD("_nodes_drag_begin"), &SceneTreeDock::_nodes_drag_begin); ClassDB::bind_method(D_METHOD("_delete_confirm"), &SceneTreeDock::_delete_confirm); ClassDB::bind_method(D_METHOD("_node_prerenamed"), &SceneTreeDock::_node_prerenamed); ClassDB::bind_method(D_METHOD("_import_subscene"), &SceneTreeDock::_import_subscene); ClassDB::bind_method(D_METHOD("_selection_changed"), &SceneTreeDock::_selection_changed); ClassDB::bind_method(D_METHOD("_new_scene_from"), &SceneTreeDock::_new_scene_from); ClassDB::bind_method(D_METHOD("_nodes_dragged"), &SceneTreeDock::_nodes_dragged); ClassDB::bind_method(D_METHOD("_files_dropped"), &SceneTreeDock::_files_dropped); ClassDB::bind_method(D_METHOD("_script_dropped"), &SceneTreeDock::_script_dropped); ClassDB::bind_method(D_METHOD("_tree_rmb"), &SceneTreeDock::_tree_rmb); ClassDB::bind_method(D_METHOD("_filter_changed"), &SceneTreeDock::_filter_changed); ClassDB::bind_method(D_METHOD("_focus_node"), &SceneTreeDock::_focus_node); ClassDB::bind_method(D_METHOD("_remote_tree_selected"), &SceneTreeDock::_remote_tree_selected); ClassDB::bind_method(D_METHOD("_local_tree_selected"), &SceneTreeDock::_local_tree_selected); ClassDB::bind_method(D_METHOD("instance"), &SceneTreeDock::instance); ADD_SIGNAL(MethodInfo("remote_tree_selected")); } SceneTreeDock::SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSelection *p_editor_selection, EditorData &p_editor_data) { set_name("Scene"); editor = p_editor; edited_scene = NULL; editor_data = &p_editor_data; editor_selection = p_editor_selection; scene_root = p_scene_root; VBoxContainer *vbc = this; HBoxContainer *filter_hbc = memnew(HBoxContainer); filter_hbc->add_constant_override("separate", 0); ToolButton *tb; ED_SHORTCUT("scene_tree/add_child_node", TTR("Add Child Node"), KEY_MASK_CMD | KEY_A); ED_SHORTCUT("scene_tree/instance_scene", TTR("Instance Child Scene")); ED_SHORTCUT("scene_tree/change_node_type", TTR("Change Type")); ED_SHORTCUT("scene_tree/attach_script", TTR("Attach Script")); ED_SHORTCUT("scene_tree/clear_script", TTR("Clear Script")); ED_SHORTCUT("scene_tree/move_up", TTR("Move Up"), KEY_MASK_CMD | KEY_UP); ED_SHORTCUT("scene_tree/move_down", TTR("Move Down"), KEY_MASK_CMD | KEY_DOWN); ED_SHORTCUT("scene_tree/duplicate", TTR("Duplicate"), KEY_MASK_CMD | KEY_D); ED_SHORTCUT("scene_tree/reparent", TTR("Reparent")); ED_SHORTCUT("scene_tree/merge_from_scene", TTR("Merge From Scene")); ED_SHORTCUT("scene_tree/save_branch_as_scene", TTR("Save Branch as Scene")); ED_SHORTCUT("scene_tree/copy_node_path", TTR("Copy Node Path"), KEY_MASK_CMD | KEY_C); ED_SHORTCUT("scene_tree/delete_no_confirm", TTR("Delete (No Confirm)"), KEY_MASK_SHIFT | KEY_DELETE); ED_SHORTCUT("scene_tree/delete", TTR("Delete"), KEY_DELETE); tb = memnew(ToolButton); tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_NEW, false)); tb->set_tooltip(TTR("Add/Create a New Node")); tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/add_child_node")); filter_hbc->add_child(tb); button_add = tb; tb = memnew(ToolButton); tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_INSTANCE, false)); tb->set_tooltip(TTR("Instance a scene file as a Node. Creates an inherited scene if no root node exists.")); tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/instance_scene")); filter_hbc->add_child(tb); button_instance = tb; vbc->add_child(filter_hbc); filter = memnew(LineEdit); filter->set_h_size_flags(SIZE_EXPAND_FILL); filter->set_placeholder(TTR("Filter nodes")); filter_hbc->add_child(filter); filter->connect("text_changed", this, "_filter_changed"); tb = memnew(ToolButton); tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_ATTACH_SCRIPT, false)); tb->set_tooltip(TTR("Attach a new or existing script for the selected node.")); tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/attach_script")); filter_hbc->add_child(tb); tb->hide(); button_create_script = tb; tb = memnew(ToolButton); tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_CLEAR_SCRIPT, false)); tb->set_tooltip(TTR("Clear a script for the selected node.")); tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/clear_script")); filter_hbc->add_child(tb); button_clear_script = tb; tb->hide(); button_hb = memnew(HBoxContainer); vbc->add_child(button_hb); edit_remote = memnew(ToolButton); button_hb->add_child(edit_remote); edit_remote->set_h_size_flags(SIZE_EXPAND_FILL); edit_remote->set_text(TTR("Remote")); edit_remote->set_toggle_mode(true); edit_remote->connect("pressed", this, "_remote_tree_selected"); edit_local = memnew(ToolButton); button_hb->add_child(edit_local); edit_local->set_h_size_flags(SIZE_EXPAND_FILL); edit_local->set_text(TTR("Local")); edit_local->set_toggle_mode(true); edit_local->connect("pressed", this, "_local_tree_selected"); remote_tree = NULL; button_hb->hide(); scene_tree = memnew(SceneTreeEditor(false, true, true)); vbc->add_child(scene_tree); scene_tree->set_v_size_flags(SIZE_EXPAND | SIZE_FILL); scene_tree->connect("rmb_pressed", this, "_tree_rmb"); scene_tree->connect("node_selected", this, "_node_selected", varray(), CONNECT_DEFERRED); scene_tree->connect("node_renamed", this, "_node_renamed", varray(), CONNECT_DEFERRED); scene_tree->connect("node_prerename", this, "_node_prerenamed"); scene_tree->connect("open", this, "_load_request"); scene_tree->connect("open_script", this, "_script_open_request"); scene_tree->connect("nodes_rearranged", this, "_nodes_dragged"); scene_tree->connect("files_dropped", this, "_files_dropped"); scene_tree->connect("script_dropped", this, "_script_dropped"); scene_tree->connect("nodes_dragged", this, "_nodes_drag_begin"); scene_tree->get_scene_tree()->connect("item_double_clicked", this, "_focus_node"); scene_tree->set_undo_redo(&editor_data->get_undo_redo()); scene_tree->set_editor_selection(editor_selection); create_dialog = memnew(CreateDialog); create_dialog->set_base_type("Node"); add_child(create_dialog); create_dialog->connect("create", this, "_create"); script_create_dialog = memnew(ScriptCreateDialog); add_child(script_create_dialog); script_create_dialog->connect("script_created", this, "_script_created"); reparent_dialog = memnew(ReparentDialog); add_child(reparent_dialog); reparent_dialog->connect("reparent", this, "_node_reparent"); accept = memnew(AcceptDialog); add_child(accept); file = memnew(EditorFileDialog); add_child(file); file->connect("file_selected", this, "instance"); set_process_unhandled_key_input(true); delete_dialog = memnew(ConfirmationDialog); add_child(delete_dialog); delete_dialog->connect("confirmed", this, "_delete_confirm"); import_subscene_dialog = memnew(EditorSubScene); add_child(import_subscene_dialog); import_subscene_dialog->connect("subscene_selected", this, "_import_subscene"); new_scene_from_dialog = memnew(EditorFileDialog); new_scene_from_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE); add_child(new_scene_from_dialog); new_scene_from_dialog->connect("file_selected", this, "_new_scene_from"); menu = memnew(PopupMenu); add_child(menu); menu->connect("id_pressed", this, "_tool_selected"); menu_subresources = memnew(PopupMenu); menu_subresources->set_name("Sub-Resources"); menu_subresources->connect("id_pressed", this, "_tool_selected"); menu->add_child(menu_subresources); first_enter = true; restore_script_editor_on_drag = false; clear_inherit_confirm = memnew(ConfirmationDialog); clear_inherit_confirm->set_text(TTR("Clear Inheritance? (No Undo!)")); clear_inherit_confirm->get_ok()->set_text(TTR("Clear!")); add_child(clear_inherit_confirm); set_process_input(true); } Fix overwriting all common properties when using `Change Type` tool If you change the type of an existing node, it checks if you have modified the initial value of their properties before overwriting their values in the new node. For example, if you created a `Label` and changed it to `LineEdit`, the `mouse_filter` property was created as `Ignore` for the original `Label` node, and was maintained after changing it to `LineEdit` causing not to work as expected. Now it checks if `Ignore` is the default value for `Label` nodes, and as it is, the property value is left unchanged, maintaining the default value for `LineEdit`, which is `Stop`. Fix #13955 and alike. /*************************************************************************/ /* scene_tree_dock.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "scene_tree_dock.h" #include "core/io/resource_saver.h" #include "core/os/keyboard.h" #include "core/project_settings.h" #include "editor/animation_editor.h" #include "editor/editor_node.h" #include "editor/editor_settings.h" #include "editor/multi_node_edit.h" #include "editor/plugins/animation_player_editor_plugin.h" #include "editor/plugins/canvas_item_editor_plugin.h" #include "editor/plugins/script_editor_plugin.h" #include "editor/plugins/spatial_editor_plugin.h" #include "editor/script_editor_debugger.h" #include "scene/main/viewport.h" #include "scene/resources/packed_scene.h" void SceneTreeDock::_nodes_drag_begin() { if (restore_script_editor_on_drag) { EditorNode::get_singleton()->set_visible_editor(EditorNode::EDITOR_SCRIPT); restore_script_editor_on_drag = false; } } void SceneTreeDock::_input(Ref<InputEvent> p_event) { Ref<InputEventMouseButton> mb = p_event; if (mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) { restore_script_editor_on_drag = false; //lost chance } } void SceneTreeDock::_unhandled_key_input(Ref<InputEvent> p_event) { if (get_viewport()->get_modal_stack_top()) return; //ignore because of modal window if (get_focus_owner() && get_focus_owner()->is_text_field()) return; if (!p_event->is_pressed() || p_event->is_echo()) return; if (ED_IS_SHORTCUT("scene_tree/add_child_node", p_event)) { _tool_selected(TOOL_NEW); } else if (ED_IS_SHORTCUT("scene_tree/instance_scene", p_event)) { _tool_selected(TOOL_INSTANCE); } else if (ED_IS_SHORTCUT("scene_tree/change_node_type", p_event)) { _tool_selected(TOOL_REPLACE); } else if (ED_IS_SHORTCUT("scene_tree/duplicate", p_event)) { _tool_selected(TOOL_DUPLICATE); } else if (ED_IS_SHORTCUT("scene_tree/attach_script", p_event)) { _tool_selected(TOOL_ATTACH_SCRIPT); } else if (ED_IS_SHORTCUT("scene_tree/clear_script", p_event)) { _tool_selected(TOOL_CLEAR_SCRIPT); } else if (ED_IS_SHORTCUT("scene_tree/move_up", p_event)) { _tool_selected(TOOL_MOVE_UP); } else if (ED_IS_SHORTCUT("scene_tree/move_down", p_event)) { _tool_selected(TOOL_MOVE_DOWN); } else if (ED_IS_SHORTCUT("scene_tree/reparent", p_event)) { _tool_selected(TOOL_REPARENT); } else if (ED_IS_SHORTCUT("scene_tree/merge_from_scene", p_event)) { _tool_selected(TOOL_MERGE_FROM_SCENE); } else if (ED_IS_SHORTCUT("scene_tree/save_branch_as_scene", p_event)) { _tool_selected(TOOL_NEW_SCENE_FROM); } else if (ED_IS_SHORTCUT("scene_tree/delete_no_confirm", p_event)) { _tool_selected(TOOL_ERASE, true); } else if (ED_IS_SHORTCUT("scene_tree/copy_node_path", p_event)) { _tool_selected(TOOL_COPY_NODE_PATH); } else if (ED_IS_SHORTCUT("scene_tree/delete", p_event)) { _tool_selected(TOOL_ERASE); } } void SceneTreeDock::instance(const String &p_file) { Node *parent = scene_tree->get_selected(); if (!parent || !edited_scene) { current_option = -1; accept->get_ok()->set_text(TTR("OK :(")); accept->set_text(TTR("No parent to instance a child at.")); accept->popup_centered_minsize(); return; }; ERR_FAIL_COND(!parent); Vector<String> scenes; scenes.push_back(p_file); _perform_instance_scenes(scenes, parent, -1); } void SceneTreeDock::instance_scenes(const Vector<String> &p_files, Node *p_parent) { Node *parent = p_parent; if (!parent) { parent = scene_tree->get_selected(); } if (!parent || !edited_scene) { accept->get_ok()->set_text(TTR("OK")); accept->set_text(TTR("No parent to instance the scenes at.")); accept->popup_centered_minsize(); return; }; _perform_instance_scenes(p_files, parent, -1); } void SceneTreeDock::_perform_instance_scenes(const Vector<String> &p_files, Node *parent, int p_pos) { ERR_FAIL_COND(!parent); Vector<Node *> instances; bool error = false; for (int i = 0; i < p_files.size(); i++) { Ref<PackedScene> sdata = ResourceLoader::load(p_files[i]); if (!sdata.is_valid()) { current_option = -1; accept->get_ok()->set_text(TTR("Ugh")); accept->set_text(vformat(TTR("Error loading scene from %s"), p_files[i])); accept->popup_centered_minsize(); error = true; break; } Node *instanced_scene = sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE); if (!instanced_scene) { current_option = -1; accept->get_ok()->set_text(TTR("Ugh")); accept->set_text(vformat(TTR("Error instancing scene from %s"), p_files[i])); accept->popup_centered_minsize(); error = true; break; } if (edited_scene->get_filename() != "") { if (_cyclical_dependency_exists(edited_scene->get_filename(), instanced_scene)) { accept->get_ok()->set_text(TTR("Ok")); accept->set_text(vformat(TTR("Cannot instance the scene '%s' because the current scene exists within one of its nodes."), p_files[i])); accept->popup_centered_minsize(); error = true; break; } } instanced_scene->set_filename(ProjectSettings::get_singleton()->localize_path(p_files[i])); instances.push_back(instanced_scene); } if (error) { for (int i = 0; i < instances.size(); i++) { memdelete(instances[i]); } return; } editor_data->get_undo_redo().create_action(TTR("Instance Scene(s)")); for (int i = 0; i < instances.size(); i++) { Node *instanced_scene = instances[i]; editor_data->get_undo_redo().add_do_method(parent, "add_child", instanced_scene); if (p_pos >= 0) { editor_data->get_undo_redo().add_do_method(parent, "move_child", instanced_scene, p_pos + i); } editor_data->get_undo_redo().add_do_method(instanced_scene, "set_owner", edited_scene); editor_data->get_undo_redo().add_do_method(editor_selection, "clear"); editor_data->get_undo_redo().add_do_method(editor_selection, "add_node", instanced_scene); editor_data->get_undo_redo().add_do_reference(instanced_scene); editor_data->get_undo_redo().add_undo_method(parent, "remove_child", instanced_scene); String new_name = parent->validate_child_name(instanced_scene); ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger(); editor_data->get_undo_redo().add_do_method(sed, "live_debug_instance_node", edited_scene->get_path_to(parent), p_files[i], new_name); editor_data->get_undo_redo().add_undo_method(sed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)) + "/" + new_name)); } editor_data->get_undo_redo().commit_action(); } void SceneTreeDock::_replace_with_branch_scene(const String &p_file, Node *base) { Ref<PackedScene> sdata = ResourceLoader::load(p_file); if (!sdata.is_valid()) { accept->get_ok()->set_text(TTR("Ugh")); accept->set_text(vformat(TTR("Error loading scene from %s"), p_file)); accept->popup_centered_minsize(); return; } Node *instanced_scene = sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE); if (!instanced_scene) { accept->get_ok()->set_text(TTR("Ugh")); accept->set_text(vformat(TTR("Error instancing scene from %s"), p_file)); accept->popup_centered_minsize(); return; } Node *parent = base->get_parent(); int pos = base->get_index(); parent->remove_child(base); parent->add_child(instanced_scene); parent->move_child(instanced_scene, pos); instanced_scene->set_owner(edited_scene); editor_selection->clear(); editor_selection->add_node(instanced_scene); scene_tree->set_selected(instanced_scene); // Delete the node as late as possible because before another one is selected // an editor plugin could be referencing it to do something with it before // switching to another (or to none); and since some steps of changing the // editor state are deferred, the safest thing is to do this is as the last // step of this function and also by enqueing instead of memdelete()-ing it here base->queue_delete(); } bool SceneTreeDock::_cyclical_dependency_exists(const String &p_target_scene_path, Node *p_desired_node) { int childCount = p_desired_node->get_child_count(); if (p_desired_node->get_filename() == p_target_scene_path) { return true; } for (int i = 0; i < childCount; i++) { Node *child = p_desired_node->get_child(i); if (_cyclical_dependency_exists(p_target_scene_path, child)) { return true; } } return false; } void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) { current_option = p_tool; switch (p_tool) { case TOOL_NEW: { String preferred = ""; Node *current_edited_scene_root = EditorNode::get_singleton()->get_edited_scene(); if (current_edited_scene_root) { if (ClassDB::is_parent_class(current_edited_scene_root->get_class_name(), "Node2D")) preferred = "Node2D"; else if (ClassDB::is_parent_class(current_edited_scene_root->get_class_name(), "Spatial")) preferred = "Spatial"; } create_dialog->set_preferred_search_result_type(preferred); create_dialog->popup_create(true); } break; case TOOL_INSTANCE: { Node *scene = edited_scene; if (!scene) { EditorNode::get_singleton()->new_inherited_scene(); break; } file->set_mode(EditorFileDialog::MODE_OPEN_FILE); List<String> extensions; ResourceLoader::get_recognized_extensions_for_type("PackedScene", &extensions); file->clear_filters(); for (int i = 0; i < extensions.size(); i++) { file->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper()); } file->popup_centered_ratio(); } break; case TOOL_REPLACE: { create_dialog->popup_create(false, true); } break; case TOOL_ATTACH_SCRIPT: { Node *selected = scene_tree->get_selected(); if (!selected) break; Ref<Script> existing = selected->get_script(); if (existing.is_valid()) editor->push_item(existing.ptr()); else { String path = selected->get_filename(); if (path == "") { String root_path = editor_data->get_edited_scene_root()->get_filename(); if (root_path == "") { path = "res://" + selected->get_name(); } else { path = root_path.get_base_dir() + "/" + selected->get_name(); } } script_create_dialog->config(selected->get_class(), path); script_create_dialog->popup_centered(); } } break; case TOOL_CLEAR_SCRIPT: { Node *selected = scene_tree->get_selected(); if (!selected) break; Ref<Script> existing = selected->get_script(); if (existing.is_valid()) { const RefPtr empty; selected->set_script(empty); _update_script_button(); } } break; case TOOL_MOVE_UP: case TOOL_MOVE_DOWN: { if (!scene_tree->get_selected()) break; if (scene_tree->get_selected() == edited_scene) { current_option = -1; accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("This operation can't be done on the tree root.")); accept->popup_centered_minsize(); break; } if (!_validate_no_foreign()) break; bool MOVING_DOWN = (p_tool == TOOL_MOVE_DOWN); bool MOVING_UP = !MOVING_DOWN; Node *common_parent = scene_tree->get_selected()->get_parent(); List<Node *> selection = editor_selection->get_selected_node_list(); selection.sort_custom<Node::Comparator>(); // sort by index if (MOVING_DOWN) selection.invert(); int lowest_id = common_parent->get_child_count() - 1; int highest_id = 0; for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { int index = E->get()->get_index(); if (index > highest_id) highest_id = index; if (index < lowest_id) lowest_id = index; if (E->get()->get_parent() != common_parent) common_parent = NULL; } if (!common_parent || (MOVING_DOWN && highest_id >= common_parent->get_child_count() - MOVING_DOWN) || (MOVING_UP && lowest_id == 0)) break; // one or more nodes can not be moved if (selection.size() == 1) editor_data->get_undo_redo().create_action(TTR("Move Node In Parent")); if (selection.size() > 1) editor_data->get_undo_redo().create_action(TTR("Move Nodes In Parent")); for (int i = 0; i < selection.size(); i++) { Node *top_node = selection[i]; Node *bottom_node = selection[selection.size() - 1 - i]; ERR_FAIL_COND(!top_node->get_parent()); ERR_FAIL_COND(!bottom_node->get_parent()); int bottom_node_pos = bottom_node->get_index(); int top_node_pos_next = top_node->get_index() + (MOVING_DOWN ? 1 : -1); editor_data->get_undo_redo().add_do_method(top_node->get_parent(), "move_child", top_node, top_node_pos_next); editor_data->get_undo_redo().add_undo_method(bottom_node->get_parent(), "move_child", bottom_node, bottom_node_pos); } editor_data->get_undo_redo().commit_action(); } break; case TOOL_DUPLICATE: { if (!edited_scene) break; if (editor_selection->is_selected(edited_scene)) { current_option = -1; accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("This operation can't be done on the tree root.")); accept->popup_centered_minsize(); break; } if (!_validate_no_foreign()) break; List<Node *> selection = editor_selection->get_selected_node_list(); if (selection.size() == 0) break; editor_data->get_undo_redo().create_action(TTR("Duplicate Node(s)")); editor_data->get_undo_redo().add_do_method(editor_selection, "clear"); Node *dupsingle = NULL; for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { Node *node = E->get(); Node *parent = node->get_parent(); List<Node *> owned; node->get_owned_by(node->get_owner(), &owned); Map<const Node *, Node *> duplimap; Node *dup = node->duplicate_from_editor(duplimap); ERR_CONTINUE(!dup); if (selection.size() == 1) dupsingle = dup; dup->set_name(parent->validate_child_name(dup)); editor_data->get_undo_redo().add_do_method(parent, "add_child_below_node", node, dup); for (List<Node *>::Element *F = owned.front(); F; F = F->next()) { if (!duplimap.has(F->get())) { continue; } Node *d = duplimap[F->get()]; editor_data->get_undo_redo().add_do_method(d, "set_owner", node->get_owner()); } editor_data->get_undo_redo().add_do_method(editor_selection, "add_node", dup); editor_data->get_undo_redo().add_undo_method(parent, "remove_child", dup); editor_data->get_undo_redo().add_do_reference(dup); ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger(); editor_data->get_undo_redo().add_do_method(sed, "live_debug_duplicate_node", edited_scene->get_path_to(node), dup->get_name()); editor_data->get_undo_redo().add_undo_method(sed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)) + "/" + dup->get_name())); } editor_data->get_undo_redo().commit_action(); if (dupsingle) editor->push_item(dupsingle); } break; case TOOL_REPARENT: { if (!scene_tree->get_selected()) break; if (editor_selection->is_selected(edited_scene)) { current_option = -1; accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("This operation can't be done on the tree root.")); accept->popup_centered_minsize(); break; } if (!_validate_no_foreign()) break; List<Node *> nodes = editor_selection->get_selected_node_list(); Set<Node *> nodeset; for (List<Node *>::Element *E = nodes.front(); E; E = E->next()) { nodeset.insert(E->get()); } reparent_dialog->popup_centered_ratio(); reparent_dialog->set_current(nodeset); } break; case TOOL_MULTI_EDIT: { Node *root = EditorNode::get_singleton()->get_edited_scene(); if (!root) break; Ref<MultiNodeEdit> mne = memnew(MultiNodeEdit); for (const Map<Node *, Object *>::Element *E = EditorNode::get_singleton()->get_editor_selection()->get_selection().front(); E; E = E->next()) { mne->add_node(root->get_path_to(E->key())); } EditorNode::get_singleton()->push_item(mne.ptr()); } break; case TOOL_ERASE: { List<Node *> remove_list = editor_selection->get_selected_node_list(); if (remove_list.empty()) return; if (!_validate_no_foreign()) break; if (p_confirm_override) { _delete_confirm(); } else { delete_dialog->set_text(TTR("Delete Node(s)?")); delete_dialog->popup_centered_minsize(); } } break; case TOOL_MERGE_FROM_SCENE: { EditorNode::get_singleton()->merge_from_scene(); } break; case TOOL_NEW_SCENE_FROM: { Node *scene = editor_data->get_edited_scene_root(); if (!scene) { accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("This operation can't be done without a scene.")); accept->popup_centered_minsize(); break; } List<Node *> selection = editor_selection->get_selected_node_list(); if (selection.size() != 1) { accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("This operation requires a single selected node.")); accept->popup_centered_minsize(); break; } Node *tocopy = selection.front()->get(); if (tocopy == scene) { accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("Can not perform with the root node.")); accept->popup_centered_minsize(); break; } if (tocopy != editor_data->get_edited_scene_root() && tocopy->get_filename() != "") { accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("This operation can't be done on instanced scenes.")); accept->popup_centered_minsize(); break; } new_scene_from_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE); List<String> extensions; Ref<PackedScene> sd = memnew(PackedScene); ResourceSaver::get_recognized_extensions(sd, &extensions); new_scene_from_dialog->clear_filters(); for (int i = 0; i < extensions.size(); i++) { new_scene_from_dialog->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper()); } String existing; if (extensions.size()) { String root_name(tocopy->get_name()); existing = root_name + "." + extensions.front()->get().to_lower(); } new_scene_from_dialog->set_current_path(existing); new_scene_from_dialog->popup_centered_ratio(); new_scene_from_dialog->set_title(TTR("Save New Scene As..")); } break; case TOOL_COPY_NODE_PATH: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { Node *root = EditorNode::get_singleton()->get_edited_scene(); NodePath path = root->get_path().rel_path_to(node->get_path()); OS::get_singleton()->set_clipboard(path); } } } break; case TOOL_SCENE_EDITABLE_CHILDREN: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { bool editable = EditorNode::get_singleton()->get_edited_scene()->is_editable_instance(node); int editable_item_idx = menu->get_item_idx_from_text(TTR("Editable Children")); int placeholder_item_idx = menu->get_item_idx_from_text(TTR("Load As Placeholder")); editable = !editable; EditorNode::get_singleton()->get_edited_scene()->set_editable_instance(node, editable); menu->set_item_checked(editable_item_idx, editable); if (editable) { node->set_scene_instance_load_placeholder(false); menu->set_item_checked(placeholder_item_idx, false); } scene_tree->update_tree(); } } } break; case TOOL_SCENE_USE_PLACEHOLDER: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { bool placeholder = node->get_scene_instance_load_placeholder(); placeholder = !placeholder; int editable_item_idx = menu->get_item_idx_from_text(TTR("Editable Children")); int placeholder_item_idx = menu->get_item_idx_from_text(TTR("Load As Placeholder")); if (placeholder) EditorNode::get_singleton()->get_edited_scene()->set_editable_instance(node, false); node->set_scene_instance_load_placeholder(placeholder); menu->set_item_checked(editable_item_idx, false); menu->set_item_checked(placeholder_item_idx, placeholder); scene_tree->update_tree(); } } } break; case TOOL_SCENE_CLEAR_INSTANCING: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { Node *root = EditorNode::get_singleton()->get_edited_scene(); UndoRedo *undo_redo = &editor_data->get_undo_redo(); if (!root) break; ERR_FAIL_COND(node->get_filename() == String()); undo_redo->create_action(TTR("Discard Instancing")); undo_redo->add_do_method(node, "set_filename", ""); undo_redo->add_undo_method(node, "set_filename", node->get_filename()); _node_replace_owner(node, node, root); undo_redo->add_do_method(scene_tree, "update_tree"); undo_redo->add_undo_method(scene_tree, "update_tree"); undo_redo->commit_action(); } } } break; case TOOL_SCENE_OPEN: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { scene_tree->emit_signal("open", node->get_filename()); } } } break; case TOOL_SCENE_CLEAR_INHERITANCE: { clear_inherit_confirm->popup_centered_minsize(); } break; case TOOL_SCENE_CLEAR_INHERITANCE_CONFIRM: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { node->set_scene_inherited_state(Ref<SceneState>()); scene_tree->update_tree(); EditorNode::get_singleton()->get_property_editor()->update_tree(); } } } break; case TOOL_SCENE_OPEN_INHERITED: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { if (node && node->get_scene_inherited_state().is_valid()) { scene_tree->emit_signal("open", node->get_scene_inherited_state()->get_path()); } } } } break; default: { if (p_tool >= EDIT_SUBRESOURCE_BASE) { int idx = p_tool - EDIT_SUBRESOURCE_BASE; ERR_FAIL_INDEX(idx, subresources.size()); Object *obj = ObjectDB::get_instance(subresources[idx]); ERR_FAIL_COND(!obj); editor->push_item(obj); } } } } void SceneTreeDock::_notification(int p_what) { switch (p_what) { case NOTIFICATION_READY: { if (!first_enter) break; first_enter = false; CanvasItemEditorPlugin *canvas_item_plugin = Object::cast_to<CanvasItemEditorPlugin>(editor_data->get_editor("2D")); if (canvas_item_plugin) { canvas_item_plugin->get_canvas_item_editor()->connect("item_lock_status_changed", scene_tree, "_update_tree"); canvas_item_plugin->get_canvas_item_editor()->connect("item_group_status_changed", scene_tree, "_update_tree"); scene_tree->connect("node_changed", canvas_item_plugin->get_canvas_item_editor()->get_viewport_control(), "update"); } SpatialEditorPlugin *spatial_editor_plugin = Object::cast_to<SpatialEditorPlugin>(editor_data->get_editor("3D")); spatial_editor_plugin->get_spatial_editor()->connect("item_lock_status_changed", scene_tree, "_update_tree"); button_add->set_icon(get_icon("Add", "EditorIcons")); button_instance->set_icon(get_icon("Instance", "EditorIcons")); button_create_script->set_icon(get_icon("ScriptCreate", "EditorIcons")); button_clear_script->set_icon(get_icon("ScriptRemove", "EditorIcons")); filter->add_icon_override("right_icon", get_icon("Search", "EditorIcons")); EditorNode::get_singleton()->get_editor_selection()->connect("selection_changed", this, "_selection_changed"); } break; case NOTIFICATION_ENTER_TREE: { clear_inherit_confirm->connect("confirmed", this, "_tool_selected", varray(TOOL_SCENE_CLEAR_INHERITANCE_CONFIRM)); } break; case NOTIFICATION_EXIT_TREE: { clear_inherit_confirm->disconnect("confirmed", this, "_tool_selected"); } break; case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { button_add->set_icon(get_icon("Add", "EditorIcons")); button_instance->set_icon(get_icon("Instance", "EditorIcons")); button_create_script->set_icon(get_icon("ScriptCreate", "EditorIcons")); button_clear_script->set_icon(get_icon("ScriptRemove", "EditorIcons")); filter->add_icon_override("right_icon", get_icon("Search", "EditorIcons")); } break; } } void SceneTreeDock::_node_replace_owner(Node *p_base, Node *p_node, Node *p_root) { if (p_base != p_node) { if (p_node->get_owner() == p_base) { UndoRedo *undo_redo = &editor_data->get_undo_redo(); undo_redo->add_do_method(p_node, "set_owner", p_root); undo_redo->add_undo_method(p_node, "set_owner", p_base); } } for (int i = 0; i < p_node->get_child_count(); i++) { _node_replace_owner(p_base, p_node->get_child(i), p_root); } } void SceneTreeDock::_load_request(const String &p_path) { editor->open_request(p_path); } void SceneTreeDock::_script_open_request(const Ref<Script> &p_script) { editor->edit_resource(p_script); } void SceneTreeDock::_node_selected() { Node *node = scene_tree->get_selected(); if (!node) { editor->push_item(NULL); return; } if (ScriptEditor::get_singleton()->is_visible_in_tree()) { restore_script_editor_on_drag = true; } editor->push_item(node); } void SceneTreeDock::_node_renamed() { _node_selected(); } void SceneTreeDock::_set_owners(Node *p_owner, const Array &p_nodes) { for (int i = 0; i < p_nodes.size(); i++) { Node *n = Object::cast_to<Node>(p_nodes[i]); if (!n) continue; n->set_owner(p_owner); } } void SceneTreeDock::_fill_path_renames(Vector<StringName> base_path, Vector<StringName> new_base_path, Node *p_node, List<Pair<NodePath, NodePath> > *p_renames) { base_path.push_back(p_node->get_name()); if (new_base_path.size()) new_base_path.push_back(p_node->get_name()); NodePath from(base_path, true); NodePath to; if (new_base_path.size()) to = NodePath(new_base_path, true); Pair<NodePath, NodePath> npp; npp.first = from; npp.second = to; p_renames->push_back(npp); for (int i = 0; i < p_node->get_child_count(); i++) { _fill_path_renames(base_path, new_base_path, p_node->get_child(i), p_renames); } } void SceneTreeDock::fill_path_renames(Node *p_node, Node *p_new_parent, List<Pair<NodePath, NodePath> > *p_renames) { if (!bool(EDITOR_DEF("editors/animation/autorename_animation_tracks", true))) return; Vector<StringName> base_path; Node *n = p_node->get_parent(); while (n) { base_path.push_back(n->get_name()); n = n->get_parent(); } base_path.invert(); Vector<StringName> new_base_path; if (p_new_parent) { n = p_new_parent; while (n) { new_base_path.push_back(n->get_name()); n = n->get_parent(); } new_base_path.invert(); } _fill_path_renames(base_path, new_base_path, p_node, p_renames); } void SceneTreeDock::perform_node_renames(Node *p_base, List<Pair<NodePath, NodePath> > *p_renames, Map<Ref<Animation>, Set<int> > *r_rem_anims) { Map<Ref<Animation>, Set<int> > rem_anims; if (!r_rem_anims) r_rem_anims = &rem_anims; if (!bool(EDITOR_DEF("editors/animation/autorename_animation_tracks", true))) return; if (!p_base) { p_base = edited_scene; } if (!p_base) return; if (Object::cast_to<AnimationPlayer>(p_base)) { AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_base); List<StringName> anims; ap->get_animation_list(&anims); Node *root = ap->get_node(ap->get_root()); if (root) { NodePath root_path = root->get_path(); NodePath new_root_path = root_path; for (List<Pair<NodePath, NodePath> >::Element *E = p_renames->front(); E; E = E->next()) { if (E->get().first == root_path) { new_root_path = E->get().second; break; } } if (new_root_path != NodePath()) { //will not be erased for (List<StringName>::Element *E = anims.front(); E; E = E->next()) { Ref<Animation> anim = ap->get_animation(E->get()); if (!r_rem_anims->has(anim)) { r_rem_anims->insert(anim, Set<int>()); Set<int> &ran = r_rem_anims->find(anim)->get(); for (int i = 0; i < anim->get_track_count(); i++) ran.insert(i); } Set<int> &ran = r_rem_anims->find(anim)->get(); if (anim.is_null()) continue; for (int i = 0; i < anim->get_track_count(); i++) { NodePath track_np = anim->track_get_path(i); Node *n = root->get_node(track_np); if (!n) { continue; } NodePath old_np = n->get_path(); if (!ran.has(i)) continue; //channel was removed for (List<Pair<NodePath, NodePath> >::Element *E = p_renames->front(); E; E = E->next()) { if (E->get().first == old_np) { if (E->get().second == NodePath()) { //will be erased int idx = 0; Set<int>::Element *EI = ran.front(); ERR_FAIL_COND(!EI); //bug while (EI->get() != i) { idx++; EI = EI->next(); ERR_FAIL_COND(!EI); //another bug } editor_data->get_undo_redo().add_do_method(anim.ptr(), "remove_track", idx); editor_data->get_undo_redo().add_undo_method(anim.ptr(), "add_track", anim->track_get_type(i), idx); editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_set_path", idx, track_np); editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_set_interpolation_type", idx, anim->track_get_interpolation_type(i)); for (int j = 0; j < anim->track_get_key_count(i); j++) { editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_insert_key", idx, anim->track_get_key_time(i, j), anim->track_get_key_value(i, j), anim->track_get_key_transition(i, j)); } ran.erase(i); //byebye channel } else { //will be renamed NodePath rel_path = new_root_path.rel_path_to(E->get().second); NodePath new_path = NodePath(rel_path.get_names(), track_np.get_subnames(), false); if (new_path == track_np) continue; //bleh editor_data->get_undo_redo().add_do_method(anim.ptr(), "track_set_path", i, new_path); editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_set_path", i, track_np); } } } } } } } } for (int i = 0; i < p_base->get_child_count(); i++) perform_node_renames(p_base->get_child(i), p_renames, r_rem_anims); } void SceneTreeDock::_node_prerenamed(Node *p_node, const String &p_new_name) { List<Pair<NodePath, NodePath> > path_renames; Vector<StringName> base_path; Node *n = p_node->get_parent(); while (n) { base_path.push_back(n->get_name()); n = n->get_parent(); } base_path.invert(); Vector<StringName> new_base_path = base_path; base_path.push_back(p_node->get_name()); new_base_path.push_back(p_new_name); Pair<NodePath, NodePath> npp; npp.first = NodePath(base_path, true); npp.second = NodePath(new_base_path, true); path_renames.push_back(npp); for (int i = 0; i < p_node->get_child_count(); i++) _fill_path_renames(base_path, new_base_path, p_node->get_child(i), &path_renames); perform_node_renames(NULL, &path_renames); } bool SceneTreeDock::_validate_no_foreign() { List<Node *> selection = editor_selection->get_selected_node_list(); for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { if (E->get() != edited_scene && E->get()->get_owner() != edited_scene) { accept->get_ok()->set_text(TTR("Makes Sense!")); accept->set_text(TTR("Can't operate on nodes from a foreign scene!")); accept->popup_centered_minsize(); return false; } if (edited_scene->get_scene_inherited_state().is_valid() && edited_scene->get_scene_inherited_state()->find_node_by_path(edited_scene->get_path_to(E->get())) >= 0) { accept->get_ok()->set_text(TTR("Makes Sense!")); accept->set_text(TTR("Can't operate on nodes the current scene inherits from!")); accept->popup_centered_minsize(); return false; } } return true; } void SceneTreeDock::_node_reparent(NodePath p_path, bool p_keep_global_xform) { Node *new_parent = scene_root->get_node(p_path); ERR_FAIL_COND(!new_parent); List<Node *> selection = editor_selection->get_selected_node_list(); if (selection.empty()) return; //nothing to reparent Vector<Node *> nodes; for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { nodes.push_back(E->get()); } _do_reparent(new_parent, -1, nodes, p_keep_global_xform); } void SceneTreeDock::_do_reparent(Node *p_new_parent, int p_position_in_parent, Vector<Node *> p_nodes, bool p_keep_global_xform) { Node *new_parent = p_new_parent; ERR_FAIL_COND(!new_parent); Node *validate = new_parent; while (validate) { if (p_nodes.find(validate) != -1) { ERR_EXPLAIN("Selection changed at some point.. can't reparent"); ERR_FAIL(); return; } validate = validate->get_parent(); } //ok all valid if (p_nodes.size() == 0) return; //nothing to reparent //sort by tree order, so re-adding is easy p_nodes.sort_custom<Node::Comparator>(); editor_data->get_undo_redo().create_action(TTR("Reparent Node")); List<Pair<NodePath, NodePath> > path_renames; Vector<StringName> former_names; int inc = 0; for (int ni = 0; ni < p_nodes.size(); ni++) { //no undo for now, sorry Node *node = p_nodes[ni]; fill_path_renames(node, new_parent, &path_renames); former_names.push_back(node->get_name()); List<Node *> owned; node->get_owned_by(node->get_owner(), &owned); Array owners; for (List<Node *>::Element *E = owned.front(); E; E = E->next()) { owners.push_back(E->get()); } if (new_parent == node->get_parent() && node->get_index() < p_position_in_parent + ni) { //if child will generate a gap when moved, adjust inc--; } editor_data->get_undo_redo().add_do_method(node->get_parent(), "remove_child", node); editor_data->get_undo_redo().add_do_method(new_parent, "add_child", node); if (p_position_in_parent >= 0) editor_data->get_undo_redo().add_do_method(new_parent, "move_child", node, p_position_in_parent + inc); ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger(); String new_name = new_parent->validate_child_name(node); editor_data->get_undo_redo().add_do_method(sed, "live_debug_reparent_node", edited_scene->get_path_to(node), edited_scene->get_path_to(new_parent), new_name, -1); editor_data->get_undo_redo().add_undo_method(sed, "live_debug_reparent_node", NodePath(String(edited_scene->get_path_to(new_parent)) + "/" + new_name), edited_scene->get_path_to(node->get_parent()), node->get_name(), node->get_index()); if (p_keep_global_xform) { if (Object::cast_to<Node2D>(node)) editor_data->get_undo_redo().add_do_method(node, "set_global_transform", Object::cast_to<Node2D>(node)->get_global_transform()); if (Object::cast_to<Spatial>(node)) editor_data->get_undo_redo().add_do_method(node, "set_global_transform", Object::cast_to<Spatial>(node)->get_global_transform()); if (Object::cast_to<Control>(node)) editor_data->get_undo_redo().add_do_method(node, "set_global_position", Object::cast_to<Control>(node)->get_global_position()); } editor_data->get_undo_redo().add_do_method(this, "_set_owners", edited_scene, owners); if (AnimationPlayerEditor::singleton->get_key_editor()->get_root() == node) editor_data->get_undo_redo().add_do_method(AnimationPlayerEditor::singleton->get_key_editor(), "set_root", node); editor_data->get_undo_redo().add_undo_method(new_parent, "remove_child", node); editor_data->get_undo_redo().add_undo_method(node, "set_name", former_names[ni]); inc++; } //add and move in a second step.. (so old order is preserved) for (int ni = 0; ni < p_nodes.size(); ni++) { Node *node = p_nodes[ni]; List<Node *> owned; node->get_owned_by(node->get_owner(), &owned); Array owners; for (List<Node *>::Element *E = owned.front(); E; E = E->next()) { owners.push_back(E->get()); } int child_pos = node->get_position_in_parent(); editor_data->get_undo_redo().add_undo_method(node->get_parent(), "add_child", node); editor_data->get_undo_redo().add_undo_method(node->get_parent(), "move_child", node, child_pos); editor_data->get_undo_redo().add_undo_method(this, "_set_owners", edited_scene, owners); if (AnimationPlayerEditor::singleton->get_key_editor()->get_root() == node) editor_data->get_undo_redo().add_undo_method(AnimationPlayerEditor::singleton->get_key_editor(), "set_root", node); if (p_keep_global_xform) { if (Object::cast_to<Node2D>(node)) editor_data->get_undo_redo().add_undo_method(node, "set_transform", Object::cast_to<Node2D>(node)->get_transform()); if (Object::cast_to<Spatial>(node)) editor_data->get_undo_redo().add_undo_method(node, "set_transform", Object::cast_to<Spatial>(node)->get_transform()); if (Object::cast_to<Control>(node)) editor_data->get_undo_redo().add_undo_method(node, "set_position", Object::cast_to<Control>(node)->get_position()); } } perform_node_renames(NULL, &path_renames); editor_data->get_undo_redo().commit_action(); } void SceneTreeDock::_script_created(Ref<Script> p_script) { Node *selected = scene_tree->get_selected(); if (!selected) return; selected->set_script(p_script.get_ref_ptr()); editor->push_item(p_script.operator->()); _update_script_button(); } void SceneTreeDock::_delete_confirm() { List<Node *> remove_list = editor_selection->get_selected_node_list(); if (remove_list.empty()) return; editor->get_editor_plugins_over()->make_visible(false); editor_data->get_undo_redo().create_action(TTR("Remove Node(s)")); bool entire_scene = false; for (List<Node *>::Element *E = remove_list.front(); E; E = E->next()) { if (E->get() == edited_scene) { entire_scene = true; } } if (entire_scene) { editor_data->get_undo_redo().add_do_method(editor, "set_edited_scene", (Object *)NULL); editor_data->get_undo_redo().add_undo_method(editor, "set_edited_scene", edited_scene); editor_data->get_undo_redo().add_undo_method(edited_scene, "set_owner", edited_scene->get_owner()); editor_data->get_undo_redo().add_undo_method(scene_tree, "update_tree"); editor_data->get_undo_redo().add_undo_reference(edited_scene); } else { remove_list.sort_custom<Node::Comparator>(); //sort nodes to keep positions List<Pair<NodePath, NodePath> > path_renames; //delete from animation for (List<Node *>::Element *E = remove_list.front(); E; E = E->next()) { Node *n = E->get(); if (!n->is_inside_tree() || !n->get_parent()) continue; fill_path_renames(n, NULL, &path_renames); } perform_node_renames(NULL, &path_renames); //delete for read for (List<Node *>::Element *E = remove_list.front(); E; E = E->next()) { Node *n = E->get(); if (!n->is_inside_tree() || !n->get_parent()) continue; List<Node *> owned; n->get_owned_by(n->get_owner(), &owned); Array owners; for (List<Node *>::Element *E = owned.front(); E; E = E->next()) { owners.push_back(E->get()); } editor_data->get_undo_redo().add_do_method(n->get_parent(), "remove_child", n); editor_data->get_undo_redo().add_undo_method(n->get_parent(), "add_child", n); editor_data->get_undo_redo().add_undo_method(n->get_parent(), "move_child", n, n->get_index()); if (AnimationPlayerEditor::singleton->get_key_editor()->get_root() == n) editor_data->get_undo_redo().add_undo_method(AnimationPlayerEditor::singleton->get_key_editor(), "set_root", n); editor_data->get_undo_redo().add_undo_method(this, "_set_owners", edited_scene, owners); editor_data->get_undo_redo().add_undo_reference(n); ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger(); editor_data->get_undo_redo().add_do_method(sed, "live_debug_remove_and_keep_node", edited_scene->get_path_to(n), n->get_instance_id()); editor_data->get_undo_redo().add_undo_method(sed, "live_debug_restore_node", n->get_instance_id(), edited_scene->get_path_to(n->get_parent()), n->get_index()); } } editor_data->get_undo_redo().commit_action(); // hack, force 2d editor viewport to refresh after deletion if (CanvasItemEditor *editor = CanvasItemEditor::get_singleton()) editor->get_viewport_control()->update(); editor->push_item(NULL); // Fixes the EditorHistory from still offering deleted notes EditorHistory *editor_history = EditorNode::get_singleton()->get_editor_history(); editor_history->cleanup_history(); EditorNode::get_singleton()->call("_prepare_history"); } void SceneTreeDock::_update_script_button() { if (EditorNode::get_singleton()->get_editor_selection()->get_selection().size() == 1) { if (EditorNode::get_singleton()->get_editor_selection()->get_selection().front()->key()->get_script().is_null()) { button_create_script->show(); button_clear_script->hide(); } else { button_create_script->hide(); button_clear_script->show(); } } else { button_create_script->hide(); button_clear_script->hide(); } } void SceneTreeDock::_selection_changed() { int selection_size = EditorNode::get_singleton()->get_editor_selection()->get_selection().size(); if (selection_size > 1) { //automatically turn on multi-edit _tool_selected(TOOL_MULTI_EDIT); } _update_script_button(); } void SceneTreeDock::_create() { if (current_option == TOOL_NEW) { Node *parent = NULL; if (edited_scene) { // If root exists in edited scene parent = scene_tree->get_selected(); if (!parent) parent = edited_scene; } else { // If no root exist in edited scene parent = scene_root; ERR_FAIL_COND(!parent); } Object *c = create_dialog->instance_selected(); ERR_FAIL_COND(!c); Node *child = Object::cast_to<Node>(c); ERR_FAIL_COND(!child); editor_data->get_undo_redo().create_action(TTR("Create Node")); if (edited_scene) { editor_data->get_undo_redo().add_do_method(parent, "add_child", child); editor_data->get_undo_redo().add_do_method(child, "set_owner", edited_scene); editor_data->get_undo_redo().add_do_method(editor_selection, "clear"); editor_data->get_undo_redo().add_do_method(editor_selection, "add_node", child); editor_data->get_undo_redo().add_do_reference(child); editor_data->get_undo_redo().add_undo_method(parent, "remove_child", child); String new_name = parent->validate_child_name(child); ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger(); editor_data->get_undo_redo().add_do_method(sed, "live_debug_create_node", edited_scene->get_path_to(parent), child->get_class(), new_name); editor_data->get_undo_redo().add_undo_method(sed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)) + "/" + new_name)); } else { editor_data->get_undo_redo().add_do_method(editor, "set_edited_scene", child); editor_data->get_undo_redo().add_do_method(scene_tree, "update_tree"); editor_data->get_undo_redo().add_do_reference(child); editor_data->get_undo_redo().add_undo_method(editor, "set_edited_scene", (Object *)NULL); } editor_data->get_undo_redo().commit_action(); editor->push_item(c); editor_selection->clear(); editor_selection->add_node(child); if (Object::cast_to<Control>(c)) { //make editor more comfortable, so some controls don't appear super shrunk Control *ct = Object::cast_to<Control>(c); Size2 ms = ct->get_minimum_size(); if (ms.width < 4) ms.width = 40; if (ms.height < 4) ms.height = 40; ct->set_size(ms); } } else if (current_option == TOOL_REPLACE) { List<Node *> selection = editor_selection->get_selected_node_list(); ERR_FAIL_COND(selection.size() <= 0); for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { Node *n = E->get(); ERR_FAIL_COND(!n); Object *c = create_dialog->instance_selected(); ERR_FAIL_COND(!c); Node *newnode = Object::cast_to<Node>(c); ERR_FAIL_COND(!newnode); replace_node(n, newnode); } } } void SceneTreeDock::replace_node(Node *p_node, Node *p_by_node) { Node *n = p_node; Node *newnode = p_by_node; Node *default_oldnode = Object::cast_to<Node>(ClassDB::instance(n->get_class())); List<PropertyInfo> pinfo; n->get_property_list(&pinfo); for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { if (!(E->get().usage & PROPERTY_USAGE_STORAGE)) continue; if (E->get().name == "__meta__") continue; if (default_oldnode->get(E->get().name) != n->get(E->get().name)) { newnode->set(E->get().name, n->get(E->get().name)); } } memdelete(default_oldnode); editor->push_item(NULL); //reconnect signals List<MethodInfo> sl; n->get_signal_list(&sl); for (List<MethodInfo>::Element *E = sl.front(); E; E = E->next()) { List<Object::Connection> cl; n->get_signal_connection_list(E->get().name, &cl); for (List<Object::Connection>::Element *F = cl.front(); F; F = F->next()) { Object::Connection &c = F->get(); if (!(c.flags & Object::CONNECT_PERSIST)) continue; newnode->connect(c.signal, c.target, c.method, varray(), Object::CONNECT_PERSIST); } } String newname = n->get_name(); List<Node *> to_erase; for (int i = 0; i < n->get_child_count(); i++) { if (n->get_child(i)->get_owner() == NULL && n->is_owned_by_parent()) { to_erase.push_back(n->get_child(i)); } } n->replace_by(newnode, true); if (n == edited_scene) { edited_scene = newnode; editor->set_edited_scene(newnode); newnode->set_editable_instances(n->get_editable_instances()); } //small hack to make collisionshapes and other kind of nodes to work for (int i = 0; i < newnode->get_child_count(); i++) { Node *c = newnode->get_child(i); c->call("set_transform", c->call("get_transform")); } editor_data->get_undo_redo().clear_history(); newnode->set_name(newname); editor->push_item(newnode); memdelete(n); while (to_erase.front()) { memdelete(to_erase.front()->get()); to_erase.pop_front(); } } void SceneTreeDock::set_edited_scene(Node *p_scene) { edited_scene = p_scene; } void SceneTreeDock::set_selected(Node *p_node, bool p_emit_selected) { scene_tree->set_selected(p_node, p_emit_selected); } void SceneTreeDock::import_subscene() { import_subscene_dialog->popup_centered_ratio(); } void SceneTreeDock::_import_subscene() { Node *parent = scene_tree->get_selected(); if (!parent) { parent = editor_data->get_edited_scene_root(); ERR_FAIL_COND(!parent); } import_subscene_dialog->move(parent, edited_scene); editor_data->get_undo_redo().clear_history(); //no undo for now.. } void SceneTreeDock::_new_scene_from(String p_file) { List<Node *> selection = editor_selection->get_selected_node_list(); if (selection.size() != 1) { accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("This operation requires a single selected node.")); accept->popup_centered_minsize(); return; } Node *base = selection.front()->get(); Map<Node *, Node *> reown; reown[editor_data->get_edited_scene_root()] = base; Node *copy = base->duplicate_and_reown(reown); if (copy) { Ref<PackedScene> sdata = memnew(PackedScene); Error err = sdata->pack(copy); memdelete(copy); if (err != OK) { accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("Couldn't save new scene. Likely dependencies (instances) couldn't be satisfied.")); accept->popup_centered_minsize(); return; } int flg = 0; if (EditorSettings::get_singleton()->get("filesystem/on_save/compress_binary_resources")) flg |= ResourceSaver::FLAG_COMPRESS; err = ResourceSaver::save(p_file, sdata, flg); if (err != OK) { accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("Error saving scene.")); accept->popup_centered_minsize(); return; } _replace_with_branch_scene(p_file, base); } else { accept->get_ok()->set_text(TTR("I see..")); accept->set_text(TTR("Error duplicating scene to save it.")); accept->popup_centered_minsize(); return; } } static bool _is_node_visible(Node *p_node) { if (!p_node->get_owner()) return false; if (p_node->get_owner() != EditorNode::get_singleton()->get_edited_scene() && !EditorNode::get_singleton()->get_edited_scene()->is_editable_instance(p_node->get_owner())) return false; return true; } static bool _has_visible_children(Node *p_node) { bool collapsed = p_node->is_displayed_folded(); if (collapsed) return false; for (int i = 0; i < p_node->get_child_count(); i++) { Node *child = p_node->get_child(i); if (!_is_node_visible(child)) continue; return true; } return false; } static Node *_find_last_visible(Node *p_node) { Node *last = NULL; bool collapsed = p_node->is_displayed_folded(); if (!collapsed) { for (int i = 0; i < p_node->get_child_count(); i++) { if (_is_node_visible(p_node->get_child(i))) { last = p_node->get_child(i); } } } if (last) { Node *lastc = _find_last_visible(last); if (lastc) last = lastc; } else { last = p_node; } return last; } void SceneTreeDock::_normalize_drop(Node *&to_node, int &to_pos, int p_type) { to_pos = -1; if (p_type == -1) { //drop at above selected node if (to_node == EditorNode::get_singleton()->get_edited_scene()) { to_node = NULL; ERR_EXPLAIN("Cannot perform drop above the root node!"); ERR_FAIL(); } to_pos = to_node->get_index(); to_node = to_node->get_parent(); } else if (p_type == 1) { //drop at below selected node if (to_node == EditorNode::get_singleton()->get_edited_scene()) { //if at lower sibling of root node to_pos = 0; //just insert at beginning of root node return; } Node *lower_sibling = NULL; if (_has_visible_children(to_node)) { to_pos = 0; } else { for (int i = to_node->get_index() + 1; i < to_node->get_parent()->get_child_count(); i++) { Node *c = to_node->get_parent()->get_child(i); if (_is_node_visible(c)) { lower_sibling = c; break; } } if (lower_sibling) { to_pos = lower_sibling->get_index(); } to_node = to_node->get_parent(); } } } void SceneTreeDock::_files_dropped(Vector<String> p_files, NodePath p_to, int p_type) { Node *node = get_node(p_to); ERR_FAIL_COND(!node); int to_pos = -1; _normalize_drop(node, to_pos, p_type); _perform_instance_scenes(p_files, node, to_pos); } void SceneTreeDock::_script_dropped(String p_file, NodePath p_to) { Ref<Script> scr = ResourceLoader::load(p_file); ERR_FAIL_COND(!scr.is_valid()); Node *n = get_node(p_to); if (n) { n->set_script(scr.get_ref_ptr()); _update_script_button(); } } void SceneTreeDock::_nodes_dragged(Array p_nodes, NodePath p_to, int p_type) { Vector<Node *> nodes; Node *to_node; for (int i = 0; i < p_nodes.size(); i++) { Node *n = get_node((p_nodes[i])); if (n) { nodes.push_back(n); } } if (nodes.size() == 0) return; to_node = get_node(p_to); if (!to_node) return; int to_pos = -1; _normalize_drop(to_node, to_pos, p_type); _do_reparent(to_node, to_pos, nodes, true); } void SceneTreeDock::_add_children_to_popup(Object *p_obj, int p_depth) { if (p_depth > 8) return; List<PropertyInfo> pinfo; p_obj->get_property_list(&pinfo); for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { if (!(E->get().usage & PROPERTY_USAGE_EDITOR)) continue; if (E->get().hint != PROPERTY_HINT_RESOURCE_TYPE) continue; Variant value = p_obj->get(E->get().name); if (value.get_type() != Variant::OBJECT) continue; Object *obj = value; if (!obj) continue; Ref<Texture> icon; if (has_icon(obj->get_class(), "EditorIcons")) icon = get_icon(obj->get_class(), "EditorIcons"); else icon = get_icon("Object", "EditorIcons"); if (menu->get_item_count() == 0) { menu->add_submenu_item(TTR("Sub-Resources"), "Sub-Resources"); } int index = menu_subresources->get_item_count(); menu_subresources->add_icon_item(icon, E->get().name.capitalize(), EDIT_SUBRESOURCE_BASE + subresources.size()); menu_subresources->set_item_h_offset(index, p_depth * 10 * EDSCALE); subresources.push_back(obj->get_instance_id()); _add_children_to_popup(obj, p_depth + 1); } } void SceneTreeDock::_tree_rmb(const Vector2 &p_menu_pos) { if (!EditorNode::get_singleton()->get_edited_scene()) { menu->clear(); menu->add_icon_shortcut(get_icon("Add", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/add_child_node"), TOOL_NEW); menu->add_icon_shortcut(get_icon("Instance", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/instance_scene"), TOOL_INSTANCE); menu->set_size(Size2(1, 1)); menu->set_position(p_menu_pos); menu->popup(); return; } List<Node *> selection = editor_selection->get_selected_node_list(); if (selection.size() == 0) return; menu->clear(); if (selection.size() == 1) { subresources.clear(); menu_subresources->clear(); _add_children_to_popup(selection.front()->get(), 0); if (menu->get_item_count() > 0) menu->add_separator(); menu->add_icon_shortcut(get_icon("Add", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/add_child_node"), TOOL_NEW); menu->add_icon_shortcut(get_icon("Instance", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/instance_scene"), TOOL_INSTANCE); menu->add_separator(); menu->add_icon_shortcut(get_icon("ScriptCreate", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/attach_script"), TOOL_ATTACH_SCRIPT); menu->add_icon_shortcut(get_icon("ScriptRemove", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/clear_script"), TOOL_CLEAR_SCRIPT); menu->add_separator(); } menu->add_icon_shortcut(get_icon("Reload", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/change_node_type"), TOOL_REPLACE); menu->add_separator(); menu->add_icon_shortcut(get_icon("MoveUp", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/move_up"), TOOL_MOVE_UP); menu->add_icon_shortcut(get_icon("MoveDown", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/move_down"), TOOL_MOVE_DOWN); menu->add_icon_shortcut(get_icon("Duplicate", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/duplicate"), TOOL_DUPLICATE); menu->add_icon_shortcut(get_icon("Reparent", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/reparent"), TOOL_REPARENT); if (selection.size() == 1) { menu->add_separator(); menu->add_icon_shortcut(get_icon("Blend", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/merge_from_scene"), TOOL_MERGE_FROM_SCENE); menu->add_icon_shortcut(get_icon("CreateNewSceneFrom", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/save_branch_as_scene"), TOOL_NEW_SCENE_FROM); menu->add_separator(); menu->add_icon_shortcut(get_icon("CopyNodePath", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/copy_node_path"), TOOL_COPY_NODE_PATH); bool is_external = (selection[0]->get_filename() != ""); if (is_external) { bool is_inherited = selection[0]->get_scene_inherited_state() != NULL; bool is_top_level = selection[0]->get_owner() == NULL; if (is_inherited && is_top_level) { menu->add_separator(); menu->add_item(TTR("Clear Inheritance"), TOOL_SCENE_CLEAR_INHERITANCE); menu->add_icon_item(get_icon("Load", "EditorIcons"), TTR("Open in Editor"), TOOL_SCENE_OPEN_INHERITED); } else if (!is_top_level) { menu->add_separator(); bool editable = EditorNode::get_singleton()->get_edited_scene()->is_editable_instance(selection[0]); bool placeholder = selection[0]->get_scene_instance_load_placeholder(); menu->add_check_item(TTR("Editable Children"), TOOL_SCENE_EDITABLE_CHILDREN); menu->add_check_item(TTR("Load As Placeholder"), TOOL_SCENE_USE_PLACEHOLDER); menu->add_item(TTR("Discard Instancing"), TOOL_SCENE_CLEAR_INSTANCING); menu->add_icon_item(get_icon("Load", "EditorIcons"), TTR("Open in Editor"), TOOL_SCENE_OPEN); menu->set_item_checked(menu->get_item_idx_from_text(TTR("Editable Children")), editable); menu->set_item_checked(menu->get_item_idx_from_text(TTR("Load As Placeholder")), placeholder); } } } menu->add_separator(); menu->add_icon_shortcut(get_icon("Remove", "EditorIcons"), ED_SHORTCUT("scene_tree/delete", TTR("Delete Node(s)"), KEY_DELETE), TOOL_ERASE); menu->set_size(Size2(1, 1)); menu->set_position(p_menu_pos); menu->popup(); } void SceneTreeDock::_filter_changed(const String &p_filter) { scene_tree->set_filter(p_filter); } String SceneTreeDock::get_filter() { return filter->get_text(); } void SceneTreeDock::set_filter(const String &p_filter) { filter->set_text(p_filter); scene_tree->set_filter(p_filter); } void SceneTreeDock::_focus_node() { Node *node = scene_tree->get_selected(); ERR_FAIL_COND(!node); if (node->is_class("CanvasItem")) { CanvasItemEditorPlugin *editor = Object::cast_to<CanvasItemEditorPlugin>(editor_data->get_editor("2D")); editor->get_canvas_item_editor()->focus_selection(); } else { SpatialEditorPlugin *editor = Object::cast_to<SpatialEditorPlugin>(editor_data->get_editor("3D")); editor->get_spatial_editor()->get_editor_viewport(0)->focus_selection(); } } void SceneTreeDock::open_script_dialog(Node *p_for_node) { scene_tree->set_selected(p_for_node, false); _tool_selected(TOOL_ATTACH_SCRIPT); } void SceneTreeDock::add_remote_tree_editor(Control *p_remote) { ERR_FAIL_COND(remote_tree != NULL); add_child(p_remote); remote_tree = p_remote; remote_tree->hide(); } void SceneTreeDock::show_remote_tree() { _remote_tree_selected(); } void SceneTreeDock::hide_remote_tree() { _local_tree_selected(); } void SceneTreeDock::show_tab_buttons() { button_hb->show(); } void SceneTreeDock::hide_tab_buttons() { button_hb->hide(); } void SceneTreeDock::_remote_tree_selected() { scene_tree->hide(); if (remote_tree) remote_tree->show(); edit_remote->set_pressed(true); edit_local->set_pressed(false); emit_signal("remote_tree_selected"); } void SceneTreeDock::_local_tree_selected() { scene_tree->show(); if (remote_tree) remote_tree->hide(); edit_remote->set_pressed(false); edit_local->set_pressed(true); } void SceneTreeDock::_bind_methods() { ClassDB::bind_method(D_METHOD("_tool_selected"), &SceneTreeDock::_tool_selected, DEFVAL(false)); ClassDB::bind_method(D_METHOD("_create"), &SceneTreeDock::_create); ClassDB::bind_method(D_METHOD("_node_reparent"), &SceneTreeDock::_node_reparent); ClassDB::bind_method(D_METHOD("_set_owners"), &SceneTreeDock::_set_owners); ClassDB::bind_method(D_METHOD("_node_selected"), &SceneTreeDock::_node_selected); ClassDB::bind_method(D_METHOD("_node_renamed"), &SceneTreeDock::_node_renamed); ClassDB::bind_method(D_METHOD("_script_created"), &SceneTreeDock::_script_created); ClassDB::bind_method(D_METHOD("_load_request"), &SceneTreeDock::_load_request); ClassDB::bind_method(D_METHOD("_script_open_request"), &SceneTreeDock::_script_open_request); ClassDB::bind_method(D_METHOD("_unhandled_key_input"), &SceneTreeDock::_unhandled_key_input); ClassDB::bind_method(D_METHOD("_input"), &SceneTreeDock::_input); ClassDB::bind_method(D_METHOD("_nodes_drag_begin"), &SceneTreeDock::_nodes_drag_begin); ClassDB::bind_method(D_METHOD("_delete_confirm"), &SceneTreeDock::_delete_confirm); ClassDB::bind_method(D_METHOD("_node_prerenamed"), &SceneTreeDock::_node_prerenamed); ClassDB::bind_method(D_METHOD("_import_subscene"), &SceneTreeDock::_import_subscene); ClassDB::bind_method(D_METHOD("_selection_changed"), &SceneTreeDock::_selection_changed); ClassDB::bind_method(D_METHOD("_new_scene_from"), &SceneTreeDock::_new_scene_from); ClassDB::bind_method(D_METHOD("_nodes_dragged"), &SceneTreeDock::_nodes_dragged); ClassDB::bind_method(D_METHOD("_files_dropped"), &SceneTreeDock::_files_dropped); ClassDB::bind_method(D_METHOD("_script_dropped"), &SceneTreeDock::_script_dropped); ClassDB::bind_method(D_METHOD("_tree_rmb"), &SceneTreeDock::_tree_rmb); ClassDB::bind_method(D_METHOD("_filter_changed"), &SceneTreeDock::_filter_changed); ClassDB::bind_method(D_METHOD("_focus_node"), &SceneTreeDock::_focus_node); ClassDB::bind_method(D_METHOD("_remote_tree_selected"), &SceneTreeDock::_remote_tree_selected); ClassDB::bind_method(D_METHOD("_local_tree_selected"), &SceneTreeDock::_local_tree_selected); ClassDB::bind_method(D_METHOD("instance"), &SceneTreeDock::instance); ADD_SIGNAL(MethodInfo("remote_tree_selected")); } SceneTreeDock::SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSelection *p_editor_selection, EditorData &p_editor_data) { set_name("Scene"); editor = p_editor; edited_scene = NULL; editor_data = &p_editor_data; editor_selection = p_editor_selection; scene_root = p_scene_root; VBoxContainer *vbc = this; HBoxContainer *filter_hbc = memnew(HBoxContainer); filter_hbc->add_constant_override("separate", 0); ToolButton *tb; ED_SHORTCUT("scene_tree/add_child_node", TTR("Add Child Node"), KEY_MASK_CMD | KEY_A); ED_SHORTCUT("scene_tree/instance_scene", TTR("Instance Child Scene")); ED_SHORTCUT("scene_tree/change_node_type", TTR("Change Type")); ED_SHORTCUT("scene_tree/attach_script", TTR("Attach Script")); ED_SHORTCUT("scene_tree/clear_script", TTR("Clear Script")); ED_SHORTCUT("scene_tree/move_up", TTR("Move Up"), KEY_MASK_CMD | KEY_UP); ED_SHORTCUT("scene_tree/move_down", TTR("Move Down"), KEY_MASK_CMD | KEY_DOWN); ED_SHORTCUT("scene_tree/duplicate", TTR("Duplicate"), KEY_MASK_CMD | KEY_D); ED_SHORTCUT("scene_tree/reparent", TTR("Reparent")); ED_SHORTCUT("scene_tree/merge_from_scene", TTR("Merge From Scene")); ED_SHORTCUT("scene_tree/save_branch_as_scene", TTR("Save Branch as Scene")); ED_SHORTCUT("scene_tree/copy_node_path", TTR("Copy Node Path"), KEY_MASK_CMD | KEY_C); ED_SHORTCUT("scene_tree/delete_no_confirm", TTR("Delete (No Confirm)"), KEY_MASK_SHIFT | KEY_DELETE); ED_SHORTCUT("scene_tree/delete", TTR("Delete"), KEY_DELETE); tb = memnew(ToolButton); tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_NEW, false)); tb->set_tooltip(TTR("Add/Create a New Node")); tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/add_child_node")); filter_hbc->add_child(tb); button_add = tb; tb = memnew(ToolButton); tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_INSTANCE, false)); tb->set_tooltip(TTR("Instance a scene file as a Node. Creates an inherited scene if no root node exists.")); tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/instance_scene")); filter_hbc->add_child(tb); button_instance = tb; vbc->add_child(filter_hbc); filter = memnew(LineEdit); filter->set_h_size_flags(SIZE_EXPAND_FILL); filter->set_placeholder(TTR("Filter nodes")); filter_hbc->add_child(filter); filter->connect("text_changed", this, "_filter_changed"); tb = memnew(ToolButton); tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_ATTACH_SCRIPT, false)); tb->set_tooltip(TTR("Attach a new or existing script for the selected node.")); tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/attach_script")); filter_hbc->add_child(tb); tb->hide(); button_create_script = tb; tb = memnew(ToolButton); tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_CLEAR_SCRIPT, false)); tb->set_tooltip(TTR("Clear a script for the selected node.")); tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/clear_script")); filter_hbc->add_child(tb); button_clear_script = tb; tb->hide(); button_hb = memnew(HBoxContainer); vbc->add_child(button_hb); edit_remote = memnew(ToolButton); button_hb->add_child(edit_remote); edit_remote->set_h_size_flags(SIZE_EXPAND_FILL); edit_remote->set_text(TTR("Remote")); edit_remote->set_toggle_mode(true); edit_remote->connect("pressed", this, "_remote_tree_selected"); edit_local = memnew(ToolButton); button_hb->add_child(edit_local); edit_local->set_h_size_flags(SIZE_EXPAND_FILL); edit_local->set_text(TTR("Local")); edit_local->set_toggle_mode(true); edit_local->connect("pressed", this, "_local_tree_selected"); remote_tree = NULL; button_hb->hide(); scene_tree = memnew(SceneTreeEditor(false, true, true)); vbc->add_child(scene_tree); scene_tree->set_v_size_flags(SIZE_EXPAND | SIZE_FILL); scene_tree->connect("rmb_pressed", this, "_tree_rmb"); scene_tree->connect("node_selected", this, "_node_selected", varray(), CONNECT_DEFERRED); scene_tree->connect("node_renamed", this, "_node_renamed", varray(), CONNECT_DEFERRED); scene_tree->connect("node_prerename", this, "_node_prerenamed"); scene_tree->connect("open", this, "_load_request"); scene_tree->connect("open_script", this, "_script_open_request"); scene_tree->connect("nodes_rearranged", this, "_nodes_dragged"); scene_tree->connect("files_dropped", this, "_files_dropped"); scene_tree->connect("script_dropped", this, "_script_dropped"); scene_tree->connect("nodes_dragged", this, "_nodes_drag_begin"); scene_tree->get_scene_tree()->connect("item_double_clicked", this, "_focus_node"); scene_tree->set_undo_redo(&editor_data->get_undo_redo()); scene_tree->set_editor_selection(editor_selection); create_dialog = memnew(CreateDialog); create_dialog->set_base_type("Node"); add_child(create_dialog); create_dialog->connect("create", this, "_create"); script_create_dialog = memnew(ScriptCreateDialog); add_child(script_create_dialog); script_create_dialog->connect("script_created", this, "_script_created"); reparent_dialog = memnew(ReparentDialog); add_child(reparent_dialog); reparent_dialog->connect("reparent", this, "_node_reparent"); accept = memnew(AcceptDialog); add_child(accept); file = memnew(EditorFileDialog); add_child(file); file->connect("file_selected", this, "instance"); set_process_unhandled_key_input(true); delete_dialog = memnew(ConfirmationDialog); add_child(delete_dialog); delete_dialog->connect("confirmed", this, "_delete_confirm"); import_subscene_dialog = memnew(EditorSubScene); add_child(import_subscene_dialog); import_subscene_dialog->connect("subscene_selected", this, "_import_subscene"); new_scene_from_dialog = memnew(EditorFileDialog); new_scene_from_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE); add_child(new_scene_from_dialog); new_scene_from_dialog->connect("file_selected", this, "_new_scene_from"); menu = memnew(PopupMenu); add_child(menu); menu->connect("id_pressed", this, "_tool_selected"); menu_subresources = memnew(PopupMenu); menu_subresources->set_name("Sub-Resources"); menu_subresources->connect("id_pressed", this, "_tool_selected"); menu->add_child(menu_subresources); first_enter = true; restore_script_editor_on_drag = false; clear_inherit_confirm = memnew(ConfirmationDialog); clear_inherit_confirm->set_text(TTR("Clear Inheritance? (No Undo!)")); clear_inherit_confirm->get_ok()->set_text(TTR("Clear!")); add_child(clear_inherit_confirm); set_process_input(true); }
/** * The MIT License (MIT) * * Copyright (c) 2013-2020 Winlin * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SRS_CORE_VERSION4_HPP #define SRS_CORE_VERSION4_HPP #define SRS_VERSION4_REVISION 64 #endif Pick from develop. 4.0.65 /** * The MIT License (MIT) * * Copyright (c) 2013-2020 Winlin * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SRS_CORE_VERSION4_HPP #define SRS_CORE_VERSION4_HPP #define SRS_VERSION4_REVISION 65 #endif
//------------------------------------------------------------------------------ // Copyright (c) 2016 John D. Haughton // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //------------------------------------------------------------------------------ // Kindle3 Linux event #include <assert.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <unistd.h> // C++11 threads would be nicer but don't seem to be able to link // against any libs that actually work at runtime #include <pthread.h> #include "PLT/Event.h" #include "STB/Fifo.h" // ALT ? static const uint8_t DEL = PLT::BACKSPACE; static const uint8_t RET = PLT::RETURN; static const uint8_t LSH = PLT::LSHIFT; static const uint8_t UP = PLT::UP; // Cursor up static const uint8_t DWN = PLT::DOWN; // Cursor down static const uint8_t LFT = PLT::LEFT; // Cursor left static const uint8_t RGT = PLT::RIGHT; // Cursor ritgh static const uint8_t HME = PLT::ESCAPE; // Home static const uint8_t LPR = PLT::HOME; // Left previous static const uint8_t LNX = PLT::END; // Left next static const uint8_t RPR = PLT::PAGE_UP; // Right previous static const uint8_t RNX = PLT::PAGE_DOWN; // Right next static const uint8_t SEL = PLT::SELECT; // Select (center of cursor keys) static const uint8_t MNU = PLT::MENU; // Menu static const uint8_t BAK = PLT::BACK; // Back static const uint8_t AA = PLT::CAPSLOCK; // Aa static const uint8_t SYM = PLT::RALT; // Sym static const uint8_t VLD = PLT::VOL_DOWN; // Volume - static const uint8_t VLU = PLT::VOL_UP; // Volume + static const uint8_t event_decode[0xD0] = { // x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, DEL, 0, // 0x 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 0, 0, RET, 0, 'a', 's', // 1x 'd', 'f', 'g', 'h', 'j', 'k', 'l', 0, 0, 0, LSH, 0, 'z', 'x', 'c', 'v', // 2x 'b', 'n', 'm', 0, '.', 0, 0, 0, 0, ' ', 0, 0, 0, 0, 0, 0, // 3x 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4x 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 5x 0, 0, 0, 0, 0, 0, HME, UP, LNX, LFT, RGT, 0, DWN, RPR, 0, 0, // 6x 0, 0, VLD, VLU, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, SYM, 0, // 7x 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, MNU, 0, 0, 0, 0, // 8x 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, BAK, 0, // 9x 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // Ax 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, AA, RNX, // Bx 0, LPR, SEL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // Cx }; class EventImpl { private: static const uint16_t TIMER_EV = 0xFF00; pthread_t key_td; pthread_t tmr_td; volatile uint32_t tmr_period_ms; pthread_mutex_t fifo_mutex; pthread_cond_t fifo_cv; STB::Fifo<uint16_t,4> fifo; //! Push an event in a thread safe manner void pushEvent(PLT::Event::Type type, uint8_t code = 0) { uint16_t ev = (uint16_t(type) << 8) | code; pthread_mutex_lock(&fifo_mutex); if (!fifo.full()) fifo.push(ev); pthread_cond_signal(&fifo_cv); pthread_mutex_unlock(&fifo_mutex); } //! Get next event in a thread safe manner bool popEvent(bool block, PLT::Event::Type& type, uint8_t& code) { bool new_event; pthread_mutex_lock(&fifo_mutex); if (block) { while(fifo.empty()) { pthread_cond_wait(&fifo_cv, &fifo_mutex); } new_event = true; } else { new_event = !fifo.empty(); } if (new_event) { uint16_t ev = fifo.back(); fifo.pop(); type = PLT::Event::Type(ev >> 8); code = uint8_t(ev); } pthread_mutex_unlock(&fifo_mutex); return new_event; } //! Loop to wait for key events void keyEventLoop() { static const unsigned NUM_FD = 3; int fd[NUM_FD]; fd[0] = open("/dev/input/event0", O_RDONLY | O_NONBLOCK); fd[1] = open("/dev/input/event1", O_RDONLY | O_NONBLOCK); fd[2] = open("/dev/input/event2", O_RDONLY | O_NONBLOCK); int nfds = 0; for(unsigned i = 0; i < NUM_FD; ++i) { if(fd[i] > nfds) nfds = fd[i]; } nfds++; while(true) { fd_set read_fds; FD_ZERO(&read_fds); for(unsigned i = 0; i < NUM_FD; ++i) { FD_SET(fd[i], &read_fds); } if(select(nfds, &read_fds, NULL, NULL, NULL) < 0) break; for(unsigned i = 0; i < NUM_FD; ++i) { if(FD_ISSET(fd[i], &read_fds)) { uint8_t buffer[16]; if(read(fd[i], buffer, 16) != 16) break; if(buffer[10] < 0xD0) { switch(buffer[12]) { case 0: pushEvent(PLT::Event::KEY_UP, event_decode[buffer[10]]); break; case 1: pushEvent(PLT::Event::KEY_DOWN, event_decode[buffer[10]]); break; default: break; } } } } } for(unsigned i = 0; i < NUM_FD; ++i) { close(fd[i]); } } static void* thunkKeyEventLoop(void* ptr) { EventImpl* impl = (EventImpl*)ptr; impl->keyEventLoop(); return 0; } //! Loop to wait for periodic timer events void tmrEventLoop() { while(true) { usleep(tmr_period_ms * 1000); pushEvent(PLT::Event::TIMER); } } static void* thunkTmrEventLoop(void* ptr) { EventImpl* impl = (EventImpl*)ptr; impl->tmrEventLoop(); return 0; } public: EventImpl() : key_td(0) , tmr_td(0) , tmr_period_ms(0) { pthread_mutex_init(&fifo_mutex, 0); pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&key_td, &attr, thunkKeyEventLoop, this); } ~EventImpl() { pthread_cancel(key_td); pthread_cancel(tmr_td); } void setTimer(uint32_t period_ms) { tmr_period_ms = period_ms; if(tmr_td == 0) { pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&tmr_td, &attr, thunkTmrEventLoop, this); } } PLT::Event::Type getEvent(PLT::Event::Message& event, bool block) { event.type = PLT::Event::NONE; event.x = 0; event.y = 0; if(popEvent(block, event.type, event.code)) { // printf("getEvent() => EV %x:%02x\n", event.type, event.code); } return PLT::Event::Type(event.type); } }; static EventImpl impl; static PLT::Event::Type getEvent(PLT::Event::Message& event, bool wait) { return impl.getEvent(event, wait); } namespace PLT { namespace Event { Type poll(Message& event) { return getEvent(event, /* block */ false); } Type wait(Message& event) { return getEvent(event, /* block */ true); } int mainLoop(bool (*callback)(void*), void* user_data) { while(true) { Message event; Type type = wait(event); if(callback != nullptr) (*callback)(user_data); if(type == QUIT) return 0; } } int eventLoop(void (*callback)(const Message&, void*), void* user_data) { while(true) { Message event; Type type = wait(event); if(callback != nullptr) (*callback)(event, user_data); if(type == QUIT) return 0; } } void setTimer(unsigned period_ms) { impl.setTimer(period_ms); } } // namespace Event } // namespace PLT Avoid timer deadlock in Kindle3 events handling //------------------------------------------------------------------------------ // Copyright (c) 2016 John D. Haughton // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //------------------------------------------------------------------------------ // Kindle3 Linux event #include <assert.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <unistd.h> // C++11 threads would be nicer but don't seem to be able to link // against any libs that actually work at runtime #include <pthread.h> #include "PLT/Event.h" #include "STB/Fifo.h" // ALT ? static const uint8_t DEL = PLT::BACKSPACE; static const uint8_t RET = PLT::RETURN; static const uint8_t LSH = PLT::LSHIFT; static const uint8_t UP = PLT::UP; // Cursor up static const uint8_t DWN = PLT::DOWN; // Cursor down static const uint8_t LFT = PLT::LEFT; // Cursor left static const uint8_t RGT = PLT::RIGHT; // Cursor ritgh static const uint8_t HME = PLT::ESCAPE; // Home static const uint8_t LPR = PLT::HOME; // Left previous static const uint8_t LNX = PLT::END; // Left next static const uint8_t RPR = PLT::PAGE_UP; // Right previous static const uint8_t RNX = PLT::PAGE_DOWN; // Right next static const uint8_t SEL = PLT::SELECT; // Select (center of cursor keys) static const uint8_t MNU = PLT::MENU; // Menu static const uint8_t BAK = PLT::BACK; // Back static const uint8_t AA = PLT::CAPSLOCK; // Aa static const uint8_t SYM = PLT::RALT; // Sym static const uint8_t VLD = PLT::VOL_DOWN; // Volume - static const uint8_t VLU = PLT::VOL_UP; // Volume + static const uint8_t event_decode[0xD0] = { // x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, DEL, 0, // 0x 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 0, 0, RET, 0, 'a', 's', // 1x 'd', 'f', 'g', 'h', 'j', 'k', 'l', 0, 0, 0, LSH, 0, 'z', 'x', 'c', 'v', // 2x 'b', 'n', 'm', 0, '.', 0, 0, 0, 0, ' ', 0, 0, 0, 0, 0, 0, // 3x 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4x 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 5x 0, 0, 0, 0, 0, 0, HME, UP, LNX, LFT, RGT, 0, DWN, RPR, 0, 0, // 6x 0, 0, VLD, VLU, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, SYM, 0, // 7x 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, MNU, 0, 0, 0, 0, // 8x 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, BAK, 0, // 9x 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // Ax 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, AA, RNX, // Bx 0, LPR, SEL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // Cx }; class EventImpl { private: static const uint16_t TIMER_EV = 0xFF00; pthread_t key_td{0}; pthread_mutex_t fifo_mutex; pthread_cond_t fifo_cv; STB::Fifo<uint16_t,4> fifo; pthread_t timer_td{0}; volatile uint32_t timer_period_ms{0}; pthread_mutex_t timer_mutex; pthread_cond_t timer_cv; //! Push an event in a thread safe manner void pushEvent(PLT::Event::Type type, uint8_t code = 0) { uint16_t ev = (uint16_t(type) << 8) | code; pthread_mutex_lock(&fifo_mutex); if (!fifo.full()) fifo.push(ev); pthread_cond_signal(&fifo_cv); pthread_mutex_unlock(&fifo_mutex); } //! Get next event in a thread safe manner bool popEvent(bool block, PLT::Event::Type& type, uint8_t& code) { bool new_event; pthread_mutex_lock(&fifo_mutex); if (block) { while(fifo.empty()) { pthread_cond_wait(&fifo_cv, &fifo_mutex); } new_event = true; } else { new_event = !fifo.empty(); } if (new_event) { uint16_t ev = fifo.back(); fifo.pop(); type = PLT::Event::Type(ev >> 8); code = uint8_t(ev); } pthread_mutex_unlock(&fifo_mutex); return new_event; } //! Loop to wait for key events void keyEventLoop() { static const unsigned NUM_FD = 3; int fd[NUM_FD]; fd[0] = open("/dev/input/event0", O_RDONLY | O_NONBLOCK); fd[1] = open("/dev/input/event1", O_RDONLY | O_NONBLOCK); fd[2] = open("/dev/input/event2", O_RDONLY | O_NONBLOCK); int nfds = 0; for(unsigned i = 0; i < NUM_FD; ++i) { if(fd[i] > nfds) nfds = fd[i]; } nfds++; while(true) { fd_set read_fds; FD_ZERO(&read_fds); for(unsigned i = 0; i < NUM_FD; ++i) { FD_SET(fd[i], &read_fds); } if(select(nfds, &read_fds, NULL, NULL, NULL) < 0) break; for(unsigned i = 0; i < NUM_FD; ++i) { if(FD_ISSET(fd[i], &read_fds)) { uint8_t buffer[16]; if(read(fd[i], buffer, 16) != 16) break; if(buffer[10] < 0xD0) { switch(buffer[12]) { case 0: pushEvent(PLT::Event::KEY_UP, event_decode[buffer[10]]); break; case 1: pushEvent(PLT::Event::KEY_DOWN, event_decode[buffer[10]]); break; default: break; } } } } } for(unsigned i = 0; i < NUM_FD; ++i) { close(fd[i]); } } static void* thunkKeyEventLoop(void* ptr) { EventImpl* impl = (EventImpl*)ptr; impl->keyEventLoop(); return nullptr; } //! Loop to wait for periodic timer events void timerEventLoop() { while(true) { pthread_mutex_lock(&timer_mutex); while(timer_period_ms == 0) { pthread_cond_wait(&timer_cv, &timer_mutex); } unsigned period_ms = timer_period_ms; pthread_mutex_unlock(&timer_mutex); usleep(period_ms * 1000); pushEvent(PLT::Event::TIMER); } } static void* thunkTimerEventLoop(void* ptr) { EventImpl* impl = (EventImpl*)ptr; impl->timerEventLoop(); return nullptr; } public: EventImpl() { pthread_mutex_init(&fifo_mutex, 0); pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&key_td, &attr, thunkKeyEventLoop, this); } ~EventImpl() { pthread_cancel(key_td); pthread_cancel(timer_td); } void setTimer(uint32_t period_ms) { if(period_ms == timer_period_ms) return; if(timer_td == 0) { pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&timer_td, &attr, thunkTimerEventLoop, this); } pthread_mutex_lock(&timer_mutex); timer_period_ms = period_ms; pthread_cond_signal(&timer_cv); pthread_mutex_unlock(&timer_mutex); } PLT::Event::Type getEvent(PLT::Event::Message& event, bool block) { event.type = PLT::Event::NONE; event.x = 0; event.y = 0; if(popEvent(block, event.type, event.code)) { // printf("getEvent() => EV %x:%02x\n", event.type, event.code); } return PLT::Event::Type(event.type); } }; static EventImpl impl; static PLT::Event::Type getEvent(PLT::Event::Message& event, bool wait) { return impl.getEvent(event, wait); } namespace PLT { namespace Event { Type poll(Message& event) { return getEvent(event, /* block */ false); } Type wait(Message& event) { return getEvent(event, /* block */ true); } int mainLoop(bool (*callback)(void*), void* user_data) { while(true) { Message event; Type type = wait(event); if(callback != nullptr) (*callback)(user_data); if(type == QUIT) return 0; } } int eventLoop(void (*callback)(const Message&, void*), void* user_data) { while(true) { Message event; Type type = wait(event); if(callback != nullptr) (*callback)(event, user_data); if(type == QUIT) return 0; } } void setTimer(unsigned period_ms) { impl.setTimer(period_ms); } } // namespace Event } // namespace PLT
/* * Created by Rolando Abarca 2012. * Copyright (c) 2012 Rolando Abarca. All rights reserved. * Copyright (c) 2013 Zynga Inc. All rights reserved. * Copyright (c) 2013-2014 Chukong Technologies Inc. * * Heavy based on: https://github.com/funkaster/FakeWebGL/blob/master/FakeWebGL/WebGL/XMLHTTPRequest.cpp * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "XMLHTTPRequest.h" #include <string> using namespace std; //#pragma mark - MinXmlHttpRequest /** * @brief Implementation for header retrieving. * @param header */ void MinXmlHttpRequest::_gotHeader(string header) { // Get Header and Set StatusText // Split String into Tokens char * cstr = new char [header.length()+1]; // check for colon. size_t found_header_field = header.find_first_of(":"); if (found_header_field != std::string::npos) { // Found a header field. string http_field; string http_value; http_field = header.substr(0,found_header_field); http_value = header.substr(found_header_field+1, header.length()); // Get rid of all \n if (!http_value.empty() && http_value[http_value.size() - 1] == '\n') { http_value.erase(http_value.size() - 1); } _httpHeader[http_field] = http_value; } else { // Seems like we have the response Code! Parse it and check for it. char * pch; strcpy(cstr, header.c_str()); pch = strtok(cstr," "); while (pch != NULL) { stringstream ss; string val; ss << pch; val = ss.str(); size_t found_http = val.find("HTTP"); // Check for HTTP Header to set statusText if (found_http != std::string::npos) { stringstream mystream; // Get Response Status pch = strtok (NULL, " "); mystream << pch; pch = strtok (NULL, " "); mystream << " " << pch; _statusText = mystream.str(); } pch = strtok (NULL, " "); } } CC_SAFE_DELETE_ARRAY(cstr); } /** * @brief Set Request header for next call. * @param field Name of the Header to be set. * @param value Value of the Headerfield */ void MinXmlHttpRequest::_setRequestHeader(const char* field, const char* value) { stringstream header_s; stringstream value_s; string header; auto iter = _requestHeader.find(field); // Concatenate values when header exists. if (iter != _requestHeader.end()) { value_s << iter->second << "," << value; } else { value_s << value; } _requestHeader[field] = value_s.str(); } /** * @brief If headers has been set, pass them to curl. * */ void MinXmlHttpRequest::_setHttpRequestHeader() { std::vector<string> header; for (auto it = _requestHeader.begin(); it != _requestHeader.end(); ++it) { const char* first = it->first.c_str(); const char* second = it->second.c_str(); size_t len = sizeof(char) * (strlen(first) + 3 + strlen(second)); char* test = (char*) malloc(len); memset(test, 0,len); strcpy(test, first); strcpy(test + strlen(first) , ": "); strcpy(test + strlen(first) + 2, second); header.push_back(test); free(test); } if (!header.empty()) { _httpRequest->setHeaders(header); } } /** * @brief Callback for HTTPRequest. Handles the response and invokes Callback. * @param sender Object which initialized callback * @param respone Response object */ void MinXmlHttpRequest::handle_requestResponse(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response) { if (0 != strlen(response->getHttpRequest()->getTag())) { CCLOG("%s completed", response->getHttpRequest()->getTag()); } long statusCode = response->getResponseCode(); char statusString[64] = {0}; sprintf(statusString, "HTTP Status Code: %ld, tag = %s", statusCode, response->getHttpRequest()->getTag()); if (!response->isSucceed()) { CCLOG("Response failed, error buffer: %s", response->getErrorBuffer()); if (statusCode == 0) { _errorFlag = true; _status = 0; _statusText.clear(); return; } } // set header std::vector<char> *headers = response->getResponseHeader(); std::string header(headers->begin(), headers->end()); std::istringstream stream(header); std::string line; while(std::getline(stream, line)) { _gotHeader(line); } /** get the response data **/ std::vector<char> *buffer = response->getResponseData(); _status = statusCode; _readyState = DONE; _dataSize = static_cast<uint32_t>(buffer->size()); CC_SAFE_FREE(_data); _data = (char*) malloc(_dataSize + 1); _data[_dataSize] = '\0'; memcpy((void*)_data, (const void*)buffer->data(), _dataSize); js_proxy_t * p; void* ptr = (void*)this; p = jsb_get_native_proxy(ptr); if(p) { JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); if (_onreadystateCallback) { JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET //JS_IsExceptionPending(cx) && JS_ReportPendingException(cx); jsval fval = OBJECT_TO_JSVAL(_onreadystateCallback); jsval out; JS_CallFunctionValue(cx, NULL, fval, 0, NULL, &out); } } } /** * @brief Send out request and fire callback when done. * @param cx Javascript context */ void MinXmlHttpRequest::_sendRequest(JSContext *cx) { _httpRequest->setResponseCallback(this, httpresponse_selector(MinXmlHttpRequest::handle_requestResponse)); cocos2d::network::HttpClient::getInstance()->send(_httpRequest); _httpRequest->release(); } /** * @brief Constructor initializes cchttprequest and stuff * */ MinXmlHttpRequest::MinXmlHttpRequest() : _url() , _cx(ScriptingCore::getInstance()->getGlobalContext()) , _meth() , _type() , _data(nullptr) , _dataSize() , _onreadystateCallback(nullptr) , _readyState(UNSENT) , _status(0) , _statusText() , _responseType() , _timeout() , _isAsync() , _httpRequest(new cocos2d::network::HttpRequest()) , _isNetwork(true) , _withCredentialsValue(true) , _errorFlag(false) , _httpHeader() , _requestHeader() { } /** * @brief Destructor cleans up _httpRequest and stuff * */ MinXmlHttpRequest::~MinXmlHttpRequest() { if (_onreadystateCallback != NULL) { JS_RemoveObjectRoot(_cx, &_onreadystateCallback); } if (_httpRequest) { // We don't need to release _httpRequest here since it will be released in the http callback. // _httpRequest->release(); } CC_SAFE_FREE(_data); } /** * @brief Initialize Object and needed properties. * */ JS_BINDED_CLASS_GLUE_IMPL(MinXmlHttpRequest); /** * @brief Implementation for the Javascript Constructor * */ JS_BINDED_CONSTRUCTOR_IMPL(MinXmlHttpRequest) { MinXmlHttpRequest* req = new MinXmlHttpRequest(); req->autorelease(); js_proxy_t *p; jsval out; JSObject *obj = JS_NewObject(cx, &MinXmlHttpRequest::js_class, MinXmlHttpRequest::js_proto, MinXmlHttpRequest::js_parent); if (obj) { JS_SetPrivate(obj, req); out = OBJECT_TO_JSVAL(obj); } JS_SET_RVAL(cx, vp, out); p =jsb_new_proxy(req, obj); JS_AddNamedObjectRoot(cx, &p->obj, "XMLHttpRequest"); return true; } /** * @brief get Callback function for Javascript * */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, onreadystatechange) { if (_onreadystateCallback) { JSString *tmpstr = JS_NewStringCopyZ(cx, "1"); JS::RootedValue tmpval(cx); tmpval = STRING_TO_JSVAL(tmpstr); JS_SetProperty(cx, _onreadystateCallback, "readyState", tmpval); jsval out = OBJECT_TO_JSVAL(_onreadystateCallback); vp.set(out); } else { vp.set(JSVAL_NULL); } return true; } /** * @brief Set Callback function coming from Javascript * * */ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, onreadystatechange) { jsval callback = vp.get(); if (callback != JSVAL_NULL) { _onreadystateCallback = JSVAL_TO_OBJECT(callback); JS_AddNamedObjectRoot(cx, &_onreadystateCallback, "onreadystateCallback"); } return true; } /** * @brief upload getter - TODO * * Placeholder for further implementations!! */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, upload) { vp.set(JSVAL_NULL); return true; } /** * @brief upload setter - TODO * * Placeholder for further implementations */ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, upload) { vp.set(JSVAL_NULL); return true; } /** * @brief timeout getter - TODO * * Placeholder for further implementations */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, timeout) { vp.set(INT_TO_JSVAL(_timeout)); return true; } /** * @brief timeout setter - TODO * * Placeholder for further implementations */ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, timeout) { jsval timeout_ms = vp.get(); _timeout = JSVAL_TO_INT(timeout_ms); //curl_easy_setopt(curlHandle, CURLOPT_CONNECTTIMEOUT_MS, timeout); return true; } /** * @brief get response type for actual XHR * * */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseType) { JSString* str = JS_NewStringCopyN(cx, "", 0); vp.set(STRING_TO_JSVAL(str)); return true; } /** * @brief responseXML getter - TODO * * Placeholder for further implementation. */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseXML) { vp.set(JSVAL_NULL); return true; } /** * @brief set response type for actual XHR * * */ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, responseType) { jsval type = vp.get(); if (type.isString()) { JSString* str = type.toString(); bool equal; JS_StringEqualsAscii(cx, str, "text", &equal); if (equal) { _responseType = ResponseType::STRING; return true; } JS_StringEqualsAscii(cx, str, "arraybuffer", &equal); if (equal) { _responseType = ResponseType::ARRAY_BUFFER; return true; } JS_StringEqualsAscii(cx, str, "json", &equal); if (equal) { _responseType = ResponseType::JSON; return true; } // ignore the rest of the response types for now return true; } JS_ReportError(cx, "Invalid response type"); return false; } /** * @brief get readyState for actual XHR * * */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, readyState) { vp.set(INT_TO_JSVAL(_readyState)); return true; } /** * @brief get status for actual XHR * * */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, status) { vp.set(INT_TO_JSVAL(_status)); return true; } /** * @brief get statusText for actual XHR * * */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, statusText) { jsval strVal = std_string_to_jsval(cx, _statusText); if (strVal != JSVAL_NULL) { vp.set(strVal); return true; } else { JS_ReportError(cx, "Error trying to create JSString from data"); return false; } } /** * @brief get value of withCredentials property. * */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, withCredentials) { vp.set(BOOLEAN_TO_JSVAL(_withCredentialsValue)); return true; } /** * withCredentials - set value of withCredentials property. * */ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, withCredentials) { jsval credential = vp.get(); if (credential != JSVAL_NULL) { _withCredentialsValue = JSVAL_TO_BOOLEAN(credential); } return true; } /** * @brief get (raw) responseText * */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseText) { if (_data) { jsval strVal = std_string_to_jsval(cx, _data); if (strVal != JSVAL_NULL) { vp.set(strVal); return true; } } CCLOGERROR("ResponseText was empty, probably there is a network error!"); // Return an empty string vp.set(std_string_to_jsval(cx, "")); return true; } /** * @brief get response of latest XHR * */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, response) { if (_responseType == ResponseType::STRING) { return _js_get_responseText(cx, id, vp); } else { if (_readyState != DONE || _errorFlag) { vp.set(JSVAL_NULL); return true; } if (_responseType == ResponseType::JSON) { JS::RootedValue outVal(cx); jsval strVal = std_string_to_jsval(cx, _data); if (JS_ParseJSON(cx, JS_GetStringCharsZ(cx, JSVAL_TO_STRING(strVal)), _dataSize, &outVal)) { vp.set(outVal); return true; } } else if (_responseType == ResponseType::ARRAY_BUFFER) { JSObject* tmp = JS_NewArrayBuffer(cx, _dataSize); uint8_t* tmpData = JS_GetArrayBufferData(tmp); memcpy((void*)tmpData, (const void*)_data, _dataSize); jsval outVal = OBJECT_TO_JSVAL(tmp); vp.set(outVal); return true; } // by default, return text return _js_get_responseText(cx, id, vp); } } /** * @brief initialize new xhr. * */ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, open) { if (argc >= 2) { jsval* argv = JS_ARGV(cx, vp); const char* method; const char* urlstr; bool async = true; JSString* jsMethod = JS::ToString( cx, JS::RootedValue(cx, argv[0]) ); JSString* jsURL = JS::ToString( cx, JS::RootedValue(cx, argv[1]) ); if (argc > 2) { async = JS::ToBoolean( JS::RootedValue(cx, argv[2]) ); } JSStringWrapper w1(jsMethod); JSStringWrapper w2(jsURL); method = w1.get(); urlstr = w2.get(); _url = urlstr; _meth = method; _readyState = 1; _isAsync = async; if (_url.length() > 5 && _url.compare(_url.length() - 5, 5, ".json") == 0) { _responseType = ResponseType::JSON; } { auto requestType = (_meth.compare("get") == 0 || _meth.compare("GET") == 0) ? cocos2d::network::HttpRequest::Type::GET : ( (_meth.compare("post") == 0 || _meth.compare("POST") == 0) ? cocos2d::network::HttpRequest::Type::POST : ( (_meth.compare("put") == 0 || _meth.compare("PUT") == 0) ? cocos2d::network::HttpRequest::Type::PUT : ( (_meth.compare("delete") == 0 || _meth.compare("DELETE") == 0) ? cocos2d::network::HttpRequest::Type::DELETE : ( cocos2d::network::HttpRequest::Type::UNKNOWN)))); _httpRequest->setRequestType(requestType); _httpRequest->setUrl(_url.c_str()); } _isNetwork = true; _readyState = OPENED; _status = 0; return true; } JS_ReportError(cx, "invalid call: %s", __FUNCTION__); return false; } /** * @brief send xhr * */ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, send) { JSString *str = NULL; std::string data; // Clean up header map. New request, new headers! _httpHeader.clear(); _errorFlag = false; if (argc == 1) { if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &str)) { return false; } JSStringWrapper strWrap(str); data = strWrap.get(); } if (data.length() > 0 && (_meth.compare("post") == 0 || _meth.compare("POST") == 0 || _meth.compare("put") == 0 || _meth.compare("PUT") == 0)) { _httpRequest->setRequestData(data.c_str(), static_cast<unsigned int>(data.length())); } _setHttpRequestHeader(); _sendRequest(cx); return true; } /** * @brief abort function Placeholder! * */ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, abort) { return true; } /** * @brief Get all response headers as a string * */ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, getAllResponseHeaders) { stringstream responseheaders; string responseheader; for (auto it = _httpHeader.begin(); it != _httpHeader.end(); ++it) { responseheaders << it->first << ": " << it->second << "\n"; } responseheader = responseheaders.str(); jsval strVal = std_string_to_jsval(cx, responseheader); if (strVal != JSVAL_NULL) { JS_SET_RVAL(cx, vp, strVal); return true; } else { JS_ReportError(cx, "Error trying to create JSString from data"); return false; } return true; } /** * @brief Get all response headers as a string * */ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, getResponseHeader) { JSString *header_value; if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &header_value)) { return false; }; std::string data; JSStringWrapper strWrap(header_value); data = strWrap.get(); stringstream streamdata; streamdata << data; string value = streamdata.str(); auto iter = _httpHeader.find(value); if (iter != _httpHeader.end()) { jsval js_ret_val = std_string_to_jsval(cx, iter->second); JS_SET_RVAL(cx, vp, js_ret_val); return true; } else { JS_SET_RVAL(cx, vp, JSVAL_NULL); return true; } } /** * @brief Set the given Fields to request Header. * * */ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, setRequestHeader) { if (argc >= 2) { jsval* argv = JS_ARGV(cx, vp); const char* field; const char* value; JSString* jsField = JS::ToString( cx, JS::RootedValue(cx, argv[0]) ); JSString* jsValue = JS::ToString( cx, JS::RootedValue(cx, argv[1]) ); JSStringWrapper w1(jsField); JSStringWrapper w2(jsValue); field = w1.get(); value = w2.get(); // Populate the request_header map. _setRequestHeader(field, value); return true; } return false; } /** * @brief overrideMimeType function - TODO! * * Just a placeholder for further implementations. */ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, overrideMimeType) { return true; } /** * @brief destructor for Javascript * */ static void basic_object_finalize(JSFreeOp *freeOp, JSObject *obj) { CCLOG("basic_object_finalize %p ...", obj); } /** * @brief Register XMLHttpRequest to be usable in JS and add properties and Mehtods. * @param cx Global Spidermonkey JS Context. * @param global Global Spidermonkey Javascript object. */ void MinXmlHttpRequest::_js_register(JSContext *cx, JSObject *global) { JSClass jsclass = { "XMLHttpRequest", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, basic_object_finalize, JSCLASS_NO_OPTIONAL_MEMBERS }; MinXmlHttpRequest::js_class = jsclass; static JSPropertySpec props[] = { JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, onreadystatechange), JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, responseType), JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, withCredentials), JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, readyState), JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, status), JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, statusText), JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, responseText), JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, responseXML), JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, response), {0, 0, 0, 0, 0} }; static JSFunctionSpec funcs[] = { JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, open), JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, abort), JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, send), JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, setRequestHeader), JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, getAllResponseHeaders), JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, getResponseHeader), JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, overrideMimeType), JS_FS_END }; MinXmlHttpRequest::js_parent = NULL; MinXmlHttpRequest::js_proto = JS_InitClass(cx, global, NULL, &MinXmlHttpRequest::js_class , MinXmlHttpRequest::_js_constructor, 0, props, funcs, NULL, NULL); } issue #4544: fix memory leak of XMLHTTPRequest with sendImmediate /* * Created by Rolando Abarca 2012. * Copyright (c) 2012 Rolando Abarca. All rights reserved. * Copyright (c) 2013 Zynga Inc. All rights reserved. * Copyright (c) 2013-2014 Chukong Technologies Inc. * * Heavy based on: https://github.com/funkaster/FakeWebGL/blob/master/FakeWebGL/WebGL/XMLHTTPRequest.cpp * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "XMLHTTPRequest.h" #include <string> using namespace std; //#pragma mark - MinXmlHttpRequest /** * @brief Implementation for header retrieving. * @param header */ void MinXmlHttpRequest::_gotHeader(string header) { // Get Header and Set StatusText // Split String into Tokens char * cstr = new char [header.length()+1]; // check for colon. size_t found_header_field = header.find_first_of(":"); if (found_header_field != std::string::npos) { // Found a header field. string http_field; string http_value; http_field = header.substr(0,found_header_field); http_value = header.substr(found_header_field+1, header.length()); // Get rid of all \n if (!http_value.empty() && http_value[http_value.size() - 1] == '\n') { http_value.erase(http_value.size() - 1); } _httpHeader[http_field] = http_value; } else { // Seems like we have the response Code! Parse it and check for it. char * pch; strcpy(cstr, header.c_str()); pch = strtok(cstr," "); while (pch != NULL) { stringstream ss; string val; ss << pch; val = ss.str(); size_t found_http = val.find("HTTP"); // Check for HTTP Header to set statusText if (found_http != std::string::npos) { stringstream mystream; // Get Response Status pch = strtok (NULL, " "); mystream << pch; pch = strtok (NULL, " "); mystream << " " << pch; _statusText = mystream.str(); } pch = strtok (NULL, " "); } } CC_SAFE_DELETE_ARRAY(cstr); } /** * @brief Set Request header for next call. * @param field Name of the Header to be set. * @param value Value of the Headerfield */ void MinXmlHttpRequest::_setRequestHeader(const char* field, const char* value) { stringstream header_s; stringstream value_s; string header; auto iter = _requestHeader.find(field); // Concatenate values when header exists. if (iter != _requestHeader.end()) { value_s << iter->second << "," << value; } else { value_s << value; } _requestHeader[field] = value_s.str(); } /** * @brief If headers has been set, pass them to curl. * */ void MinXmlHttpRequest::_setHttpRequestHeader() { std::vector<string> header; for (auto it = _requestHeader.begin(); it != _requestHeader.end(); ++it) { const char* first = it->first.c_str(); const char* second = it->second.c_str(); size_t len = sizeof(char) * (strlen(first) + 3 + strlen(second)); char* test = (char*) malloc(len); memset(test, 0,len); strcpy(test, first); strcpy(test + strlen(first) , ": "); strcpy(test + strlen(first) + 2, second); header.push_back(test); free(test); } if (!header.empty()) { _httpRequest->setHeaders(header); } } /** * @brief Callback for HTTPRequest. Handles the response and invokes Callback. * @param sender Object which initialized callback * @param respone Response object */ void MinXmlHttpRequest::handle_requestResponse(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response) { if (0 != strlen(response->getHttpRequest()->getTag())) { CCLOG("%s completed", response->getHttpRequest()->getTag()); } long statusCode = response->getResponseCode(); char statusString[64] = {0}; sprintf(statusString, "HTTP Status Code: %ld, tag = %s", statusCode, response->getHttpRequest()->getTag()); if (!response->isSucceed()) { CCLOG("Response failed, error buffer: %s", response->getErrorBuffer()); if (statusCode == 0) { _errorFlag = true; _status = 0; _statusText.clear(); return; } } // set header std::vector<char> *headers = response->getResponseHeader(); std::string header(headers->begin(), headers->end()); std::istringstream stream(header); std::string line; while(std::getline(stream, line)) { _gotHeader(line); } /** get the response data **/ std::vector<char> *buffer = response->getResponseData(); _status = statusCode; _readyState = DONE; _dataSize = static_cast<uint32_t>(buffer->size()); CC_SAFE_FREE(_data); _data = (char*) malloc(_dataSize + 1); _data[_dataSize] = '\0'; memcpy((void*)_data, (const void*)buffer->data(), _dataSize); js_proxy_t * p; void* ptr = (void*)this; p = jsb_get_native_proxy(ptr); if(p) { JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); if (_onreadystateCallback) { JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET //JS_IsExceptionPending(cx) && JS_ReportPendingException(cx); jsval fval = OBJECT_TO_JSVAL(_onreadystateCallback); jsval out; JS_CallFunctionValue(cx, NULL, fval, 0, NULL, &out); } } } /** * @brief Send out request and fire callback when done. * @param cx Javascript context */ void MinXmlHttpRequest::_sendRequest(JSContext *cx) { _httpRequest->setResponseCallback(this, httpresponse_selector(MinXmlHttpRequest::handle_requestResponse)); cocos2d::network::HttpClient::getInstance()->sendImmediate(_httpRequest); _httpRequest->release(); } /** * @brief Constructor initializes cchttprequest and stuff * */ MinXmlHttpRequest::MinXmlHttpRequest() : _url() , _cx(ScriptingCore::getInstance()->getGlobalContext()) , _meth() , _type() , _data(nullptr) , _dataSize() , _onreadystateCallback(nullptr) , _readyState(UNSENT) , _status(0) , _statusText() , _responseType() , _timeout() , _isAsync() , _httpRequest(new cocos2d::network::HttpRequest()) , _isNetwork(true) , _withCredentialsValue(true) , _errorFlag(false) , _httpHeader() , _requestHeader() { } /** * @brief Destructor cleans up _httpRequest and stuff * */ MinXmlHttpRequest::~MinXmlHttpRequest() { if (_onreadystateCallback != NULL) { JS_RemoveObjectRoot(_cx, &_onreadystateCallback); } if (_httpRequest) { // We don't need to release _httpRequest here since it will be released in the http callback. // _httpRequest->release(); } CC_SAFE_FREE(_data); } /** * @brief Initialize Object and needed properties. * */ JS_BINDED_CLASS_GLUE_IMPL(MinXmlHttpRequest); /** * @brief Implementation for the Javascript Constructor * */ JS_BINDED_CONSTRUCTOR_IMPL(MinXmlHttpRequest) { MinXmlHttpRequest* req = new MinXmlHttpRequest(); req->autorelease(); js_proxy_t *p; jsval out; JSObject *obj = JS_NewObject(cx, &MinXmlHttpRequest::js_class, MinXmlHttpRequest::js_proto, MinXmlHttpRequest::js_parent); if (obj) { JS_SetPrivate(obj, req); out = OBJECT_TO_JSVAL(obj); } JS_SET_RVAL(cx, vp, out); p =jsb_new_proxy(req, obj); JS_AddNamedObjectRoot(cx, &p->obj, "XMLHttpRequest"); return true; } /** * @brief get Callback function for Javascript * */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, onreadystatechange) { if (_onreadystateCallback) { JSString *tmpstr = JS_NewStringCopyZ(cx, "1"); JS::RootedValue tmpval(cx); tmpval = STRING_TO_JSVAL(tmpstr); JS_SetProperty(cx, _onreadystateCallback, "readyState", tmpval); jsval out = OBJECT_TO_JSVAL(_onreadystateCallback); vp.set(out); } else { vp.set(JSVAL_NULL); } return true; } /** * @brief Set Callback function coming from Javascript * * */ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, onreadystatechange) { jsval callback = vp.get(); if (callback != JSVAL_NULL) { _onreadystateCallback = JSVAL_TO_OBJECT(callback); JS_AddNamedObjectRoot(cx, &_onreadystateCallback, "onreadystateCallback"); } return true; } /** * @brief upload getter - TODO * * Placeholder for further implementations!! */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, upload) { vp.set(JSVAL_NULL); return true; } /** * @brief upload setter - TODO * * Placeholder for further implementations */ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, upload) { vp.set(JSVAL_NULL); return true; } /** * @brief timeout getter - TODO * * Placeholder for further implementations */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, timeout) { vp.set(INT_TO_JSVAL(_timeout)); return true; } /** * @brief timeout setter - TODO * * Placeholder for further implementations */ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, timeout) { jsval timeout_ms = vp.get(); _timeout = JSVAL_TO_INT(timeout_ms); //curl_easy_setopt(curlHandle, CURLOPT_CONNECTTIMEOUT_MS, timeout); return true; } /** * @brief get response type for actual XHR * * */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseType) { JSString* str = JS_NewStringCopyN(cx, "", 0); vp.set(STRING_TO_JSVAL(str)); return true; } /** * @brief responseXML getter - TODO * * Placeholder for further implementation. */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseXML) { vp.set(JSVAL_NULL); return true; } /** * @brief set response type for actual XHR * * */ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, responseType) { jsval type = vp.get(); if (type.isString()) { JSString* str = type.toString(); bool equal; JS_StringEqualsAscii(cx, str, "text", &equal); if (equal) { _responseType = ResponseType::STRING; return true; } JS_StringEqualsAscii(cx, str, "arraybuffer", &equal); if (equal) { _responseType = ResponseType::ARRAY_BUFFER; return true; } JS_StringEqualsAscii(cx, str, "json", &equal); if (equal) { _responseType = ResponseType::JSON; return true; } // ignore the rest of the response types for now return true; } JS_ReportError(cx, "Invalid response type"); return false; } /** * @brief get readyState for actual XHR * * */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, readyState) { vp.set(INT_TO_JSVAL(_readyState)); return true; } /** * @brief get status for actual XHR * * */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, status) { vp.set(INT_TO_JSVAL(_status)); return true; } /** * @brief get statusText for actual XHR * * */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, statusText) { jsval strVal = std_string_to_jsval(cx, _statusText); if (strVal != JSVAL_NULL) { vp.set(strVal); return true; } else { JS_ReportError(cx, "Error trying to create JSString from data"); return false; } } /** * @brief get value of withCredentials property. * */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, withCredentials) { vp.set(BOOLEAN_TO_JSVAL(_withCredentialsValue)); return true; } /** * withCredentials - set value of withCredentials property. * */ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, withCredentials) { jsval credential = vp.get(); if (credential != JSVAL_NULL) { _withCredentialsValue = JSVAL_TO_BOOLEAN(credential); } return true; } /** * @brief get (raw) responseText * */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseText) { if (_data) { jsval strVal = std_string_to_jsval(cx, _data); if (strVal != JSVAL_NULL) { vp.set(strVal); return true; } } CCLOGERROR("ResponseText was empty, probably there is a network error!"); // Return an empty string vp.set(std_string_to_jsval(cx, "")); return true; } /** * @brief get response of latest XHR * */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, response) { if (_responseType == ResponseType::STRING) { return _js_get_responseText(cx, id, vp); } else { if (_readyState != DONE || _errorFlag) { vp.set(JSVAL_NULL); return true; } if (_responseType == ResponseType::JSON) { JS::RootedValue outVal(cx); jsval strVal = std_string_to_jsval(cx, _data); if (JS_ParseJSON(cx, JS_GetStringCharsZ(cx, JSVAL_TO_STRING(strVal)), _dataSize, &outVal)) { vp.set(outVal); return true; } } else if (_responseType == ResponseType::ARRAY_BUFFER) { JSObject* tmp = JS_NewArrayBuffer(cx, _dataSize); uint8_t* tmpData = JS_GetArrayBufferData(tmp); memcpy((void*)tmpData, (const void*)_data, _dataSize); jsval outVal = OBJECT_TO_JSVAL(tmp); vp.set(outVal); return true; } // by default, return text return _js_get_responseText(cx, id, vp); } } /** * @brief initialize new xhr. * */ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, open) { if (argc >= 2) { jsval* argv = JS_ARGV(cx, vp); const char* method; const char* urlstr; bool async = true; JSString* jsMethod = JS::ToString( cx, JS::RootedValue(cx, argv[0]) ); JSString* jsURL = JS::ToString( cx, JS::RootedValue(cx, argv[1]) ); if (argc > 2) { async = JS::ToBoolean( JS::RootedValue(cx, argv[2]) ); } JSStringWrapper w1(jsMethod); JSStringWrapper w2(jsURL); method = w1.get(); urlstr = w2.get(); _url = urlstr; _meth = method; _readyState = 1; _isAsync = async; if (_url.length() > 5 && _url.compare(_url.length() - 5, 5, ".json") == 0) { _responseType = ResponseType::JSON; } { auto requestType = (_meth.compare("get") == 0 || _meth.compare("GET") == 0) ? cocos2d::network::HttpRequest::Type::GET : ( (_meth.compare("post") == 0 || _meth.compare("POST") == 0) ? cocos2d::network::HttpRequest::Type::POST : ( (_meth.compare("put") == 0 || _meth.compare("PUT") == 0) ? cocos2d::network::HttpRequest::Type::PUT : ( (_meth.compare("delete") == 0 || _meth.compare("DELETE") == 0) ? cocos2d::network::HttpRequest::Type::DELETE : ( cocos2d::network::HttpRequest::Type::UNKNOWN)))); _httpRequest->setRequestType(requestType); _httpRequest->setUrl(_url.c_str()); } _isNetwork = true; _readyState = OPENED; _status = 0; return true; } JS_ReportError(cx, "invalid call: %s", __FUNCTION__); return false; } /** * @brief send xhr * */ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, send) { JSString *str = NULL; std::string data; // Clean up header map. New request, new headers! _httpHeader.clear(); _errorFlag = false; if (argc == 1) { if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &str)) { return false; } JSStringWrapper strWrap(str); data = strWrap.get(); } if (data.length() > 0 && (_meth.compare("post") == 0 || _meth.compare("POST") == 0 || _meth.compare("put") == 0 || _meth.compare("PUT") == 0)) { _httpRequest->setRequestData(data.c_str(), static_cast<unsigned int>(data.length())); } _setHttpRequestHeader(); _sendRequest(cx); return true; } /** * @brief abort function Placeholder! * */ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, abort) { return true; } /** * @brief Get all response headers as a string * */ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, getAllResponseHeaders) { stringstream responseheaders; string responseheader; for (auto it = _httpHeader.begin(); it != _httpHeader.end(); ++it) { responseheaders << it->first << ": " << it->second << "\n"; } responseheader = responseheaders.str(); jsval strVal = std_string_to_jsval(cx, responseheader); if (strVal != JSVAL_NULL) { JS_SET_RVAL(cx, vp, strVal); return true; } else { JS_ReportError(cx, "Error trying to create JSString from data"); return false; } return true; } /** * @brief Get all response headers as a string * */ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, getResponseHeader) { JSString *header_value; if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &header_value)) { return false; }; std::string data; JSStringWrapper strWrap(header_value); data = strWrap.get(); stringstream streamdata; streamdata << data; string value = streamdata.str(); auto iter = _httpHeader.find(value); if (iter != _httpHeader.end()) { jsval js_ret_val = std_string_to_jsval(cx, iter->second); JS_SET_RVAL(cx, vp, js_ret_val); return true; } else { JS_SET_RVAL(cx, vp, JSVAL_NULL); return true; } } /** * @brief Set the given Fields to request Header. * * */ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, setRequestHeader) { if (argc >= 2) { jsval* argv = JS_ARGV(cx, vp); const char* field; const char* value; JSString* jsField = JS::ToString( cx, JS::RootedValue(cx, argv[0]) ); JSString* jsValue = JS::ToString( cx, JS::RootedValue(cx, argv[1]) ); JSStringWrapper w1(jsField); JSStringWrapper w2(jsValue); field = w1.get(); value = w2.get(); // Populate the request_header map. _setRequestHeader(field, value); return true; } return false; } /** * @brief overrideMimeType function - TODO! * * Just a placeholder for further implementations. */ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, overrideMimeType) { return true; } /** * @brief destructor for Javascript * */ static void basic_object_finalize(JSFreeOp *freeOp, JSObject *obj) { CCLOG("basic_object_finalize %p ...", obj); } /** * @brief Register XMLHttpRequest to be usable in JS and add properties and Mehtods. * @param cx Global Spidermonkey JS Context. * @param global Global Spidermonkey Javascript object. */ void MinXmlHttpRequest::_js_register(JSContext *cx, JSObject *global) { JSClass jsclass = { "XMLHttpRequest", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, basic_object_finalize, JSCLASS_NO_OPTIONAL_MEMBERS }; MinXmlHttpRequest::js_class = jsclass; static JSPropertySpec props[] = { JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, onreadystatechange), JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, responseType), JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, withCredentials), JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, readyState), JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, status), JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, statusText), JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, responseText), JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, responseXML), JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, response), {0, 0, 0, 0, 0} }; static JSFunctionSpec funcs[] = { JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, open), JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, abort), JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, send), JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, setRequestHeader), JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, getAllResponseHeaders), JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, getResponseHeader), JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, overrideMimeType), JS_FS_END }; MinXmlHttpRequest::js_parent = NULL; MinXmlHttpRequest::js_proto = JS_InitClass(cx, global, NULL, &MinXmlHttpRequest::js_class , MinXmlHttpRequest::_js_constructor, 0, props, funcs, NULL, NULL); }
/***************************************************************************** * Project: RooFit * * Package: RooFitCore * * File: $Id: RooProdGenContext.cc,v 1.7 2002/09/30 00:57:29 verkerke Exp $ * Authors: * * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * * * * Copyright (c) 2000-2002, Regents of the University of California * * and Stanford University. All rights reserved. * * * * Redistribution and use in source and binary forms, * * with or without modification, are permitted according to the terms * * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ // -- CLASS DESCRIPTION [AUX} -- // RooProdGenContext is an efficient implementation of the generator context // specific for RooProdPdf PDFs. The sim-context owns a list of // component generator contexts that are used to generate the dependents // for each component PDF sequentially. #include "RooFitCore/RooProdGenContext.hh" #include "RooFitCore/RooProdPdf.hh" #include "RooFitCore/RooDataSet.hh" ClassImp(RooProdGenContext) ; RooProdGenContext::RooProdGenContext(const RooProdPdf &model, const RooArgSet &vars, const RooDataSet *prototype, Bool_t verbose) : RooAbsGenContext(model,vars,prototype,verbose), _pdf(&model) { // Constructor. Build an array of generator contexts for each product component PDF // Make full list of dependents (generated & proto) RooArgSet deps(vars) ; if (prototype) { RooArgSet* protoDeps = model.getDependents(*prototype->get()) ; deps.add(*protoDeps) ; delete protoDeps ; } // Factorize product in irreducible terms TList* termList = model.factorizeProduct(deps) ; TIterator* termIter = termList->MakeIterator() ; RooAbsPdf* pdf ; RooArgSet* term ; while(term=(RooArgSet*)termIter->Next()) { TIterator* pdfIter = term->createIterator() ; if (term->getSize()==1) { // Simple term pdf = (RooAbsPdf*) pdfIter->Next() ; RooArgSet* pdfDep = pdf->getDependents(&vars) ; if (pdfDep->getSize()>0) { RooAbsGenContext* cx = pdf->genContext(*pdfDep,prototype,verbose) ; _gcList.Add(cx) ; } delete pdfDep ; } else { // Composite term RooArgSet termDeps ; while(pdf=(RooAbsPdf*) pdfIter->Next()) { RooArgSet* pdfDep = pdf->getDependents(&vars) ; termDeps.add(*pdfDep,kFALSE) ; delete pdfDep ; } if (termDeps.getSize()>0) { const char* name = model.makeRGPPName("PRODGEN_",*term,RooArgSet(),RooArgSet()) ; RooProdPdf* multiPdf = new RooProdPdf(name,name,*term) ; multiPdf->useDefaultGen(kTRUE) ; _ownedMultiProds.addOwned(*multiPdf) ; RooAbsGenContext* cx = multiPdf->genContext(termDeps,prototype,verbose) ; _gcList.Add(cx) ; } } delete pdfIter ; } _gcIter = _gcList.MakeIterator() ; } RooProdGenContext::~RooProdGenContext() { // Destructor. Delete all owned subgenerator contexts delete _gcIter ; _gcList.Delete() ; } void RooProdGenContext::initGenerator(const RooArgSet &theEvent) { // Forward initGenerator call to all components RooAbsGenContext* gc ; _gcIter->Reset() ; while(gc=(RooAbsGenContext*)_gcIter->Next()){ gc->initGenerator(theEvent) ; } } void RooProdGenContext::generateEvent(RooArgSet &theEvent, Int_t remaining) { // Generate a single event of the product by generating the components // of the products sequentially // Loop over the component generators TList compData ; RooAbsGenContext* gc ; _gcIter->Reset() ; while(gc=(RooAbsGenContext*)_gcIter->Next()) { // Generate component gc->generateEvent(theEvent,remaining) ; } } void RooProdGenContext::printToStream(ostream &os, PrintOption opt, TString indent) const { RooAbsGenContext::printToStream(os,opt,indent) ; TString indent2(indent) ; indent2.Append(" ") ; RooAbsGenContext* gc ; _gcIter->Reset() ; while(gc=(RooAbsGenContext*)_gcIter->Next()) { gc->printToStream(os,opt,indent2) ; } } o RooProdPdf - In factorized generation mode, do not count prototypes as observables in the factorization definition git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@6873 27541ba8-7e3a-0410-8455-c3a389f83636 /***************************************************************************** * Project: RooFit * * Package: RooFitCore * * File: $Id: RooProdGenContext.cc,v 1.8 2003/04/28 20:42:39 wverkerke Exp $ * Authors: * * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * * * * Copyright (c) 2000-2002, Regents of the University of California * * and Stanford University. All rights reserved. * * * * Redistribution and use in source and binary forms, * * with or without modification, are permitted according to the terms * * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ // -- CLASS DESCRIPTION [AUX} -- // RooProdGenContext is an efficient implementation of the generator context // specific for RooProdPdf PDFs. The sim-context owns a list of // component generator contexts that are used to generate the dependents // for each component PDF sequentially. #include "RooFitCore/RooProdGenContext.hh" #include "RooFitCore/RooProdPdf.hh" #include "RooFitCore/RooDataSet.hh" ClassImp(RooProdGenContext) ; RooProdGenContext::RooProdGenContext(const RooProdPdf &model, const RooArgSet &vars, const RooDataSet *prototype, Bool_t verbose) : RooAbsGenContext(model,vars,prototype,verbose), _pdf(&model) { // Constructor. Build an array of generator contexts for each product component PDF // Make full list of dependents (generated & proto) RooArgSet deps(vars) ; if (prototype) { RooArgSet* protoDeps = model.getDependents(*prototype->get()) ; deps.add(*protoDeps) ; delete protoDeps ; } // Factorize product in irreducible terms TList* termList = model.factorizeProduct(vars) ; TIterator* termIter = termList->MakeIterator() ; RooAbsPdf* pdf ; RooArgSet* term ; while(term=(RooArgSet*)termIter->Next()) { TIterator* pdfIter = term->createIterator() ; if (term->getSize()==1) { // Simple term pdf = (RooAbsPdf*) pdfIter->Next() ; RooArgSet* pdfDep = pdf->getDependents(&vars) ; if (pdfDep->getSize()>0) { RooAbsGenContext* cx = pdf->genContext(*pdfDep,prototype,verbose) ; _gcList.Add(cx) ; } delete pdfDep ; } else { // Composite term RooArgSet termDeps ; while(pdf=(RooAbsPdf*) pdfIter->Next()) { RooArgSet* pdfDep = pdf->getDependents(&vars) ; termDeps.add(*pdfDep,kFALSE) ; delete pdfDep ; } if (termDeps.getSize()>0) { const char* name = model.makeRGPPName("PRODGEN_",*term,RooArgSet(),RooArgSet()) ; RooProdPdf* multiPdf = new RooProdPdf(name,name,*term) ; multiPdf->useDefaultGen(kTRUE) ; _ownedMultiProds.addOwned(*multiPdf) ; RooAbsGenContext* cx = multiPdf->genContext(termDeps,prototype,verbose) ; _gcList.Add(cx) ; } } delete pdfIter ; } _gcIter = _gcList.MakeIterator() ; } RooProdGenContext::~RooProdGenContext() { // Destructor. Delete all owned subgenerator contexts delete _gcIter ; _gcList.Delete() ; } void RooProdGenContext::initGenerator(const RooArgSet &theEvent) { // Forward initGenerator call to all components RooAbsGenContext* gc ; _gcIter->Reset() ; while(gc=(RooAbsGenContext*)_gcIter->Next()){ gc->initGenerator(theEvent) ; } } void RooProdGenContext::generateEvent(RooArgSet &theEvent, Int_t remaining) { // Generate a single event of the product by generating the components // of the products sequentially // Loop over the component generators TList compData ; RooAbsGenContext* gc ; _gcIter->Reset() ; while(gc=(RooAbsGenContext*)_gcIter->Next()) { // Generate component gc->generateEvent(theEvent,remaining) ; } } void RooProdGenContext::printToStream(ostream &os, PrintOption opt, TString indent) const { RooAbsGenContext::printToStream(os,opt,indent) ; TString indent2(indent) ; indent2.Append(" ") ; RooAbsGenContext* gc ; _gcIter->Reset() ; while(gc=(RooAbsGenContext*)_gcIter->Next()) { gc->printToStream(os,opt,indent2) ; } }
#include "ride/wx.h" #include "ride/filepropertiesdlg.h" #include "ride/fileedit.h" #include <map> #include <vector> class StringIntConverter { private: typedef std::vector<int> Ints; typedef std::map<int, wxString> IntsToStrings; public: StringIntConverter& operator()(int i, const wxString& str) { strings_.Add(str); ints_.push_back(i); intstostrings_.insert(IntsToStrings::value_type(i, str)); return *this; } const wxArrayString& strings() const { return strings_; } int GetInt(int index) const { return ints_[index]; } int GetIndex(int i) const { for (int index = 0; index < ints_.size(); ++index) { if (ints_[index] == i) return index; } return 0; } wxString ToString(int i) const { IntsToStrings::const_iterator ret = intstostrings_.find(i); if (ret == intstostrings_.end()) return "Unknown"; else return ret->second; } private: wxArrayString strings_; Ints ints_; IntsToStrings intstostrings_; }; const StringIntConverter& EOLString() { static StringIntConverter sic = StringIntConverter() (wxSTC_EOL_CR, wxT("CR (Unix)")) (wxSTC_EOL_CRLF, wxT("CRLF (Windows)")) (wxSTC_EOL_LF, wxT("CR (Macintosh)")); return sic; } const StringIntConverter& CodePageString() { static StringIntConverter sic = StringIntConverter() (wxSTC_CP_UTF8, "UTF-8") (wxSTC_CHARSET_ANSI, "Ansi") (wxSTC_CHARSET_DEFAULT, "Default") (wxSTC_CHARSET_BALTIC, "Baltic") (wxSTC_CHARSET_CHINESEBIG5, "Chinesebig5") (wxSTC_CHARSET_EASTEUROPE, "Easteurope") (wxSTC_CHARSET_GB2312, "Gb2312") (wxSTC_CHARSET_GREEK, "Greek") (wxSTC_CHARSET_HANGUL, "Hangul") (wxSTC_CHARSET_MAC, "Mac") (wxSTC_CHARSET_OEM, "Oem") (wxSTC_CHARSET_RUSSIAN, "Russian") (wxSTC_CHARSET_CYRILLIC, "Cyrillic") (wxSTC_CHARSET_SHIFTJIS, "Shiftjis") (wxSTC_CHARSET_SYMBOL, "Symbol") (wxSTC_CHARSET_TURKISH, "Turkish") (wxSTC_CHARSET_JOHAB, "Johab") (wxSTC_CHARSET_HEBREW, "Hebrew") (wxSTC_CHARSET_ARABIC, "Arabic") (wxSTC_CHARSET_VIETNAMESE, "Vietnamese") (wxSTC_CHARSET_THAI, "Thai") (wxSTC_CHARSET_8859_15, "8859_15"); return sic; } FilePropertiesDlg::FilePropertiesDlg(FileEdit* parent, wxStyledTextCtrl* ctrl) : ::ui::FileProperties(parent, wxID_ANY), ctrl_(ctrl) { uiFileName->SetLabel(parent->filename()); uiLanguage->SetLabelText(parent->GetLanguageName()); UpdateGui(); } void FilePropertiesDlg::UpdateGui() { uiEncoding->SetLabelText(CodePageString().ToString(ctrl_->GetCodePage())); uiLineEndings->SetLabelText(EOLString().ToString(ctrl_->GetEOLMode())); } // remove the encoding part? void FilePropertiesDlg::OnChangeEncoding(wxCommandEvent& event) { #ifdef wxUSE_UNICODE wxMessageBox("Unable to change encoding in unicode build", "Unicode only", wxICON_INFORMATION); #else wxSingleChoiceDialog dlg(this, "Select new text encoding", "Text encoding", CodePageString().strings()); if (dlg.ShowModal() != wxID_OK) return; const int selected = dlg.GetSelection(); const int new_encoding = CodePageString().GetInt(selected); ctrl_->SetCodePage(new_encoding); UpdateGui(); #endif } void FilePropertiesDlg::OnChangeLineEnding(wxCommandEvent& event) { wxSingleChoiceDialog dlg(this, "Select new line ending", "Line ending?", EOLString().strings()); dlg.SetSelection(EOLString().GetIndex(ctrl_->GetEOLMode())); if (dlg.ShowModal() != wxID_OK) return; const int selected = dlg.GetSelection(); const int new_ending = EOLString().GetInt(selected); ctrl_->SetEOLMode(new_ending); ctrl_->ConvertEOLs(new_ending); UpdateGui(); } Fixed warning #include "ride/wx.h" #include "ride/filepropertiesdlg.h" #include "ride/fileedit.h" #include <map> #include <vector> class StringIntConverter { private: typedef std::vector<int> Ints; typedef std::map<int, wxString> IntsToStrings; public: StringIntConverter& operator()(int i, const wxString& str) { strings_.Add(str); ints_.push_back(i); intstostrings_.insert(IntsToStrings::value_type(i, str)); return *this; } const wxArrayString& strings() const { return strings_; } int GetInt(int index) const { return ints_[index]; } size_t GetIndex(size_t i) const { for (size_t index = 0; index < ints_.size(); ++index) { if (ints_[index] == i) return index; } return 0; } wxString ToString(int i) const { IntsToStrings::const_iterator ret = intstostrings_.find(i); if (ret == intstostrings_.end()) return "Unknown"; else return ret->second; } private: wxArrayString strings_; Ints ints_; IntsToStrings intstostrings_; }; const StringIntConverter& EOLString() { static StringIntConverter sic = StringIntConverter() (wxSTC_EOL_CR, wxT("CR (Unix)")) (wxSTC_EOL_CRLF, wxT("CRLF (Windows)")) (wxSTC_EOL_LF, wxT("CR (Macintosh)")); return sic; } const StringIntConverter& CodePageString() { static StringIntConverter sic = StringIntConverter() (wxSTC_CP_UTF8, "UTF-8") (wxSTC_CHARSET_ANSI, "Ansi") (wxSTC_CHARSET_DEFAULT, "Default") (wxSTC_CHARSET_BALTIC, "Baltic") (wxSTC_CHARSET_CHINESEBIG5, "Chinesebig5") (wxSTC_CHARSET_EASTEUROPE, "Easteurope") (wxSTC_CHARSET_GB2312, "Gb2312") (wxSTC_CHARSET_GREEK, "Greek") (wxSTC_CHARSET_HANGUL, "Hangul") (wxSTC_CHARSET_MAC, "Mac") (wxSTC_CHARSET_OEM, "Oem") (wxSTC_CHARSET_RUSSIAN, "Russian") (wxSTC_CHARSET_CYRILLIC, "Cyrillic") (wxSTC_CHARSET_SHIFTJIS, "Shiftjis") (wxSTC_CHARSET_SYMBOL, "Symbol") (wxSTC_CHARSET_TURKISH, "Turkish") (wxSTC_CHARSET_JOHAB, "Johab") (wxSTC_CHARSET_HEBREW, "Hebrew") (wxSTC_CHARSET_ARABIC, "Arabic") (wxSTC_CHARSET_VIETNAMESE, "Vietnamese") (wxSTC_CHARSET_THAI, "Thai") (wxSTC_CHARSET_8859_15, "8859_15"); return sic; } FilePropertiesDlg::FilePropertiesDlg(FileEdit* parent, wxStyledTextCtrl* ctrl) : ::ui::FileProperties(parent, wxID_ANY), ctrl_(ctrl) { uiFileName->SetLabel(parent->filename()); uiLanguage->SetLabelText(parent->GetLanguageName()); UpdateGui(); } void FilePropertiesDlg::UpdateGui() { uiEncoding->SetLabelText(CodePageString().ToString(ctrl_->GetCodePage())); uiLineEndings->SetLabelText(EOLString().ToString(ctrl_->GetEOLMode())); } // remove the encoding part? void FilePropertiesDlg::OnChangeEncoding(wxCommandEvent& event) { #ifdef wxUSE_UNICODE wxMessageBox("Unable to change encoding in unicode build", "Unicode only", wxICON_INFORMATION); #else wxSingleChoiceDialog dlg(this, "Select new text encoding", "Text encoding", CodePageString().strings()); if (dlg.ShowModal() != wxID_OK) return; const int selected = dlg.GetSelection(); const int new_encoding = CodePageString().GetInt(selected); ctrl_->SetCodePage(new_encoding); UpdateGui(); #endif } void FilePropertiesDlg::OnChangeLineEnding(wxCommandEvent& event) { wxSingleChoiceDialog dlg(this, "Select new line ending", "Line ending?", EOLString().strings()); dlg.SetSelection(EOLString().GetIndex(ctrl_->GetEOLMode())); if (dlg.ShowModal() != wxID_OK) return; const int selected = dlg.GetSelection(); const int new_ending = EOLString().GetInt(selected); ctrl_->SetEOLMode(new_ending); ctrl_->ConvertEOLs(new_ending); UpdateGui(); }
/** \brief MARC grep the Next Generation. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <cstring> #include <cstdlib> #include "Compiler.h" #include "MARC.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { ::Usage("--query=query --output=field_and_or_subfield_list [--output-format=output_format] marc_file1 [marc_file2 .. marc_fileN]\n" "Queries have the following syntax:\n" "expression → term {OR term}\n" "term → factor {AND factor}\n" "factor → field_or_subfield_reference (== | !=) string_constant_or_regex\n" "factor → NOT factor\n" "factor → '(' expression ')'\n" "\'field_and_or_subfield_list\" is a semicolon-separated list of field or subfield references. The special \"list\" is\n" "the assterisk which implies that an entire record will be output." ); std::exit(EXIT_FAILURE); } enum TokenType { AND, OR, NOT, STRING_CONST, FUNC_CALL, OPEN_PAREN, CLOSE_PAREN, REGEX, EQUALS, NOT_EQUALS, COMMA, ERROR, END_OF_QUERY }; class Tokenizer { struct FunctionDesc { std::string name_; unsigned argument_count_; }; std::string::const_iterator next_ch_; const std::string::const_iterator end_; bool pushed_back_; TokenType last_token_; std::string last_error_message_; std::string last_string_; std::string last_function_name_; const static std::vector<FunctionDesc> function_descriptions_; public: explicit Tokenizer(const std:: string &query): next_ch_(query.cbegin()), end_(query.cend()), pushed_back_(false) { } TokenType getNextToken(); void ungetLastToken(); inline const std::string &getLastErrorMessage() const { return last_error_message_; } inline const std::string &getLastString() const { return last_string_; } inline const std::string &getLastFunctionName() const { return last_function_name_; } static std::string TokenTypeToString(const TokenType token); private: TokenType parseStringConstantOrRegex(); bool isKnownFunctionName(const std::string &name_candidate) const; }; const std::vector<Tokenizer::FunctionDesc> Tokenizer::function_descriptions_{ { "HasField", 1 }, { "HasSubfield", 2} }; TokenType Tokenizer::getNextToken() { if (pushed_back_) { pushed_back_ = false; return last_token_; } // Skip over spaces: while (next_ch_ != end_ and *next_ch_ == ' ') ++next_ch_; if (next_ch_ == end_) return last_token_ = END_OF_QUERY; if (*next_ch_ == '"' or *next_ch_ == '/') return last_token_ = parseStringConstantOrRegex(); if (*next_ch_ == ',') { ++next_ch_; return last_token_ = COMMA; } if (*next_ch_ == '(') { ++next_ch_; return last_token_ = OPEN_PAREN; } if (*next_ch_ == ')') { ++next_ch_; return last_token_ = CLOSE_PAREN; } if (*next_ch_ == '=') { ++next_ch_; if (next_ch_ == end_ or *next_ch_ != '=') { last_error_message_ = "unexpected single equal sign found!"; return ERROR; } return last_token_ = EQUALS; } if (*next_ch_ == '!') { ++next_ch_; if (next_ch_ == end_ or *next_ch_ != '=') { last_error_message_ = "unexpected single exclamation point found!"; return ERROR; } return last_token_ = NOT_EQUALS; } if (unlikely(not StringUtil::IsAsciiLetter(*next_ch_))) { last_error_message_ = "expected ASCII letter!"; return ERROR; } std::string id; while (next_ch_ != end_ and StringUtil::IsAsciiLetter(*next_ch_)) id += *next_ch_; if (id == "AND") return last_token_ = AND; if (id == "OR") return last_token_ = OR; if (id == "NOT") return last_token_ = NOT; if (isKnownFunctionName(id)) { last_function_name_ = id; return last_token_ = FUNC_CALL; } last_error_message_ = "unknown function name \"" + id + "\"!"; return ERROR; } void Tokenizer::ungetLastToken() { if (unlikely(pushed_back_)) LOG_ERROR("can't push back two tokens in a row!"); pushed_back_ = true; } TokenType Tokenizer::parseStringConstantOrRegex() { const char terminator(*next_ch_++); last_string_.clear(); bool escaped(false); for (/* Intentionally empty! */; next_ch_ != end_; ++next_ch_) { if (escaped) { escaped = false; last_string_ += *next_ch_; } else if (*next_ch_ == terminator) { ++next_ch_; return (terminator == '"') ? STRING_CONST : REGEX; } else if (*next_ch_ == '\\') escaped = true; else last_string_ += *next_ch_; } last_error_message_ = "unterminated string constant or regex!"; return ERROR; } bool Tokenizer::isKnownFunctionName(const std::string &name_candidate) const { for (const auto &function_description : function_descriptions_) { if (function_description.name_ == name_candidate) return true; } return false; } std::string Tokenizer::TokenTypeToString(const TokenType token) { switch (token) { case AND: return "AND"; case OR: return "OR"; case NOT: return "NOT"; case STRING_CONST: return "string constant"; case FUNC_CALL: return "function call"; case OPEN_PAREN: return "("; case CLOSE_PAREN: return ")"; case REGEX: return "regular expression"; case EQUALS: return "=="; case NOT_EQUALS: return "!="; case COMMA: return ","; case ERROR: return "unexpected input"; case END_OF_QUERY: return "end-of-query"; } } class Query { enum NodeType { AND_NODE, OR_NODE, STRING_COMPARISON_NODE, REGEX_COMPARISON_NODE }; class Node { protected: bool invert_; protected: Node(): invert_(false) {} public: virtual ~Node() = 0; virtual NodeType getNodeType() const = 0; virtual bool eval(const MARC::Record &record) const = 0; inline void toggleInvert() { invert_ = not invert_; } }; class AndNode final : public Node { std::vector<Node *> children_; public: explicit AndNode(std::vector<Node *> &children) { children.swap(children_); } ~AndNode() { for (const auto child_node : children_) delete child_node; } virtual NodeType getNodeType() const override { return AND_NODE; } virtual bool eval(const MARC::Record &record) const override; }; class OrNode final : public Node { std::vector<Node *> children_; public: explicit OrNode(std::vector<Node *> &children) { children.swap(children_); } ~OrNode() { for (const auto child_node : children_) delete child_node; } virtual NodeType getNodeType() const override { return OR_NODE; } virtual bool eval(const MARC::Record &record) const override; }; class StringComparisonNode final : public Node { MARC::Tag field_tag_; char subfield_code_; std::string string_const_; public: StringComparisonNode(const std::string &field_or_subfield_reference, const std::string &string_const, const bool invert) : field_tag_(field_or_subfield_reference.substr(0, MARC::Record::TAG_LENGTH)), subfield_code_(field_or_subfield_reference.length() > MARC::Record::TAG_LENGTH ? field_or_subfield_reference[MARC::Record::TAG_LENGTH] : '\0'), string_const_(string_const) { invert_ = invert; } ~StringComparisonNode() = default; virtual NodeType getNodeType() const override { return STRING_COMPARISON_NODE; } virtual bool eval(const MARC::Record &record) const override; }; class RegexComparisonNode final : public Node { MARC::Tag field_tag_; char subfield_code_; RegexMatcher *regex_; bool invert_; public: RegexComparisonNode(const std::string &field_or_subfield_reference, RegexMatcher * const regex, const bool invert) : field_tag_(field_or_subfield_reference.substr(0, MARC::Record::TAG_LENGTH)), subfield_code_(field_or_subfield_reference.length() > MARC::Record::TAG_LENGTH ? field_or_subfield_reference[MARC::Record::TAG_LENGTH] : '\0'), regex_(regex), invert_(invert) { } ~RegexComparisonNode() { delete regex_; } virtual NodeType getNodeType() const override { return STRING_COMPARISON_NODE; } virtual bool eval(const MARC::Record &record) const override; }; Tokenizer tokenizer_; Node *root_; public: explicit Query(const std:: string &query); ~Query() { delete root_; } bool matched(const MARC::Record &record) const; private: Node *parseExpression(); Node *parseTerm(); Node *parseFactor(); static void DeletePointerVector(std::vector<Node *> &nodes); }; Query::Node::~Node() { /* Intentionally empty! */ } bool Query::AndNode::eval(const MARC::Record &record) const { for (const auto child_node : children_) { if (not child_node->eval(record)) return invert_ ? true : false; } return true; } bool Query::OrNode::eval(const MARC::Record &record) const { for (const auto child_node : children_) { if (child_node->eval(record)) return invert_ ? false : true; } return false; } bool Query::StringComparisonNode::eval(const MARC::Record &record) const { for (const auto &field : record.getTagRange(field_tag_)) { if (subfield_code_ == '\0') { if (field .getContents() == string_const_) { if (not invert_) return true; } else if (invert_) return true; } else { const MARC::Subfields subfields(field.getSubfields()); for (const auto &value_and_code : subfields) { if (value_and_code.code_ == subfield_code_) { if (value_and_code.value_ == string_const_) { if (not invert_) return true; } else if (invert_) return true; } } } } return false; } bool Query::RegexComparisonNode::eval(const MARC::Record &record) const { for (const auto &field : record.getTagRange(field_tag_)) { if (subfield_code_ == '\0') { if (regex_->matched(field .getContents())) { if (not invert_) return true; } else if (invert_) return true; } else { const MARC::Subfields subfields(field.getSubfields()); for (const auto &value_and_code : subfields) { if (value_and_code.code_ == subfield_code_) { if (regex_->matched(value_and_code.value_)) { if (not invert_) return true; } else if (invert_) return true; } } } } return false; } Query::Query(const std:: string &query) : tokenizer_(query), root_(parseExpression()) { } bool Query::matched(const MARC::Record &record) const { return root_->eval(record); } Query::Node *Query::parseExpression() { std::vector<Node *> children; children.emplace_back(parseTerm()); TokenType token(tokenizer_.getNextToken()); while (token == OR) { children.emplace_back(parseTerm()); token = tokenizer_.getNextToken(); } if (token == ERROR) { DeletePointerVector(children); throw std::runtime_error("error in OR expression: " + tokenizer_.getLastErrorMessage()); } tokenizer_.ungetLastToken(); return new OrNode(children); } Query::Node *Query::parseTerm() { std::vector<Node *> children; children.emplace_back(parseFactor()); TokenType token(tokenizer_.getNextToken()); while (token == AND) { children.emplace_back(parseFactor()); token = tokenizer_.getNextToken(); } if (token == ERROR) { DeletePointerVector(children); throw std::runtime_error("error in AND expression: " + tokenizer_.getLastErrorMessage()); } tokenizer_.ungetLastToken(); return new AndNode(children); } /* factor → field_or_subfield_reference (== | !=) string_constant_or_regex factor → NOT factor factor → '(' expression ') */ Query::Node *Query::parseFactor() { TokenType token(tokenizer_.getNextToken()); if (token == STRING_CONST) { const std::string field_or_subfield_reference(tokenizer_.getLastString()); if (field_or_subfield_reference.length() != MARC::Record::TAG_LENGTH and tokenizer_.getLastString().length() != MARC::Record::TAG_LENGTH + 1) throw std::runtime_error("invalid field or subfield reference \"" + field_or_subfield_reference + "\"!"); token = tokenizer_.getNextToken(); if (token != EQUALS and token != NOT_EQUALS) throw std::runtime_error("expected == or != after field or subfield reference, found " + Tokenizer::TokenTypeToString(token) + " instead!"); const TokenType equality_operator(token); token = tokenizer_.getNextToken(); if (token != STRING_CONST and token != REGEX) throw std::runtime_error("expected a string constant or a regex after " + Tokenizer::TokenTypeToString(equality_operator) + ", found " + Tokenizer::TokenTypeToString(token) + " instead!"); RegexMatcher *regex_matcher; if (token == REGEX) regex_matcher = RegexMatcher::RegexMatcherFactoryOrDie(tokenizer_.getLastString()); if (token == REGEX) return new RegexComparisonNode(field_or_subfield_reference, regex_matcher, equality_operator == EQUALS); else return new StringComparisonNode(field_or_subfield_reference, tokenizer_.getLastString(), equality_operator == EQUALS); } if (token == NOT) { Node * const factor_node(parseFactor()); factor_node->toggleInvert(); return factor_node; } if (token != OPEN_PAREN) throw std::runtime_error("opening parenthesis, NOT or string constant expected found " + Tokenizer::TokenTypeToString(token) + "instead!"); Node * const expression_node(parseExpression()); token = tokenizer_.getNextToken(); if (token != CLOSE_PAREN) { delete expression_node; throw std::runtime_error("closing parenthesis after expression expected, found " + Tokenizer::TokenTypeToString(token) + "instead!"); } return expression_node; } void Query::DeletePointerVector(std::vector<Query::Node *> &nodes) { for (auto node_ptr : nodes) delete node_ptr; } inline void ExtractRefsToSingleField(std::vector<std::string>::const_iterator &range_start, std::vector<std::string>::const_iterator &range_end, const std::vector<std::string>::const_iterator &list_end) { range_end = range_start; while (range_end + 1 != list_end and std::memcmp(range_start->c_str(), (range_end + 1)->c_str(), MARC::Record::TAG_LENGTH) == 0) ++range_end; ++range_end; // half-open iterator interval, i.e. we want to point 1 past the end of the range` } void GenerateOutput(const MARC::Record::Field &/*field*/, const std::vector<std::string> &/*field_and_subfield_output_list*/, const std::vector<std::string>::const_iterator &/*range_start*/, const std::vector<std::string>::const_iterator &/*range_end*/) { } void ProcessRecords(const Query &query, MARC::Reader * const marc_reader, const std::vector<std::string> &field_and_subfield_output_list) { unsigned record_count(0), matched_count(0); while (const MARC::Record record = marc_reader->read()) { ++record_count; if (not query.matched(record)) continue; ++matched_count; auto range_start(field_and_subfield_output_list.cbegin()); auto range_end(range_start); ExtractRefsToSingleField(range_start, range_end, field_and_subfield_output_list.cend()); auto field(record.begin()); while (field != record.end() and range_start != field_and_subfield_output_list.cend()) { if (field->getTag() == range_start->substr(0, MARC::Record::TAG_LENGTH)) { GenerateOutput(*field, field_and_subfield_output_list, range_start, range_end); ++field; } else if (field->getTag() > range_start->substr(0, MARC::Record::TAG_LENGTH)) { range_start = range_end; while (range_start != field_and_subfield_output_list.cend() and field->getTag() > range_start->substr(0, MARC::Record::TAG_LENGTH)) ++range_start; if (range_start != field_and_subfield_output_list.cend()) ExtractRefsToSingleField(range_start, range_end, field_and_subfield_output_list.cend()); } else ++field; } } std::cerr << "Matched " << matched_count << " of " << record_count << " records.\n"; } bool ParseOutputList(const std::string &output_list_candidate, std::vector<std::string> * const field_and_subfield_output_list) { if (StringUtil::SplitThenTrimWhite(output_list_candidate, ';', field_and_subfield_output_list, /* suppress_empty_components = */true) == 0) return false; if (field_and_subfield_output_list->size() == 1 and field_and_subfield_output_list->front() == "*") return true; for (const auto &field_or_subfield_reference_candidate : *field_and_subfield_output_list) { if (field_or_subfield_reference_candidate.length() != MARC::Record::TAG_LENGTH and field_or_subfield_reference_candidate.length() != MARC::Record::TAG_LENGTH + 1) return false; } std::sort(field_and_subfield_output_list->begin(), field_and_subfield_output_list->end()); return true; } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 4) Usage(); const std::string QUERY_PREFIX("--query="); if (not StringUtil::StartsWith(argv[1], QUERY_PREFIX)) LOG_ERROR("missing " + QUERY_PREFIX + "...!"); const std::string query_str(argv[1] + QUERY_PREFIX.length()); Query query(query_str); const std::string OUTPUT_PREFIX("--output="); if (not StringUtil::StartsWith(argv[2], OUTPUT_PREFIX)) LOG_ERROR("missing " + OUTPUT_PREFIX + "...!"); std::vector<std::string> field_and_subfield_output_list; if (not ParseOutputList(argv[2] + OUTPUT_PREFIX.length(), &field_and_subfield_output_list)) LOG_ERROR("bad output specification: \"" + std::string(argv[2] + OUTPUT_PREFIX.length())); for (int arg_no(1); arg_no < argc; ++arg_no) { auto marc_reader(MARC::Reader::Factory(argv[1])); ProcessRecords(query, marc_reader.get(), field_and_subfield_output_list); } return EXIT_SUCCESS; } Fixed more nonsense. /** \brief MARC grep the Next Generation. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <cstring> #include <cstdlib> #include "Compiler.h" #include "MARC.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { ::Usage("--query=query --output=field_and_or_subfield_list [--output-format=output_format] marc_file1 [marc_file2 .. marc_fileN]\n" "Queries have the following syntax:\n" "expression → term {OR term}\n" "term → factor {AND factor}\n" "factor → field_or_subfield_reference (== | !=) string_constant_or_regex\n" "factor → NOT factor\n" "factor → '(' expression ')'\n" "\'field_and_or_subfield_list\" is a semicolon-separated list of field or subfield references. The special \"list\" is\n" "the assterisk which implies that an entire record will be output." ); std::exit(EXIT_FAILURE); } enum TokenType { AND, OR, NOT, STRING_CONST, FUNC_CALL, OPEN_PAREN, CLOSE_PAREN, REGEX, EQUALS, NOT_EQUALS, COMMA, ERROR, END_OF_QUERY }; class Tokenizer { struct FunctionDesc { std::string name_; unsigned argument_count_; }; std::string::const_iterator next_ch_; const std::string::const_iterator end_; bool pushed_back_; TokenType last_token_; std::string last_error_message_; std::string last_string_; std::string last_function_name_; const static std::vector<FunctionDesc> function_descriptions_; public: explicit Tokenizer(const std:: string &query): next_ch_(query.cbegin()), end_(query.cend()), pushed_back_(false) { } TokenType getNextToken(); void ungetLastToken(); inline const std::string &getLastErrorMessage() const { return last_error_message_; } inline const std::string &getLastString() const { return last_string_; } inline const std::string &getLastFunctionName() const { return last_function_name_; } static std::string TokenTypeToString(const TokenType token); private: TokenType parseStringConstantOrRegex(); bool isKnownFunctionName(const std::string &name_candidate) const; }; const std::vector<Tokenizer::FunctionDesc> Tokenizer::function_descriptions_{ { "HasField", 1 }, { "HasSubfield", 2} }; TokenType Tokenizer::getNextToken() { if (pushed_back_) { pushed_back_ = false; return last_token_; } // Skip over spaces: while (next_ch_ != end_ and *next_ch_ == ' ') ++next_ch_; if (next_ch_ == end_) return last_token_ = END_OF_QUERY; if (*next_ch_ == '"' or *next_ch_ == '/') return last_token_ = parseStringConstantOrRegex(); if (*next_ch_ == ',') { ++next_ch_; return last_token_ = COMMA; } if (*next_ch_ == '(') { ++next_ch_; return last_token_ = OPEN_PAREN; } if (*next_ch_ == ')') { ++next_ch_; return last_token_ = CLOSE_PAREN; } if (*next_ch_ == '=') { ++next_ch_; if (next_ch_ == end_ or *next_ch_ != '=') { last_error_message_ = "unexpected single equal sign found!"; return ERROR; } return last_token_ = EQUALS; } if (*next_ch_ == '!') { ++next_ch_; if (next_ch_ == end_ or *next_ch_ != '=') { last_error_message_ = "unexpected single exclamation point found!"; return ERROR; } return last_token_ = NOT_EQUALS; } if (unlikely(not StringUtil::IsAsciiLetter(*next_ch_))) { last_error_message_ = "expected ASCII letter!"; return ERROR; } std::string id; while (next_ch_ != end_ and StringUtil::IsAsciiLetter(*next_ch_)) id += *next_ch_; if (id == "AND") return last_token_ = AND; if (id == "OR") return last_token_ = OR; if (id == "NOT") return last_token_ = NOT; if (isKnownFunctionName(id)) { last_function_name_ = id; return last_token_ = FUNC_CALL; } last_error_message_ = "unknown function name \"" + id + "\"!"; return ERROR; } void Tokenizer::ungetLastToken() { if (unlikely(pushed_back_)) LOG_ERROR("can't push back two tokens in a row!"); pushed_back_ = true; } TokenType Tokenizer::parseStringConstantOrRegex() { const char terminator(*next_ch_++); last_string_.clear(); bool escaped(false); for (/* Intentionally empty! */; next_ch_ != end_; ++next_ch_) { if (escaped) { escaped = false; last_string_ += *next_ch_; } else if (*next_ch_ == terminator) { ++next_ch_; return (terminator == '"') ? STRING_CONST : REGEX; } else if (*next_ch_ == '\\') escaped = true; else last_string_ += *next_ch_; } last_error_message_ = "unterminated string constant or regex!"; return ERROR; } bool Tokenizer::isKnownFunctionName(const std::string &name_candidate) const { for (const auto &function_description : function_descriptions_) { if (function_description.name_ == name_candidate) return true; } return false; } std::string Tokenizer::TokenTypeToString(const TokenType token) { switch (token) { case AND: return "AND"; case OR: return "OR"; case NOT: return "NOT"; case STRING_CONST: return "string constant"; case FUNC_CALL: return "function call"; case OPEN_PAREN: return "("; case CLOSE_PAREN: return ")"; case REGEX: return "regular expression"; case EQUALS: return "=="; case NOT_EQUALS: return "!="; case COMMA: return ","; case ERROR: return "unexpected input"; case END_OF_QUERY: return "end-of-query"; } } class Query { enum NodeType { AND_NODE, OR_NODE, STRING_COMPARISON_NODE, REGEX_COMPARISON_NODE }; class Node { protected: bool invert_; protected: Node(): invert_(false) {} public: virtual ~Node() = 0; virtual NodeType getNodeType() const = 0; virtual bool eval(const MARC::Record &record) const = 0; inline void toggleInvert() { invert_ = not invert_; } }; class AndNode final : public Node { std::vector<Node *> children_; public: explicit AndNode(std::vector<Node *> &children) { children.swap(children_); } ~AndNode() { for (const auto child_node : children_) delete child_node; } virtual NodeType getNodeType() const override { return AND_NODE; } virtual bool eval(const MARC::Record &record) const override; }; class OrNode final : public Node { std::vector<Node *> children_; public: explicit OrNode(std::vector<Node *> &children) { children.swap(children_); } ~OrNode() { for (const auto child_node : children_) delete child_node; } virtual NodeType getNodeType() const override { return OR_NODE; } virtual bool eval(const MARC::Record &record) const override; }; class StringComparisonNode final : public Node { MARC::Tag field_tag_; char subfield_code_; std::string string_const_; public: StringComparisonNode(const std::string &field_or_subfield_reference, const std::string &string_const, const bool invert) : field_tag_(field_or_subfield_reference.substr(0, MARC::Record::TAG_LENGTH)), subfield_code_(field_or_subfield_reference.length() > MARC::Record::TAG_LENGTH ? field_or_subfield_reference[MARC::Record::TAG_LENGTH] : '\0'), string_const_(string_const) { invert_ = invert; } ~StringComparisonNode() = default; virtual NodeType getNodeType() const override { return STRING_COMPARISON_NODE; } virtual bool eval(const MARC::Record &record) const override; }; class RegexComparisonNode final : public Node { MARC::Tag field_tag_; char subfield_code_; RegexMatcher *regex_; bool invert_; public: RegexComparisonNode(const std::string &field_or_subfield_reference, RegexMatcher * const regex, const bool invert) : field_tag_(field_or_subfield_reference.substr(0, MARC::Record::TAG_LENGTH)), subfield_code_(field_or_subfield_reference.length() > MARC::Record::TAG_LENGTH ? field_or_subfield_reference[MARC::Record::TAG_LENGTH] : '\0'), regex_(regex), invert_(invert) { } ~RegexComparisonNode() { delete regex_; } virtual NodeType getNodeType() const override { return STRING_COMPARISON_NODE; } virtual bool eval(const MARC::Record &record) const override; }; Tokenizer tokenizer_; Node *root_; public: explicit Query(const std:: string &query); ~Query() { delete root_; } bool matched(const MARC::Record &record) const; private: Node *parseExpression(); Node *parseTerm(); Node *parseFactor(); static void DeletePointerVector(std::vector<Node *> &nodes); }; Query::Node::~Node() { /* Intentionally empty! */ } bool Query::AndNode::eval(const MARC::Record &record) const { for (const auto child_node : children_) { if (not child_node->eval(record)) return invert_ ? true : false; } return true; } bool Query::OrNode::eval(const MARC::Record &record) const { for (const auto child_node : children_) { if (child_node->eval(record)) return invert_ ? false : true; } return false; } bool Query::StringComparisonNode::eval(const MARC::Record &record) const { for (const auto &field : record.getTagRange(field_tag_)) { if (subfield_code_ == '\0') { if (field .getContents() == string_const_) { if (not invert_) return true; } else if (invert_) return true; } else { const MARC::Subfields subfields(field.getSubfields()); for (const auto &value_and_code : subfields) { if (value_and_code.code_ == subfield_code_) { if (value_and_code.value_ == string_const_) { if (not invert_) return true; } else if (invert_) return true; } } } } return false; } bool Query::RegexComparisonNode::eval(const MARC::Record &record) const { for (const auto &field : record.getTagRange(field_tag_)) { if (subfield_code_ == '\0') { if (regex_->matched(field .getContents())) { if (not invert_) return true; } else if (invert_) return true; } else { const MARC::Subfields subfields(field.getSubfields()); for (const auto &value_and_code : subfields) { if (value_and_code.code_ == subfield_code_) { if (regex_->matched(value_and_code.value_)) { if (not invert_) return true; } else if (invert_) return true; } } } } return false; } Query::Query(const std:: string &query) : tokenizer_(query), root_(parseExpression()) { } bool Query::matched(const MARC::Record &record) const { return root_->eval(record); } Query::Node *Query::parseExpression() { std::vector<Node *> children; children.emplace_back(parseTerm()); TokenType token(tokenizer_.getNextToken()); while (token == OR) { children.emplace_back(parseTerm()); token = tokenizer_.getNextToken(); } if (token == ERROR) { DeletePointerVector(children); throw std::runtime_error("error in OR expression: " + tokenizer_.getLastErrorMessage()); } tokenizer_.ungetLastToken(); return new OrNode(children); } Query::Node *Query::parseTerm() { std::vector<Node *> children; children.emplace_back(parseFactor()); TokenType token(tokenizer_.getNextToken()); while (token == AND) { children.emplace_back(parseFactor()); token = tokenizer_.getNextToken(); } if (token == ERROR) { DeletePointerVector(children); throw std::runtime_error("error in AND expression: " + tokenizer_.getLastErrorMessage()); } tokenizer_.ungetLastToken(); return new AndNode(children); } /* factor → field_or_subfield_reference (== | !=) string_constant_or_regex factor → NOT factor factor → '(' expression ') */ Query::Node *Query::parseFactor() { TokenType token(tokenizer_.getNextToken()); if (token == STRING_CONST) { const std::string field_or_subfield_reference(tokenizer_.getLastString()); if (field_or_subfield_reference.length() != MARC::Record::TAG_LENGTH and tokenizer_.getLastString().length() != MARC::Record::TAG_LENGTH + 1) throw std::runtime_error("invalid field or subfield reference \"" + field_or_subfield_reference + "\"!"); token = tokenizer_.getNextToken(); if (token != EQUALS and token != NOT_EQUALS) throw std::runtime_error("expected == or != after field or subfield reference, found " + Tokenizer::TokenTypeToString(token) + " instead!"); const TokenType equality_operator(token); token = tokenizer_.getNextToken(); if (token != STRING_CONST and token != REGEX) throw std::runtime_error("expected a string constant or a regex after " + Tokenizer::TokenTypeToString(equality_operator) + ", found " + Tokenizer::TokenTypeToString(token) + " instead!"); RegexMatcher *regex_matcher; if (token == REGEX) regex_matcher = RegexMatcher::RegexMatcherFactoryOrDie(tokenizer_.getLastString()); if (token == REGEX) return new RegexComparisonNode(field_or_subfield_reference, regex_matcher, equality_operator == EQUALS); else return new StringComparisonNode(field_or_subfield_reference, tokenizer_.getLastString(), equality_operator == EQUALS); } if (token == NOT) { Node * const factor_node(parseFactor()); factor_node->toggleInvert(); return factor_node; } if (token != OPEN_PAREN) throw std::runtime_error("opening parenthesis, NOT or string constant expected found " + Tokenizer::TokenTypeToString(token) + "instead!"); Node * const expression_node(parseExpression()); token = tokenizer_.getNextToken(); if (token != CLOSE_PAREN) { delete expression_node; throw std::runtime_error("closing parenthesis after expression expected, found " + Tokenizer::TokenTypeToString(token) + "instead!"); } return expression_node; } void Query::DeletePointerVector(std::vector<Query::Node *> &nodes) { for (auto node_ptr : nodes) delete node_ptr; } inline void ExtractRefsToSingleField(std::vector<std::string>::const_iterator &range_start, std::vector<std::string>::const_iterator &range_end, const std::vector<std::string>::const_iterator &list_end) { range_end = range_start; while (range_end + 1 != list_end and std::memcmp(range_start->c_str(), (range_end + 1)->c_str(), MARC::Record::TAG_LENGTH) == 0) ++range_end; ++range_end; // half-open iterator interval, i.e. we want to point 1 past the end of the range` } void GenerateOutput(const MARC::Record::Field &/*field*/, const std::vector<std::string> &/*field_and_subfield_output_list*/, const std::vector<std::string>::const_iterator &/*range_start*/, const std::vector<std::string>::const_iterator &/*range_end*/) { } void ProcessRecords(const Query &query, MARC::Reader * const marc_reader, const std::vector<std::string> &field_and_subfield_output_list) { unsigned record_count(0), matched_count(0); while (const MARC::Record record = marc_reader->read()) { ++record_count; if (not query.matched(record)) continue; ++matched_count; auto range_start(field_and_subfield_output_list.cbegin()); auto range_end(range_start); ExtractRefsToSingleField(range_start, range_end, field_and_subfield_output_list.cend()); auto field(record.begin()); while (field != record.end() and range_start != field_and_subfield_output_list.cend()) { if (field->getTag() == range_start->substr(0, MARC::Record::TAG_LENGTH)) { GenerateOutput(*field, field_and_subfield_output_list, range_start, range_end); ++field; } else if (field->getTag() > range_start->substr(0, MARC::Record::TAG_LENGTH)) { range_start = range_end; while (range_start != field_and_subfield_output_list.cend() and field->getTag() > range_start->substr(0, MARC::Record::TAG_LENGTH)) ++range_start; if (range_start != field_and_subfield_output_list.cend()) ExtractRefsToSingleField(range_start, range_end, field_and_subfield_output_list.cend()); } else ++field; } } std::cerr << "Matched " << matched_count << " of " << record_count << " records.\n"; } bool ParseOutputList(const std::string &output_list_candidate, std::vector<std::string> * const field_and_subfield_output_list) { if (StringUtil::SplitThenTrimWhite(output_list_candidate, ';', field_and_subfield_output_list, /* suppress_empty_components = */true) == 0) return false; if (field_and_subfield_output_list->size() == 1 and field_and_subfield_output_list->front() == "*") return true; for (const auto &field_or_subfield_reference_candidate : *field_and_subfield_output_list) { if (field_or_subfield_reference_candidate.length() != MARC::Record::TAG_LENGTH and field_or_subfield_reference_candidate.length() != MARC::Record::TAG_LENGTH + 1) return false; } std::sort(field_and_subfield_output_list->begin(), field_and_subfield_output_list->end()); return true; } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 4) Usage(); const std::string QUERY_PREFIX("--query="); if (not StringUtil::StartsWith(argv[1], QUERY_PREFIX)) LOG_ERROR("missing " + QUERY_PREFIX + "...!"); const std::string query_str(argv[1] + QUERY_PREFIX.length()); Query query(query_str); const std::string OUTPUT_PREFIX("--output="); if (not StringUtil::StartsWith(argv[2], OUTPUT_PREFIX)) LOG_ERROR("missing " + OUTPUT_PREFIX + "...!"); std::vector<std::string> field_and_subfield_output_list; if (not ParseOutputList(argv[2] + OUTPUT_PREFIX.length(), &field_and_subfield_output_list)) LOG_ERROR("bad output specification: \"" + std::string(argv[2] + OUTPUT_PREFIX.length())); for (int arg_no(3); arg_no < argc; ++arg_no) { auto marc_reader(MARC::Reader::Factory(argv[arg_no])); ProcessRecords(query, marc_reader.get(), field_and_subfield_output_list); } return EXIT_SUCCESS; }
#include <maya/MFnMesh.h> #include <maya/MFnMeshData.h> #include <maya/MArrayDataBuilder.h> #include <maya/MGlobal.h> #include <maya/MEulerRotation.h> #include <maya/MQuaternion.h> #include <maya/MMatrix.h> #include <maya/MTime.h> #include <maya/MFnArrayAttrsData.h> #include <maya/MFnDoubleArrayData.h> #include <maya/MFnNurbsCurve.h> #include <maya/MFnNurbsCurveData.h> #include <maya/MPointArray.h> #if MAYA_API_VERSION >= 201400 #include <maya/MFnFloatArrayData.h> #endif #include <maya/MFnVectorArrayData.h> #include <vector> #include <limits> #include "Asset.h" #include "AssetNode.h" #include "OutputGeometryPart.h" #include "util.h" void clearMesh( MDataHandle &hasMeshHandle, MDataHandle &meshHandle ) { hasMeshHandle.setBool(false); meshHandle.setMObject(MObject::kNullObj); } static void clearCurvesBuilder( MArrayDataBuilder &curvesBuilder, int count ) { for(int i = (int) curvesBuilder.elementCount(); i-- > count;) { curvesBuilder.removeElement(i); } } static void clearCurves( MDataHandle &curvesHandle, MDataHandle &curvesIsBezier ) { MArrayDataHandle curvesArrayHandle(curvesHandle); MArrayDataBuilder curvesBuilder = curvesArrayHandle.builder(); clearCurvesBuilder(curvesBuilder, 0); curvesArrayHandle.set(curvesBuilder); curvesIsBezier.setBool(false); } OutputGeometryPart::OutputGeometryPart( int assetId, int objectId, int geoId, int partId ) : myAssetId(assetId), myObjectId(objectId), myGeoId(geoId), myPartId(partId), myNeverBuilt(true) { update(); } OutputGeometryPart::~OutputGeometryPart() {} #if MAYA_API_VERSION >= 201400 void OutputGeometryPart::computeVolumeTransform( const MTime &time, MDataHandle& volumeTransformHandle ) { HAPI_Transform transform = myVolumeInfo.transform; MDataHandle translateHandle = volumeTransformHandle.child(AssetNode::outputPartVolumeTranslate); MDataHandle rotateHandle = volumeTransformHandle.child(AssetNode::outputPartVolumeRotate); MDataHandle scaleHandle = volumeTransformHandle.child(AssetNode::outputPartVolumeScale); MEulerRotation r = MQuaternion(transform.rotationQuaternion[0], transform.rotationQuaternion[1], transform.rotationQuaternion[2], transform.rotationQuaternion[3]).asEulerRotation(); const double rot[3] = {r[0], r[1], r[2]}; const double scale[3] = {transform.scale[0], transform.scale[1], transform.scale[2]}; MTransformationMatrix matrix; matrix.addScale(scale, MSpace::kTransform); matrix.addRotation(rot, MTransformationMatrix::kXYZ, MSpace::kTransform); matrix.addTranslation(MVector(transform.position[0], transform.position[1], transform.position[2]), MSpace::kTransform); double xoffset = myVolumeInfo.xLength/2.0 + myVolumeInfo.minX; double yoffset = myVolumeInfo.yLength/2.0 + myVolumeInfo.minY; double zoffset = myVolumeInfo.zLength/2.0 + myVolumeInfo.minZ; const double scale2[3] = {2, 2, 2}; matrix.addScale(scale2, MSpace::kPreTransform); matrix.addTranslation(MVector(-0.5, -0.5, -0.5), MSpace::kPreTransform); matrix.addTranslation(MVector(xoffset, yoffset, zoffset), MSpace::kPreTransform); const double scale3[3] = { static_cast<double>(myVolumeInfo.xLength), static_cast<double>(myVolumeInfo.yLength), static_cast<double>(myVolumeInfo.zLength) }; matrix.addScale(scale3, MSpace::kPreTransform); double final_scale[3]; double final_rotate[3]; MTransformationMatrix::RotationOrder order = MTransformationMatrix::kXYZ; matrix.getScale(final_scale, MSpace::kTransform); matrix.getRotation(final_rotate, order); translateHandle.set(matrix.getTranslation(MSpace::kTransform)); rotateHandle.set3Double(final_rotate[0], final_rotate[1], final_rotate[2]); scaleHandle.set3Double(final_scale[0], final_scale[1], final_scale[2]); translateHandle.setClean(); rotateHandle.setClean(); scaleHandle.setClean(); volumeTransformHandle.setClean(); } #endif void OutputGeometryPart::update() { HAPI_Result hstat = HAPI_RESULT_SUCCESS; try { hstat = HAPI_GetPartInfo(myAssetId, myObjectId, myGeoId, myPartId, &myPartInfo); Util::checkHAPIStatus(hstat); if(myPartInfo.hasVolume) { hstat = HAPI_GetVolumeInfo(myAssetId, myObjectId, myGeoId, myPartId, &myVolumeInfo); Util::checkHAPIStatus(hstat); } if(myPartInfo.isCurve) { hstat = HAPI_GetCurveInfo(myAssetId, myObjectId, myGeoId, myPartId, &myCurveInfo); Util::checkHAPIStatus(hstat); } else { HAPI_CurveInfo_Init(&myCurveInfo); } } catch (HAPIError& e) { cerr << e.what() << endl; HAPI_PartInfo_Init(&myPartInfo); } } static HAPI_Result getAttributeDataWrapper( int asset_id, int object_id, int geo_id, int part_id, const char* name, HAPI_AttributeInfo* attr_info, float* data, int start, int length ) { return HAPI_GetAttributeFloatData( asset_id, object_id, geo_id, part_id, name, attr_info, data, start, length ); } static HAPI_Result getAttributeDataWrapper( int asset_id, int object_id, int geo_id, int part_id, const char* name, HAPI_AttributeInfo* attr_info, int* data, int start, int length ) { return HAPI_GetAttributeIntData( asset_id, object_id, geo_id, part_id, name, attr_info, data, start, length ); } template<typename T> bool OutputGeometryPart::getAttributeData( std::vector<T> &array, const char* name, HAPI_AttributeOwner owner ) { HAPI_AttributeInfo attr_info; attr_info.exists = false; HAPI_GetAttributeInfo( myAssetId, myObjectId, myGeoId, myPartId, name, owner, &attr_info ); if(!attr_info.exists) { array.clear(); return false; } array.resize(attr_info.count * attr_info.tupleSize); getAttributeDataWrapper( myAssetId, myObjectId, myGeoId, myPartId, name, &attr_info, &array.front(), 0, attr_info.count ); return true; } MStatus OutputGeometryPart::compute( const MTime &time, MDataHandle& handle, bool hasGeoChanged, bool hasMaterialChanged, bool &needToSyncOutputs ) { update(); if(myNeverBuilt || hasGeoChanged) { // Name MDataHandle nameHandle = handle.child(AssetNode::outputPartName); MString partName; if(myPartInfo.nameSH != 0) { partName = Util::getString(myPartInfo.nameSH); } nameHandle.set(partName); // Mesh MDataHandle hasMeshHandle = handle.child(AssetNode::outputPartHasMesh); MDataHandle meshHandle = handle.child(AssetNode::outputPartMesh); if(myPartInfo.pointCount != 0 && myPartInfo.vertexCount != 0 && myPartInfo.faceCount != 0) { computeMesh(time, hasMeshHandle, meshHandle); } else { clearMesh(hasMeshHandle, meshHandle); } // Particle MDataHandle hasParticlesHandle = handle.child(AssetNode::outputPartHasParticles); MDataHandle particleHandle = handle.child(AssetNode::outputPartParticle); if(myPartInfo.pointCount != 0 && myPartInfo.vertexCount == 0 && myPartInfo.faceCount == 0) { computeParticle(time, hasParticlesHandle, particleHandle); } #if MAYA_API_VERSION >= 201400 // Volume MDataHandle volumeHandle = handle.child(AssetNode::outputPartVolume); if(myPartInfo.hasVolume) { computeVolume(time, volumeHandle); } #endif // Curve MDataHandle curvesHandle = handle.child(AssetNode::outputPartCurves); MDataHandle curvesIsBezierHandle = handle.child(AssetNode::outputPartCurvesIsBezier); if(myCurveInfo.curveCount) { computeCurves(time, curvesHandle, curvesIsBezierHandle); } else { clearCurves(curvesHandle, curvesIsBezierHandle); } } if(myNeverBuilt || hasMaterialChanged) { MDataHandle materialHandle = handle.child(AssetNode::outputPartMaterial); computeMaterial(time, materialHandle); } myNeverBuilt = false; return MS::kSuccess; } void OutputGeometryPart::computeCurves( const MTime &time, MDataHandle &curvesHandle, MDataHandle &curvesIsBezierHandle ) { MStatus status; MArrayDataHandle curvesArrayHandle(curvesHandle); MArrayDataBuilder curvesBuilder = curvesArrayHandle.builder(); std::vector<float> pArray, pwArray; getAttributeData(pArray, "P", HAPI_ATTROWNER_POINT); getAttributeData(pwArray, "Pw", HAPI_ATTROWNER_POINT); int vertexOffset = 0; int knotOffset = 0; for(int iCurve = 0; iCurve < myCurveInfo.curveCount; iCurve++) { MDataHandle curve = curvesBuilder.addElement(iCurve ); MObject curveDataObj = curve.data(); MFnNurbsCurveData curveDataFn(curveDataObj); if(curve.data().isNull()) { // set the MDataHandle curveDataObj = curveDataFn.create(); curve.setMObject(curveDataObj); // then get the copy from MDataHandle curveDataObj = curve.data(); curveDataFn.setObject(curveDataObj); } // Number of CVs int numVertices = 0; HAPI_GetCurveCounts(myAssetId, myObjectId, myGeoId, myPartId, &numVertices, iCurve , 1); const int nextVertexOffset = vertexOffset + numVertices; if ( nextVertexOffset > static_cast<int>( pArray.size() ) * 3 || (!pwArray.empty() && nextVertexOffset > static_cast<int>( pwArray.size() ) ) ) { MGlobal::displayError( "Not enough points to create a curve" ); break; } // Order of this particular curve int order; if ( myCurveInfo.order != HAPI_CURVE_ORDER_VARYING && myCurveInfo.order != HAPI_CURVE_ORDER_INVALID ) { order = myCurveInfo.order; } else { HAPI_GetCurveOrders(myAssetId, myObjectId, myGeoId, myPartId, &order, iCurve , 1); } // If there's not enough vertices, then don't try to create the curve. if(numVertices < order) { // Need to make sure we clear out the curve that was created // previously. curve.setMObject(curveDataFn.create()); // The curve at i will have numVertices vertices, and may have // some knots. The knot count will be numVertices + order for // nurbs curves vertexOffset = nextVertexOffset; knotOffset += numVertices + order; continue; } MPointArray controlVertices( numVertices ); for(int iDst = 0, iSrc = vertexOffset; iDst < numVertices; ++iDst, ++iSrc) { controlVertices[iDst] = MPoint( pArray[iSrc * 3], pArray[iSrc * 3 + 1], pArray[iSrc * 3 + 2], pwArray.empty() ? 1.0f : pwArray[iSrc] ); } MDoubleArray knotSequences; if(myCurveInfo.hasKnots) { std::vector<float> knots; knots.resize(numVertices + order); // The Maya knot vector has two fewer knots; // the first and last houdini knot are excluded knotSequences.setLength(numVertices + order - 2); HAPI_GetCurveKnots(myAssetId, myObjectId, myGeoId, myPartId, &knots.front(), knotOffset, numVertices + order); // Maya doesn't need the first and last knots for(int j=0; j<numVertices + order - 2; j++) knotSequences[j] = knots[j+1]; } else if(myCurveInfo.curveType == HAPI_CURVETYPE_BEZIER) { // Bezier knot vector needs to still be passed in knotSequences.setLength(numVertices + order - 2); for(int j=0; j<numVertices + order - 2; j++) knotSequences[j] = j / (order - 1); } else { knotSequences.setLength(numVertices + order - 2); int j = 0; for(; j < order - 1; j++) knotSequences[j] = 0.0; for(; j < numVertices - 1; j++) knotSequences[j] = (double) j / (numVertices - order + 1); for(; j < numVertices + order - 2; j++) knotSequences[j] = 1.0; } // NOTE: Periodicity is always constant, so periodic and // non-periodic curve meshes will have different parts. MFnNurbsCurve curveFn; MObject nurbsCurve = curveFn.create(controlVertices, knotSequences, order-1, myCurveInfo.isPeriodic ? MFnNurbsCurve::kPeriodic : MFnNurbsCurve::kOpen, false /* 2d? */, myCurveInfo.isRational /* rational? */, curveDataObj, &status); CHECK_MSTATUS(status); // The curve at i will have numVertices vertices, and may have // some knots. The knot count will be numVertices + order for // nurbs curves vertexOffset = nextVertexOffset; knotOffset += numVertices + order; } // There may be curves created in the previous cook. So we need to clear // the output attributes to remove any curves that may have been created // previously. clearCurvesBuilder(curvesBuilder, myCurveInfo.curveCount); curvesArrayHandle.set(curvesBuilder); curvesIsBezierHandle.setBool(myCurveInfo.curveType == HAPI_CURVETYPE_BEZIER); } static void bufferToParticleArray(MVectorArray &particleArray, const std::vector<float> &buffer) { for(unsigned int i = 0, j = 0; i < particleArray.length(); i++, j += 3) { MVector &vector = particleArray[i]; vector.x = buffer[j + 0]; vector.y = buffer[j + 1]; vector.z = buffer[j + 2]; } } static void bufferToParticleArray(MDoubleArray &particleArray, const std::vector<float> &buffer) { for(unsigned int i = 0; i < particleArray.length(); i++) { particleArray[i] = buffer[i]; } } static void bufferToParticleArray(MIntArray &particleArray, const std::vector<int> &buffer) { for(unsigned int i = 0; i < particleArray.length(); i++) { particleArray[i] = buffer[i]; } } static void zeroParticleArray(MVectorArray &particleArray) { for(unsigned int i = 0; i < particleArray.length(); i++) { MVector &vector = particleArray[i]; vector.x = 0.0; vector.y = 0.0; vector.z = 0.0; } } static void zeroParticleArray(MDoubleArray &particleArray) { for(unsigned int i = 0; i < particleArray.length(); i++) { particleArray[i] = 0.0; } } static void zeroParticleArray(MIntArray &particleArray) { for(unsigned int i = 0; i < particleArray.length(); i++) { particleArray[i] = 0; } } static void getParticleArray( MVectorArray &particleArray, MFnArrayAttrsData &arrayDataFn, const MString &attrName, int particleCount ) { particleArray = arrayDataFn.vectorArray(attrName); particleArray.setLength(particleCount); } static void getParticleArray( MDoubleArray &particleArray, MFnArrayAttrsData &arrayDataFn, const MString &attrName, int particleCount ) { particleArray = arrayDataFn.doubleArray(attrName); particleArray.setLength(particleCount); } static void getParticleArray( MIntArray &particleArray, MFnArrayAttrsData &arrayDataFn, const MString &attrName, int particleCount ) { particleArray = arrayDataFn.intArray(attrName); particleArray.setLength(particleCount); } template<typename T, typename U> void OutputGeometryPart::convertParticleAttribute( MFnArrayAttrsData &arrayDataFn, const MString &mayaName, U &buffer, const char* houdiniName, int particleCount ) { if(getAttributeData(buffer, houdiniName, HAPI_ATTROWNER_POINT)) { T particleArray; getParticleArray(particleArray, arrayDataFn, mayaName, particleCount); bufferToParticleArray(particleArray, buffer); } else { T particleArray; getParticleArray(particleArray, arrayDataFn, mayaName, particleCount); zeroParticleArray(particleArray); } } void OutputGeometryPart::computeParticle( const MTime &time, MDataHandle &hasParticlesHandle, MDataHandle &particleHandle ) { hasParticlesHandle.setBool(true); MDataHandle currentTimeHandle = particleHandle.child(AssetNode::outputPartParticleCurrentTime); MDataHandle positionsHandle = particleHandle.child(AssetNode::outputPartParticlePositions); MDataHandle arrayDataHandle = particleHandle.child(AssetNode::outputPartParticleArrayData); std::vector<float> floatArray; std::vector<int> intArray; int particleCount = myPartInfo.pointCount; // currentTime currentTimeHandle.setMTime(time); // positions MObject positionsObj = positionsHandle.data(); MFnVectorArrayData positionDataFn(positionsObj); if(positionsObj.isNull()) { positionsObj = positionDataFn.create(); positionsHandle.setMObject(positionsObj); } MVectorArray positions = positionDataFn.array(); { getAttributeData(floatArray, "P", HAPI_ATTROWNER_POINT); positions.setLength(particleCount); bufferToParticleArray(positions, floatArray); } // array data MObject arrayDataObj = arrayDataHandle.data(); MFnArrayAttrsData arrayDataFn(arrayDataObj); if(arrayDataObj.isNull()) { arrayDataObj = arrayDataFn.create(); arrayDataHandle.setMObject(arrayDataObj); } // id { MDoubleArray idArray = arrayDataFn.doubleArray("id"); idArray.setLength(particleCount); if(getAttributeData(intArray, "id", HAPI_ATTROWNER_POINT)) { for(unsigned int i = 0; i < idArray.length(); i++) { idArray[i] = intArray[i]; } } else { zeroParticleArray(idArray); } } // count MDoubleArray countArray = arrayDataFn.doubleArray("count"); countArray.setLength(1); countArray[0] = particleCount; // position arrayDataFn.vectorArray("position").copy(positions); // velocity MVectorArray velocityArray; getParticleArray(velocityArray, arrayDataFn, "velocity", particleCount); if(getAttributeData(floatArray, "v", HAPI_ATTROWNER_POINT)) { bufferToParticleArray(velocityArray, floatArray); } else { zeroParticleArray(velocityArray); } // acceleration convertParticleAttribute<MVectorArray>( arrayDataFn, "acceleration", floatArray, "force", particleCount ); // worldPosition arrayDataFn.vectorArray("worldPosition").copy(positions); // worldVelocity arrayDataFn.vectorArray("worldVelocity").copy(velocityArray); // worldVelocityInObjectSpace arrayDataFn.vectorArray("worldVelocityInObjectSpace").copy(velocityArray); // mass convertParticleAttribute<MDoubleArray>( arrayDataFn, "mass", floatArray, "mass", particleCount ); // birthTime convertParticleAttribute<MDoubleArray>( arrayDataFn, "birthTime", floatArray, "birthTime", particleCount ); // age convertParticleAttribute<MDoubleArray>( arrayDataFn, "age", floatArray, "age", particleCount ); // finalLifespanPP convertParticleAttribute<MDoubleArray>( arrayDataFn, "finalLifespanPP", floatArray, "finalLifespanPP", particleCount ); // lifespanPP convertParticleAttribute<MDoubleArray>( arrayDataFn, "lifespanPP", floatArray, "life", particleCount ); // other attributes int* attributeNames = new int[myPartInfo.pointAttributeCount]; HAPI_GetAttributeNames(myAssetId, myObjectId, myGeoId, myPartId, HAPI_ATTROWNER_POINT, attributeNames, myPartInfo.pointAttributeCount); for(int i = 0; i < myPartInfo.pointAttributeCount; i++) { MString attributeName = Util::getString(attributeNames[i]); // skip attributes that were done above already if(attributeName == "id" || attributeName == "count" || attributeName == "P" // houdini name || attributeName == "position" || attributeName == "v" // houdini name || attributeName == "velocity" || attributeName == "force" // houdini name || attributeName == "acceleration" || attributeName == "worldPosition" || attributeName == "worldVelocity" || attributeName == "worldVelocityInObjectSpace" || attributeName == "mass" || attributeName == "birthTime" || attributeName == "age" || attributeName == "finalLifespanPP" || attributeName == "life" || attributeName == "lifespanPP" ) { continue; } // translate certain attributes into Maya names MString translatedAttributeName; if(attributeName == "Cd") { translatedAttributeName = "rgbPP"; } else if(attributeName == "Alpha") { translatedAttributeName = "opacityPP"; } else if(attributeName == "pscale") { translatedAttributeName = "radiusPP"; } else { translatedAttributeName = attributeName; } HAPI_AttributeInfo attributeInfo; HAPI_GetAttributeInfo(myAssetId, myObjectId, myGeoId, myPartId, attributeName.asChar(), HAPI_ATTROWNER_POINT, &attributeInfo); // put the data into MFnArrayAttrsData if(attributeInfo.storage == HAPI_STORAGETYPE_FLOAT && attributeInfo.tupleSize == 3) { convertParticleAttribute<MVectorArray>( arrayDataFn, translatedAttributeName, floatArray, attributeName.asChar(), particleCount ); } else if(attributeInfo.storage == HAPI_STORAGETYPE_FLOAT && attributeInfo.tupleSize == 1) { convertParticleAttribute<MDoubleArray>( arrayDataFn, translatedAttributeName, floatArray, attributeName.asChar(), particleCount ); } else if(attributeInfo.storage == HAPI_STORAGETYPE_INT && attributeInfo.tupleSize == 1) { convertParticleAttribute<MIntArray>( arrayDataFn, translatedAttributeName, intArray, attributeName.asChar(), particleCount ); } } delete [] attributeNames; currentTimeHandle.setClean(); positionsHandle.setClean(); arrayDataHandle.setClean(); } #if MAYA_API_VERSION >= 201400 void OutputGeometryPart::computeVolume( const MTime &time, MDataHandle &volumeHandle ) { MDataHandle gridHandle = volumeHandle.child(AssetNode::outputPartVolumeGrid); MDataHandle transformHandle = volumeHandle.child(AssetNode::outputPartVolumeTransform); MDataHandle resHandle = volumeHandle.child(AssetNode::outputPartVolumeRes); MDataHandle nameHandle = volumeHandle.child(AssetNode::outputPartVolumeName); // grid { MObject gridDataObj = gridHandle.data(); MFnFloatArrayData gridDataFn(gridDataObj); if(gridDataObj.isNull()) { gridDataObj = gridDataFn.create(); gridHandle.setMObject(gridDataObj); } MFloatArray grid = gridDataFn.array(); int xres = myVolumeInfo.xLength; int yres = myVolumeInfo.yLength; int zres = myVolumeInfo.zLength; int tileSize = myVolumeInfo.tileSize; grid.setLength(xres * yres * zres); for(unsigned int i=0; i<grid.length(); i++) grid[i] = 0.0f; std::vector<float> tile; tile.resize(tileSize * tileSize * tileSize); HAPI_VolumeTileInfo tileInfo; HAPI_GetFirstVolumeTile(myAssetId, myObjectId, myGeoId, myPartId, &tileInfo); #ifdef max #undef max #endif while(tileInfo.minX != std::numeric_limits<int>::max() && tileInfo.minY != std::numeric_limits<int>::max() && tileInfo.minZ != std::numeric_limits<int>::max()) { HAPI_GetVolumeTileFloatData(myAssetId, myObjectId, myGeoId, myPartId, &tileInfo, &tile.front()); for(int k=0; k<tileSize; k++) for(int j=0; j<tileSize; j++) for(int i=0; i<tileSize; i++) { int z = k + tileInfo.minZ - myVolumeInfo.minZ, y = j + tileInfo.minY - myVolumeInfo.minY, x = i + tileInfo.minX - myVolumeInfo.minX; int index = xres * yres * z + xres * y + x; float value = tile[k * tileSize*tileSize + j * tileSize + i]; if(x < xres && y < yres && z < zres && x > 0 && y > 0 && z > 0) { grid[index] = value; } } HAPI_GetNextVolumeTile(myAssetId, myObjectId, myGeoId, myPartId, &tileInfo); } } // transform computeVolumeTransform(time, transformHandle); // resolution MFloatArray resolution; resolution.append(myVolumeInfo.xLength); resolution.append(myVolumeInfo.yLength); resolution.append(myVolumeInfo.zLength); MFnFloatArrayData resCreator; resHandle.set(resCreator.create(resolution)); // name nameHandle.set(Util::getString(myVolumeInfo.nameSH)); } #endif void OutputGeometryPart::computeMesh( const MTime &time, MDataHandle &hasMeshHandle, MDataHandle &meshHandle ) { MStatus status; hasMeshHandle.setBool(true); // create mesh MObject meshDataObj = meshHandle.data(); MFnMeshData meshDataFn(meshDataObj); if(meshDataObj.isNull()) { // set the MDataHandle meshDataObj = meshDataFn.create(); meshHandle.setMObject(meshDataObj); // then get the copy from MDataHandle meshDataObj = meshHandle.data(); meshDataFn.setObject(meshDataObj); } std::vector<float> floatArray; std::vector<int> intArray; // vertex array MFloatPointArray vertexArray; { getAttributeData(floatArray, "P", HAPI_ATTROWNER_POINT); // assume 3 tuple vertexArray.setLength(floatArray.size() / 3); for(unsigned int i = 0, length = vertexArray.length(); i < length; ++i) { MFloatPoint &floatPoint = vertexArray[i]; floatPoint.x = floatArray[i * 3 + 0]; floatPoint.y = floatArray[i * 3 + 1]; floatPoint.z = floatArray[i * 3 + 2]; floatPoint.w = 1.0f; } } // polygon counts MIntArray polygonCounts; { intArray.resize(myPartInfo.faceCount); if(myPartInfo.faceCount) { HAPI_GetFaceCounts( myAssetId, myObjectId, myGeoId, myPartId, &intArray.front(), 0, myPartInfo.faceCount ); } polygonCounts = MIntArray(&intArray.front(), intArray.size()); } // polygon connects MIntArray polygonConnects; { intArray.resize(myPartInfo.vertexCount); if(myPartInfo.vertexCount) { HAPI_GetVertexList( myAssetId, myObjectId, myGeoId, myPartId, &intArray.front(), 0, myPartInfo.vertexCount ); } polygonConnects = MIntArray(&intArray.front(), intArray.size()); Util::reverseWindingOrder(polygonConnects, polygonCounts); } MFnMesh meshFn; meshFn.create( vertexArray.length(), polygonCounts.length(), vertexArray, polygonCounts, polygonConnects, meshDataObj, &status ); CHECK_MSTATUS(status); // Check that the mesh created is what we tried to create. Assets could // output mesh with bad faces that Maya cannot handle. When this happens, // Maya would skip the bad faces, so the resulting mesh would be slightly // different. This makes it no longer possible to apply geometry attributes // (like UVs and color sets) to the mesh. { bool mismatch_topology = false; if(vertexArray.length() != (unsigned int) meshFn.numVertices()) { DISPLAY_WARNING( "Attempted to create ^1s vertices, but only ^2s vertices " "were created.", MString() + vertexArray.length(), MString() + meshFn.numVertices() ); mismatch_topology = true; } if(polygonCounts.length() != (unsigned int) meshFn.numPolygons()) { DISPLAY_WARNING( "Attempted to create ^1s polygons, but only ^2s polygons " "were created.", MString() + polygonCounts.length(), MString() + meshFn.numPolygons() ); mismatch_topology = true; } if(polygonConnects.length() != (unsigned int) meshFn.numFaceVertices()) { DISPLAY_WARNING( "Attempted to create ^1s face-vertices, but only ^2s " "face-vertices were created.", MString() + polygonConnects.length(), MString() + meshFn.numFaceVertices() ); mismatch_topology = true; } if(mismatch_topology) { DISPLAY_WARNING(MString( "This likely means that the Houdini Digital Asset is " "outputting bad geometry that Maya cannot handle. As a " "result, other attributes (such as UVs and color sets) " "cannot be transferred." )); return; } } // normal array if(polygonCounts.length()) { HAPI_AttributeOwner owner = HAPI_ATTROWNER_MAX; if(getAttributeData(floatArray, "N", HAPI_ATTROWNER_VERTEX)) { owner = HAPI_ATTROWNER_VERTEX; } else if(getAttributeData(floatArray, "N", HAPI_ATTROWNER_POINT)) { owner = HAPI_ATTROWNER_POINT; } if(owner != HAPI_ATTROWNER_MAX) { // assume 3 tuple MVectorArray normals( reinterpret_cast<float(*)[3]>(&floatArray.front()), floatArray.size() / 3); if(owner == HAPI_ATTROWNER_VERTEX) { Util::reverseWindingOrder(normals, polygonCounts); MIntArray faceList; faceList.setLength(polygonConnects.length()); for(unsigned int i = 0, j = 0, length = polygonCounts.length(); i < length; ++i) { for(int k = 0; k < polygonCounts[i]; ++j, ++k) { faceList[j] = i; } } meshFn.setFaceVertexNormals(normals, faceList, polygonConnects); } else if(owner == HAPI_ATTROWNER_POINT) { MIntArray vertexList; vertexList.setLength(vertexArray.length()); for(unsigned int i = 0, length = vertexList.length(); i < length; ++i) { vertexList[i] = i; } meshFn.setVertexNormals(normals, vertexList); } } } // uv if(polygonCounts.length()) { HAPI_AttributeOwner owner = HAPI_ATTROWNER_MAX; if(getAttributeData(floatArray, "uv", HAPI_ATTROWNER_VERTEX)) { owner = HAPI_ATTROWNER_VERTEX; } else if(getAttributeData(floatArray, "uv", HAPI_ATTROWNER_POINT)) { owner = HAPI_ATTROWNER_POINT; } if(owner != HAPI_ATTROWNER_MAX) { // assume 3 tuple MFloatArray uArray; MFloatArray vArray; uArray.setLength(floatArray.size() / 3); vArray.setLength(floatArray.size() / 3); for(unsigned int i = 0, length = uArray.length(); i < length; ++i) { uArray[i] = floatArray[i * 3 + 0]; vArray[i] = floatArray[i * 3 + 1]; } MIntArray vertexList; vertexList.setLength(polygonConnects.length()); if(owner == HAPI_ATTROWNER_VERTEX) { Util::reverseWindingOrder(uArray, polygonCounts); Util::reverseWindingOrder(vArray, polygonCounts); for(unsigned int i = 0, length = polygonConnects.length(); i < length; ++i) { vertexList[i] = i; } } else if(owner == HAPI_ATTROWNER_POINT) { for(unsigned int i = 0, length = polygonConnects.length(); i < length; ++i) { vertexList[i] = polygonConnects[i]; } } meshFn.setUVs(uArray, vArray); meshFn.assignUVs(polygonCounts, vertexList); } } // color and alpha if(polygonCounts.length()) { // Get color data HAPI_AttributeOwner colorOwner = HAPI_ATTROWNER_MAX; if(getAttributeData(floatArray, "Cd", HAPI_ATTROWNER_VERTEX)) { colorOwner = HAPI_ATTROWNER_VERTEX; } else if(getAttributeData(floatArray, "Cd", HAPI_ATTROWNER_POINT)) { colorOwner = HAPI_ATTROWNER_POINT; } else if(getAttributeData(floatArray, "Cd", HAPI_ATTROWNER_PRIM)) { colorOwner = HAPI_ATTROWNER_PRIM; } else if(getAttributeData(floatArray, "Cd", HAPI_ATTROWNER_DETAIL)) { colorOwner = HAPI_ATTROWNER_DETAIL; } HAPI_AttributeOwner alphaOwner = HAPI_ATTROWNER_MAX; std::vector<float> alphaArray; if(getAttributeData(alphaArray, "Alpha", HAPI_ATTROWNER_VERTEX)) { alphaOwner = HAPI_ATTROWNER_VERTEX; } else if(getAttributeData(alphaArray, "Alpha", HAPI_ATTROWNER_POINT)) { alphaOwner = HAPI_ATTROWNER_POINT; } else if(getAttributeData(alphaArray, "Alpha", HAPI_ATTROWNER_PRIM)) { alphaOwner = HAPI_ATTROWNER_PRIM; } else if(getAttributeData(alphaArray, "Alpha", HAPI_ATTROWNER_DETAIL)) { alphaOwner = HAPI_ATTROWNER_DETAIL; } if(colorOwner != HAPI_ATTROWNER_MAX || alphaOwner != HAPI_ATTROWNER_MAX) { // Convert to color array MColorArray colors(floatArray.size() / 3); if(colorOwner != HAPI_ATTROWNER_MAX) { for(unsigned int i = 0, length = colors.length(); i < length; ++i) { MColor &color = colors[i]; color.r = floatArray[i * 3 + 0]; color.g = floatArray[i * 3 + 1]; color.b = floatArray[i * 3 + 2]; } } HAPI_AttributeOwner owner; if((colorOwner == HAPI_ATTROWNER_POINT && alphaOwner == HAPI_ATTROWNER_PRIM) || (colorOwner == HAPI_ATTROWNER_PRIM && alphaOwner == HAPI_ATTROWNER_POINT)) { // Don't convert the prim attributes to point attributes, // because that would lose information. Convert everything to // vertex attributs instead. owner = HAPI_ATTROWNER_VERTEX; } else { if(colorOwner < alphaOwner) { owner = colorOwner; } else { owner = alphaOwner; } } if(owner == HAPI_ATTROWNER_DETAIL) { // Handle detail color and alpha as points owner = HAPI_ATTROWNER_POINT; } // If there's no color, then use a default color if(colorOwner == HAPI_ATTROWNER_MAX) { colorOwner = HAPI_ATTROWNER_DETAIL; colors.setLength(1); colors[0] = MColor(1.0f, 1.0f, 1.0f); } // If there's no alpha, then use a default alpha if(alphaOwner == HAPI_ATTROWNER_MAX) { alphaOwner = HAPI_ATTROWNER_DETAIL; alphaArray.resize(1); alphaArray[0] = 1.0f; } // Promte the attributes MColorArray promotedColors; Util::promoteAttributeData<0, 0, 3, float>( owner, promotedColors, colorOwner, colors, vertexArray.length(), &polygonCounts, &polygonConnects ); Util::promoteAttributeData<3, 0, 1, float>( owner, promotedColors, alphaOwner, alphaArray, vertexArray.length(), &polygonCounts, &polygonConnects ); if(owner == HAPI_ATTROWNER_VERTEX) { Util::reverseWindingOrder(promotedColors, polygonCounts); MIntArray faceList; faceList.setLength(polygonConnects.length()); for(unsigned int i = 0, j = 0, length = polygonCounts.length(); i < length; ++i) { for(int k = 0; k < polygonCounts[i]; ++j, ++k) { faceList[j] = i; } } meshFn.setFaceVertexColors(promotedColors, faceList, polygonConnects); } else if(owner == HAPI_ATTROWNER_POINT) { MIntArray vertexList; vertexList.setLength(vertexArray.length()); for(unsigned int i = 0, length = vertexList.length(); i < length; ++i) { vertexList[i] = i; } meshFn.setVertexColors(promotedColors, vertexList); } else if(owner == HAPI_ATTROWNER_PRIM) { MIntArray faceList; faceList.setLength(polygonCounts.length()); for(unsigned int i = 0, length = faceList.length(); i < length; ++i) { faceList[i] = i; } meshFn.setFaceColors(promotedColors, faceList); } } } } void OutputGeometryPart::computeMaterial( const MTime &time, MDataHandle& materialHandle ) { MDataHandle matExistsHandle = materialHandle.child(AssetNode::outputPartMaterialExists); MDataHandle nameHandle = materialHandle.child(AssetNode::outputPartMaterialName); MDataHandle ambientHandle = materialHandle.child(AssetNode::outputPartAmbientColor); MDataHandle diffuseHandle = materialHandle.child(AssetNode::outputPartDiffuseColor); MDataHandle specularHandle = materialHandle.child(AssetNode::outputPartSpecularColor); MDataHandle alphaHandle = materialHandle.child(AssetNode::outputPartAlphaColor); MDataHandle texturePathHandle = materialHandle.child(AssetNode::outputPartTexturePath); HAPI_GetMaterialOnPart( myAssetId, myObjectId, myGeoId, myPartId, &myMaterialInfo ); if(!myMaterialInfo.exists) { matExistsHandle.set(false); } else { // get material info HAPI_NodeInfo materialNodeInfo; HAPI_GetNodeInfo(myMaterialInfo.nodeId, &materialNodeInfo); std::vector<HAPI_ParmInfo> parms(materialNodeInfo.parmCount); HAPI_GetParameters(myMaterialInfo.nodeId, &parms[0], 0, materialNodeInfo.parmCount); int ambientParmIndex = Util::findParm(parms, "ogl_amb"); int diffuseParmIndex = Util::findParm(parms, "ogl_diff"); int alphaParmIndex = Util::findParm(parms, "ogl_alpha"); int specularParmIndex = Util::findParm(parms, "ogl_spec"); int texturePathSHParmIndex = Util::findParm(parms, "ogl_tex#", 1); float valueHolder[4]; matExistsHandle.set(true); nameHandle.setString( Util::getString(materialNodeInfo.nameSH) ); if(ambientParmIndex >= 0) { HAPI_GetParmFloatValues(myMaterialInfo.nodeId, valueHolder, parms[ambientParmIndex].floatValuesIndex, 3); ambientHandle.set3Float(valueHolder[0], valueHolder[1], valueHolder[2]); } if(specularParmIndex >= 0) { HAPI_GetParmFloatValues(myMaterialInfo.nodeId, valueHolder, parms[specularParmIndex].floatValuesIndex, 3); specularHandle.set3Float(valueHolder[0], valueHolder[1], valueHolder[2]); } if(diffuseParmIndex >= 0) { HAPI_GetParmFloatValues(myMaterialInfo.nodeId, valueHolder, parms[diffuseParmIndex].floatValuesIndex, 3); diffuseHandle.set3Float(valueHolder[0], valueHolder[1], valueHolder[2]); } if(alphaParmIndex >= 0) { HAPI_GetParmFloatValues(myMaterialInfo.nodeId, valueHolder, parms[alphaParmIndex].floatValuesIndex, 1); float alpha = 1 - valueHolder[0]; alphaHandle.set3Float(alpha, alpha, alpha); } if(texturePathSHParmIndex >= 0) { HAPI_ParmInfo texturePathParm; HAPI_GetParameters( myMaterialInfo.nodeId, &texturePathParm, texturePathSHParmIndex, 1 ); int texturePathSH; HAPI_GetParmStringValues( myMaterialInfo.nodeId, true, &texturePathSH, texturePathParm.stringValuesIndex, 1 ); bool hasTextureSource = Util::getString(texturePathSH).length() > 0; bool canRenderTexture = false; if(hasTextureSource) { HAPI_Result hapiResult; // this could fail if texture parameter is empty hapiResult = HAPI_RenderTextureToImage( myAssetId, myMaterialInfo.id, texturePathSHParmIndex ); canRenderTexture = hapiResult == HAPI_RESULT_SUCCESS; } int destinationFilePathSH = 0; if(canRenderTexture) { MString destinationFolderPath; MGlobal::executeCommand("workspace -expandName `workspace -q -fileRuleEntry sourceImages`;", destinationFolderPath); // this could fail if the image planes don't exist HAPI_ExtractImageToFile( myAssetId, myMaterialInfo.id, HAPI_PNG_FORMAT_NAME, "C A", destinationFolderPath.asChar(), NULL, &destinationFilePathSH ); } if(destinationFilePathSH > 0) { MString texturePath = Util::getString(destinationFilePathSH); texturePathHandle.set(texturePath); } } } materialHandle.setClean(); matExistsHandle.setClean(); ambientHandle.setClean(); diffuseHandle.setClean(); specularHandle.setClean(); alphaHandle.setClean(); texturePathHandle.setClean(); } Refactored utility functions for processing arrays Set array lengths at bufferToParticleArray() and zeroParticleArray(), instead of at getParticleArray(). #include <maya/MFnMesh.h> #include <maya/MFnMeshData.h> #include <maya/MArrayDataBuilder.h> #include <maya/MGlobal.h> #include <maya/MEulerRotation.h> #include <maya/MQuaternion.h> #include <maya/MMatrix.h> #include <maya/MTime.h> #include <maya/MFnArrayAttrsData.h> #include <maya/MFnDoubleArrayData.h> #include <maya/MFnNurbsCurve.h> #include <maya/MFnNurbsCurveData.h> #include <maya/MPointArray.h> #if MAYA_API_VERSION >= 201400 #include <maya/MFnFloatArrayData.h> #endif #include <maya/MFnVectorArrayData.h> #include <vector> #include <limits> #include "Asset.h" #include "AssetNode.h" #include "OutputGeometryPart.h" #include "util.h" void clearMesh( MDataHandle &hasMeshHandle, MDataHandle &meshHandle ) { hasMeshHandle.setBool(false); meshHandle.setMObject(MObject::kNullObj); } static void clearCurvesBuilder( MArrayDataBuilder &curvesBuilder, int count ) { for(int i = (int) curvesBuilder.elementCount(); i-- > count;) { curvesBuilder.removeElement(i); } } static void clearCurves( MDataHandle &curvesHandle, MDataHandle &curvesIsBezier ) { MArrayDataHandle curvesArrayHandle(curvesHandle); MArrayDataBuilder curvesBuilder = curvesArrayHandle.builder(); clearCurvesBuilder(curvesBuilder, 0); curvesArrayHandle.set(curvesBuilder); curvesIsBezier.setBool(false); } OutputGeometryPart::OutputGeometryPart( int assetId, int objectId, int geoId, int partId ) : myAssetId(assetId), myObjectId(objectId), myGeoId(geoId), myPartId(partId), myNeverBuilt(true) { update(); } OutputGeometryPart::~OutputGeometryPart() {} #if MAYA_API_VERSION >= 201400 void OutputGeometryPart::computeVolumeTransform( const MTime &time, MDataHandle& volumeTransformHandle ) { HAPI_Transform transform = myVolumeInfo.transform; MDataHandle translateHandle = volumeTransformHandle.child(AssetNode::outputPartVolumeTranslate); MDataHandle rotateHandle = volumeTransformHandle.child(AssetNode::outputPartVolumeRotate); MDataHandle scaleHandle = volumeTransformHandle.child(AssetNode::outputPartVolumeScale); MEulerRotation r = MQuaternion(transform.rotationQuaternion[0], transform.rotationQuaternion[1], transform.rotationQuaternion[2], transform.rotationQuaternion[3]).asEulerRotation(); const double rot[3] = {r[0], r[1], r[2]}; const double scale[3] = {transform.scale[0], transform.scale[1], transform.scale[2]}; MTransformationMatrix matrix; matrix.addScale(scale, MSpace::kTransform); matrix.addRotation(rot, MTransformationMatrix::kXYZ, MSpace::kTransform); matrix.addTranslation(MVector(transform.position[0], transform.position[1], transform.position[2]), MSpace::kTransform); double xoffset = myVolumeInfo.xLength/2.0 + myVolumeInfo.minX; double yoffset = myVolumeInfo.yLength/2.0 + myVolumeInfo.minY; double zoffset = myVolumeInfo.zLength/2.0 + myVolumeInfo.minZ; const double scale2[3] = {2, 2, 2}; matrix.addScale(scale2, MSpace::kPreTransform); matrix.addTranslation(MVector(-0.5, -0.5, -0.5), MSpace::kPreTransform); matrix.addTranslation(MVector(xoffset, yoffset, zoffset), MSpace::kPreTransform); const double scale3[3] = { static_cast<double>(myVolumeInfo.xLength), static_cast<double>(myVolumeInfo.yLength), static_cast<double>(myVolumeInfo.zLength) }; matrix.addScale(scale3, MSpace::kPreTransform); double final_scale[3]; double final_rotate[3]; MTransformationMatrix::RotationOrder order = MTransformationMatrix::kXYZ; matrix.getScale(final_scale, MSpace::kTransform); matrix.getRotation(final_rotate, order); translateHandle.set(matrix.getTranslation(MSpace::kTransform)); rotateHandle.set3Double(final_rotate[0], final_rotate[1], final_rotate[2]); scaleHandle.set3Double(final_scale[0], final_scale[1], final_scale[2]); translateHandle.setClean(); rotateHandle.setClean(); scaleHandle.setClean(); volumeTransformHandle.setClean(); } #endif void OutputGeometryPart::update() { HAPI_Result hstat = HAPI_RESULT_SUCCESS; try { hstat = HAPI_GetPartInfo(myAssetId, myObjectId, myGeoId, myPartId, &myPartInfo); Util::checkHAPIStatus(hstat); if(myPartInfo.hasVolume) { hstat = HAPI_GetVolumeInfo(myAssetId, myObjectId, myGeoId, myPartId, &myVolumeInfo); Util::checkHAPIStatus(hstat); } if(myPartInfo.isCurve) { hstat = HAPI_GetCurveInfo(myAssetId, myObjectId, myGeoId, myPartId, &myCurveInfo); Util::checkHAPIStatus(hstat); } else { HAPI_CurveInfo_Init(&myCurveInfo); } } catch (HAPIError& e) { cerr << e.what() << endl; HAPI_PartInfo_Init(&myPartInfo); } } static HAPI_Result getAttributeDataWrapper( int asset_id, int object_id, int geo_id, int part_id, const char* name, HAPI_AttributeInfo* attr_info, float* data, int start, int length ) { return HAPI_GetAttributeFloatData( asset_id, object_id, geo_id, part_id, name, attr_info, data, start, length ); } static HAPI_Result getAttributeDataWrapper( int asset_id, int object_id, int geo_id, int part_id, const char* name, HAPI_AttributeInfo* attr_info, int* data, int start, int length ) { return HAPI_GetAttributeIntData( asset_id, object_id, geo_id, part_id, name, attr_info, data, start, length ); } template<typename T> bool OutputGeometryPart::getAttributeData( std::vector<T> &array, const char* name, HAPI_AttributeOwner owner ) { HAPI_AttributeInfo attr_info; attr_info.exists = false; HAPI_GetAttributeInfo( myAssetId, myObjectId, myGeoId, myPartId, name, owner, &attr_info ); if(!attr_info.exists) { array.clear(); return false; } array.resize(attr_info.count * attr_info.tupleSize); getAttributeDataWrapper( myAssetId, myObjectId, myGeoId, myPartId, name, &attr_info, &array.front(), 0, attr_info.count ); return true; } MStatus OutputGeometryPart::compute( const MTime &time, MDataHandle& handle, bool hasGeoChanged, bool hasMaterialChanged, bool &needToSyncOutputs ) { update(); if(myNeverBuilt || hasGeoChanged) { // Name MDataHandle nameHandle = handle.child(AssetNode::outputPartName); MString partName; if(myPartInfo.nameSH != 0) { partName = Util::getString(myPartInfo.nameSH); } nameHandle.set(partName); // Mesh MDataHandle hasMeshHandle = handle.child(AssetNode::outputPartHasMesh); MDataHandle meshHandle = handle.child(AssetNode::outputPartMesh); if(myPartInfo.pointCount != 0 && myPartInfo.vertexCount != 0 && myPartInfo.faceCount != 0) { computeMesh(time, hasMeshHandle, meshHandle); } else { clearMesh(hasMeshHandle, meshHandle); } // Particle MDataHandle hasParticlesHandle = handle.child(AssetNode::outputPartHasParticles); MDataHandle particleHandle = handle.child(AssetNode::outputPartParticle); if(myPartInfo.pointCount != 0 && myPartInfo.vertexCount == 0 && myPartInfo.faceCount == 0) { computeParticle(time, hasParticlesHandle, particleHandle); } #if MAYA_API_VERSION >= 201400 // Volume MDataHandle volumeHandle = handle.child(AssetNode::outputPartVolume); if(myPartInfo.hasVolume) { computeVolume(time, volumeHandle); } #endif // Curve MDataHandle curvesHandle = handle.child(AssetNode::outputPartCurves); MDataHandle curvesIsBezierHandle = handle.child(AssetNode::outputPartCurvesIsBezier); if(myCurveInfo.curveCount) { computeCurves(time, curvesHandle, curvesIsBezierHandle); } else { clearCurves(curvesHandle, curvesIsBezierHandle); } } if(myNeverBuilt || hasMaterialChanged) { MDataHandle materialHandle = handle.child(AssetNode::outputPartMaterial); computeMaterial(time, materialHandle); } myNeverBuilt = false; return MS::kSuccess; } void OutputGeometryPart::computeCurves( const MTime &time, MDataHandle &curvesHandle, MDataHandle &curvesIsBezierHandle ) { MStatus status; MArrayDataHandle curvesArrayHandle(curvesHandle); MArrayDataBuilder curvesBuilder = curvesArrayHandle.builder(); std::vector<float> pArray, pwArray; getAttributeData(pArray, "P", HAPI_ATTROWNER_POINT); getAttributeData(pwArray, "Pw", HAPI_ATTROWNER_POINT); int vertexOffset = 0; int knotOffset = 0; for(int iCurve = 0; iCurve < myCurveInfo.curveCount; iCurve++) { MDataHandle curve = curvesBuilder.addElement(iCurve ); MObject curveDataObj = curve.data(); MFnNurbsCurveData curveDataFn(curveDataObj); if(curve.data().isNull()) { // set the MDataHandle curveDataObj = curveDataFn.create(); curve.setMObject(curveDataObj); // then get the copy from MDataHandle curveDataObj = curve.data(); curveDataFn.setObject(curveDataObj); } // Number of CVs int numVertices = 0; HAPI_GetCurveCounts(myAssetId, myObjectId, myGeoId, myPartId, &numVertices, iCurve , 1); const int nextVertexOffset = vertexOffset + numVertices; if ( nextVertexOffset > static_cast<int>( pArray.size() ) * 3 || (!pwArray.empty() && nextVertexOffset > static_cast<int>( pwArray.size() ) ) ) { MGlobal::displayError( "Not enough points to create a curve" ); break; } // Order of this particular curve int order; if ( myCurveInfo.order != HAPI_CURVE_ORDER_VARYING && myCurveInfo.order != HAPI_CURVE_ORDER_INVALID ) { order = myCurveInfo.order; } else { HAPI_GetCurveOrders(myAssetId, myObjectId, myGeoId, myPartId, &order, iCurve , 1); } // If there's not enough vertices, then don't try to create the curve. if(numVertices < order) { // Need to make sure we clear out the curve that was created // previously. curve.setMObject(curveDataFn.create()); // The curve at i will have numVertices vertices, and may have // some knots. The knot count will be numVertices + order for // nurbs curves vertexOffset = nextVertexOffset; knotOffset += numVertices + order; continue; } MPointArray controlVertices( numVertices ); for(int iDst = 0, iSrc = vertexOffset; iDst < numVertices; ++iDst, ++iSrc) { controlVertices[iDst] = MPoint( pArray[iSrc * 3], pArray[iSrc * 3 + 1], pArray[iSrc * 3 + 2], pwArray.empty() ? 1.0f : pwArray[iSrc] ); } MDoubleArray knotSequences; if(myCurveInfo.hasKnots) { std::vector<float> knots; knots.resize(numVertices + order); // The Maya knot vector has two fewer knots; // the first and last houdini knot are excluded knotSequences.setLength(numVertices + order - 2); HAPI_GetCurveKnots(myAssetId, myObjectId, myGeoId, myPartId, &knots.front(), knotOffset, numVertices + order); // Maya doesn't need the first and last knots for(int j=0; j<numVertices + order - 2; j++) knotSequences[j] = knots[j+1]; } else if(myCurveInfo.curveType == HAPI_CURVETYPE_BEZIER) { // Bezier knot vector needs to still be passed in knotSequences.setLength(numVertices + order - 2); for(int j=0; j<numVertices + order - 2; j++) knotSequences[j] = j / (order - 1); } else { knotSequences.setLength(numVertices + order - 2); int j = 0; for(; j < order - 1; j++) knotSequences[j] = 0.0; for(; j < numVertices - 1; j++) knotSequences[j] = (double) j / (numVertices - order + 1); for(; j < numVertices + order - 2; j++) knotSequences[j] = 1.0; } // NOTE: Periodicity is always constant, so periodic and // non-periodic curve meshes will have different parts. MFnNurbsCurve curveFn; MObject nurbsCurve = curveFn.create(controlVertices, knotSequences, order-1, myCurveInfo.isPeriodic ? MFnNurbsCurve::kPeriodic : MFnNurbsCurve::kOpen, false /* 2d? */, myCurveInfo.isRational /* rational? */, curveDataObj, &status); CHECK_MSTATUS(status); // The curve at i will have numVertices vertices, and may have // some knots. The knot count will be numVertices + order for // nurbs curves vertexOffset = nextVertexOffset; knotOffset += numVertices + order; } // There may be curves created in the previous cook. So we need to clear // the output attributes to remove any curves that may have been created // previously. clearCurvesBuilder(curvesBuilder, myCurveInfo.curveCount); curvesArrayHandle.set(curvesBuilder); curvesIsBezierHandle.setBool(myCurveInfo.curveType == HAPI_CURVETYPE_BEZIER); } static void convertArray(MVectorArray &dstArray, const std::vector<float> &srcArray) { dstArray.setLength(srcArray.size() / 3); for(unsigned int i = 0, j = 0; i < dstArray.length(); i++, j += 3) { MVector &vector = dstArray[i]; vector.x = srcArray[j + 0]; vector.y = srcArray[j + 1]; vector.z = srcArray[j + 2]; } } static void convertArray(MDoubleArray &dstArray, const std::vector<float> &srcArray) { dstArray.setLength(srcArray.size()); for(unsigned int i = 0; i < dstArray.length(); i++) { dstArray[i] = srcArray[i]; } } static void convertArray(MIntArray &dstArray, const std::vector<int> &srcArray) { dstArray.setLength(srcArray.size()); for(unsigned int i = 0; i < dstArray.length(); i++) { dstArray[i] = srcArray[i]; } } static void zeroArray(MVectorArray &dstArray, int count) { dstArray.setLength(count); for(unsigned int i = 0; i < dstArray.length(); i++) { MVector &vector = dstArray[i]; vector.x = 0.0; vector.y = 0.0; vector.z = 0.0; } } static void zeroArray(MDoubleArray &dstArray, int count) { dstArray.setLength(count); for(unsigned int i = 0; i < dstArray.length(); i++) { dstArray[i] = 0.0; } } static void zeroArray(MIntArray &dstArray, int count) { dstArray.setLength(count); for(unsigned int i = 0; i < dstArray.length(); i++) { dstArray[i] = 0; } } static void getParticleArray( MVectorArray &particleArray, MFnArrayAttrsData &arrayDataFn, const MString &attrName ) { particleArray = arrayDataFn.vectorArray(attrName); } static void getParticleArray( MDoubleArray &particleArray, MFnArrayAttrsData &arrayDataFn, const MString &attrName ) { particleArray = arrayDataFn.doubleArray(attrName); } static void getParticleArray( MIntArray &particleArray, MFnArrayAttrsData &arrayDataFn, const MString &attrName ) { particleArray = arrayDataFn.intArray(attrName); } template<typename T, typename U> void OutputGeometryPart::convertParticleAttribute( MFnArrayAttrsData &arrayDataFn, const MString &mayaName, U &buffer, const char* houdiniName, int particleCount ) { if(getAttributeData(buffer, houdiniName, HAPI_ATTROWNER_POINT)) { T particleArray; getParticleArray(particleArray, arrayDataFn, mayaName); convertArray(particleArray, buffer); } else { T particleArray; getParticleArray(particleArray, arrayDataFn, mayaName); zeroArray(particleArray, particleCount); } } void OutputGeometryPart::computeParticle( const MTime &time, MDataHandle &hasParticlesHandle, MDataHandle &particleHandle ) { hasParticlesHandle.setBool(true); MDataHandle currentTimeHandle = particleHandle.child(AssetNode::outputPartParticleCurrentTime); MDataHandle positionsHandle = particleHandle.child(AssetNode::outputPartParticlePositions); MDataHandle arrayDataHandle = particleHandle.child(AssetNode::outputPartParticleArrayData); std::vector<float> floatArray; std::vector<int> intArray; int particleCount = myPartInfo.pointCount; // currentTime currentTimeHandle.setMTime(time); // positions MObject positionsObj = positionsHandle.data(); MFnVectorArrayData positionDataFn(positionsObj); if(positionsObj.isNull()) { positionsObj = positionDataFn.create(); positionsHandle.setMObject(positionsObj); } MVectorArray positions = positionDataFn.array(); { getAttributeData(floatArray, "P", HAPI_ATTROWNER_POINT); positions.setLength(particleCount); convertArray(positions, floatArray); } // array data MObject arrayDataObj = arrayDataHandle.data(); MFnArrayAttrsData arrayDataFn(arrayDataObj); if(arrayDataObj.isNull()) { arrayDataObj = arrayDataFn.create(); arrayDataHandle.setMObject(arrayDataObj); } // id { MDoubleArray idArray = arrayDataFn.doubleArray("id"); idArray.setLength(particleCount); if(getAttributeData(intArray, "id", HAPI_ATTROWNER_POINT)) { for(unsigned int i = 0; i < idArray.length(); i++) { idArray[i] = intArray[i]; } } else { zeroArray(idArray, particleCount); } } // count MDoubleArray countArray = arrayDataFn.doubleArray("count"); countArray.setLength(1); countArray[0] = particleCount; // position arrayDataFn.vectorArray("position").copy(positions); // velocity MVectorArray velocityArray; getParticleArray(velocityArray, arrayDataFn, "velocity"); if(getAttributeData(floatArray, "v", HAPI_ATTROWNER_POINT)) { convertArray(velocityArray, floatArray); } else { zeroArray(velocityArray, particleCount); } // acceleration convertParticleAttribute<MVectorArray>( arrayDataFn, "acceleration", floatArray, "force", particleCount ); // worldPosition arrayDataFn.vectorArray("worldPosition").copy(positions); // worldVelocity arrayDataFn.vectorArray("worldVelocity").copy(velocityArray); // worldVelocityInObjectSpace arrayDataFn.vectorArray("worldVelocityInObjectSpace").copy(velocityArray); // mass convertParticleAttribute<MDoubleArray>( arrayDataFn, "mass", floatArray, "mass", particleCount ); // birthTime convertParticleAttribute<MDoubleArray>( arrayDataFn, "birthTime", floatArray, "birthTime", particleCount ); // age convertParticleAttribute<MDoubleArray>( arrayDataFn, "age", floatArray, "age", particleCount ); // finalLifespanPP convertParticleAttribute<MDoubleArray>( arrayDataFn, "finalLifespanPP", floatArray, "finalLifespanPP", particleCount ); // lifespanPP convertParticleAttribute<MDoubleArray>( arrayDataFn, "lifespanPP", floatArray, "life", particleCount ); // other attributes int* attributeNames = new int[myPartInfo.pointAttributeCount]; HAPI_GetAttributeNames(myAssetId, myObjectId, myGeoId, myPartId, HAPI_ATTROWNER_POINT, attributeNames, myPartInfo.pointAttributeCount); for(int i = 0; i < myPartInfo.pointAttributeCount; i++) { MString attributeName = Util::getString(attributeNames[i]); // skip attributes that were done above already if(attributeName == "id" || attributeName == "count" || attributeName == "P" // houdini name || attributeName == "position" || attributeName == "v" // houdini name || attributeName == "velocity" || attributeName == "force" // houdini name || attributeName == "acceleration" || attributeName == "worldPosition" || attributeName == "worldVelocity" || attributeName == "worldVelocityInObjectSpace" || attributeName == "mass" || attributeName == "birthTime" || attributeName == "age" || attributeName == "finalLifespanPP" || attributeName == "life" || attributeName == "lifespanPP" ) { continue; } // translate certain attributes into Maya names MString translatedAttributeName; if(attributeName == "Cd") { translatedAttributeName = "rgbPP"; } else if(attributeName == "Alpha") { translatedAttributeName = "opacityPP"; } else if(attributeName == "pscale") { translatedAttributeName = "radiusPP"; } else { translatedAttributeName = attributeName; } HAPI_AttributeInfo attributeInfo; HAPI_GetAttributeInfo(myAssetId, myObjectId, myGeoId, myPartId, attributeName.asChar(), HAPI_ATTROWNER_POINT, &attributeInfo); // put the data into MFnArrayAttrsData if(attributeInfo.storage == HAPI_STORAGETYPE_FLOAT && attributeInfo.tupleSize == 3) { convertParticleAttribute<MVectorArray>( arrayDataFn, translatedAttributeName, floatArray, attributeName.asChar(), particleCount ); } else if(attributeInfo.storage == HAPI_STORAGETYPE_FLOAT && attributeInfo.tupleSize == 1) { convertParticleAttribute<MDoubleArray>( arrayDataFn, translatedAttributeName, floatArray, attributeName.asChar(), particleCount ); } else if(attributeInfo.storage == HAPI_STORAGETYPE_INT && attributeInfo.tupleSize == 1) { convertParticleAttribute<MIntArray>( arrayDataFn, translatedAttributeName, intArray, attributeName.asChar(), particleCount ); } } delete [] attributeNames; currentTimeHandle.setClean(); positionsHandle.setClean(); arrayDataHandle.setClean(); } #if MAYA_API_VERSION >= 201400 void OutputGeometryPart::computeVolume( const MTime &time, MDataHandle &volumeHandle ) { MDataHandle gridHandle = volumeHandle.child(AssetNode::outputPartVolumeGrid); MDataHandle transformHandle = volumeHandle.child(AssetNode::outputPartVolumeTransform); MDataHandle resHandle = volumeHandle.child(AssetNode::outputPartVolumeRes); MDataHandle nameHandle = volumeHandle.child(AssetNode::outputPartVolumeName); // grid { MObject gridDataObj = gridHandle.data(); MFnFloatArrayData gridDataFn(gridDataObj); if(gridDataObj.isNull()) { gridDataObj = gridDataFn.create(); gridHandle.setMObject(gridDataObj); } MFloatArray grid = gridDataFn.array(); int xres = myVolumeInfo.xLength; int yres = myVolumeInfo.yLength; int zres = myVolumeInfo.zLength; int tileSize = myVolumeInfo.tileSize; grid.setLength(xres * yres * zres); for(unsigned int i=0; i<grid.length(); i++) grid[i] = 0.0f; std::vector<float> tile; tile.resize(tileSize * tileSize * tileSize); HAPI_VolumeTileInfo tileInfo; HAPI_GetFirstVolumeTile(myAssetId, myObjectId, myGeoId, myPartId, &tileInfo); #ifdef max #undef max #endif while(tileInfo.minX != std::numeric_limits<int>::max() && tileInfo.minY != std::numeric_limits<int>::max() && tileInfo.minZ != std::numeric_limits<int>::max()) { HAPI_GetVolumeTileFloatData(myAssetId, myObjectId, myGeoId, myPartId, &tileInfo, &tile.front()); for(int k=0; k<tileSize; k++) for(int j=0; j<tileSize; j++) for(int i=0; i<tileSize; i++) { int z = k + tileInfo.minZ - myVolumeInfo.minZ, y = j + tileInfo.minY - myVolumeInfo.minY, x = i + tileInfo.minX - myVolumeInfo.minX; int index = xres * yres * z + xres * y + x; float value = tile[k * tileSize*tileSize + j * tileSize + i]; if(x < xres && y < yres && z < zres && x > 0 && y > 0 && z > 0) { grid[index] = value; } } HAPI_GetNextVolumeTile(myAssetId, myObjectId, myGeoId, myPartId, &tileInfo); } } // transform computeVolumeTransform(time, transformHandle); // resolution MFloatArray resolution; resolution.append(myVolumeInfo.xLength); resolution.append(myVolumeInfo.yLength); resolution.append(myVolumeInfo.zLength); MFnFloatArrayData resCreator; resHandle.set(resCreator.create(resolution)); // name nameHandle.set(Util::getString(myVolumeInfo.nameSH)); } #endif void OutputGeometryPart::computeMesh( const MTime &time, MDataHandle &hasMeshHandle, MDataHandle &meshHandle ) { MStatus status; hasMeshHandle.setBool(true); // create mesh MObject meshDataObj = meshHandle.data(); MFnMeshData meshDataFn(meshDataObj); if(meshDataObj.isNull()) { // set the MDataHandle meshDataObj = meshDataFn.create(); meshHandle.setMObject(meshDataObj); // then get the copy from MDataHandle meshDataObj = meshHandle.data(); meshDataFn.setObject(meshDataObj); } std::vector<float> floatArray; std::vector<int> intArray; // vertex array MFloatPointArray vertexArray; { getAttributeData(floatArray, "P", HAPI_ATTROWNER_POINT); // assume 3 tuple vertexArray.setLength(floatArray.size() / 3); for(unsigned int i = 0, length = vertexArray.length(); i < length; ++i) { MFloatPoint &floatPoint = vertexArray[i]; floatPoint.x = floatArray[i * 3 + 0]; floatPoint.y = floatArray[i * 3 + 1]; floatPoint.z = floatArray[i * 3 + 2]; floatPoint.w = 1.0f; } } // polygon counts MIntArray polygonCounts; { intArray.resize(myPartInfo.faceCount); if(myPartInfo.faceCount) { HAPI_GetFaceCounts( myAssetId, myObjectId, myGeoId, myPartId, &intArray.front(), 0, myPartInfo.faceCount ); } polygonCounts = MIntArray(&intArray.front(), intArray.size()); } // polygon connects MIntArray polygonConnects; { intArray.resize(myPartInfo.vertexCount); if(myPartInfo.vertexCount) { HAPI_GetVertexList( myAssetId, myObjectId, myGeoId, myPartId, &intArray.front(), 0, myPartInfo.vertexCount ); } polygonConnects = MIntArray(&intArray.front(), intArray.size()); Util::reverseWindingOrder(polygonConnects, polygonCounts); } MFnMesh meshFn; meshFn.create( vertexArray.length(), polygonCounts.length(), vertexArray, polygonCounts, polygonConnects, meshDataObj, &status ); CHECK_MSTATUS(status); // Check that the mesh created is what we tried to create. Assets could // output mesh with bad faces that Maya cannot handle. When this happens, // Maya would skip the bad faces, so the resulting mesh would be slightly // different. This makes it no longer possible to apply geometry attributes // (like UVs and color sets) to the mesh. { bool mismatch_topology = false; if(vertexArray.length() != (unsigned int) meshFn.numVertices()) { DISPLAY_WARNING( "Attempted to create ^1s vertices, but only ^2s vertices " "were created.", MString() + vertexArray.length(), MString() + meshFn.numVertices() ); mismatch_topology = true; } if(polygonCounts.length() != (unsigned int) meshFn.numPolygons()) { DISPLAY_WARNING( "Attempted to create ^1s polygons, but only ^2s polygons " "were created.", MString() + polygonCounts.length(), MString() + meshFn.numPolygons() ); mismatch_topology = true; } if(polygonConnects.length() != (unsigned int) meshFn.numFaceVertices()) { DISPLAY_WARNING( "Attempted to create ^1s face-vertices, but only ^2s " "face-vertices were created.", MString() + polygonConnects.length(), MString() + meshFn.numFaceVertices() ); mismatch_topology = true; } if(mismatch_topology) { DISPLAY_WARNING(MString( "This likely means that the Houdini Digital Asset is " "outputting bad geometry that Maya cannot handle. As a " "result, other attributes (such as UVs and color sets) " "cannot be transferred." )); return; } } // normal array if(polygonCounts.length()) { HAPI_AttributeOwner owner = HAPI_ATTROWNER_MAX; if(getAttributeData(floatArray, "N", HAPI_ATTROWNER_VERTEX)) { owner = HAPI_ATTROWNER_VERTEX; } else if(getAttributeData(floatArray, "N", HAPI_ATTROWNER_POINT)) { owner = HAPI_ATTROWNER_POINT; } if(owner != HAPI_ATTROWNER_MAX) { // assume 3 tuple MVectorArray normals( reinterpret_cast<float(*)[3]>(&floatArray.front()), floatArray.size() / 3); if(owner == HAPI_ATTROWNER_VERTEX) { Util::reverseWindingOrder(normals, polygonCounts); MIntArray faceList; faceList.setLength(polygonConnects.length()); for(unsigned int i = 0, j = 0, length = polygonCounts.length(); i < length; ++i) { for(int k = 0; k < polygonCounts[i]; ++j, ++k) { faceList[j] = i; } } meshFn.setFaceVertexNormals(normals, faceList, polygonConnects); } else if(owner == HAPI_ATTROWNER_POINT) { MIntArray vertexList; vertexList.setLength(vertexArray.length()); for(unsigned int i = 0, length = vertexList.length(); i < length; ++i) { vertexList[i] = i; } meshFn.setVertexNormals(normals, vertexList); } } } // uv if(polygonCounts.length()) { HAPI_AttributeOwner owner = HAPI_ATTROWNER_MAX; if(getAttributeData(floatArray, "uv", HAPI_ATTROWNER_VERTEX)) { owner = HAPI_ATTROWNER_VERTEX; } else if(getAttributeData(floatArray, "uv", HAPI_ATTROWNER_POINT)) { owner = HAPI_ATTROWNER_POINT; } if(owner != HAPI_ATTROWNER_MAX) { // assume 3 tuple MFloatArray uArray; MFloatArray vArray; uArray.setLength(floatArray.size() / 3); vArray.setLength(floatArray.size() / 3); for(unsigned int i = 0, length = uArray.length(); i < length; ++i) { uArray[i] = floatArray[i * 3 + 0]; vArray[i] = floatArray[i * 3 + 1]; } MIntArray vertexList; vertexList.setLength(polygonConnects.length()); if(owner == HAPI_ATTROWNER_VERTEX) { Util::reverseWindingOrder(uArray, polygonCounts); Util::reverseWindingOrder(vArray, polygonCounts); for(unsigned int i = 0, length = polygonConnects.length(); i < length; ++i) { vertexList[i] = i; } } else if(owner == HAPI_ATTROWNER_POINT) { for(unsigned int i = 0, length = polygonConnects.length(); i < length; ++i) { vertexList[i] = polygonConnects[i]; } } meshFn.setUVs(uArray, vArray); meshFn.assignUVs(polygonCounts, vertexList); } } // color and alpha if(polygonCounts.length()) { // Get color data HAPI_AttributeOwner colorOwner = HAPI_ATTROWNER_MAX; if(getAttributeData(floatArray, "Cd", HAPI_ATTROWNER_VERTEX)) { colorOwner = HAPI_ATTROWNER_VERTEX; } else if(getAttributeData(floatArray, "Cd", HAPI_ATTROWNER_POINT)) { colorOwner = HAPI_ATTROWNER_POINT; } else if(getAttributeData(floatArray, "Cd", HAPI_ATTROWNER_PRIM)) { colorOwner = HAPI_ATTROWNER_PRIM; } else if(getAttributeData(floatArray, "Cd", HAPI_ATTROWNER_DETAIL)) { colorOwner = HAPI_ATTROWNER_DETAIL; } HAPI_AttributeOwner alphaOwner = HAPI_ATTROWNER_MAX; std::vector<float> alphaArray; if(getAttributeData(alphaArray, "Alpha", HAPI_ATTROWNER_VERTEX)) { alphaOwner = HAPI_ATTROWNER_VERTEX; } else if(getAttributeData(alphaArray, "Alpha", HAPI_ATTROWNER_POINT)) { alphaOwner = HAPI_ATTROWNER_POINT; } else if(getAttributeData(alphaArray, "Alpha", HAPI_ATTROWNER_PRIM)) { alphaOwner = HAPI_ATTROWNER_PRIM; } else if(getAttributeData(alphaArray, "Alpha", HAPI_ATTROWNER_DETAIL)) { alphaOwner = HAPI_ATTROWNER_DETAIL; } if(colorOwner != HAPI_ATTROWNER_MAX || alphaOwner != HAPI_ATTROWNER_MAX) { // Convert to color array MColorArray colors(floatArray.size() / 3); if(colorOwner != HAPI_ATTROWNER_MAX) { for(unsigned int i = 0, length = colors.length(); i < length; ++i) { MColor &color = colors[i]; color.r = floatArray[i * 3 + 0]; color.g = floatArray[i * 3 + 1]; color.b = floatArray[i * 3 + 2]; } } HAPI_AttributeOwner owner; if((colorOwner == HAPI_ATTROWNER_POINT && alphaOwner == HAPI_ATTROWNER_PRIM) || (colorOwner == HAPI_ATTROWNER_PRIM && alphaOwner == HAPI_ATTROWNER_POINT)) { // Don't convert the prim attributes to point attributes, // because that would lose information. Convert everything to // vertex attributs instead. owner = HAPI_ATTROWNER_VERTEX; } else { if(colorOwner < alphaOwner) { owner = colorOwner; } else { owner = alphaOwner; } } if(owner == HAPI_ATTROWNER_DETAIL) { // Handle detail color and alpha as points owner = HAPI_ATTROWNER_POINT; } // If there's no color, then use a default color if(colorOwner == HAPI_ATTROWNER_MAX) { colorOwner = HAPI_ATTROWNER_DETAIL; colors.setLength(1); colors[0] = MColor(1.0f, 1.0f, 1.0f); } // If there's no alpha, then use a default alpha if(alphaOwner == HAPI_ATTROWNER_MAX) { alphaOwner = HAPI_ATTROWNER_DETAIL; alphaArray.resize(1); alphaArray[0] = 1.0f; } // Promte the attributes MColorArray promotedColors; Util::promoteAttributeData<0, 0, 3, float>( owner, promotedColors, colorOwner, colors, vertexArray.length(), &polygonCounts, &polygonConnects ); Util::promoteAttributeData<3, 0, 1, float>( owner, promotedColors, alphaOwner, alphaArray, vertexArray.length(), &polygonCounts, &polygonConnects ); if(owner == HAPI_ATTROWNER_VERTEX) { Util::reverseWindingOrder(promotedColors, polygonCounts); MIntArray faceList; faceList.setLength(polygonConnects.length()); for(unsigned int i = 0, j = 0, length = polygonCounts.length(); i < length; ++i) { for(int k = 0; k < polygonCounts[i]; ++j, ++k) { faceList[j] = i; } } meshFn.setFaceVertexColors(promotedColors, faceList, polygonConnects); } else if(owner == HAPI_ATTROWNER_POINT) { MIntArray vertexList; vertexList.setLength(vertexArray.length()); for(unsigned int i = 0, length = vertexList.length(); i < length; ++i) { vertexList[i] = i; } meshFn.setVertexColors(promotedColors, vertexList); } else if(owner == HAPI_ATTROWNER_PRIM) { MIntArray faceList; faceList.setLength(polygonCounts.length()); for(unsigned int i = 0, length = faceList.length(); i < length; ++i) { faceList[i] = i; } meshFn.setFaceColors(promotedColors, faceList); } } } } void OutputGeometryPart::computeMaterial( const MTime &time, MDataHandle& materialHandle ) { MDataHandle matExistsHandle = materialHandle.child(AssetNode::outputPartMaterialExists); MDataHandle nameHandle = materialHandle.child(AssetNode::outputPartMaterialName); MDataHandle ambientHandle = materialHandle.child(AssetNode::outputPartAmbientColor); MDataHandle diffuseHandle = materialHandle.child(AssetNode::outputPartDiffuseColor); MDataHandle specularHandle = materialHandle.child(AssetNode::outputPartSpecularColor); MDataHandle alphaHandle = materialHandle.child(AssetNode::outputPartAlphaColor); MDataHandle texturePathHandle = materialHandle.child(AssetNode::outputPartTexturePath); HAPI_GetMaterialOnPart( myAssetId, myObjectId, myGeoId, myPartId, &myMaterialInfo ); if(!myMaterialInfo.exists) { matExistsHandle.set(false); } else { // get material info HAPI_NodeInfo materialNodeInfo; HAPI_GetNodeInfo(myMaterialInfo.nodeId, &materialNodeInfo); std::vector<HAPI_ParmInfo> parms(materialNodeInfo.parmCount); HAPI_GetParameters(myMaterialInfo.nodeId, &parms[0], 0, materialNodeInfo.parmCount); int ambientParmIndex = Util::findParm(parms, "ogl_amb"); int diffuseParmIndex = Util::findParm(parms, "ogl_diff"); int alphaParmIndex = Util::findParm(parms, "ogl_alpha"); int specularParmIndex = Util::findParm(parms, "ogl_spec"); int texturePathSHParmIndex = Util::findParm(parms, "ogl_tex#", 1); float valueHolder[4]; matExistsHandle.set(true); nameHandle.setString( Util::getString(materialNodeInfo.nameSH) ); if(ambientParmIndex >= 0) { HAPI_GetParmFloatValues(myMaterialInfo.nodeId, valueHolder, parms[ambientParmIndex].floatValuesIndex, 3); ambientHandle.set3Float(valueHolder[0], valueHolder[1], valueHolder[2]); } if(specularParmIndex >= 0) { HAPI_GetParmFloatValues(myMaterialInfo.nodeId, valueHolder, parms[specularParmIndex].floatValuesIndex, 3); specularHandle.set3Float(valueHolder[0], valueHolder[1], valueHolder[2]); } if(diffuseParmIndex >= 0) { HAPI_GetParmFloatValues(myMaterialInfo.nodeId, valueHolder, parms[diffuseParmIndex].floatValuesIndex, 3); diffuseHandle.set3Float(valueHolder[0], valueHolder[1], valueHolder[2]); } if(alphaParmIndex >= 0) { HAPI_GetParmFloatValues(myMaterialInfo.nodeId, valueHolder, parms[alphaParmIndex].floatValuesIndex, 1); float alpha = 1 - valueHolder[0]; alphaHandle.set3Float(alpha, alpha, alpha); } if(texturePathSHParmIndex >= 0) { HAPI_ParmInfo texturePathParm; HAPI_GetParameters( myMaterialInfo.nodeId, &texturePathParm, texturePathSHParmIndex, 1 ); int texturePathSH; HAPI_GetParmStringValues( myMaterialInfo.nodeId, true, &texturePathSH, texturePathParm.stringValuesIndex, 1 ); bool hasTextureSource = Util::getString(texturePathSH).length() > 0; bool canRenderTexture = false; if(hasTextureSource) { HAPI_Result hapiResult; // this could fail if texture parameter is empty hapiResult = HAPI_RenderTextureToImage( myAssetId, myMaterialInfo.id, texturePathSHParmIndex ); canRenderTexture = hapiResult == HAPI_RESULT_SUCCESS; } int destinationFilePathSH = 0; if(canRenderTexture) { MString destinationFolderPath; MGlobal::executeCommand("workspace -expandName `workspace -q -fileRuleEntry sourceImages`;", destinationFolderPath); // this could fail if the image planes don't exist HAPI_ExtractImageToFile( myAssetId, myMaterialInfo.id, HAPI_PNG_FORMAT_NAME, "C A", destinationFolderPath.asChar(), NULL, &destinationFilePathSH ); } if(destinationFilePathSH > 0) { MString texturePath = Util::getString(destinationFilePathSH); texturePathHandle.set(texturePath); } } } materialHandle.setClean(); matExistsHandle.setClean(); ambientHandle.setClean(); diffuseHandle.setClean(); specularHandle.setClean(); alphaHandle.setClean(); texturePathHandle.setClean(); }
#include "Console.h" #include <iostream> #include <map> #include <vector> #include <sstream> #include <llvm/ADT/OwningPtr.h> #include <llvm/Support/MemoryBuffer.h> #include <llvm/Linker.h> #include <llvm/Module.h> #include <llvm/ModuleProvider.h> #include <llvm/DerivedTypes.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/GenericValue.h> #include <clang/AST/AST.h> #include <clang/Basic/LangOptions.h> #include <clang/Basic/SourceManager.h> #include <clang/Basic/TargetInfo.h> #include <clang/Frontend/CompileOptions.h> #include <clang/CodeGen/ModuleBuilder.h> #include <clang/Lex/Preprocessor.h> #include "ClangUtils.h" #include "Diagnostics.h" #include "InternalCommands.h" #include "Parser.h" #include "SrcGen.h" #include "StringUtils.h" #include "Visitors.h" using std::string; namespace ccons { Console::Console(bool debugMode, std::ostream& out, std::ostream& err) : _debugMode(debugMode), _out(out), _err(err), _raw_err(err), _prompt(">>> ") { _options.C99 = true; _parser.reset(new Parser(_options)); // Declare exit() so users may call it without needing to #include <stdio.h> _lines.push_back(CodeLine("void exit(int status);", DeclLine)); } Console::~Console() { if (_linker) _linker->releaseModule(); } const char * Console::prompt() const { return _prompt.c_str(); } const char * Console::input() const { return _input.c_str(); } void Console::reportInputError() { _err << "\nNote: Last line ignored due to errors.\n"; } string Console::genSource(string appendix) const { string src; for (unsigned i = 0; i < _lines.size(); ++i) { if (_lines[i].second == PrprLine) { src += _lines[i].first; src += "\n"; } else if (_lines[i].second == DeclLine) { src += _lines[i].first; src += "\n"; } } src += appendix; return src; } int Console::splitInput(const string& source, const string& input, std::vector<string> *statements) { string src = source; src += "void __ccons_internal() {\n"; const unsigned pos = src.length(); src += input; src += "\n}\n"; // Set offset on the diagnostics provider. _dp->setOffset(pos); std::vector<clang::Stmt*> stmts; ParseOperation *parseOp = _parser->createParseOperation(_dp->getDiagnostic()); clang::SourceManager *sm = parseOp->getSourceManager(); StmtSplitter splitter(src, *sm, _options, &stmts); clang::ASTContext *ast = parseOp->getASTContext(); FunctionBodyConsumer<StmtSplitter> consumer(&splitter, ast, "__ccons_internal"); if (_debugMode) oprintf(_err, "Parsing in splitInput()...\n"); _parser->parse(src, parseOp, &consumer); statements->clear(); if (_dp->getDiagnostic()->hasErrorOccurred()) { reportInputError(); return 0; } else if (stmts.size() == 1) { statements->push_back(input); } else { for (unsigned i = 0; i < stmts.size(); i++) { SrcRange range = getStmtRangeWithSemicolon(stmts[i], *sm, _options); string s = src.substr(range.first, range.second - range.first); if (_debugMode) oprintf(_err, "Split %d is: %s\n", i, s.c_str()); statements->push_back(s); } } return stmts.size(); } clang::Stmt * Console::lineToStmt(const std::string& line, std::string *src) { *src += "void __ccons_internal() {\n"; const unsigned pos = src->length(); *src += line; *src += "\n}\n"; // Set offset on the diagnostics provider. _dp->setOffset(pos); ParseOperation *parseOp = _parser->createParseOperation(_dp->getDiagnostic()); StmtFinder finder(pos, *parseOp->getSourceManager()); clang::ASTContext *ast = parseOp->getASTContext(); FunctionBodyConsumer<StmtFinder> consumer(&finder, ast, "__ccons_internal"); if (_debugMode) oprintf(_err, "Parsing in lineToStmt()...\n"); _parser->parse(*src, parseOp, &consumer); if (_dp->getDiagnostic()->hasErrorOccurred()) { src->clear(); return NULL; } return finder.getStmt(); } void Console::printGV(const llvm::Function *F, const llvm::GenericValue& GV, const clang::QualType& QT) const { const char *type = QT.getAsString().c_str(); const llvm::FunctionType *FTy = F->getFunctionType(); const llvm::Type *RetTy = FTy->getReturnType(); switch (RetTy->getTypeID()) { case llvm::Type::IntegerTyID: if (QT->isUnsignedIntegerType()) oprintf(_out, "=> (%s) %lu\n", type, GV.IntVal.getZExtValue()); else oprintf(_out, "=> (%s) %ld\n", type, GV.IntVal.getZExtValue()); return; case llvm::Type::FloatTyID: oprintf(_out, "=> (%s) %f\n", type, GV.FloatVal); return; case llvm::Type::DoubleTyID: oprintf(_out, "=> (%s) %lf\n", type, GV.DoubleVal); return; case llvm::Type::PointerTyID: { void *p = GVTOP(GV); // FIXME: this is a hack if (p && !strncmp(type, "char", 4)) { oprintf(_out, "=> (%s) \"%s\"\n", type, p); } else if (QT->isFunctionType()) { string str = "*"; QT.getUnqualifiedType().getAsStringInternal(str); type = str.c_str(); oprintf(_out, "=> (%s) %p\n", type, p); } else { oprintf(_out, "=> (%s) %p\n", type, p); } return; } case llvm::Type::VoidTyID: if (strcmp(type, "void")) oprintf(_out, "=> (%s)\n", type); return; default: break; } assert(0 && "Unknown return type!"); } bool Console::handleDeclStmt(const clang::DeclStmt *DS, const string& src, string *appendix, string *funcBody, std::vector<CodeLine> *moreLines) { bool initializers = false; for (clang::DeclStmt::const_decl_iterator D = DS->decl_begin(), E = DS->decl_end(); D != E; ++D) { if (const clang::VarDecl *VD = dyn_cast<clang::VarDecl>(*D)) { if (VD->getInit()) { initializers = true; } } } if (initializers) { std::vector<string> decls; std::vector<string> stmts; clang::SourceManager *sm = _parser->getLastParseOperation()->getSourceManager(); clang::ASTContext *context = _parser->getLastParseOperation()->getASTContext(); for (clang::DeclStmt::const_decl_iterator D = DS->decl_begin(), E = DS->decl_end(); D != E; ++D) { if (const clang::VarDecl *VD = dyn_cast<clang::VarDecl>(*D)) { string decl = genVarDecl(VD->getType(), VD->getNameAsCString()); if (const clang::Expr *I = VD->getInit()) { SrcRange range = getStmtRange(I, *sm, _options); if (I->isConstantInitializer(*context)) { // Keep the whole thing in the global context. std::stringstream global; global << decl << " = "; global << src.substr(range.first, range.second - range.first); *appendix += global.str() + ";\n"; } else if (const clang::InitListExpr *ILE = dyn_cast<clang::InitListExpr>(I)) { // If it's an InitListExpr like {'a','b','c'}, but with non-constant // initializers, then split it up into x[0] = 'a'; x[1] = 'b'; and // so forth, which would go in the function body, while making the // declaration global. unsigned numInits = ILE->getNumInits(); for (unsigned i = 0; i < numInits; i++) { std::stringstream stmt; stmt << VD->getNameAsCString() << "[" << i << "] = "; range = getStmtRange(ILE->getInit(i), *sm, _options); stmt << src.substr(range.first, range.second - range.first) << ";"; stmts.push_back(stmt.str()); } *appendix += decl + ";\n"; } else { std::stringstream stmt; stmt << VD->getNameAsCString() << " = " << src.substr(range.first, range.second - range.first) << ";"; stmts.push_back(stmt.str()); *appendix += decl + ";\n"; } } else { // Just add it as a definition without an initializer. *appendix += decl + ";\n"; } decls.push_back(decl + ";"); } } for (unsigned i = 0; i < decls.size(); ++i) moreLines->push_back(CodeLine("extern " + decls[i], DeclLine)); for (unsigned i = 0; i < stmts.size(); ++i) { moreLines->push_back(CodeLine(stmts[i], StmtLine)); *funcBody += stmts[i] + "\n"; } return true; } return false; } string Console::genAppendix(const char *source, const char *line, string *fName, clang::QualType& QT, std::vector<CodeLine> *moreLines, bool *hadErrors) { bool wasExpr = false; string appendix; string funcBody; string src = source; while (isspace(*line)) line++; *hadErrors = false; if (*line == '#') { moreLines->push_back(CodeLine(line, PrprLine)); appendix += line; } else if (const clang::Stmt *S = lineToStmt(line, &src)) { if (_debugMode) oprintf(_err, "Found Stmt for input.\n"); if (const clang::Expr *E = dyn_cast<clang::Expr>(S)) { QT = E->getType(); funcBody = line; moreLines->push_back(CodeLine(line, StmtLine)); wasExpr = true; } else if (const clang::DeclStmt *DS = dyn_cast<clang::DeclStmt>(S)) { if (!handleDeclStmt(DS, src, &appendix, &funcBody, moreLines)) { moreLines->push_back(CodeLine(line, DeclLine)); appendix += line; appendix += "\n"; } } else { funcBody = line; // ex: if statement moreLines->push_back(CodeLine(line, StmtLine)); } } else if (src.empty()) { reportInputError(); *hadErrors = true; } if (!funcBody.empty()) { int funcNo = 0; for (unsigned i = 0; i < _lines.size(); ++i) funcNo += (_lines[i].second == StmtLine); *fName = "__ccons_anon" + to_string(funcNo); int bodyOffset; clang::ASTContext *context = _parser->getLastParseOperation()->getASTContext(); appendix += genFunc(wasExpr ? &QT : NULL, context, *fName, funcBody, bodyOffset); _dp->setOffset(bodyOffset + strlen(source)); if (_debugMode) oprintf(_err, "Generating function %s()...\n", fName->c_str()); } return appendix; } void Console::process(const char *line) { std::vector<CodeLine> linesToAppend; bool hadErrors = false; string appendix; if (_buffer.empty() && HandleInternalCommand(line, _debugMode, _out, _err)) return; string src = genSource(""); _buffer += line; Parser p(_options); int indentLevel; std::vector<clang::FunctionDecl *> fnDecls; bool shouldBeTopLevel = false; switch (p.analyzeInput(src, _buffer, indentLevel, &fnDecls)) { case Parser::Incomplete: _input = string(indentLevel * 2, ' '); _prompt = "... "; return; case Parser::TopLevel: shouldBeTopLevel = true; case Parser::Stmt: _prompt = ">>> "; _input = ""; break; } _dp.reset(new DiagnosticsProvider(_raw_err, _options)); if (shouldBeTopLevel) { if (_debugMode) oprintf(_err, "Treating input as top-level.\n"); appendix = _buffer; for (unsigned i = 0; i < fnDecls.size(); ++i) linesToAppend.push_back(CodeLine(getFunctionDeclAsString(fnDecls[i]), DeclLine)); _buffer.clear(); if (hadErrors) return; src = genSource(appendix); string empty; clang::QualType retType(0, 0); if (compileLinkAndRun(src, empty, retType)) { for (unsigned i = 0; i < linesToAppend.size(); ++i) _lines.push_back(linesToAppend[i]); } } else { if (_debugMode) oprintf(_err, "Treating input as function-level.\n"); std::vector<string> split; if (_buffer[0] == '#') { split.push_back(_buffer); } else { string input = _buffer; splitInput(src, input, &split); } _buffer.clear(); for (unsigned i = 0; i < split.size(); i++) { string fName; clang::QualType retType(0, 0); appendix = genAppendix(src.c_str(), split[i].c_str(), &fName, retType, &linesToAppend, &hadErrors); if (hadErrors) return; src = genSource(appendix); if (compileLinkAndRun(src, fName, retType)) { for (unsigned i = 0; i < linesToAppend.size(); ++i) { _lines.push_back(linesToAppend[i]); } } } } _parser->releaseAccumulatedParseOperations(); } bool Console::compileLinkAndRun(const string& src, const string& fName, const clang::QualType& retType) { if (_debugMode) oprintf(_err, "Running code-generator.\n"); llvm::OwningPtr<clang::CodeGenerator> codegen; clang::CompileOptions compileOptions; codegen.reset(CreateLLVMCodeGen(*_dp->getDiagnostic(), "-", compileOptions)); if (_debugMode) oprintf(_err, "Parsing in compileLinkAndRun()...\n"); _parser->parse(src, _dp->getDiagnostic(), codegen.get()); if (_dp->getDiagnostic()->hasErrorOccurred()) { reportInputError(); return false; } llvm::Module *module = codegen->ReleaseModule(); if (module) { if (!_linker) _linker.reset(new llvm::Linker("ccons", "ccons")); string error; _linker->LinkInModule(module, &error); if (!error.empty()) oprintf(_err, "Error: %s\n", error.c_str()); // link it with the existing ones if (!fName.empty()) { module = _linker->getModule(); if (!_engine) _engine.reset(llvm::ExecutionEngine::create(module)); llvm::Function *F = module->getFunction(fName.c_str()); assert(F && "Function was not found!"); std::vector<llvm::GenericValue> params; if (_debugMode) oprintf(_err, "Calling function %s()...\n", fName.c_str()); llvm::GenericValue result = _engine->runFunction(F, params); if (retType.getTypePtr()) printGV(F, result, retType); } else { if (_debugMode) oprintf(_err, "Code generation done; function call not needed.\n"); } } else { if (_debugMode) oprintf(_err, "Could not release module.\n"); } return true; } } // namespace ccons no longer need to always create new parsers #include "Console.h" #include <iostream> #include <map> #include <vector> #include <sstream> #include <llvm/ADT/OwningPtr.h> #include <llvm/Support/MemoryBuffer.h> #include <llvm/Linker.h> #include <llvm/Module.h> #include <llvm/ModuleProvider.h> #include <llvm/DerivedTypes.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/GenericValue.h> #include <clang/AST/AST.h> #include <clang/Basic/LangOptions.h> #include <clang/Basic/SourceManager.h> #include <clang/Basic/TargetInfo.h> #include <clang/Frontend/CompileOptions.h> #include <clang/CodeGen/ModuleBuilder.h> #include <clang/Lex/Preprocessor.h> #include "ClangUtils.h" #include "Diagnostics.h" #include "InternalCommands.h" #include "Parser.h" #include "SrcGen.h" #include "StringUtils.h" #include "Visitors.h" using std::string; namespace ccons { Console::Console(bool debugMode, std::ostream& out, std::ostream& err) : _debugMode(debugMode), _out(out), _err(err), _raw_err(err), _prompt(">>> ") { _options.C99 = true; _parser.reset(new Parser(_options)); // Declare exit() so users may call it without needing to #include <stdio.h> _lines.push_back(CodeLine("void exit(int status);", DeclLine)); } Console::~Console() { if (_linker) _linker->releaseModule(); } const char * Console::prompt() const { return _prompt.c_str(); } const char * Console::input() const { return _input.c_str(); } void Console::reportInputError() { _err << "\nNote: Last line ignored due to errors.\n"; } string Console::genSource(string appendix) const { string src; for (unsigned i = 0; i < _lines.size(); ++i) { if (_lines[i].second == PrprLine) { src += _lines[i].first; src += "\n"; } else if (_lines[i].second == DeclLine) { src += _lines[i].first; src += "\n"; } } src += appendix; return src; } int Console::splitInput(const string& source, const string& input, std::vector<string> *statements) { string src = source; src += "void __ccons_internal() {\n"; const unsigned pos = src.length(); src += input; src += "\n}\n"; // Set offset on the diagnostics provider. _dp->setOffset(pos); std::vector<clang::Stmt*> stmts; ParseOperation *parseOp = _parser->createParseOperation(_dp->getDiagnostic()); clang::SourceManager *sm = parseOp->getSourceManager(); StmtSplitter splitter(src, *sm, _options, &stmts); clang::ASTContext *ast = parseOp->getASTContext(); FunctionBodyConsumer<StmtSplitter> consumer(&splitter, ast, "__ccons_internal"); if (_debugMode) oprintf(_err, "Parsing in splitInput()...\n"); _parser->parse(src, parseOp, &consumer); statements->clear(); if (_dp->getDiagnostic()->hasErrorOccurred()) { reportInputError(); return 0; } else if (stmts.size() == 1) { statements->push_back(input); } else { for (unsigned i = 0; i < stmts.size(); i++) { SrcRange range = getStmtRangeWithSemicolon(stmts[i], *sm, _options); string s = src.substr(range.first, range.second - range.first); if (_debugMode) oprintf(_err, "Split %d is: %s\n", i, s.c_str()); statements->push_back(s); } } return stmts.size(); } clang::Stmt * Console::lineToStmt(const std::string& line, std::string *src) { *src += "void __ccons_internal() {\n"; const unsigned pos = src->length(); *src += line; *src += "\n}\n"; // Set offset on the diagnostics provider. _dp->setOffset(pos); ParseOperation *parseOp = _parser->createParseOperation(_dp->getDiagnostic()); StmtFinder finder(pos, *parseOp->getSourceManager()); clang::ASTContext *ast = parseOp->getASTContext(); FunctionBodyConsumer<StmtFinder> consumer(&finder, ast, "__ccons_internal"); if (_debugMode) oprintf(_err, "Parsing in lineToStmt()...\n"); _parser->parse(*src, parseOp, &consumer); if (_dp->getDiagnostic()->hasErrorOccurred()) { src->clear(); return NULL; } return finder.getStmt(); } void Console::printGV(const llvm::Function *F, const llvm::GenericValue& GV, const clang::QualType& QT) const { const char *type = QT.getAsString().c_str(); const llvm::FunctionType *FTy = F->getFunctionType(); const llvm::Type *RetTy = FTy->getReturnType(); switch (RetTy->getTypeID()) { case llvm::Type::IntegerTyID: if (QT->isUnsignedIntegerType()) oprintf(_out, "=> (%s) %lu\n", type, GV.IntVal.getZExtValue()); else oprintf(_out, "=> (%s) %ld\n", type, GV.IntVal.getZExtValue()); return; case llvm::Type::FloatTyID: oprintf(_out, "=> (%s) %f\n", type, GV.FloatVal); return; case llvm::Type::DoubleTyID: oprintf(_out, "=> (%s) %lf\n", type, GV.DoubleVal); return; case llvm::Type::PointerTyID: { void *p = GVTOP(GV); // FIXME: this is a hack if (p && !strncmp(type, "char", 4)) { oprintf(_out, "=> (%s) \"%s\"\n", type, p); } else if (QT->isFunctionType()) { string str = "*"; QT.getUnqualifiedType().getAsStringInternal(str); type = str.c_str(); oprintf(_out, "=> (%s) %p\n", type, p); } else { oprintf(_out, "=> (%s) %p\n", type, p); } return; } case llvm::Type::VoidTyID: if (strcmp(type, "void")) oprintf(_out, "=> (%s)\n", type); return; default: break; } assert(0 && "Unknown return type!"); } bool Console::handleDeclStmt(const clang::DeclStmt *DS, const string& src, string *appendix, string *funcBody, std::vector<CodeLine> *moreLines) { bool initializers = false; for (clang::DeclStmt::const_decl_iterator D = DS->decl_begin(), E = DS->decl_end(); D != E; ++D) { if (const clang::VarDecl *VD = dyn_cast<clang::VarDecl>(*D)) { if (VD->getInit()) { initializers = true; } } } if (initializers) { std::vector<string> decls; std::vector<string> stmts; clang::SourceManager *sm = _parser->getLastParseOperation()->getSourceManager(); clang::ASTContext *context = _parser->getLastParseOperation()->getASTContext(); for (clang::DeclStmt::const_decl_iterator D = DS->decl_begin(), E = DS->decl_end(); D != E; ++D) { if (const clang::VarDecl *VD = dyn_cast<clang::VarDecl>(*D)) { string decl = genVarDecl(VD->getType(), VD->getNameAsCString()); if (const clang::Expr *I = VD->getInit()) { SrcRange range = getStmtRange(I, *sm, _options); if (I->isConstantInitializer(*context)) { // Keep the whole thing in the global context. std::stringstream global; global << decl << " = "; global << src.substr(range.first, range.second - range.first); *appendix += global.str() + ";\n"; } else if (const clang::InitListExpr *ILE = dyn_cast<clang::InitListExpr>(I)) { // If it's an InitListExpr like {'a','b','c'}, but with non-constant // initializers, then split it up into x[0] = 'a'; x[1] = 'b'; and // so forth, which would go in the function body, while making the // declaration global. unsigned numInits = ILE->getNumInits(); for (unsigned i = 0; i < numInits; i++) { std::stringstream stmt; stmt << VD->getNameAsCString() << "[" << i << "] = "; range = getStmtRange(ILE->getInit(i), *sm, _options); stmt << src.substr(range.first, range.second - range.first) << ";"; stmts.push_back(stmt.str()); } *appendix += decl + ";\n"; } else { std::stringstream stmt; stmt << VD->getNameAsCString() << " = " << src.substr(range.first, range.second - range.first) << ";"; stmts.push_back(stmt.str()); *appendix += decl + ";\n"; } } else { // Just add it as a definition without an initializer. *appendix += decl + ";\n"; } decls.push_back(decl + ";"); } } for (unsigned i = 0; i < decls.size(); ++i) moreLines->push_back(CodeLine("extern " + decls[i], DeclLine)); for (unsigned i = 0; i < stmts.size(); ++i) { moreLines->push_back(CodeLine(stmts[i], StmtLine)); *funcBody += stmts[i] + "\n"; } return true; } return false; } string Console::genAppendix(const char *source, const char *line, string *fName, clang::QualType& QT, std::vector<CodeLine> *moreLines, bool *hadErrors) { bool wasExpr = false; string appendix; string funcBody; string src = source; while (isspace(*line)) line++; *hadErrors = false; if (*line == '#') { moreLines->push_back(CodeLine(line, PrprLine)); appendix += line; } else if (const clang::Stmt *S = lineToStmt(line, &src)) { if (_debugMode) oprintf(_err, "Found Stmt for input.\n"); if (const clang::Expr *E = dyn_cast<clang::Expr>(S)) { QT = E->getType(); funcBody = line; moreLines->push_back(CodeLine(line, StmtLine)); wasExpr = true; } else if (const clang::DeclStmt *DS = dyn_cast<clang::DeclStmt>(S)) { if (!handleDeclStmt(DS, src, &appendix, &funcBody, moreLines)) { moreLines->push_back(CodeLine(line, DeclLine)); appendix += line; appendix += "\n"; } } else { funcBody = line; // ex: if statement moreLines->push_back(CodeLine(line, StmtLine)); } } else if (src.empty()) { reportInputError(); *hadErrors = true; } if (!funcBody.empty()) { int funcNo = 0; for (unsigned i = 0; i < _lines.size(); ++i) funcNo += (_lines[i].second == StmtLine); *fName = "__ccons_anon" + to_string(funcNo); int bodyOffset; clang::ASTContext *context = _parser->getLastParseOperation()->getASTContext(); appendix += genFunc(wasExpr ? &QT : NULL, context, *fName, funcBody, bodyOffset); _dp->setOffset(bodyOffset + strlen(source)); if (_debugMode) oprintf(_err, "Generating function %s()...\n", fName->c_str()); } return appendix; } void Console::process(const char *line) { std::vector<CodeLine> linesToAppend; bool hadErrors = false; string appendix; if (_buffer.empty() && HandleInternalCommand(line, _debugMode, _out, _err)) return; string src = genSource(""); _buffer += line; int indentLevel; std::vector<clang::FunctionDecl *> fnDecls; bool shouldBeTopLevel = false; switch (_parser->analyzeInput(src, _buffer, indentLevel, &fnDecls)) { case Parser::Incomplete: _input = string(indentLevel * 2, ' '); _prompt = "... "; return; case Parser::TopLevel: shouldBeTopLevel = true; case Parser::Stmt: _prompt = ">>> "; _input = ""; break; } _dp.reset(new DiagnosticsProvider(_raw_err, _options)); if (shouldBeTopLevel) { if (_debugMode) oprintf(_err, "Treating input as top-level.\n"); appendix = _buffer; for (unsigned i = 0; i < fnDecls.size(); ++i) linesToAppend.push_back(CodeLine(getFunctionDeclAsString(fnDecls[i]), DeclLine)); _buffer.clear(); if (hadErrors) return; src = genSource(appendix); string empty; clang::QualType retType(0, 0); if (compileLinkAndRun(src, empty, retType)) { for (unsigned i = 0; i < linesToAppend.size(); ++i) _lines.push_back(linesToAppend[i]); } } else { if (_debugMode) oprintf(_err, "Treating input as function-level.\n"); std::vector<string> split; if (_buffer[0] == '#') { split.push_back(_buffer); } else { string input = _buffer; splitInput(src, input, &split); } _buffer.clear(); for (unsigned i = 0; i < split.size(); i++) { string fName; clang::QualType retType(0, 0); appendix = genAppendix(src.c_str(), split[i].c_str(), &fName, retType, &linesToAppend, &hadErrors); if (hadErrors) return; src = genSource(appendix); if (compileLinkAndRun(src, fName, retType)) { for (unsigned i = 0; i < linesToAppend.size(); ++i) { _lines.push_back(linesToAppend[i]); } } } } _parser->releaseAccumulatedParseOperations(); } bool Console::compileLinkAndRun(const string& src, const string& fName, const clang::QualType& retType) { if (_debugMode) oprintf(_err, "Running code-generator.\n"); llvm::OwningPtr<clang::CodeGenerator> codegen; clang::CompileOptions compileOptions; codegen.reset(CreateLLVMCodeGen(*_dp->getDiagnostic(), "-", compileOptions)); if (_debugMode) oprintf(_err, "Parsing in compileLinkAndRun()...\n"); _parser->parse(src, _dp->getDiagnostic(), codegen.get()); if (_dp->getDiagnostic()->hasErrorOccurred()) { reportInputError(); return false; } llvm::Module *module = codegen->ReleaseModule(); if (module) { if (!_linker) _linker.reset(new llvm::Linker("ccons", "ccons")); string error; _linker->LinkInModule(module, &error); if (!error.empty()) oprintf(_err, "Error: %s\n", error.c_str()); // link it with the existing ones if (!fName.empty()) { module = _linker->getModule(); if (!_engine) _engine.reset(llvm::ExecutionEngine::create(module)); llvm::Function *F = module->getFunction(fName.c_str()); assert(F && "Function was not found!"); std::vector<llvm::GenericValue> params; if (_debugMode) oprintf(_err, "Calling function %s()...\n", fName.c_str()); llvm::GenericValue result = _engine->runFunction(F, params); if (retType.getTypePtr()) printGV(F, result, retType); } else { if (_debugMode) oprintf(_err, "Code generation done; function call not needed.\n"); } } else { if (_debugMode) oprintf(_err, "Could not release module.\n"); } return true; } } // namespace ccons
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: uicommanddescription.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:59:35 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_UIELEMENT_UICOMMANDDESCRPTION_HXX_ #include "uielement/uicommanddescription.hxx" #endif #ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_ #include <threadhelp/resetableguard.hxx> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include "services.h" #endif #include "properties.h" //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_ #include <com/sun/star/container/XContainer.hpp> #endif //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _UTL_CONFIGMGR_HXX_ #include <unotools/configmgr.hxx> #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _VCL_MNEMONIC_HXX_ #include <vcl/mnemonic.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _RTL_LOGFILE_HXX_ #include <rtl/logfile.hxx> #endif //_________________________________________________________________________________________________________________ // Defines //_________________________________________________________________________________________________________________ // using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::container; using namespace ::com::sun::star::frame; //_________________________________________________________________________________________________________________ // Namespace //_________________________________________________________________________________________________________________ // struct ModuleToCommands { const char* pModuleId; const char* pCommands; }; static const char GENERIC_UICOMMANDS[] = "generic"; static const char COMMANDS[] = "Commands"; static const char CONFIGURATION_ROOT_ACCESS[] = "/org.openoffice.Office.UI."; static const char CONFIGURATION_CMD_ELEMENT_ACCESS[] = "/UserInterface/Commands"; static const char CONFIGURATION_POP_ELEMENT_ACCESS[] = "/UserInterface/Popups"; static const char CONFIGURATION_PROPERTY_LABEL[] = "Label"; static const char CONFIGURATION_PROPERTY_CONTEXT_LABEL[] = "ContextLabel"; // Property names of the resulting Property Set static const char PROPSET_LABEL[] = "Label"; static const char PROPSET_NAME[] = "Name"; static const char PROPSET_POPUP[] = "Popup"; static const char PROPSET_PROPERTIES[] = "Properties"; // Special resource URLs to retrieve additional information static const char PRIVATE_RESOURCE_URL[] = "private:"; const sal_Int32 COMMAND_PROPERTY_IMAGE = 1; const sal_Int32 COMMAND_PROPERTY_ROTATE = 2; const sal_Int32 COMMAND_PROPERTY_MIRROR = 4; namespace framework { //***************************************************************************************************************** // Configuration access class for PopupMenuControllerFactory implementation //***************************************************************************************************************** class ConfigurationAccess_UICommand : // interfaces public XTypeProvider , public XNameAccess , public XContainerListener , // baseclasses // Order is neccessary for right initialization! private ThreadHelpBase , public ::cppu::OWeakObject { public: ConfigurationAccess_UICommand( const ::rtl::OUString& aModuleName, const Reference< XNameAccess >& xGenericUICommands, const Reference< XMultiServiceFactory >& rServiceManager ); virtual ~ConfigurationAccess_UICommand(); // XInterface, XTypeProvider DECLARE_XINTERFACE DECLARE_XTYPEPROVIDER // XNameAccess virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames() throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException); // XElementAccess virtual ::com::sun::star::uno::Type SAL_CALL getElementType() throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasElements() throw (::com::sun::star::uno::RuntimeException); // container.XContainerListener virtual void SAL_CALL elementInserted( const ContainerEvent& aEvent ) throw(RuntimeException); virtual void SAL_CALL elementRemoved ( const ContainerEvent& aEvent ) throw(RuntimeException); virtual void SAL_CALL elementReplaced( const ContainerEvent& aEvent ) throw(RuntimeException); // lang.XEventListener virtual void SAL_CALL disposing( const EventObject& aEvent ) throw(RuntimeException); protected: struct CmdToInfoMap { CmdToInfoMap() : bPopup( sal_False ), bCommandNameCreated( sal_False ), nProperties( 0 ) {} rtl::OUString aLabel; rtl::OUString aContextLabel; rtl::OUString aCommandName; sal_Bool bPopup : 1, bCommandNameCreated : 1; sal_Int32 nProperties; }; Any getSequenceFromCache( const rtl::OUString& aCommandURL ); Any getInfoFromCommand( const rtl::OUString& rCommandURL ); void fillInfoFromResult( CmdToInfoMap& rCmdInfo, const rtl::OUString& aLabel ); Any getUILabelFromCommand( const rtl::OUString& rCommandURL ); Sequence< rtl::OUString > getAllCommands(); void resetCache(); sal_Bool fillCache(); sal_Bool addGenericInfoToCache(); private: typedef ::std::hash_map< ::rtl::OUString, CmdToInfoMap, OUStringHashCode, ::std::equal_to< ::rtl::OUString > > CommandToInfoCache; sal_Bool initializeConfigAccess(); rtl::OUString m_aConfigCmdAccess; rtl::OUString m_aConfigPopupAccess; rtl::OUString m_aPropUILabel; rtl::OUString m_aPropUIContextLabel; rtl::OUString m_aPropLabel; rtl::OUString m_aPropName; rtl::OUString m_aPropPopup; rtl::OUString m_aPropProperties; rtl::OUString m_aBrandName; rtl::OUString m_aXMLFileFormatVersion; rtl::OUString m_aVersion; rtl::OUString m_aExtension; rtl::OUString m_aPrivateResourceURL; Reference< XNameAccess > m_xGenericUICommands; Reference< XMultiServiceFactory > m_xServiceManager; Reference< XMultiServiceFactory > m_xConfigProvider; Reference< XMultiServiceFactory > m_xConfigProviderPopups; Reference< XNameAccess > m_xConfigAccess; Reference< XNameAccess > m_xConfigAccessPopups; Sequence< rtl::OUString > m_aCommandImageList; Sequence< rtl::OUString > m_aCommandRotateImageList; Sequence< rtl::OUString > m_aCommandMirrorImageList; CommandToInfoCache m_aCmdInfoCache; sal_Bool m_bConfigAccessInitialized; sal_Bool m_bCacheFilled; sal_Bool m_bGenericDataRetrieved; }; //***************************************************************************************************************** // XInterface, XTypeProvider //***************************************************************************************************************** DEFINE_XINTERFACE_5 ( ConfigurationAccess_UICommand , OWeakObject , DIRECT_INTERFACE ( css::container::XNameAccess ), DIRECT_INTERFACE ( css::container::XContainerListener ), DIRECT_INTERFACE ( css::lang::XTypeProvider ), DERIVED_INTERFACE( css::container::XElementAccess, css::container::XNameAccess ), DERIVED_INTERFACE( css::lang::XEventListener, XContainerListener ) ) DEFINE_XTYPEPROVIDER_5 ( ConfigurationAccess_UICommand , css::container::XNameAccess , css::container::XElementAccess , css::container::XContainerListener , css::lang::XTypeProvider , css::lang::XEventListener ) ConfigurationAccess_UICommand::ConfigurationAccess_UICommand( const rtl::OUString& aModuleName, const Reference< XNameAccess >& rGenericUICommands, const Reference< XMultiServiceFactory >& rServiceManager ) : ThreadHelpBase(), m_xServiceManager( rServiceManager ), m_aPropUILabel( RTL_CONSTASCII_USTRINGPARAM( CONFIGURATION_PROPERTY_LABEL )), m_aPropUIContextLabel( RTL_CONSTASCII_USTRINGPARAM( CONFIGURATION_PROPERTY_CONTEXT_LABEL )), m_bConfigAccessInitialized( sal_False ), m_bCacheFilled( sal_False ), m_bGenericDataRetrieved( sal_False ), m_aConfigCmdAccess( RTL_CONSTASCII_USTRINGPARAM( CONFIGURATION_ROOT_ACCESS )), m_aConfigPopupAccess( RTL_CONSTASCII_USTRINGPARAM( CONFIGURATION_ROOT_ACCESS )), m_aPropLabel( RTL_CONSTASCII_USTRINGPARAM( PROPSET_LABEL )), m_aPropName( RTL_CONSTASCII_USTRINGPARAM( PROPSET_NAME )), m_aPropPopup( RTL_CONSTASCII_USTRINGPARAM( PROPSET_POPUP )), m_aPropProperties( RTL_CONSTASCII_USTRINGPARAM( PROPSET_PROPERTIES )), m_aPrivateResourceURL( RTL_CONSTASCII_USTRINGPARAM( PRIVATE_RESOURCE_URL )), m_xGenericUICommands( rGenericUICommands ) { // Create configuration hierachical access name m_aConfigCmdAccess += aModuleName; m_aConfigCmdAccess += rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( CONFIGURATION_CMD_ELEMENT_ACCESS )); m_xConfigProvider = Reference< XMultiServiceFactory >( rServiceManager->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationProvider" ))), UNO_QUERY ); m_aConfigPopupAccess += aModuleName; m_aConfigPopupAccess += rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( CONFIGURATION_POP_ELEMENT_ACCESS )); m_xConfigProviderPopups = Reference< XMultiServiceFactory >( rServiceManager->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationProvider" ))), UNO_QUERY ); Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME ); rtl::OUString aTmp; aRet >>= aTmp; m_aBrandName = aTmp; } ConfigurationAccess_UICommand::~ConfigurationAccess_UICommand() { // SAFE ResetableGuard aLock( m_aLock ); Reference< XContainer > xContainer( m_xConfigAccess, UNO_QUERY ); if ( xContainer.is() ) xContainer->removeContainerListener( this ); xContainer = Reference< XContainer >( m_xConfigAccessPopups, UNO_QUERY ); if ( xContainer.is() ) xContainer->removeContainerListener( this ); } // XNameAccess Any SAL_CALL ConfigurationAccess_UICommand::getByName( const ::rtl::OUString& rCommandURL ) throw ( NoSuchElementException, WrappedTargetException, RuntimeException) { static sal_Int32 nRequests = 0; ResetableGuard aLock( m_aLock ); if ( !m_bConfigAccessInitialized ) { initializeConfigAccess(); m_bConfigAccessInitialized = sal_True; fillCache(); } if ( rCommandURL.indexOf( m_aPrivateResourceURL ) == 0 ) { // special keys to retrieve information about a set of commands // SAFE addGenericInfoToCache(); if ( rCommandURL.equalsIgnoreAsciiCaseAscii( UICOMMANDDESCRIPTION_NAMEACCESS_COMMANDIMAGELIST )) return makeAny( m_aCommandImageList ); else if ( rCommandURL.equalsIgnoreAsciiCaseAscii( UICOMMANDDESCRIPTION_NAMEACCESS_COMMANDROTATEIMAGELIST )) return makeAny( m_aCommandRotateImageList ); else if ( rCommandURL.equalsIgnoreAsciiCaseAscii( UICOMMANDDESCRIPTION_NAMEACCESS_COMMANDMIRRORIMAGELIST )) return makeAny( m_aCommandMirrorImageList ); else throw NoSuchElementException(); } else { // SAFE ++nRequests; Any a = getInfoFromCommand( rCommandURL ); if ( !a.hasValue() ) throw NoSuchElementException(); return a; } } Sequence< ::rtl::OUString > SAL_CALL ConfigurationAccess_UICommand::getElementNames() throw ( RuntimeException ) { return getAllCommands(); } sal_Bool SAL_CALL ConfigurationAccess_UICommand::hasByName( const ::rtl::OUString& rCommandURL ) throw (::com::sun::star::uno::RuntimeException) { Any a = getByName( rCommandURL ); if ( a != Any() ) return sal_True; else return sal_False; } // XElementAccess Type SAL_CALL ConfigurationAccess_UICommand::getElementType() throw ( RuntimeException ) { return( ::getCppuType( (const Sequence< PropertyValue >*)NULL ) ); } sal_Bool SAL_CALL ConfigurationAccess_UICommand::hasElements() throw ( RuntimeException ) { // There must are global commands! return sal_True; } void ConfigurationAccess_UICommand::fillInfoFromResult( CmdToInfoMap& rCmdInfo, const rtl::OUString& aLabel ) { String rStr( aLabel ); if ( rStr.SearchAscii( "%PRODUCT" ) != STRING_NOTFOUND ) rStr.SearchAndReplaceAllAscii( "%PRODUCTNAME", m_aBrandName ); rCmdInfo.aLabel = OUString( rStr ); rStr.EraseTrailingChars( '.' ); // Remove "..." from string rCmdInfo.aCommandName = OUString( MnemonicGenerator::EraseAllMnemonicChars( rStr )); rCmdInfo.bCommandNameCreated = sal_True; } Any ConfigurationAccess_UICommand::getSequenceFromCache( const OUString& aCommandURL ) { CommandToInfoCache::iterator pIter = m_aCmdInfoCache.find( aCommandURL ); if ( pIter != m_aCmdInfoCache.end() ) { if ( !pIter->second.bCommandNameCreated ) fillInfoFromResult( pIter->second, pIter->second.aLabel ); Sequence< PropertyValue > aPropSeq( 3 ); aPropSeq[0].Name = m_aPropLabel; aPropSeq[0].Value = pIter->second.aContextLabel.getLength() ? makeAny( pIter->second.aContextLabel ): makeAny( pIter->second.aLabel ); aPropSeq[1].Name = m_aPropName; aPropSeq[1].Value = makeAny( pIter->second.aCommandName ); aPropSeq[2].Name = m_aPropPopup; aPropSeq[2].Value = makeAny( pIter->second.bPopup ); return makeAny( aPropSeq ); } return Any(); } void ConfigurationAccess_UICommand::resetCache() { m_aCmdInfoCache.clear(); m_bCacheFilled = sal_False; m_bGenericDataRetrieved = sal_False; } sal_Bool ConfigurationAccess_UICommand::fillCache() { RTL_LOGFILE_CONTEXT( aLog, "framework (cd100003) ::ConfigurationAccess_UICommand::fillCache" ); if ( m_bCacheFilled ) return sal_True; sal_Int32 i( 0 ); Any a; Sequence< OUString > aNameSeq = m_xConfigAccess->getElementNames(); std::vector< OUString > aImageCommandVector; std::vector< OUString > aImageRotateVector; std::vector< OUString > aImageMirrorVector; for ( i = 0; i < aNameSeq.getLength(); i++ ) { try { Reference< XNameAccess > xNameAccess; a = m_xConfigAccess->getByName( aNameSeq[i] ); if ( a >>= xNameAccess ) { CmdToInfoMap aCmdToInfo; a = xNameAccess->getByName( m_aPropUILabel ); a >>= aCmdToInfo.aLabel; a = xNameAccess->getByName( m_aPropUIContextLabel ); a >>= aCmdToInfo.aContextLabel; a = xNameAccess->getByName( m_aPropProperties ); a >>= aCmdToInfo.nProperties; m_aCmdInfoCache.insert( CommandToInfoCache::value_type( aNameSeq[i], aCmdToInfo )); if ( aCmdToInfo.nProperties & COMMAND_PROPERTY_IMAGE ) aImageCommandVector.push_back( aNameSeq[i] ); if ( aCmdToInfo.nProperties & COMMAND_PROPERTY_ROTATE ) aImageRotateVector.push_back( aNameSeq[i] ); if ( aCmdToInfo.nProperties & COMMAND_PROPERTY_MIRROR ) aImageMirrorVector.push_back( aNameSeq[i] ); } } catch ( com::sun::star::lang::WrappedTargetException& ) { } catch ( com::sun::star::container::NoSuchElementException& ) { } } aNameSeq = m_xConfigAccessPopups->getElementNames(); for ( i = 0; i < aNameSeq.getLength(); i++ ) { try { Reference< XNameAccess > xNameAccess; a = m_xConfigAccessPopups->getByName( aNameSeq[i] ); if ( a >>= xNameAccess ) { CmdToInfoMap aCmdToInfo; aCmdToInfo.bPopup = sal_True; a = xNameAccess->getByName( m_aPropUILabel ); a >>= aCmdToInfo.aLabel; a = xNameAccess->getByName( m_aPropUIContextLabel ); a >>= aCmdToInfo.aContextLabel; a = xNameAccess->getByName( m_aPropProperties ); a >>= aCmdToInfo.nProperties; m_aCmdInfoCache.insert( CommandToInfoCache::value_type( aNameSeq[i], aCmdToInfo )); if ( aCmdToInfo.nProperties & COMMAND_PROPERTY_IMAGE ) aImageCommandVector.push_back( aNameSeq[i] ); if ( aCmdToInfo.nProperties & COMMAND_PROPERTY_ROTATE ) aImageRotateVector.push_back( aNameSeq[i] ); if ( aCmdToInfo.nProperties & COMMAND_PROPERTY_MIRROR ) aImageMirrorVector.push_back( aNameSeq[i] ); } } catch ( com::sun::star::lang::WrappedTargetException& ) { } catch ( com::sun::star::container::NoSuchElementException& ) { } } // Create cached sequences for fast retrieving m_aCommandImageList = comphelper::containerToSequence< rtl::OUString >( aImageCommandVector ); m_aCommandRotateImageList = comphelper::containerToSequence< rtl::OUString >( aImageRotateVector ); m_aCommandMirrorImageList = comphelper::containerToSequence< rtl::OUString >( aImageMirrorVector ); m_bCacheFilled = sal_True; return sal_True; } sal_Bool ConfigurationAccess_UICommand::addGenericInfoToCache() { if ( m_xGenericUICommands.is() && !m_bGenericDataRetrieved ) { Sequence< rtl::OUString > aCommandNameSeq; try { if ( m_xGenericUICommands->getByName( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( UICOMMANDDESCRIPTION_NAMEACCESS_COMMANDROTATEIMAGELIST ))) >>= aCommandNameSeq ) m_aCommandRotateImageList = comphelper::concatSequences< rtl::OUString >( m_aCommandRotateImageList, aCommandNameSeq ); } catch ( RuntimeException& e ) { throw e; } catch ( Exception& ) { } try { if ( m_xGenericUICommands->getByName( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( UICOMMANDDESCRIPTION_NAMEACCESS_COMMANDMIRRORIMAGELIST ))) >>= aCommandNameSeq ) m_aCommandMirrorImageList = comphelper::concatSequences< rtl::OUString >( m_aCommandMirrorImageList, aCommandNameSeq ); } catch ( RuntimeException& e ) { throw e; } catch ( Exception& ) { } m_bGenericDataRetrieved = sal_True; } return sal_True; } Any ConfigurationAccess_UICommand::getInfoFromCommand( const rtl::OUString& rCommandURL ) { Any a; try { a = getSequenceFromCache( rCommandURL ); if ( !a.hasValue() ) { // First try to ask our global commands configuration access. It also caches maybe // we find the entry in its cache first. if ( m_xGenericUICommands.is() ) { try { return m_xGenericUICommands->getByName( rCommandURL ); } catch ( com::sun::star::lang::WrappedTargetException& ) { } catch ( com::sun::star::container::NoSuchElementException& ) { } } } } catch( com::sun::star::container::NoSuchElementException& ) { } catch ( com::sun::star::lang::WrappedTargetException& ) { } return a; } Sequence< rtl::OUString > ConfigurationAccess_UICommand::getAllCommands() { // SAFE ResetableGuard aLock( m_aLock ); if ( !m_bConfigAccessInitialized ) { initializeConfigAccess(); m_bConfigAccessInitialized = sal_True; fillCache(); } if ( m_xConfigAccess.is() ) { Any a; Reference< XNameAccess > xNameAccess; try { Sequence< OUString > aNameSeq = m_xConfigAccess->getElementNames(); if ( m_xGenericUICommands.is() ) { // Create concat list of supported user interface commands of the module Sequence< OUString > aGenericNameSeq = m_xGenericUICommands->getElementNames(); sal_uInt32 nCount1 = aNameSeq.getLength(); sal_uInt32 nCount2 = aGenericNameSeq.getLength(); aNameSeq.realloc( nCount1 + nCount2 ); OUString* pNameSeq = aNameSeq.getArray(); const OUString* pGenericSeq = aGenericNameSeq.getConstArray(); for ( sal_uInt32 i = 0; i < nCount2; i++ ) pNameSeq[nCount1+i] = pGenericSeq[i]; } return aNameSeq; } catch( com::sun::star::container::NoSuchElementException& ) { } catch ( com::sun::star::lang::WrappedTargetException& ) { } } return Sequence< rtl::OUString >(); } sal_Bool ConfigurationAccess_UICommand::initializeConfigAccess() { Sequence< Any > aArgs( 1 ); PropertyValue aPropValue; try { aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "nodepath" )); aPropValue.Value = makeAny( m_aConfigCmdAccess ); aArgs[0] <<= aPropValue; m_xConfigAccess = Reference< XNameAccess >( m_xConfigProvider->createInstanceWithArguments( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationAccess" )), aArgs ), UNO_QUERY ); if ( m_xConfigAccess.is() ) { // Add as container listener Reference< XContainer > xContainer( m_xConfigAccess, UNO_QUERY ); if ( xContainer.is() ) xContainer->addContainerListener( this ); } aPropValue.Value = makeAny( m_aConfigPopupAccess ); aArgs[0] <<= aPropValue; m_xConfigAccessPopups = Reference< XNameAccess >( m_xConfigProvider->createInstanceWithArguments( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationAccess" )), aArgs ), UNO_QUERY ); if ( m_xConfigAccessPopups.is() ) { // Add as container listener Reference< XContainer > xContainer( m_xConfigAccessPopups, UNO_QUERY ); if ( xContainer.is() ) xContainer->addContainerListener( this ); } return sal_True; } catch ( WrappedTargetException& ) { } catch ( Exception& ) { } return sal_False; } // container.XContainerListener void SAL_CALL ConfigurationAccess_UICommand::elementInserted( const ContainerEvent& aEvent ) throw(RuntimeException) { } void SAL_CALL ConfigurationAccess_UICommand::elementRemoved ( const ContainerEvent& aEvent ) throw(RuntimeException) { } void SAL_CALL ConfigurationAccess_UICommand::elementReplaced( const ContainerEvent& aEvent ) throw(RuntimeException) { } // lang.XEventListener void SAL_CALL ConfigurationAccess_UICommand::disposing( const EventObject& aEvent ) throw(RuntimeException) { // SAFE // remove our reference to the config access ResetableGuard aLock( m_aLock ); Reference< XInterface > xIfac1( aEvent.Source, UNO_QUERY ); Reference< XInterface > xIfac2( m_xConfigAccess, UNO_QUERY ); if ( xIfac1 == xIfac2 ) m_xConfigAccess.clear(); else { xIfac2 = Reference< XInterface >( m_xConfigAccessPopups, UNO_QUERY ); if ( xIfac1 == xIfac2 ) m_xConfigAccessPopups.clear(); } } //***************************************************************************************************************** // XInterface, XTypeProvider, XServiceInfo //***************************************************************************************************************** DEFINE_XINTERFACE_4 ( UICommandDescription , OWeakObject , DIRECT_INTERFACE( css::lang::XTypeProvider ), DIRECT_INTERFACE( css::lang::XServiceInfo ), DIRECT_INTERFACE( css::container::XNameAccess ), DERIVED_INTERFACE( css::container::XElementAccess, css::container::XNameAccess ) ) DEFINE_XTYPEPROVIDER_4 ( UICommandDescription , css::lang::XTypeProvider , css::lang::XServiceInfo , css::container::XNameAccess , css::container::XElementAccess ) DEFINE_XSERVICEINFO_ONEINSTANCESERVICE ( UICommandDescription , ::cppu::OWeakObject , SERVICENAME_UICOMMANDDESCRIPTION , IMPLEMENTATIONNAME_UICOMMANDDESCRIPTION ) DEFINE_INIT_SERVICE ( UICommandDescription, {} ) UICommandDescription::UICommandDescription( const Reference< XMultiServiceFactory >& xServiceManager ) : ThreadHelpBase(), m_aPrivateResourceURL( RTL_CONSTASCII_USTRINGPARAM( PRIVATE_RESOURCE_URL )), m_xServiceManager( xServiceManager ) { Reference< XNameAccess > xEmpty; rtl::OUString aGenericUICommand( OUString::createFromAscii( "GenericCommands" )); m_xGenericUICommands = new ConfigurationAccess_UICommand( aGenericUICommand, xEmpty, xServiceManager ); m_xModuleManager = Reference< XModuleManager >( m_xServiceManager->createInstance( SERVICENAME_MODULEMANAGER ), UNO_QUERY ); Reference< XNameAccess > xNameAccess( m_xModuleManager, UNO_QUERY_THROW ); Sequence< rtl::OUString > aElementNames = xNameAccess->getElementNames(); Sequence< PropertyValue > aSeq; OUString aModuleIdentifier; for ( sal_Int32 i = 0; i < aElementNames.getLength(); i++ ) { aModuleIdentifier = aElementNames[i]; Any a = xNameAccess->getByName( aModuleIdentifier ); if ( a >>= aSeq ) { OUString aCommandStr; for ( sal_Int32 y = 0; y < aSeq.getLength(); y++ ) { if ( aSeq[y].Name.equalsAscii("ooSetupFactoryCommandConfigRef") ) { aSeq[y].Value >>= aCommandStr; break; } } // Create first mapping ModuleIdentifier ==> Command File m_aModuleToCommandFileMap.insert( ModuleToCommandFileMap::value_type( aModuleIdentifier, aCommandStr )); // Create second mapping Command File ==> commands instance UICommandsHashMap::iterator pIter = m_aUICommandsHashMap.find( aCommandStr ); if ( pIter == m_aUICommandsHashMap.end() ) m_aUICommandsHashMap.insert( UICommandsHashMap::value_type( aCommandStr, Reference< XNameAccess >() )); } } // insert generic commands UICommandsHashMap::iterator pIter = m_aUICommandsHashMap.find( aGenericUICommand ); if ( pIter != m_aUICommandsHashMap.end() ) pIter->second = m_xGenericUICommands; } UICommandDescription::~UICommandDescription() { ResetableGuard aLock( m_aLock ); m_aModuleToCommandFileMap.clear(); m_aUICommandsHashMap.clear(); m_xGenericUICommands.clear(); } Any SAL_CALL UICommandDescription::getByName( const ::rtl::OUString& aName ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) { Any a; ResetableGuard aLock( m_aLock ); ModuleToCommandFileMap::const_iterator pIter = m_aModuleToCommandFileMap.find( aName ); if ( pIter != m_aModuleToCommandFileMap.end() ) { OUString aCommandFile( pIter->second ); UICommandsHashMap::iterator pIter = m_aUICommandsHashMap.find( aCommandFile ); if ( pIter != m_aUICommandsHashMap.end() ) { if ( pIter->second.is() ) a <<= pIter->second; else { Reference< XNameAccess > xUICommands; ConfigurationAccess_UICommand* pUICommands = new ConfigurationAccess_UICommand( aCommandFile, m_xGenericUICommands, m_xServiceManager ); xUICommands = Reference< XNameAccess >( static_cast< cppu::OWeakObject* >( pUICommands ),UNO_QUERY ); pIter->second = xUICommands; a <<= xUICommands; } } } else if ( aName.indexOf( m_aPrivateResourceURL ) == 0 ) { // special keys to retrieve information about a set of commands return m_xGenericUICommands->getByName( aName ); } else { throw NoSuchElementException(); } return a; } Sequence< ::rtl::OUString > SAL_CALL UICommandDescription::getElementNames() throw (::com::sun::star::uno::RuntimeException) { ResetableGuard aLock( m_aLock ); Sequence< rtl::OUString > aSeq( m_aModuleToCommandFileMap.size() ); sal_Int32 n = 0; ModuleToCommandFileMap::const_iterator pIter = m_aModuleToCommandFileMap.begin(); while ( pIter != m_aModuleToCommandFileMap.end() ) { aSeq[n] = pIter->first; ++pIter; } return aSeq; } sal_Bool SAL_CALL UICommandDescription::hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException) { ResetableGuard aLock( m_aLock ); ModuleToCommandFileMap::const_iterator pIter = m_aModuleToCommandFileMap.find( aName ); return ( pIter != m_aModuleToCommandFileMap.end() ); } // XElementAccess Type SAL_CALL UICommandDescription::getElementType() throw (::com::sun::star::uno::RuntimeException) { return( ::getCppuType( (const Reference< XNameAccess >*)NULL ) ); } sal_Bool SAL_CALL UICommandDescription::hasElements() throw (::com::sun::star::uno::RuntimeException) { // generic UI commands are always available! return sal_True; } } // namespace framework INTEGRATION: CWS fwk20 (1.8.98); FILE MERGED 2005/07/08 11:42:32 cd 1.8.98.2: #122192# Check configuration access reference before usage 2005/07/08 11:32:17 cd 1.8.98.1: #122192# Check configuration access reference before usage /************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: uicommanddescription.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2005-09-23 15:42:06 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_UIELEMENT_UICOMMANDDESCRPTION_HXX_ #include "uielement/uicommanddescription.hxx" #endif #ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_ #include <threadhelp/resetableguard.hxx> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include "services.h" #endif #include "properties.h" //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_ #include <com/sun/star/container/XContainer.hpp> #endif //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _UTL_CONFIGMGR_HXX_ #include <unotools/configmgr.hxx> #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _VCL_MNEMONIC_HXX_ #include <vcl/mnemonic.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _RTL_LOGFILE_HXX_ #include <rtl/logfile.hxx> #endif //_________________________________________________________________________________________________________________ // Defines //_________________________________________________________________________________________________________________ // using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::container; using namespace ::com::sun::star::frame; //_________________________________________________________________________________________________________________ // Namespace //_________________________________________________________________________________________________________________ // struct ModuleToCommands { const char* pModuleId; const char* pCommands; }; static const char GENERIC_UICOMMANDS[] = "generic"; static const char COMMANDS[] = "Commands"; static const char CONFIGURATION_ROOT_ACCESS[] = "/org.openoffice.Office.UI."; static const char CONFIGURATION_CMD_ELEMENT_ACCESS[] = "/UserInterface/Commands"; static const char CONFIGURATION_POP_ELEMENT_ACCESS[] = "/UserInterface/Popups"; static const char CONFIGURATION_PROPERTY_LABEL[] = "Label"; static const char CONFIGURATION_PROPERTY_CONTEXT_LABEL[] = "ContextLabel"; // Property names of the resulting Property Set static const char PROPSET_LABEL[] = "Label"; static const char PROPSET_NAME[] = "Name"; static const char PROPSET_POPUP[] = "Popup"; static const char PROPSET_PROPERTIES[] = "Properties"; // Special resource URLs to retrieve additional information static const char PRIVATE_RESOURCE_URL[] = "private:"; const sal_Int32 COMMAND_PROPERTY_IMAGE = 1; const sal_Int32 COMMAND_PROPERTY_ROTATE = 2; const sal_Int32 COMMAND_PROPERTY_MIRROR = 4; namespace framework { //***************************************************************************************************************** // Configuration access class for PopupMenuControllerFactory implementation //***************************************************************************************************************** class ConfigurationAccess_UICommand : // interfaces public XTypeProvider , public XNameAccess , public XContainerListener , // baseclasses // Order is neccessary for right initialization! private ThreadHelpBase , public ::cppu::OWeakObject { public: ConfigurationAccess_UICommand( const ::rtl::OUString& aModuleName, const Reference< XNameAccess >& xGenericUICommands, const Reference< XMultiServiceFactory >& rServiceManager ); virtual ~ConfigurationAccess_UICommand(); // XInterface, XTypeProvider DECLARE_XINTERFACE DECLARE_XTYPEPROVIDER // XNameAccess virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames() throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException); // XElementAccess virtual ::com::sun::star::uno::Type SAL_CALL getElementType() throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasElements() throw (::com::sun::star::uno::RuntimeException); // container.XContainerListener virtual void SAL_CALL elementInserted( const ContainerEvent& aEvent ) throw(RuntimeException); virtual void SAL_CALL elementRemoved ( const ContainerEvent& aEvent ) throw(RuntimeException); virtual void SAL_CALL elementReplaced( const ContainerEvent& aEvent ) throw(RuntimeException); // lang.XEventListener virtual void SAL_CALL disposing( const EventObject& aEvent ) throw(RuntimeException); protected: struct CmdToInfoMap { CmdToInfoMap() : bPopup( sal_False ), bCommandNameCreated( sal_False ), nProperties( 0 ) {} rtl::OUString aLabel; rtl::OUString aContextLabel; rtl::OUString aCommandName; sal_Bool bPopup : 1, bCommandNameCreated : 1; sal_Int32 nProperties; }; Any getSequenceFromCache( const rtl::OUString& aCommandURL ); Any getInfoFromCommand( const rtl::OUString& rCommandURL ); void fillInfoFromResult( CmdToInfoMap& rCmdInfo, const rtl::OUString& aLabel ); Any getUILabelFromCommand( const rtl::OUString& rCommandURL ); Sequence< rtl::OUString > getAllCommands(); void resetCache(); sal_Bool fillCache(); sal_Bool addGenericInfoToCache(); private: typedef ::std::hash_map< ::rtl::OUString, CmdToInfoMap, OUStringHashCode, ::std::equal_to< ::rtl::OUString > > CommandToInfoCache; sal_Bool initializeConfigAccess(); rtl::OUString m_aConfigCmdAccess; rtl::OUString m_aConfigPopupAccess; rtl::OUString m_aPropUILabel; rtl::OUString m_aPropUIContextLabel; rtl::OUString m_aPropLabel; rtl::OUString m_aPropName; rtl::OUString m_aPropPopup; rtl::OUString m_aPropProperties; rtl::OUString m_aBrandName; rtl::OUString m_aXMLFileFormatVersion; rtl::OUString m_aVersion; rtl::OUString m_aExtension; rtl::OUString m_aPrivateResourceURL; Reference< XNameAccess > m_xGenericUICommands; Reference< XMultiServiceFactory > m_xServiceManager; Reference< XMultiServiceFactory > m_xConfigProvider; Reference< XMultiServiceFactory > m_xConfigProviderPopups; Reference< XNameAccess > m_xConfigAccess; Reference< XNameAccess > m_xConfigAccessPopups; Sequence< rtl::OUString > m_aCommandImageList; Sequence< rtl::OUString > m_aCommandRotateImageList; Sequence< rtl::OUString > m_aCommandMirrorImageList; CommandToInfoCache m_aCmdInfoCache; sal_Bool m_bConfigAccessInitialized; sal_Bool m_bCacheFilled; sal_Bool m_bGenericDataRetrieved; }; //***************************************************************************************************************** // XInterface, XTypeProvider //***************************************************************************************************************** DEFINE_XINTERFACE_5 ( ConfigurationAccess_UICommand , OWeakObject , DIRECT_INTERFACE ( css::container::XNameAccess ), DIRECT_INTERFACE ( css::container::XContainerListener ), DIRECT_INTERFACE ( css::lang::XTypeProvider ), DERIVED_INTERFACE( css::container::XElementAccess, css::container::XNameAccess ), DERIVED_INTERFACE( css::lang::XEventListener, XContainerListener ) ) DEFINE_XTYPEPROVIDER_5 ( ConfigurationAccess_UICommand , css::container::XNameAccess , css::container::XElementAccess , css::container::XContainerListener , css::lang::XTypeProvider , css::lang::XEventListener ) ConfigurationAccess_UICommand::ConfigurationAccess_UICommand( const rtl::OUString& aModuleName, const Reference< XNameAccess >& rGenericUICommands, const Reference< XMultiServiceFactory >& rServiceManager ) : ThreadHelpBase(), m_xServiceManager( rServiceManager ), m_aPropUILabel( RTL_CONSTASCII_USTRINGPARAM( CONFIGURATION_PROPERTY_LABEL )), m_aPropUIContextLabel( RTL_CONSTASCII_USTRINGPARAM( CONFIGURATION_PROPERTY_CONTEXT_LABEL )), m_bConfigAccessInitialized( sal_False ), m_bCacheFilled( sal_False ), m_bGenericDataRetrieved( sal_False ), m_aConfigCmdAccess( RTL_CONSTASCII_USTRINGPARAM( CONFIGURATION_ROOT_ACCESS )), m_aConfigPopupAccess( RTL_CONSTASCII_USTRINGPARAM( CONFIGURATION_ROOT_ACCESS )), m_aPropLabel( RTL_CONSTASCII_USTRINGPARAM( PROPSET_LABEL )), m_aPropName( RTL_CONSTASCII_USTRINGPARAM( PROPSET_NAME )), m_aPropPopup( RTL_CONSTASCII_USTRINGPARAM( PROPSET_POPUP )), m_aPropProperties( RTL_CONSTASCII_USTRINGPARAM( PROPSET_PROPERTIES )), m_aPrivateResourceURL( RTL_CONSTASCII_USTRINGPARAM( PRIVATE_RESOURCE_URL )), m_xGenericUICommands( rGenericUICommands ) { // Create configuration hierachical access name m_aConfigCmdAccess += aModuleName; m_aConfigCmdAccess += rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( CONFIGURATION_CMD_ELEMENT_ACCESS )); m_xConfigProvider = Reference< XMultiServiceFactory >( rServiceManager->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationProvider" ))), UNO_QUERY ); m_aConfigPopupAccess += aModuleName; m_aConfigPopupAccess += rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( CONFIGURATION_POP_ELEMENT_ACCESS )); m_xConfigProviderPopups = Reference< XMultiServiceFactory >( rServiceManager->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationProvider" ))), UNO_QUERY ); Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME ); rtl::OUString aTmp; aRet >>= aTmp; m_aBrandName = aTmp; } ConfigurationAccess_UICommand::~ConfigurationAccess_UICommand() { // SAFE ResetableGuard aLock( m_aLock ); Reference< XContainer > xContainer( m_xConfigAccess, UNO_QUERY ); if ( xContainer.is() ) xContainer->removeContainerListener( this ); xContainer = Reference< XContainer >( m_xConfigAccessPopups, UNO_QUERY ); if ( xContainer.is() ) xContainer->removeContainerListener( this ); } // XNameAccess Any SAL_CALL ConfigurationAccess_UICommand::getByName( const ::rtl::OUString& rCommandURL ) throw ( NoSuchElementException, WrappedTargetException, RuntimeException) { static sal_Int32 nRequests = 0; ResetableGuard aLock( m_aLock ); if ( !m_bConfigAccessInitialized ) { initializeConfigAccess(); m_bConfigAccessInitialized = sal_True; fillCache(); } if ( rCommandURL.indexOf( m_aPrivateResourceURL ) == 0 ) { // special keys to retrieve information about a set of commands // SAFE addGenericInfoToCache(); if ( rCommandURL.equalsIgnoreAsciiCaseAscii( UICOMMANDDESCRIPTION_NAMEACCESS_COMMANDIMAGELIST )) return makeAny( m_aCommandImageList ); else if ( rCommandURL.equalsIgnoreAsciiCaseAscii( UICOMMANDDESCRIPTION_NAMEACCESS_COMMANDROTATEIMAGELIST )) return makeAny( m_aCommandRotateImageList ); else if ( rCommandURL.equalsIgnoreAsciiCaseAscii( UICOMMANDDESCRIPTION_NAMEACCESS_COMMANDMIRRORIMAGELIST )) return makeAny( m_aCommandMirrorImageList ); else throw NoSuchElementException(); } else { // SAFE ++nRequests; Any a = getInfoFromCommand( rCommandURL ); if ( !a.hasValue() ) throw NoSuchElementException(); return a; } } Sequence< ::rtl::OUString > SAL_CALL ConfigurationAccess_UICommand::getElementNames() throw ( RuntimeException ) { return getAllCommands(); } sal_Bool SAL_CALL ConfigurationAccess_UICommand::hasByName( const ::rtl::OUString& rCommandURL ) throw (::com::sun::star::uno::RuntimeException) { Any a = getByName( rCommandURL ); if ( a != Any() ) return sal_True; else return sal_False; } // XElementAccess Type SAL_CALL ConfigurationAccess_UICommand::getElementType() throw ( RuntimeException ) { return( ::getCppuType( (const Sequence< PropertyValue >*)NULL ) ); } sal_Bool SAL_CALL ConfigurationAccess_UICommand::hasElements() throw ( RuntimeException ) { // There must are global commands! return sal_True; } void ConfigurationAccess_UICommand::fillInfoFromResult( CmdToInfoMap& rCmdInfo, const rtl::OUString& aLabel ) { String rStr( aLabel ); if ( rStr.SearchAscii( "%PRODUCT" ) != STRING_NOTFOUND ) rStr.SearchAndReplaceAllAscii( "%PRODUCTNAME", m_aBrandName ); rCmdInfo.aLabel = OUString( rStr ); rStr.EraseTrailingChars( '.' ); // Remove "..." from string rCmdInfo.aCommandName = OUString( MnemonicGenerator::EraseAllMnemonicChars( rStr )); rCmdInfo.bCommandNameCreated = sal_True; } Any ConfigurationAccess_UICommand::getSequenceFromCache( const OUString& aCommandURL ) { CommandToInfoCache::iterator pIter = m_aCmdInfoCache.find( aCommandURL ); if ( pIter != m_aCmdInfoCache.end() ) { if ( !pIter->second.bCommandNameCreated ) fillInfoFromResult( pIter->second, pIter->second.aLabel ); Sequence< PropertyValue > aPropSeq( 3 ); aPropSeq[0].Name = m_aPropLabel; aPropSeq[0].Value = pIter->second.aContextLabel.getLength() ? makeAny( pIter->second.aContextLabel ): makeAny( pIter->second.aLabel ); aPropSeq[1].Name = m_aPropName; aPropSeq[1].Value = makeAny( pIter->second.aCommandName ); aPropSeq[2].Name = m_aPropPopup; aPropSeq[2].Value = makeAny( pIter->second.bPopup ); return makeAny( aPropSeq ); } return Any(); } void ConfigurationAccess_UICommand::resetCache() { m_aCmdInfoCache.clear(); m_bCacheFilled = sal_False; m_bGenericDataRetrieved = sal_False; } sal_Bool ConfigurationAccess_UICommand::fillCache() { RTL_LOGFILE_CONTEXT( aLog, "framework (cd100003) ::ConfigurationAccess_UICommand::fillCache" ); if ( m_bCacheFilled ) return sal_True; sal_Int32 i( 0 ); Any a; std::vector< OUString > aImageCommandVector; std::vector< OUString > aImageRotateVector; std::vector< OUString > aImageMirrorVector; Sequence< OUString > aNameSeq; if ( m_xConfigAccess.is() ) { aNameSeq = m_xConfigAccess->getElementNames(); for ( i = 0; i < aNameSeq.getLength(); i++ ) { try { Reference< XNameAccess > xNameAccess; a = m_xConfigAccess->getByName( aNameSeq[i] ); if ( a >>= xNameAccess ) { CmdToInfoMap aCmdToInfo; a = xNameAccess->getByName( m_aPropUILabel ); a >>= aCmdToInfo.aLabel; a = xNameAccess->getByName( m_aPropUIContextLabel ); a >>= aCmdToInfo.aContextLabel; a = xNameAccess->getByName( m_aPropProperties ); a >>= aCmdToInfo.nProperties; m_aCmdInfoCache.insert( CommandToInfoCache::value_type( aNameSeq[i], aCmdToInfo )); if ( aCmdToInfo.nProperties & COMMAND_PROPERTY_IMAGE ) aImageCommandVector.push_back( aNameSeq[i] ); if ( aCmdToInfo.nProperties & COMMAND_PROPERTY_ROTATE ) aImageRotateVector.push_back( aNameSeq[i] ); if ( aCmdToInfo.nProperties & COMMAND_PROPERTY_MIRROR ) aImageMirrorVector.push_back( aNameSeq[i] ); } } catch ( com::sun::star::lang::WrappedTargetException& ) { } catch ( com::sun::star::container::NoSuchElementException& ) { } } } if ( m_xConfigAccessPopups.is() ) { aNameSeq = m_xConfigAccessPopups->getElementNames(); for ( i = 0; i < aNameSeq.getLength(); i++ ) { try { Reference< XNameAccess > xNameAccess; a = m_xConfigAccessPopups->getByName( aNameSeq[i] ); if ( a >>= xNameAccess ) { CmdToInfoMap aCmdToInfo; aCmdToInfo.bPopup = sal_True; a = xNameAccess->getByName( m_aPropUILabel ); a >>= aCmdToInfo.aLabel; a = xNameAccess->getByName( m_aPropUIContextLabel ); a >>= aCmdToInfo.aContextLabel; a = xNameAccess->getByName( m_aPropProperties ); a >>= aCmdToInfo.nProperties; m_aCmdInfoCache.insert( CommandToInfoCache::value_type( aNameSeq[i], aCmdToInfo )); if ( aCmdToInfo.nProperties & COMMAND_PROPERTY_IMAGE ) aImageCommandVector.push_back( aNameSeq[i] ); if ( aCmdToInfo.nProperties & COMMAND_PROPERTY_ROTATE ) aImageRotateVector.push_back( aNameSeq[i] ); if ( aCmdToInfo.nProperties & COMMAND_PROPERTY_MIRROR ) aImageMirrorVector.push_back( aNameSeq[i] ); } } catch ( com::sun::star::lang::WrappedTargetException& ) { } catch ( com::sun::star::container::NoSuchElementException& ) { } } } // Create cached sequences for fast retrieving m_aCommandImageList = comphelper::containerToSequence< rtl::OUString >( aImageCommandVector ); m_aCommandRotateImageList = comphelper::containerToSequence< rtl::OUString >( aImageRotateVector ); m_aCommandMirrorImageList = comphelper::containerToSequence< rtl::OUString >( aImageMirrorVector ); m_bCacheFilled = sal_True; return sal_True; } sal_Bool ConfigurationAccess_UICommand::addGenericInfoToCache() { if ( m_xGenericUICommands.is() && !m_bGenericDataRetrieved ) { Sequence< rtl::OUString > aCommandNameSeq; try { if ( m_xGenericUICommands->getByName( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( UICOMMANDDESCRIPTION_NAMEACCESS_COMMANDROTATEIMAGELIST ))) >>= aCommandNameSeq ) m_aCommandRotateImageList = comphelper::concatSequences< rtl::OUString >( m_aCommandRotateImageList, aCommandNameSeq ); } catch ( RuntimeException& e ) { throw e; } catch ( Exception& ) { } try { if ( m_xGenericUICommands->getByName( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( UICOMMANDDESCRIPTION_NAMEACCESS_COMMANDMIRRORIMAGELIST ))) >>= aCommandNameSeq ) m_aCommandMirrorImageList = comphelper::concatSequences< rtl::OUString >( m_aCommandMirrorImageList, aCommandNameSeq ); } catch ( RuntimeException& e ) { throw e; } catch ( Exception& ) { } m_bGenericDataRetrieved = sal_True; } return sal_True; } Any ConfigurationAccess_UICommand::getInfoFromCommand( const rtl::OUString& rCommandURL ) { Any a; try { a = getSequenceFromCache( rCommandURL ); if ( !a.hasValue() ) { // First try to ask our global commands configuration access. It also caches maybe // we find the entry in its cache first. if ( m_xGenericUICommands.is() ) { try { return m_xGenericUICommands->getByName( rCommandURL ); } catch ( com::sun::star::lang::WrappedTargetException& ) { } catch ( com::sun::star::container::NoSuchElementException& ) { } } } } catch( com::sun::star::container::NoSuchElementException& ) { } catch ( com::sun::star::lang::WrappedTargetException& ) { } return a; } Sequence< rtl::OUString > ConfigurationAccess_UICommand::getAllCommands() { // SAFE ResetableGuard aLock( m_aLock ); if ( !m_bConfigAccessInitialized ) { initializeConfigAccess(); m_bConfigAccessInitialized = sal_True; fillCache(); } if ( m_xConfigAccess.is() ) { Any a; Reference< XNameAccess > xNameAccess; try { Sequence< OUString > aNameSeq = m_xConfigAccess->getElementNames(); if ( m_xGenericUICommands.is() ) { // Create concat list of supported user interface commands of the module Sequence< OUString > aGenericNameSeq = m_xGenericUICommands->getElementNames(); sal_uInt32 nCount1 = aNameSeq.getLength(); sal_uInt32 nCount2 = aGenericNameSeq.getLength(); aNameSeq.realloc( nCount1 + nCount2 ); OUString* pNameSeq = aNameSeq.getArray(); const OUString* pGenericSeq = aGenericNameSeq.getConstArray(); for ( sal_uInt32 i = 0; i < nCount2; i++ ) pNameSeq[nCount1+i] = pGenericSeq[i]; } return aNameSeq; } catch( com::sun::star::container::NoSuchElementException& ) { } catch ( com::sun::star::lang::WrappedTargetException& ) { } } return Sequence< rtl::OUString >(); } sal_Bool ConfigurationAccess_UICommand::initializeConfigAccess() { Sequence< Any > aArgs( 1 ); PropertyValue aPropValue; try { aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "nodepath" )); aPropValue.Value = makeAny( m_aConfigCmdAccess ); aArgs[0] <<= aPropValue; m_xConfigAccess = Reference< XNameAccess >( m_xConfigProvider->createInstanceWithArguments( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationAccess" )), aArgs ), UNO_QUERY ); if ( m_xConfigAccess.is() ) { // Add as container listener Reference< XContainer > xContainer( m_xConfigAccess, UNO_QUERY ); if ( xContainer.is() ) xContainer->addContainerListener( this ); } aPropValue.Value = makeAny( m_aConfigPopupAccess ); aArgs[0] <<= aPropValue; m_xConfigAccessPopups = Reference< XNameAccess >( m_xConfigProvider->createInstanceWithArguments( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationAccess" )), aArgs ), UNO_QUERY ); if ( m_xConfigAccessPopups.is() ) { // Add as container listener Reference< XContainer > xContainer( m_xConfigAccessPopups, UNO_QUERY ); if ( xContainer.is() ) xContainer->addContainerListener( this ); } return sal_True; } catch ( WrappedTargetException& ) { } catch ( Exception& ) { } return sal_False; } // container.XContainerListener void SAL_CALL ConfigurationAccess_UICommand::elementInserted( const ContainerEvent& aEvent ) throw(RuntimeException) { } void SAL_CALL ConfigurationAccess_UICommand::elementRemoved ( const ContainerEvent& aEvent ) throw(RuntimeException) { } void SAL_CALL ConfigurationAccess_UICommand::elementReplaced( const ContainerEvent& aEvent ) throw(RuntimeException) { } // lang.XEventListener void SAL_CALL ConfigurationAccess_UICommand::disposing( const EventObject& aEvent ) throw(RuntimeException) { // SAFE // remove our reference to the config access ResetableGuard aLock( m_aLock ); Reference< XInterface > xIfac1( aEvent.Source, UNO_QUERY ); Reference< XInterface > xIfac2( m_xConfigAccess, UNO_QUERY ); if ( xIfac1 == xIfac2 ) m_xConfigAccess.clear(); else { xIfac2 = Reference< XInterface >( m_xConfigAccessPopups, UNO_QUERY ); if ( xIfac1 == xIfac2 ) m_xConfigAccessPopups.clear(); } } //***************************************************************************************************************** // XInterface, XTypeProvider, XServiceInfo //***************************************************************************************************************** DEFINE_XINTERFACE_4 ( UICommandDescription , OWeakObject , DIRECT_INTERFACE( css::lang::XTypeProvider ), DIRECT_INTERFACE( css::lang::XServiceInfo ), DIRECT_INTERFACE( css::container::XNameAccess ), DERIVED_INTERFACE( css::container::XElementAccess, css::container::XNameAccess ) ) DEFINE_XTYPEPROVIDER_4 ( UICommandDescription , css::lang::XTypeProvider , css::lang::XServiceInfo , css::container::XNameAccess , css::container::XElementAccess ) DEFINE_XSERVICEINFO_ONEINSTANCESERVICE ( UICommandDescription , ::cppu::OWeakObject , SERVICENAME_UICOMMANDDESCRIPTION , IMPLEMENTATIONNAME_UICOMMANDDESCRIPTION ) DEFINE_INIT_SERVICE ( UICommandDescription, {} ) UICommandDescription::UICommandDescription( const Reference< XMultiServiceFactory >& xServiceManager ) : ThreadHelpBase(), m_aPrivateResourceURL( RTL_CONSTASCII_USTRINGPARAM( PRIVATE_RESOURCE_URL )), m_xServiceManager( xServiceManager ) { Reference< XNameAccess > xEmpty; rtl::OUString aGenericUICommand( OUString::createFromAscii( "GenericCommands" )); m_xGenericUICommands = new ConfigurationAccess_UICommand( aGenericUICommand, xEmpty, xServiceManager ); m_xModuleManager = Reference< XModuleManager >( m_xServiceManager->createInstance( SERVICENAME_MODULEMANAGER ), UNO_QUERY ); Reference< XNameAccess > xNameAccess( m_xModuleManager, UNO_QUERY_THROW ); Sequence< rtl::OUString > aElementNames = xNameAccess->getElementNames(); Sequence< PropertyValue > aSeq; OUString aModuleIdentifier; for ( sal_Int32 i = 0; i < aElementNames.getLength(); i++ ) { aModuleIdentifier = aElementNames[i]; Any a = xNameAccess->getByName( aModuleIdentifier ); if ( a >>= aSeq ) { OUString aCommandStr; for ( sal_Int32 y = 0; y < aSeq.getLength(); y++ ) { if ( aSeq[y].Name.equalsAscii("ooSetupFactoryCommandConfigRef") ) { aSeq[y].Value >>= aCommandStr; break; } } // Create first mapping ModuleIdentifier ==> Command File m_aModuleToCommandFileMap.insert( ModuleToCommandFileMap::value_type( aModuleIdentifier, aCommandStr )); // Create second mapping Command File ==> commands instance UICommandsHashMap::iterator pIter = m_aUICommandsHashMap.find( aCommandStr ); if ( pIter == m_aUICommandsHashMap.end() ) m_aUICommandsHashMap.insert( UICommandsHashMap::value_type( aCommandStr, Reference< XNameAccess >() )); } } // insert generic commands UICommandsHashMap::iterator pIter = m_aUICommandsHashMap.find( aGenericUICommand ); if ( pIter != m_aUICommandsHashMap.end() ) pIter->second = m_xGenericUICommands; } UICommandDescription::~UICommandDescription() { ResetableGuard aLock( m_aLock ); m_aModuleToCommandFileMap.clear(); m_aUICommandsHashMap.clear(); m_xGenericUICommands.clear(); } Any SAL_CALL UICommandDescription::getByName( const ::rtl::OUString& aName ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) { Any a; ResetableGuard aLock( m_aLock ); ModuleToCommandFileMap::const_iterator pIter = m_aModuleToCommandFileMap.find( aName ); if ( pIter != m_aModuleToCommandFileMap.end() ) { OUString aCommandFile( pIter->second ); UICommandsHashMap::iterator pIter = m_aUICommandsHashMap.find( aCommandFile ); if ( pIter != m_aUICommandsHashMap.end() ) { if ( pIter->second.is() ) a <<= pIter->second; else { Reference< XNameAccess > xUICommands; ConfigurationAccess_UICommand* pUICommands = new ConfigurationAccess_UICommand( aCommandFile, m_xGenericUICommands, m_xServiceManager ); xUICommands = Reference< XNameAccess >( static_cast< cppu::OWeakObject* >( pUICommands ),UNO_QUERY ); pIter->second = xUICommands; a <<= xUICommands; } } } else if ( aName.indexOf( m_aPrivateResourceURL ) == 0 ) { // special keys to retrieve information about a set of commands return m_xGenericUICommands->getByName( aName ); } else { throw NoSuchElementException(); } return a; } Sequence< ::rtl::OUString > SAL_CALL UICommandDescription::getElementNames() throw (::com::sun::star::uno::RuntimeException) { ResetableGuard aLock( m_aLock ); Sequence< rtl::OUString > aSeq( m_aModuleToCommandFileMap.size() ); sal_Int32 n = 0; ModuleToCommandFileMap::const_iterator pIter = m_aModuleToCommandFileMap.begin(); while ( pIter != m_aModuleToCommandFileMap.end() ) { aSeq[n] = pIter->first; ++pIter; } return aSeq; } sal_Bool SAL_CALL UICommandDescription::hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException) { ResetableGuard aLock( m_aLock ); ModuleToCommandFileMap::const_iterator pIter = m_aModuleToCommandFileMap.find( aName ); return ( pIter != m_aModuleToCommandFileMap.end() ); } // XElementAccess Type SAL_CALL UICommandDescription::getElementType() throw (::com::sun::star::uno::RuntimeException) { return( ::getCppuType( (const Reference< XNameAccess >*)NULL ) ); } sal_Bool SAL_CALL UICommandDescription::hasElements() throw (::com::sun::star::uno::RuntimeException) { // generic UI commands are always available! return sal_True; } } // namespace framework
namespace treap { mt19937 rnd = []() { random_device rd; return mt19937(rd()); }(); template <typename T> struct Node { Node* l; Node* r; uint32_t y; size_t sz; T data; Node(): l(nullptr), r(nullptr), y(rnd()), sz(1), data() {} Node(const T& data): l(nullptr), r(nullptr), y(rnd()), sz(1), data(data) {} Node(T&& data): l(nullptr), r(nullptr), y(rnd()), sz(1), data(data) {} Node* update() { sz = size(l) + 1 + size(r); return this; } Node* setL(Node* l) { this->l = l; return update(); } Node* setR(Node* r) { this->r = r; return update(); } }; template <typename T> size_t size(T* t) { if (!t) return 0; return t->sz; } template <typename T> T* merge(T* l, T* r) { if (!l || !r) return l ? l : r; if (l->y > r->y) return l->setR(merge(l->r, r)); else return r->setL(merge(l, r->l)); } template <typename T> pair<T*, T*> split(T* t, size_t sz) { if (!t) return make_pair(t, t); if (size(t->l) < sz) { auto tmp = split(t->r, sz - 1 - size(t->l)); return make_pair(t->setR(tmp.first), tmp.second); } else { auto tmp = split(t->l, sz); return make_pair(tmp.first, t->setL(tmp.second)); } } template <typename T> tuple<T*, T*, T*> cut(T* t, size_t l, size_t r) { T *a, *b, *c; tie(a, b) = split(t, l); tie(b, c) = split(b, r - l); return make_tuple(a, b, c); } template <typename T, typename C> void walk(T* t, const C& callback) { if (!t) return; walk(t->l, callback); callback(*t); walk(t->r, callback); } const auto printData = [](const node& n) { cout << n.data << " "; }; } using namespace treap; using node = Node<int>; treap fix namespace treap { mt19937 rnd = []() { random_device rd; return mt19937(rd()); }(); template <typename T> struct Node { Node* l; Node* r; uint32_t y; size_t sz; T data; Node(): l(nullptr), r(nullptr), y(rnd()), sz(1), data() {} Node(const T& data): l(nullptr), r(nullptr), y(rnd()), sz(1), data(data) {} Node(T&& data): l(nullptr), r(nullptr), y(rnd()), sz(1), data(data) {} Node* update() { sz = size(l) + 1 + size(r); return this; } Node* setL(Node* l) { this->l = l; return update(); } Node* setR(Node* r) { this->r = r; return update(); } }; template <typename T> size_t size(T* t) { if (!t) return 0; return t->sz; } template <typename T> T* merge(T* l, T* r) { if (!l || !r) return l ? l : r; if (l->y > r->y) return l->setR(merge(l->r, r)); else return r->setL(merge(l, r->l)); } template <typename T> pair<T*, T*> split(T* t, size_t sz) { if (!t) return make_pair(t, t); if (size(t->l) < sz) { auto tmp = split(t->r, sz - 1 - size(t->l)); return make_pair(t->setR(tmp.first), tmp.second); } else { auto tmp = split(t->l, sz); return make_pair(tmp.first, t->setL(tmp.second)); } } template <typename T> tuple<T*, T*, T*> cut(T* t, size_t l, size_t r) { T *a, *b, *c; tie(a, b) = split(t, l); tie(b, c) = split(b, r - l); return make_tuple(a, b, c); } template <typename T, typename C> void walk(T* t, const C& callback) { if (!t) return; walk(t->l, callback); callback(*t); walk(t->r, callback); } } using namespace treap; using node = Node<int>; const auto printData = [](const node& n) { cout << n.data << " "; };
/** ** \file object/float-class.cc ** \brief Creation of the URBI object float. */ #include <cmath> #include "sdk/config.h" #ifndef HAVE_ROUND # include "libport/ufloat.h" #endif #include "object/float-class.hh" #include "object/object.hh" #include "object/atom.hh" #include "object/urbi-exception.hh" namespace object { rObject float_class; /*-----------------------------------------. | Routines to implement float primitives. | `-----------------------------------------*/ // This macro is used to generate modulo // and division functions. #define FCT_OP_PROTECTED(Name, Operator, ErrorMessage) \ static \ libport::ufloat \ float_##Name (libport::ufloat l, libport::ufloat r) \ { \ if (!r) \ throw PrimitiveError("Operator " #Operator, \ ErrorMessage); \ return l Operator r; \ } #define FCT_M_PROTECTED(Name, Method, ErrorMessage) \ static \ libport::ufloat \ float_##Name (libport::ufloat l, libport::ufloat r) \ { \ if (!r) \ throw PrimitiveError(#Method, ErrorMessage); \ return Method(l, r); \ } FCT_OP_PROTECTED(div, /, "division by 0") FCT_M_PROTECTED(mod, fmod, "modulo by 0") #undef FCT_M_PROTECTED #undef FCT_OP_PROTECTED static libport::ufloat float_req (libport::ufloat l, libport::ufloat r) { // FIXME: get epsilontilde from environment // ENSURE_COMPARISON ("Approximate", l, r); // UVariable *epsilontilde = // ::urbiserver->getVariable(MAINDEVICE, "epsilontilde"); // if (epsilontilde) // $EXEC$ // else // return 0; #define epsilontilde 0.0001 return fabs(l - r) <= epsilontilde; #undef epsilontilde } static float float_deq (libport::ufloat l, libport::ufloat r) { // FIXME: get deltas for l and r // ENSURE_COMPARISON ("Approximate", l, r); libport::ufloat dl = 0.f; libport::ufloat dr = 0.f; // dl = 0, get l->delta // dr = 0, get r->delta return fabs(l - r) <= dl + dr; } static float float_peq (libport::ufloat l, libport::ufloat r) { // FIXME: get epsilonpercent from environment // FIXME: return error on div by 0 // ENSURE_COMPARISON ("Approximate", l, r); // UVariable *epsilonpercent = // ::urbiserver->getVariable(MAINDEVICE, "epsilonpercent"); // if (epsilonpercent) // $EXEC$ // else // return 0; if (r == 0) // FIXME: error return 0; # define epsilonpercent 0.0001 return fabs(1.f - l / r) < epsilonpercent; # undef epsilonpercent } static float float_sgn (libport::ufloat x) { return 0 < x ? 1 : x < 0 ? -1 : 0; } static float float_random (libport::ufloat x) { float res = 0.f; const long long range = libport::to_long_long (x); if (range) res = rand () % range; return res; } // This is quite hideous, to be cleaned once we have integers. # define INTEGER_BIN_OP(Name, Op) \ static float \ float_ ## Name (libport::ufloat lhs, libport::ufloat rhs) \ { \ return libport::to_long_long (lhs) Op libport::to_long_long (rhs); \ } INTEGER_BIN_OP(lshift, <<) INTEGER_BIN_OP(rshift, >>) INTEGER_BIN_OP(xor, ^) # undef INTEGER_BIN_OP /*-------------------------------------------------------------------. | Float Primitives. | | | | I.e., the signature is runner::Runner& x objects_type -> rObject. | `--------------------------------------------------------------------*/ /// Clone. static rObject float_class_clone(runner::Runner&, objects_type args) { CHECK_ARG_COUNT(1); FETCH_ARG(0, Float); return clone(arg0); } /// Change the value. static rObject float_class_set(runner::Runner&, objects_type args) { CHECK_ARG_COUNT(2); FETCH_ARG(0, Float); FETCH_ARG(1, Float); arg0->value_set (arg1->value_get()); return arg0; } /// Unary or binary minus. static rObject float_class_sub(runner::Runner&, objects_type args) { // FIXME: The error message requires 2 although 1 is ok. if (args.size () != 1 && args.size() != 2) throw WrongArgumentCount(2, args.size (), __PRETTY_FUNCTION__); FETCH_ARG(0, Float); if (args.size() == 1) return new Float(- arg0->value_get()); else { FETCH_ARG(1, Float); return new Float(arg0->value_get() - arg1->value_get()); } } /// Internal macro used to define a primitive for float numbers. /// \param Name primitive's name /// \param Call C++ code executed when primitive is called. /// \param Pre C++ code executed before call (typically to check args) #define PRIMITIVE_0_FLOAT_(Name, Call, Pre) \ static rObject \ float_class_ ## Name (runner::Runner&, objects_type args) \ { \ CHECK_ARG_COUNT(1); \ FETCH_ARG(0, Float); \ Pre; \ return new Float(Call(arg0->value_get())); \ } /// Define a primitive for float numbers. /// \param Call Name primitive's name #define PRIMITIVE_0_FLOAT(Name, Call) \ PRIMITIVE_0_FLOAT_(Name, Call, ) #define PRIMITIVE_0_FLOAT_CHECK_POSITIVE(Name, Call) \ PRIMITIVE_0_FLOAT_(Name, Call, \ if (VALUE(args[0], Float) < 0) \ throw PrimitiveError(#Name, \ "argument has to be positive")) #define PRIMITIVE_0_FLOAT_CHECK_RANGE(Name, Call, Min, Max) \ PRIMITIVE_0_FLOAT_(Name, Call, \ if (VALUE(args[0], Float) < Min || Max < VALUE(args[0], Float)) \ throw PrimitiveError(#Name, "invalid range")) #define PRIMITIVE_2_FLOAT(Name, Call) \ PRIMITIVE_2_V(float, Name, Call, Float, Float, Float) #define PRIMITIVE_OP_FLOAT(Name, Op) \ PRIMITIVE_OP_V(float, Name, Op, Float, Float, Float) // Binary arithmetics operators. PRIMITIVE_OP_FLOAT(PLUS, +) PRIMITIVE_2_FLOAT(SLASH, float_div) PRIMITIVE_OP_FLOAT(STAR, *) PRIMITIVE_2_FLOAT(PERCENT, float_mod) PRIMITIVE_2_FLOAT(STAR_STAR, powf) PRIMITIVE_2_FLOAT(LT_LT, float_lshift) // << PRIMITIVE_2_FLOAT(GT_GT, float_rshift) // >> PRIMITIVE_2_FLOAT(CARET, float_xor) // ^ PRIMITIVE_OP_FLOAT(AMPSERSAND_AMPSERSAND, &&) PRIMITIVE_OP_FLOAT(PIPE_PIPE, ||) PRIMITIVE_OP_FLOAT(EQ_EQ, ==) PRIMITIVE_2_FLOAT(TILDA_EQ, float_req) //REQ ~= PRIMITIVE_2_FLOAT(EQ_TILDA_EQ, float_deq) //DEQ =~= PRIMITIVE_2_FLOAT(PERCENT_EQ, float_peq) //PEQ %= PRIMITIVE_OP_FLOAT(LT, <) PRIMITIVE_0_FLOAT(sin, sin) PRIMITIVE_0_FLOAT_CHECK_RANGE(asin, asin, -1, 1) PRIMITIVE_0_FLOAT(cos, cos) PRIMITIVE_0_FLOAT_CHECK_RANGE(acos, acos, -1, 1) PRIMITIVE_0_FLOAT(tan, tan) PRIMITIVE_0_FLOAT(atan, atan) PRIMITIVE_0_FLOAT(sgn, float_sgn) PRIMITIVE_0_FLOAT(abs, fabs) PRIMITIVE_0_FLOAT(exp, exp) PRIMITIVE_0_FLOAT_CHECK_POSITIVE(log, log) PRIMITIVE_0_FLOAT(round, round) PRIMITIVE_0_FLOAT(random, float_random) PRIMITIVE_0_FLOAT(trunc, trunc) PRIMITIVE_0_FLOAT_CHECK_POSITIVE(sqrt, sqrt) #undef PRIMITIVE_2_FLOAT #undef PRIMITIVE_0_FLOAT_CHECK_RANGE #undef PRIMITIVE_0_FLOAT_CHECK_POSITIVE #undef PRIMITIVE_0_FLOAT #undef PRIMITIVE_0_FLOAT_ #undef PRIMITIVE_OP_FLOAT /// Initialize the Float class. void float_class_initialize () { /// \a Call gives the name of the C++ function, and \a Name that in Urbi. #define DECLARE(Name) \ DECLARE_PRIMITIVE(float, Name, Name) DECLARE(PLUS); DECLARE(SLASH); DECLARE(STAR); DECLARE(MINUS); DECLARE(STAR_STAR); DECLARE(PERCENT); DECLARE(LT_LT); DECLARE(GT_GT); DECLARE(CARET); DECLARE(AMPERSAND_AMPERSAND); DECLARE(PIPE_PIPE); DECLARE(EQ_EQ); DECLARE(TILDA_EQ); DECLARE(EQ_TILDA_EQ); DECLARE(PERCENT_EQ); DECLARE(LT); DECLARE(clone); DECLARE(set); DECLARE(sin); DECLARE(asin); DECLARE(cos); DECLARE(acos); DECLARE(tan); DECLARE(atan); DECLARE(sgn); DECLARE(abs); DECLARE(exp); DECLARE(log); DECLARE(round); DECLARE(random); DECLARE(trunc); DECLARE(sqrt); #undef DECLARE } }; // namespace object More symbols. * src/object/float-class.cc (float_class_sub): Rename as... (float_class_MINUS): this. Fix typo. /** ** \file object/float-class.cc ** \brief Creation of the URBI object float. */ #include <cmath> #include "sdk/config.h" #ifndef HAVE_ROUND # include "libport/ufloat.h" #endif #include "object/float-class.hh" #include "object/object.hh" #include "object/atom.hh" #include "object/urbi-exception.hh" namespace object { rObject float_class; /*-----------------------------------------. | Routines to implement float primitives. | `-----------------------------------------*/ // This macro is used to generate modulo // and division functions. #define FCT_OP_PROTECTED(Name, Operator, ErrorMessage) \ static \ libport::ufloat \ float_##Name (libport::ufloat l, libport::ufloat r) \ { \ if (!r) \ throw PrimitiveError("Operator " #Operator, \ ErrorMessage); \ return l Operator r; \ } #define FCT_M_PROTECTED(Name, Method, ErrorMessage) \ static \ libport::ufloat \ float_##Name (libport::ufloat l, libport::ufloat r) \ { \ if (!r) \ throw PrimitiveError(#Method, ErrorMessage); \ return Method(l, r); \ } FCT_OP_PROTECTED(div, /, "division by 0") FCT_M_PROTECTED(mod, fmod, "modulo by 0") #undef FCT_M_PROTECTED #undef FCT_OP_PROTECTED static libport::ufloat float_req (libport::ufloat l, libport::ufloat r) { // FIXME: get epsilontilde from environment // ENSURE_COMPARISON ("Approximate", l, r); // UVariable *epsilontilde = // ::urbiserver->getVariable(MAINDEVICE, "epsilontilde"); // if (epsilontilde) // $EXEC$ // else // return 0; #define epsilontilde 0.0001 return fabs(l - r) <= epsilontilde; #undef epsilontilde } static float float_deq (libport::ufloat l, libport::ufloat r) { // FIXME: get deltas for l and r // ENSURE_COMPARISON ("Approximate", l, r); libport::ufloat dl = 0.f; libport::ufloat dr = 0.f; // dl = 0, get l->delta // dr = 0, get r->delta return fabs(l - r) <= dl + dr; } static float float_peq (libport::ufloat l, libport::ufloat r) { // FIXME: get epsilonpercent from environment // FIXME: return error on div by 0 // ENSURE_COMPARISON ("Approximate", l, r); // UVariable *epsilonpercent = // ::urbiserver->getVariable(MAINDEVICE, "epsilonpercent"); // if (epsilonpercent) // $EXEC$ // else // return 0; if (r == 0) // FIXME: error return 0; # define epsilonpercent 0.0001 return fabs(1.f - l / r) < epsilonpercent; # undef epsilonpercent } static float float_sgn (libport::ufloat x) { return 0 < x ? 1 : x < 0 ? -1 : 0; } static float float_random (libport::ufloat x) { float res = 0.f; const long long range = libport::to_long_long (x); if (range) res = rand () % range; return res; } // This is quite hideous, to be cleaned once we have integers. # define INTEGER_BIN_OP(Name, Op) \ static float \ float_ ## Name (libport::ufloat lhs, libport::ufloat rhs) \ { \ return libport::to_long_long (lhs) Op libport::to_long_long (rhs); \ } INTEGER_BIN_OP(lshift, <<) INTEGER_BIN_OP(rshift, >>) INTEGER_BIN_OP(xor, ^) # undef INTEGER_BIN_OP /*-------------------------------------------------------------------. | Float Primitives. | | | | I.e., the signature is runner::Runner& x objects_type -> rObject. | `--------------------------------------------------------------------*/ /// Clone. static rObject float_class_clone(runner::Runner&, objects_type args) { CHECK_ARG_COUNT(1); FETCH_ARG(0, Float); return clone(arg0); } /// Change the value. static rObject float_class_set(runner::Runner&, objects_type args) { CHECK_ARG_COUNT(2); FETCH_ARG(0, Float); FETCH_ARG(1, Float); arg0->value_set (arg1->value_get()); return arg0; } /// Unary or binary minus. static rObject float_class_MINUS(runner::Runner&, objects_type args) { // FIXME: The error message requires 2 although 1 is ok. if (args.size () != 1 && args.size() != 2) throw WrongArgumentCount(2, args.size (), __PRETTY_FUNCTION__); FETCH_ARG(0, Float); if (args.size() == 1) return new Float(- arg0->value_get()); else { FETCH_ARG(1, Float); return new Float(arg0->value_get() - arg1->value_get()); } } /// Internal macro used to define a primitive for float numbers. /// \param Name primitive's name /// \param Call C++ code executed when primitive is called. /// \param Pre C++ code executed before call (typically to check args) #define PRIMITIVE_0_FLOAT_(Name, Call, Pre) \ static rObject \ float_class_ ## Name (runner::Runner&, objects_type args) \ { \ CHECK_ARG_COUNT(1); \ FETCH_ARG(0, Float); \ Pre; \ return new Float(Call(arg0->value_get())); \ } /// Define a primitive for float numbers. /// \param Call Name primitive's name #define PRIMITIVE_0_FLOAT(Name, Call) \ PRIMITIVE_0_FLOAT_(Name, Call, ) #define PRIMITIVE_0_FLOAT_CHECK_POSITIVE(Name, Call) \ PRIMITIVE_0_FLOAT_(Name, Call, \ if (VALUE(args[0], Float) < 0) \ throw PrimitiveError(#Name, \ "argument has to be positive")) #define PRIMITIVE_0_FLOAT_CHECK_RANGE(Name, Call, Min, Max) \ PRIMITIVE_0_FLOAT_(Name, Call, \ if (VALUE(args[0], Float) < Min || Max < VALUE(args[0], Float)) \ throw PrimitiveError(#Name, "invalid range")) #define PRIMITIVE_2_FLOAT(Name, Call) \ PRIMITIVE_2_V(float, Name, Call, Float, Float, Float) #define PRIMITIVE_OP_FLOAT(Name, Op) \ PRIMITIVE_OP_V(float, Name, Op, Float, Float, Float) // Binary arithmetics operators. PRIMITIVE_OP_FLOAT(PLUS, +) PRIMITIVE_2_FLOAT(SLASH, float_div) PRIMITIVE_OP_FLOAT(STAR, *) PRIMITIVE_2_FLOAT(PERCENT, float_mod) PRIMITIVE_2_FLOAT(STAR_STAR, powf) PRIMITIVE_2_FLOAT(LT_LT, float_lshift) // << PRIMITIVE_2_FLOAT(GT_GT, float_rshift) // >> PRIMITIVE_2_FLOAT(CARET, float_xor) // ^ PRIMITIVE_OP_FLOAT(AMPERSAND_AMPERSAND, &&) PRIMITIVE_OP_FLOAT(PIPE_PIPE, ||) PRIMITIVE_OP_FLOAT(EQ_EQ, ==) PRIMITIVE_2_FLOAT(TILDA_EQ, float_req) //REQ ~= PRIMITIVE_2_FLOAT(EQ_TILDA_EQ, float_deq) //DEQ =~= PRIMITIVE_2_FLOAT(PERCENT_EQ, float_peq) //PEQ %= PRIMITIVE_OP_FLOAT(LT, <) PRIMITIVE_0_FLOAT(sin, sin) PRIMITIVE_0_FLOAT_CHECK_RANGE(asin, asin, -1, 1) PRIMITIVE_0_FLOAT(cos, cos) PRIMITIVE_0_FLOAT_CHECK_RANGE(acos, acos, -1, 1) PRIMITIVE_0_FLOAT(tan, tan) PRIMITIVE_0_FLOAT(atan, atan) PRIMITIVE_0_FLOAT(sgn, float_sgn) PRIMITIVE_0_FLOAT(abs, fabs) PRIMITIVE_0_FLOAT(exp, exp) PRIMITIVE_0_FLOAT_CHECK_POSITIVE(log, log) PRIMITIVE_0_FLOAT(round, round) PRIMITIVE_0_FLOAT(random, float_random) PRIMITIVE_0_FLOAT(trunc, trunc) PRIMITIVE_0_FLOAT_CHECK_POSITIVE(sqrt, sqrt) #undef PRIMITIVE_2_FLOAT #undef PRIMITIVE_0_FLOAT_CHECK_RANGE #undef PRIMITIVE_0_FLOAT_CHECK_POSITIVE #undef PRIMITIVE_0_FLOAT #undef PRIMITIVE_0_FLOAT_ #undef PRIMITIVE_OP_FLOAT /// Initialize the Float class. void float_class_initialize () { /// \a Call gives the name of the C++ function, and \a Name that in Urbi. #define DECLARE(Name) \ DECLARE_PRIMITIVE(float, Name, Name) DECLARE(PLUS); DECLARE(SLASH); DECLARE(STAR); DECLARE(MINUS); DECLARE(STAR_STAR); DECLARE(PERCENT); DECLARE(LT_LT); DECLARE(GT_GT); DECLARE(CARET); DECLARE(AMPERSAND_AMPERSAND); DECLARE(PIPE_PIPE); DECLARE(EQ_EQ); DECLARE(TILDA_EQ); DECLARE(EQ_TILDA_EQ); DECLARE(PERCENT_EQ); DECLARE(LT); DECLARE(clone); DECLARE(set); DECLARE(sin); DECLARE(asin); DECLARE(cos); DECLARE(acos); DECLARE(tan); DECLARE(atan); DECLARE(sgn); DECLARE(abs); DECLARE(exp); DECLARE(log); DECLARE(round); DECLARE(random); DECLARE(trunc); DECLARE(sqrt); #undef DECLARE } }; // namespace object
/*++ Module Name: BaseAligner.cpp Abstract: Single-end aligner Authors: Bill Bolosky, August, 2011 Environment: User mode service. This class is NOT thread safe. It's the caller's responsibility to ensure that at most one thread uses an instance at any time. Revision History: Adapted from Matei Zaharia's Scala implementation. --*/ #include "stdafx.h" #include "BaseAligner.h" #include "Compat.h" #include "LandauVishkin.h" #include "BigAlloc.h" #include "mapq.h" #include "SeedSequencer.h" #include "exit.h" #include "AlignerOptions.h" #include "Error.h" using std::min; // #define TRACE_ALIGNER 1 #ifdef TRACE_ALIGNER // If you turn this on, then stdout writing won't work. #define TRACE printf #else #define TRACE(...) {} #endif BaseAligner::BaseAligner( GenomeIndex *i_genomeIndex, unsigned i_maxHitsToConsider, unsigned i_maxK, unsigned i_maxReadSize, unsigned i_maxSeedsToUseFromCommandLine, double i_maxSeedCoverage, unsigned i_minWeightToCheck, unsigned i_extraSearchDepth, bool i_noUkkonen, bool i_noOrderedEvaluation, bool i_noTruncation, bool i_useAffineGap, bool i_ignoreAlignmentAdjustmentsForOm, int i_maxSecondaryAlignmentsPerContig, LandauVishkin<1>*i_landauVishkin, LandauVishkin<-1>*i_reverseLandauVishkin, unsigned i_matchReward, unsigned i_subPenalty, unsigned i_gapOpenPenalty, unsigned i_gapExtendPenalty, unsigned i_minAGScore, AlignerStats *i_stats, BigAllocator *allocator) : genomeIndex(i_genomeIndex), maxHitsToConsider(i_maxHitsToConsider), maxK(i_maxK), maxReadSize(i_maxReadSize), maxSeedsToUseFromCommandLine(i_maxSeedsToUseFromCommandLine), maxSeedCoverage(i_maxSeedCoverage), readId(-1), extraSearchDepth(i_extraSearchDepth), explorePopularSeeds(false), stopOnFirstHit(false), stats(i_stats), noUkkonen(i_noUkkonen), noOrderedEvaluation(i_noOrderedEvaluation), noTruncation(i_noTruncation), useAffineGap(i_useAffineGap), matchReward(i_matchReward), subPenalty(i_subPenalty), gapOpenPenalty(i_gapOpenPenalty), gapExtendPenalty(i_gapExtendPenalty), minAGScore(i_minAGScore), minWeightToCheck(max(1u, i_minWeightToCheck)), maxSecondaryAlignmentsPerContig(i_maxSecondaryAlignmentsPerContig), alignmentAdjuster(i_genomeIndex->getGenome()), ignoreAlignmentAdjustmentsForOm(i_ignoreAlignmentAdjustmentsForOm) /*++ Routine Description: Constructor for the BaseAligner class. Aligners align reads against an indexed genome. Arguments: i_genomeIndex - The index against which to do the alignments i_maxHitsToConsider - The maximum number of hits to use from a seed lookup. Any lookups that return more than this are ignored. i_maxK - The largest string difference to consider for any comparison. i_maxReadSize - Bound on the number of bases in any read. There's no reason to make it tight, it just affects a little memory allocation. i_maxSeedsToUse - The maximum number of seeds to use when aligning any read (not counting ones ignored because they resulted in too many hits). Once we've looked up this many seeds, we just score what we've got. i_maxSeedCoverage - The maximum number of seeds to use expressed as readSize/seedSize i_extraSearchDepth - How deeply beyond bestScore do we search? i_noUkkonen - Don't use Ukkonen's algorithm (i.e., don't reduce the max edit distance depth as we score candidates) i_noOrderedEvaluation-Don't order evaluating the reads by the hit count in order to drive down the max edit distance more quickly i_noTruncation - Don't truncate searches based on count of disjoint seed misses i_useAffineGap - Use affine gap scoring for seed extension i_ignoreAlignmentAdjustmentsForOm - When a read score is adjusted because of soft clipping for being near the end of a contig, don't use the adjusted score when computing what to keep for -om i_maxSecondaryAlignmentsPerContig - Maximum secondary alignments per contig; -1 means don't limit this i_landauVishkin - an externally supplied LandauVishkin string edit distance object. This is useful if we're expecting repeated computations and use the LV cache. i_reverseLandauVishkin - the same for the reverse direction. i_matchReward - affine gap score for a match i_subPenalty - affine gap score for a substitution i_gapOpenPenalty - affine gap cost for opening a gap (indel) i_gapExtendPenalty - affine gap cost for extending a gap (indel) i_minAGScore - minimum score for alignment using affine gap score i_stats - an object into which we report out statistics allocator - an allocator that's used to allocate our local memory. This is useful for TLB optimization. If this is supplied, the caller is responsible for deallocation, we'll not deallocate any dynamic memory in our destructor. --*/ { hadBigAllocator = allocator != NULL; nHashTableLookups = 0; nLocationsScored = 0; nHitsIgnoredBecauseOfTooHighPopularity = 0; nReadsIgnoredBecauseOfTooManyNs = 0; nIndelsMerged = 0; genome = genomeIndex->getGenome(); seedLen = genomeIndex->getSeedLength(); doesGenomeIndexHave64BitLocations = genomeIndex->doesGenomeIndexHave64BitLocations(); probDistance = new ProbabilityDistance(SNP_PROB, GAP_OPEN_PROB, GAP_EXTEND_PROB); // Match Mason if ((i_landauVishkin == NULL) != (i_reverseLandauVishkin == NULL)) { WriteErrorMessage("Must supply both or neither of forward & reverse Landau-Vishkin objects. You tried exactly one.\n"); soft_exit(1); } if (i_subPenalty > (i_gapOpenPenalty + i_gapExtendPenalty)) { WriteErrorMessage("Substitutions may be penalized too high to be seen in alignments. Make sure subPenalty < gapOpen + gapExtend\n"); soft_exit(1); } if (i_landauVishkin == NULL) { if (allocator) { landauVishkin = new (allocator) LandauVishkin<>; reverseLandauVishkin = new (allocator) LandauVishkin<-1>; } else { landauVishkin = new LandauVishkin<>; reverseLandauVishkin = new LandauVishkin<-1>; } ownLandauVishkin = true; } else { landauVishkin = i_landauVishkin; reverseLandauVishkin = i_reverseLandauVishkin; ownLandauVishkin = false; } if (allocator) { // affineGap = new (allocator) AffineGap<>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty); // reverseAffineGap = new (allocator) AffineGap<-1>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty); affineGap = new (allocator) AffineGapVectorized<>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty); reverseAffineGap = new (allocator) AffineGapVectorized<-1>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty); } else { // affineGap = new AffineGap<>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty); // reverseAffineGap = new AffineGap<-1>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty); affineGap = new AffineGapVectorized<>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty); reverseAffineGap = new AffineGapVectorized<-1>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty); } unsigned maxSeedsToUse; if (0 != maxSeedsToUseFromCommandLine) { maxSeedsToUse = maxSeedsToUseFromCommandLine; } else { maxSeedsToUse = (int)(maxSeedCoverage * maxReadSize / genomeIndex->getSeedLength()); } numWeightLists = maxSeedsToUse + 1; candidateHashTablesSize = (maxHitsToConsider * maxSeedsToUse * 3)/2; // *1.5 for hash table slack hashTableElementPoolSize = maxHitsToConsider * maxSeedsToUse * 2 ; // *2 for RC if (allocator) { rcReadData = (char *)allocator->allocate(sizeof(char) * maxReadSize * 2); // The *2 is to allocte space for the quality string } else { rcReadData = (char *)BigAlloc(sizeof(char) * maxReadSize * 2); // The *2 is to allocte space for the quality string } rcReadQuality = rcReadData + maxReadSize; if (allocator) { reversedRead[FORWARD] = (char *)allocator->allocate(sizeof(char) * maxReadSize * 4 + 2 * MAX_K); // Times 4 to also hold RC version and genome data (+2MAX_K is for genome data) } else { reversedRead[FORWARD] = (char *)BigAlloc(sizeof(char) * maxReadSize * 4 + 2 * MAX_K); // Times 4 to also hold RC version and genome data (+2MAX_K is for genome data) } rcReadData = (char *)BigAlloc(sizeof(char) * maxReadSize); // treat everything but ACTG like N for (unsigned i = 0; i < 256; i++) { nTable[i] = 1; rcTranslationTable[i] = 'N'; } reversedRead[RC] = reversedRead[FORWARD] + maxReadSize; rcTranslationTable['A'] = 'T'; rcTranslationTable['G'] = 'C'; rcTranslationTable['C'] = 'G'; rcTranslationTable['T'] = 'A'; rcTranslationTable['N'] = 'N'; memset(nTable, 0, sizeof(nTable)); nTable['N'] = 1; if (allocator) { seedUsed = (BYTE *)allocator->allocate((sizeof(BYTE) * (maxReadSize + 7 + 128) / 8)); // +128 to make sure it extends at both } else { seedUsed = (BYTE *)BigAlloc((sizeof(BYTE) * (maxReadSize + 7 + 128) / 8)); // +128 to make sure it extends at both } seedUsedAsAllocated = seedUsed; // Save the pointer for the delete. seedUsed += 8; // This moves the pointer up an _int64, so we now have the appropriate before buffer. nUsedHashTableElements = 0; if (allocator) { candidateHashTable[FORWARD] = (HashTableAnchor *)allocator->allocate(sizeof(HashTableAnchor) * candidateHashTablesSize); candidateHashTable[RC] = (HashTableAnchor *)allocator->allocate(sizeof(HashTableAnchor) * candidateHashTablesSize); weightLists = (HashTableElement *)allocator->allocate(sizeof(HashTableElement) * numWeightLists); hashTableElementPool = (HashTableElement *)allocator->allocate(sizeof(HashTableElement) * hashTableElementPoolSize); // Allocte last, because it's biggest and usually unused. This puts all of the commonly used stuff into one large page. hitCountByExtraSearchDepth = (unsigned *)allocator->allocate(sizeof(*hitCountByExtraSearchDepth) * extraSearchDepth); if (maxSecondaryAlignmentsPerContig > 0) { hitsPerContigCounts = (HitsPerContigCounts *)allocator->allocate(sizeof(*hitsPerContigCounts) * genome->getNumContigs()); memset(hitsPerContigCounts, 0, sizeof(*hitsPerContigCounts) * genome->getNumContigs()); } else { hitsPerContigCounts = NULL; } } else { candidateHashTable[FORWARD] = (HashTableAnchor *)BigAlloc(sizeof(HashTableAnchor) * candidateHashTablesSize); candidateHashTable[RC] = (HashTableAnchor *)BigAlloc(sizeof(HashTableAnchor) * candidateHashTablesSize); weightLists = (HashTableElement *)BigAlloc(sizeof(HashTableElement) * numWeightLists); hashTableElementPool = (HashTableElement *)BigAlloc(sizeof(HashTableElement) * hashTableElementPoolSize); hitCountByExtraSearchDepth = (unsigned *)BigAlloc(sizeof(*hitCountByExtraSearchDepth) * extraSearchDepth); if (maxSecondaryAlignmentsPerContig > 0) { hitsPerContigCounts = (HitsPerContigCounts *)BigAlloc(sizeof(*hitsPerContigCounts) * genome->getNumContigs()); memset(hitsPerContigCounts, 0, sizeof(*hitsPerContigCounts) * genome->getNumContigs()); } else { hitsPerContigCounts = NULL; } } for (unsigned i = 0; i < hashTableElementPoolSize; i++) { hashTableElementPool[i].init(); } for (unsigned i = 0; i < maxSeedsToUse + 1; i++) { weightLists[i].init(); } for (Direction rc = 0; rc < NUM_DIRECTIONS; rc++) { memset(candidateHashTable[rc],0,sizeof(HashTableAnchor) * candidateHashTablesSize); } hashTableEpoch = 0; } #ifdef _DEBUG bool _DumpAlignments = true; #endif // _DEBUG bool BaseAligner::AlignRead( Read *inputRead, SingleAlignmentResult *primaryResult, int maxEditDistanceForSecondaryResults, _int64 secondaryResultBufferSize, _int64 *nSecondaryResults, _int64 maxSecondaryResults, SingleAlignmentResult *secondaryResults // The caller passes in a buffer of secondaryResultBufferSize and it's filled in by AlignRead() ) /*++ Routine Description: Align a particular read, possibly constraining the search around a given location. Arguments: read - the read to align primaryResult - the best alignment result found maxEditDistanceForSecondaryResults - How much worse than the primary result should we look? secondaryResultBufferSize - the size of the secondaryResults buffer. If provided, it must be at least maxK * maxSeeds * 2. nRescondaryResults - returns the number of secondary results found maxSecondaryResults - limit the number of secondary results to this secondaryResults - returns the secondary results Return Value: true if there was enough space in secondaryResults, false otherwise --*/ { bool overflowedSecondaryResultsBuffer = false; memset(hitCountByExtraSearchDepth, 0, sizeof(*hitCountByExtraSearchDepth) * extraSearchDepth); if (NULL != nSecondaryResults) { *nSecondaryResults = 0; } firstPassSeedsNotSkipped[FORWARD] = firstPassSeedsNotSkipped[RC] = 0; smallestSkippedSeed[FORWARD] = smallestSkippedSeed[RC] = 0x8fffffffffffffff; highestWeightListChecked = 0; unsigned maxSeedsToUse; if (0 != maxSeedsToUseFromCommandLine) { maxSeedsToUse = maxSeedsToUseFromCommandLine; } else { maxSeedsToUse = (int)(2 * maxSeedCoverage * inputRead->getDataLength() / genomeIndex->getSeedLength()); // 2x is for FORWARD/RC } primaryResult->location = InvalidGenomeLocation; // Value to return if we don't find a location. primaryResult->direction = FORWARD; // So we deterministically print the read forward in this case. primaryResult->score = UnusedScoreValue; primaryResult->status = NotFound; primaryResult->clippingForReadAdjustment = 0; primaryResult->usedAffineGapScoring = false; primaryResult->basesClippedBefore = 0; primaryResult->basesClippedAfter = 0; primaryResult->agScore = 0; unsigned lookupsThisRun = 0; popularSeedsSkipped = 0; // // A bitvector for used seeds, indexed on the starting location of the seed within the read. // if (inputRead->getDataLength() > maxReadSize) { WriteErrorMessage("BaseAligner:: got too big read (%d > %d)\n" "Increase MAX_READ_LENGTH at the beginning of Read.h and recompile\n", inputRead->getDataLength(), maxReadSize); soft_exit(1); } if ((int)inputRead->getDataLength() < seedLen) { // // Too short to have any seeds, it's hopeless. // No need to finalize secondary results, since we don't have any. // return true; } #ifdef TRACE_ALIGNER printf("Aligning read '%.*s':\n%.*s\n%.*s\n", inputRead->getIdLength(), inputRead->getId(), inputRead->getDataLength(), inputRead->getData(), inputRead->getDataLength(), inputRead->getQuality()); #endif #ifdef _DEBUG if (_DumpAlignments) { printf("BaseAligner: aligning read ID '%.*s', data '%.*s'\n", inputRead->getIdLength(), inputRead->getId(), inputRead->getDataLength(), inputRead->getData()); } #endif // _DEBUG // // Clear out the seed used array. // memset(seedUsed, 0, (inputRead->getDataLength() + 7) / 8); unsigned readLen = inputRead->getDataLength(); const char *readData = inputRead->getData(); const char *readQuality = inputRead->getQuality(); unsigned countOfNs = 0; for (unsigned i = 0; i < readLen; i++) { char baseByte = readData[i]; char complement = rcTranslationTable[baseByte]; rcReadData[readLen - i - 1] = complement; rcReadQuality[readLen - i - 1] = readQuality[i]; reversedRead[FORWARD][readLen - i - 1] = baseByte; reversedRead[RC][i] = complement; countOfNs += nTable[baseByte]; } if (countOfNs > maxK) { nReadsIgnoredBecauseOfTooManyNs++; // No need to finalize secondary results, since we don't have any. return true; } // // Block off any seeds that would contain an N. // if (countOfNs > 0) { int minSeedToConsiderNing = 0; // In English, any word can be verbed. Including, apparently, "N." for (int i = 0; i < (int) readLen; i++) { if (BASE_VALUE[readData[i]] > 3) { int limit = __min(i + seedLen - 1, readLen-1); for (int j = __max(minSeedToConsiderNing, i - (int) seedLen + 1); j <= limit; j++) { SetSeedUsed(j); } minSeedToConsiderNing = limit+1; if (minSeedToConsiderNing >= (int) readLen) break; } } } Read reverseComplimentRead; Read *read[NUM_DIRECTIONS]; read[FORWARD] = inputRead; read[RC] = &reverseComplimentRead; read[RC]->init(NULL, 0, rcReadData, rcReadQuality, readLen); clearCandidates(); // // Initialize the bases table, which represents which bases we've checked. // We have readSize - seeds size + 1 possible seeds. // unsigned nPossibleSeeds = readLen - seedLen + 1; TRACE("nPossibleSeeds: %d\n", nPossibleSeeds); unsigned nextSeedToTest = 0; unsigned wrapCount = 0; lowestPossibleScoreOfAnyUnseenLocation[FORWARD] = lowestPossibleScoreOfAnyUnseenLocation[RC] = 0; mostSeedsContainingAnyParticularBase[FORWARD] = mostSeedsContainingAnyParticularBase[RC] = 1; // Instead of tracking this for real, we're just conservative and use wrapCount+1. It's faster. bestScore = UnusedScoreValue; secondBestScore = UnusedScoreValue; nSeedsApplied[FORWARD] = nSeedsApplied[RC] = 0; lvScores = 0; lvScoresAfterBestFound = 0; probabilityOfAllCandidates = 0.0; probabilityOfBestCandidate = 0.0; scoreLimit = maxK + extraSearchDepth; // For MAPQ computation while (nSeedsApplied[FORWARD] + nSeedsApplied[RC] < maxSeedsToUse) { // // Choose the next seed to use. Choose the first one that isn't used // if (nextSeedToTest >= nPossibleSeeds) { // // We're wrapping. We want to space the seeds out as much as possible, so if we had // a seed length of 20 we'd want to take 0, 10, 5, 15, 2, 7, 12, 17. To make the computation // fast, we use use a table lookup. // wrapCount++; if (wrapCount >= seedLen) { // // We tried all possible seeds without matching or even getting enough seeds to // exceed our seed count. Do the best we can with what we have. // #ifdef TRACE_ALIGNER printf("Calling score with force=true because we wrapped around enough\n"); #endif score( true, read, primaryResult, maxEditDistanceForSecondaryResults, secondaryResultBufferSize, nSecondaryResults, secondaryResults, &overflowedSecondaryResultsBuffer); #ifdef _DEBUG if (_DumpAlignments) printf("\tFinal result score %d MAPQ %d (%e probability of best candidate, %e probability of all candidates) at %llu\n", primaryResult->score, primaryResult->mapq, probabilityOfBestCandidate, probabilityOfAllCandidates, primaryResult->location.location); #endif // _DEBUG if (overflowedSecondaryResultsBuffer) { return false; } finalizeSecondaryResults(read[FORWARD], primaryResult, nSecondaryResults, secondaryResults, maxSecondaryResults, maxEditDistanceForSecondaryResults, bestScore); return true; } nextSeedToTest = GetWrappedNextSeedToTest(seedLen, wrapCount); mostSeedsContainingAnyParticularBase[FORWARD] = mostSeedsContainingAnyParticularBase[RC] = wrapCount + 1; } while (nextSeedToTest < nPossibleSeeds && IsSeedUsed(nextSeedToTest)) { // // This seed is already used. Try the next one. // TRACE("Skipping due to IsSeedUsed\n"); nextSeedToTest++; } if (nextSeedToTest >= nPossibleSeeds) { // // Unusable seeds have pushed us past the end of the read. Go back around the outer loop so we wrap properly. // TRACE("Eek, we're past the end of the read\n"); continue; } SetSeedUsed(nextSeedToTest); if (!Seed::DoesTextRepresentASeed(read[FORWARD]->getData() + nextSeedToTest, seedLen)) { continue; } Seed seed(read[FORWARD]->getData() + nextSeedToTest, seedLen); _int64 nHits[NUM_DIRECTIONS]; // Number of times this seed hits in the genome const GenomeLocation *hits[NUM_DIRECTIONS]; // The actual hits (of size nHits) GenomeLocation singletonHits[NUM_DIRECTIONS]; // Storage for single hits (this is required for 64 bit genome indices, since they might use fewer than 8 bytes internally) const unsigned *hits32[NUM_DIRECTIONS]; if (doesGenomeIndexHave64BitLocations) { genomeIndex->lookupSeed(seed, &nHits[FORWARD], &hits[FORWARD], &nHits[RC], &hits[RC], &singletonHits[FORWARD], &singletonHits[RC]); } else { genomeIndex->lookupSeed32(seed, &nHits[FORWARD], &hits32[FORWARD], &nHits[RC], &hits32[RC]); } nHashTableLookups++; lookupsThisRun++; #ifdef _DEBUG if (_DumpAlignments) { printf("\tSeed offset %2d, %4lld hits, %4lld rcHits.", nextSeedToTest, nHits[0], nHits[1]); for (int rc = 0; rc < 2; rc++) { for (unsigned i = 0; i < __min(nHits[rc], 5); i++) { printf(" %sHit at %9llu.", rc == 1 ? "RC " : "", doesGenomeIndexHave64BitLocations ? hits[rc][i].location : (_int64)hits32[rc][i]); } } printf("\n"); } #endif // _DEUBG #ifdef TRACE_ALIGNER printf("Looked up seed %.*s (offset %d): hits=%u, rchits=%u\n", seedLen, inputRead->getData() + nextSeedToTest, nextSeedToTest, nHits[0], nHits[1]); for (int rc = 0; rc < 2; rc++) { if (nHits[rc] <= maxHitsToConsider) { printf("%sHits:", rc == 1 ? "RC " : ""); for (unsigned i = 0; i < nHits[rc]; i++) printf(" %9llu", doesGenomeIndexHave64BitLocations ? hits[rc][i].location : (_int64)hits32[rc][i]); printf("\n"); } } #endif bool appliedEitherSeed = false; for (Direction direction = 0; direction < NUM_DIRECTIONS; direction++) { if (nHits[direction] > maxHitsToConsider && !explorePopularSeeds) { // // This seed is matching too many places. Just pretend we never looked and keep going. // nHitsIgnoredBecauseOfTooHighPopularity++; popularSeedsSkipped++; smallestSkippedSeed[direction] = __min(nHits[direction], smallestSkippedSeed[direction]); } else { if (0 == wrapCount) { firstPassSeedsNotSkipped[direction]++; } // // Update the candidates list with any hits from this seed. If lowest possible score of any unseen location is // more than best_score + confDiff then we know that if this location is newly seen then its location won't ever be a // winner, and we can ignore it. // unsigned offset; if (direction == FORWARD) { offset = nextSeedToTest; } else { // // The RC seed is at offset ReadSize - SeedSize - seed offset in the RC seed. // // To see why, imagine that you had a read that looked like 0123456 (where the digits // represented some particular bases, and digit' is the base's complement). Then the // RC of that read is 6'5'4'3'2'1'. So, when we look up the hits for the seed at // offset 0 in the forward read (i.e. 012 assuming a seed size of 3) then the index // will also return the results for the seed's reverse complement, i.e., 3'2'1'. // This happens as the last seed in the RC read. // offset = readLen - seedLen - nextSeedToTest; } const unsigned prefetchDepth = 30; _int64 limit = min(nHits[direction], (_int64)maxHitsToConsider) + prefetchDepth; for (unsigned iBase = 0 ; iBase < limit; iBase += prefetchDepth) { // // This works in two phases: we launch prefetches for a group of hash table lines, // then we do all of the inserts, and then repeat. // _int64 innerLimit = min((_int64)iBase + prefetchDepth, min(nHits[direction], (_int64)maxHitsToConsider)); if (doAlignerPrefetch) { for (unsigned i = iBase; i < innerLimit; i++) { if (doesGenomeIndexHave64BitLocations) { prefetchHashTableBucket(GenomeLocationAsInt64(hits[direction][i]) - offset, direction); } else { prefetchHashTableBucket(hits32[direction][i] - offset, direction); } } } for (unsigned i = iBase; i < innerLimit; i++) { // // Find the genome location where the beginning of the read would hit, given a match on this seed. // GenomeLocation genomeLocationOfThisHit; if (doesGenomeIndexHave64BitLocations) { genomeLocationOfThisHit = hits[direction][i] - offset; } else { genomeLocationOfThisHit = hits32[direction][i] - offset; } Candidate *candidate = NULL; HashTableElement *hashTableElement; findCandidate(genomeLocationOfThisHit, direction, &candidate, &hashTableElement); if (NULL != hashTableElement) { if (!noOrderedEvaluation) { // If noOrderedEvaluation, just leave them all on the one-hit weight list so they get evaluated in whatever order incrementWeight(hashTableElement); } candidate->seedOffset = offset; _ASSERT((unsigned)candidate->seedOffset <= readLen - seedLen); } else if (lowestPossibleScoreOfAnyUnseenLocation[direction] <= scoreLimit || noTruncation) { _ASSERT(offset <= readLen - seedLen); allocateNewCandidate(genomeLocationOfThisHit, direction, lowestPossibleScoreOfAnyUnseenLocation[direction], offset, &candidate, &hashTableElement); } } } nSeedsApplied[direction]++; appliedEitherSeed = true; } // not too popular } // directions #if 1 nextSeedToTest += seedLen; #else // 0 // // If we don't have enough seeds left to reach the end of the read, space out the seeds more-or-less evenly. // if ((maxSeedsToUse - (nSeedsApplied[FORWARD] + nSeedsApplied[RC]) + 1) * seedLen + nextSeedToTest < nPossibleSeeds) { _ASSERT((nPossibleSeeds + nextSeedToTest) / (maxSeedsToUse - (nSeedsApplied[FORWARD] + nSeedsApplied[RC]) + 1) > seedLen); nextSeedToTest += (nPossibleSeeds + nextSeedToTest) / (maxSeedsToUse - (nSeedsApplied[FORWARD] + nSeedsApplied[RC]) + 1); } else { nextSeedToTest += seedLen; } #endif // 0 if (appliedEitherSeed) { // // And finally, try scoring. // if (score( false, read, primaryResult, maxEditDistanceForSecondaryResults, secondaryResultBufferSize, nSecondaryResults, secondaryResults, &overflowedSecondaryResultsBuffer)) { #ifdef _DEBUG if (_DumpAlignments) printf("\tFinal result score %d MAPQ %d at %llu\n", primaryResult->score, primaryResult->mapq, primaryResult->location.location); #endif // _DEBUG if (overflowedSecondaryResultsBuffer) { return false; } finalizeSecondaryResults(read[FORWARD], primaryResult, nSecondaryResults, secondaryResults, maxSecondaryResults, maxEditDistanceForSecondaryResults, bestScore); return true; } } } // // Do the best with what we've got. // #ifdef TRACE_ALIGNER printf("Calling score with force=true because we ran out of seeds\n"); #endif score( true, read, primaryResult, maxEditDistanceForSecondaryResults, secondaryResultBufferSize, nSecondaryResults, secondaryResults, &overflowedSecondaryResultsBuffer); #ifdef _DEBUG if (_DumpAlignments) printf("\tFinal result score %d MAPQ %d (%e probability of best candidate, %e probability of all candidates) at %llu\n", primaryResult->score, primaryResult->mapq, probabilityOfBestCandidate, probabilityOfAllCandidates, primaryResult->location.location); #endif // _DEBUG if (overflowedSecondaryResultsBuffer) { return false; } finalizeSecondaryResults(read[FORWARD], primaryResult, nSecondaryResults, secondaryResults, maxSecondaryResults, maxEditDistanceForSecondaryResults, bestScore); return true; } bool BaseAligner::score( bool forceResult, Read *read[NUM_DIRECTIONS], SingleAlignmentResult *primaryResult, int maxEditDistanceForSecondaryResults, _int64 secondaryResultBufferSize, _int64 *nSecondaryResults, SingleAlignmentResult *secondaryResults, bool *overflowedSecondaryBuffer) /*++ Routine Description: Make progress in scoring a possibly partial alignment. This is a private method of the BaseAligner class that's used only by AlignRead. It does a number of things. First, it computes the lowest possible score of any unseen location. This is useful because once we have a scored hit that's more than confDiff better than all unseen locations, there's no need to lookup more of them, we can just score what we've got and be sure that the answer is right (unless errors have pushed the read to be closer to a wrong location than to the correct one, in which case it's hopeless). It then decides whether it should score a location, and if so what one to score. It chooses the unscored location that's got the highest weight (i.e., appeared in the most hash table lookups), since that's most likely to be the winner. If there are multiple candidates with the same best weight, it breaks the tie using the best possible score for the candidates (which is determined when they're first hit). Remaining ties are broken arbitrarily. It merges indels with scored candidates. If there's an insertion or deletion in the read, then we'll get very close but unequal results out of the hash table lookup for parts of the read on opposite sides of the insertion or deletion. This throws out the one with the worse score. It then figures out if we have a definitive answer, and says what that is. Arguments: forceResult - should we generate an answer even if it's not definitive? read - the read we're aligning in both directions result - returns the result if we reach one singleHitGenomeLocation - returns the location in the genome if we return a single hit hitDirection - if we return a single hit, indicates its direction candidates - in/out the array of candidates that have hit and possibly been scored mapq - returns the map quality if we've reached a final result secondary - returns secondary alignment locations & directions (optional) Return Value: true iff we've reached a result. When called with forceResult, we'll always return true. --*/ { *overflowedSecondaryBuffer = false; #ifdef TRACE_ALIGNER printf("score() called with force=%d nsa=%d nrcsa=%d best=%u bestloc=%u 2nd=%u\n", forceResult, nSeedsApplied[FORWARD], nSeedsApplied[RC], bestScore, bestScoreGenomeLocation, secondBestScore); //printf("Candidates:\n"); //for (int i = 0; i < nCandidates; i++) { // Candidate* c = candidates + i; // printf(" loc=%u rc=%d weight=%u minps=%u scored=%d score=%u r=%u-%u\n", // c->genomeLocation, c->isRC, c->weight, c->minPossibleScore, c->scored, // c->score, c->minRange, c->maxRange); //} //printf("\n\n"); #endif if (0 == mostSeedsContainingAnyParticularBase[FORWARD] && 0 == mostSeedsContainingAnyParticularBase[RC]) { // // The only way we can get here is if we've tried all of the seeds that we're willing // to try and every one of them generated too many hits to process. Give up. // _ASSERT(forceResult); primaryResult->status = NotFound; primaryResult->mapq = 0; return true; } // // Recompute lowestPossibleScore. // for (Direction direction = 0; direction < 2; direction++) { if (0 != mostSeedsContainingAnyParticularBase[direction]) { lowestPossibleScoreOfAnyUnseenLocation[direction] = __max(lowestPossibleScoreOfAnyUnseenLocation[direction], nSeedsApplied[direction] / mostSeedsContainingAnyParticularBase[direction]); } } #ifdef TRACE_ALIGNER printf("Lowest possible scores for unseen locations: %d (fwd), %d (RC)\n", lowestPossibleScoreOfAnyUnseenLocation[FORWARD], lowestPossibleScoreOfAnyUnseenLocation[RC]); #endif unsigned weightListToCheck = highestUsedWeightList; do { // // Grab the next element to score, and score it. // while (weightListToCheck > 0 && weightLists[weightListToCheck].weightNext == &weightLists[weightListToCheck]) { weightListToCheck--; highestUsedWeightList = weightListToCheck; } if ((__min(lowestPossibleScoreOfAnyUnseenLocation[FORWARD],lowestPossibleScoreOfAnyUnseenLocation[RC]) > scoreLimit && !noTruncation) || forceResult) { if (weightListToCheck< minWeightToCheck) { // // We've scored all live candidates and excluded all non-candidates, or we've checked enough that we've hit the cutoff. We have our // answer. // primaryResult->score = bestScore; if (bestScore <= maxK) { primaryResult->location = bestScoreGenomeLocation; primaryResult->mapq = computeMAPQ(probabilityOfAllCandidates, probabilityOfBestCandidate, bestScore, popularSeedsSkipped); if (primaryResult->mapq >= MAPQ_LIMIT_FOR_SINGLE_HIT) { primaryResult->status = SingleHit; } else { primaryResult->status = MultipleHits; } return true; } else { primaryResult->status = NotFound; primaryResult->mapq = 0; return true; } } // // Nothing that we haven't already looked up can possibly be the answer. Score what we've got and exit. // forceResult = true; } else if (weightListToCheck == 0) { // // No candidates, look for more. // return false; } HashTableElement *elementToScore = weightLists[weightListToCheck].weightNext; _ASSERT(!elementToScore->allExtantCandidatesScored); _ASSERT(elementToScore->candidatesUsed != 0); _ASSERT(elementToScore != &weightLists[weightListToCheck]); if (doAlignerPrefetch) { // // Our prefetch pipeline is one loop out we get the genome data for the next loop, and two loops out we get the element to score. // _mm_prefetch((const char *)(elementToScore->weightNext->weightNext), _MM_HINT_T2); // prefetch the next element, it's likely to be the next thing we score. genome->prefetchData(elementToScore->weightNext->baseGenomeLocation); } if (elementToScore->lowestPossibleScore <= scoreLimit) { unsigned long candidateIndexToScore; _uint64 candidatesMask = elementToScore->candidatesUsed; while (_BitScanForward64(&candidateIndexToScore,candidatesMask)) { _uint64 candidateBit = ((_uint64)1 << candidateIndexToScore); candidatesMask &= ~candidateBit; if ((elementToScore->candidatesScored & candidateBit) != 0) { // Already scored it, or marked it as scored due to using ProbabilityDistance continue; } bool anyNearbyCandidatesAlreadyScored = elementToScore->candidatesScored != 0; elementToScore->candidatesScored |= candidateBit; _ASSERT(candidateIndexToScore < hashTableElementSize); Candidate *candidateToScore = &elementToScore->candidates[candidateIndexToScore]; GenomeLocation genomeLocation = elementToScore->baseGenomeLocation + candidateIndexToScore; GenomeLocation elementGenomeLocation = genomeLocation; // This is the genome location prior to any adjustments for indels // // We're about to run edit distance computation on the genome. Launch a prefetch for it // so that it's in cache when we do (or at least on the way). // if (doAlignerPrefetch) { genomeIndex->prefetchGenomeData(genomeLocation); } unsigned score = -1; double matchProbability = 0; unsigned readDataLength = read[elementToScore->direction]->getDataLength(); GenomeDistance genomeDataLength = readDataLength + MAX_K; // Leave extra space in case the read has deletions const char *data = genome->getSubstring(genomeLocation, genomeDataLength); bool usedAffineGapScoring = false; int basesClippedBefore = 0; int basesClippedAfter = 0; int agScore = 0; if (data != NULL) { Read *readToScore = read[elementToScore->direction]; _ASSERT(candidateToScore->seedOffset + seedLen <= readToScore->getDataLength()); // // Compute the distance separately in the forward and backward directions from the seed, to allow // arbitrary offsets at both the start and end. // double matchProb1, matchProb2; int score1, score2; // First, do the forward direction from where the seed aligns to past of it int readLen = readToScore->getDataLength(); int seedLen = genomeIndex->getSeedLength(); int seedOffset = candidateToScore->seedOffset; // Since the data is reversed int tailStart = seedOffset + seedLen; int agScore1 = seedLen, agScore2 = 0; // Compute maxK for which edit distance and affine gap scoring report the same alignment // GapOpenPenalty + k.GapExtendPenalty >= k * SubPenalty // int maxKForSameAlignment = gapOpenPenalty / (subPenalty - gapExtendPenalty); int maxKForSameAlignment = 1; int totalIndels = 0; int genomeLocationOffset; _ASSERT(!memcmp(data+seedOffset, readToScore->getData() + seedOffset, seedLen)); int textLen = (int)__min(genomeDataLength - tailStart, 0x7ffffff0); score1 = landauVishkin->computeEditDistance(data + tailStart, textLen, readToScore->getData() + tailStart, readToScore->getQuality() + tailStart, readLen - tailStart, scoreLimit, &matchProb1, NULL, &totalIndels); agScore1 = (seedLen + (readLen - tailStart - score1) * matchReward - score1 * subPenalty); if (score1 == -1) { score = -1; } else if (useAffineGap && ((totalIndels > 1) || (score1 > maxKForSameAlignment))) { agScore1 = affineGap->computeScore(data + tailStart, textLen, readToScore->getData() + tailStart, readToScore->getQuality() + tailStart, readLen - tailStart, scoreLimit, seedLen, NULL, &basesClippedAfter, &score1, &matchProb1); usedAffineGapScoring = true; if (score1 == -1) { score = -1; agScore = 0; } } if (score1 != -1) { // The tail of the read matched; now let's reverse match the reference genome and the head int limitLeft = scoreLimit - score1; totalIndels = 0; score2 = reverseLandauVishkin->computeEditDistance(data + seedOffset, seedOffset + MAX_K, reversedRead[elementToScore->direction] + readLen - seedOffset, read[OppositeDirection(elementToScore->direction)]->getQuality() + readLen - seedOffset, seedOffset, limitLeft, &matchProb2, &genomeLocationOffset, &totalIndels); agScore2 = (seedOffset - score2) * matchReward - score2 * subPenalty; if (score2 == -1) { score = -1; } else if (useAffineGap && ((totalIndels > 1) || (score2 > maxKForSameAlignment))) { agScore2 = reverseAffineGap->computeScore(data + seedOffset, seedOffset + limitLeft, reversedRead[elementToScore->direction] + readLen - seedOffset, read[OppositeDirection(elementToScore->direction)]->getQuality() + readLen - seedOffset, seedOffset, limitLeft, readLen - seedOffset, // FIXME: Assumes the rest of the read matches exactly &genomeLocationOffset, &basesClippedBefore, &score2, &matchProb2); usedAffineGapScoring = true; agScore2 -= (readLen - seedOffset); if (score2 == -1) { score = -1; agScore = 0; } } if (score2 != -1) { score = score1 + score2; // Map probabilities for substrings can be multiplied, but make sure to count seed too matchProbability = matchProb1 * matchProb2 * pow(1 - SNP_PROB, seedLen); // // Adjust the genome location based on any indels that we found. // genomeLocation += genomeLocationOffset; agScore = agScore1 + agScore2; // // We could mark as scored anything in between the old and new genome offsets, but it's probably not worth the effort since this is // so rare and all it would do is same time. // } } } else { // if we had genome data to compare against matchProbability = 0; } #ifdef TRACE_ALIGNER printf("Computing distance at %u (RC) with limit %d: %d (prob %g)\n", genomeLocation, scoreLimit, score, matchProbability); #endif #ifdef _DEBUG if (_DumpAlignments) printf("Scored %9llu weight %2d limit %d, result %2d %s\n", genomeLocation.location, elementToScore->weight, scoreLimit, score, elementToScore->direction ? "RC" : ""); #endif // _DEBUG candidateToScore->score = score; nLocationsScored++; lvScores++; lvScoresAfterBestFound++; // // Handle the special case where we just scored a different offset for a region that's already been scored. This can happen when // there are indels in the read. In this case, we want to treat them as a single aignment, not two different ones (which would // cause us to lose confidence in the alignment, since they're probably both pretty good). // if (anyNearbyCandidatesAlreadyScored) { // if (elementToScore->bestScore < score || elementToScore->bestScore == score && matchProbability <= elementToScore->matchProbabilityForBestScore) { if (matchProbability <= elementToScore->matchProbabilityForBestScore) { // // This is a no better mapping than something nearby that we already tried. Just ignore it. // continue; } } else { _ASSERT(elementToScore->matchProbabilityForBestScore == 0.0); } elementToScore->bestScoreGenomeLocation = genomeLocation; elementToScore->usedAffineGapScoring = usedAffineGapScoring; elementToScore->basesClippedBefore = basesClippedBefore; elementToScore->basesClippedAfter = basesClippedAfter; elementToScore->agScore = agScore; // // Look up the hash table element that's closest to the genomeLocation but that doesn't // contain it, to check if this location is already scored. // // We do this computation in a strange way in order to avoid generating a branch instruction that // the processor's branch predictor will get wrong half of the time. Think about it like this: // The genome location lies in a bucket of size hashTableElementSize. Its offset in the bucket // is genomeLocation % hashTableElementSize. If we take that quantity and integer divide it by // hashTableElementSize / 2, we get 0 if it's in the first half and 1 if it's in the second. Double that and subtract // one, and you're at the right place with no branches. // HashTableElement *nearbyElement; GenomeLocation nearbyGenomeLocation; if (-1 != score) { nearbyGenomeLocation = elementGenomeLocation + (2*(GenomeLocationAsInt64(elementGenomeLocation) % hashTableElementSize / (hashTableElementSize/2)) - 1) * (hashTableElementSize/2); _ASSERT((GenomeLocationAsInt64(elementGenomeLocation) % hashTableElementSize >= (hashTableElementSize/2) ? elementGenomeLocation + (hashTableElementSize/2) : elementGenomeLocation - (hashTableElementSize/2)) == nearbyGenomeLocation); // Assert that the logic in the above comment is right. findElement(nearbyGenomeLocation, elementToScore->direction, &nearbyElement); } else { nearbyElement = NULL; } if (NULL != nearbyElement && nearbyElement->candidatesScored != 0) { // // Just because there's a "nearby" element doesn't mean it's really within the maxMergeDist. Check that now. // if (!genomeLocationIsWithin(genomeLocation, nearbyElement->bestScoreGenomeLocation, maxMergeDist)) { // // There's a nearby element, but its best score is too far away to merge. Forget it. // nearbyElement = NULL; } if (NULL != nearbyElement) { // if (nearbyElement->bestScore < score || nearbyElement->bestScore == score && nearbyElement->matchProbabilityForBestScore >= matchProbability) { if (nearbyElement->matchProbabilityForBestScore >= matchProbability) { // // Again, this no better than something nearby we already tried. Give up. // continue; } anyNearbyCandidatesAlreadyScored = true; probabilityOfAllCandidates = __max(0.0, probabilityOfAllCandidates - nearbyElement->matchProbabilityForBestScore); nearbyElement->matchProbabilityForBestScore = 0; // keeps us from backing it out twice } } probabilityOfAllCandidates = __max(0.0, probabilityOfAllCandidates - elementToScore->matchProbabilityForBestScore); // need the max due to floating point lossage. probabilityOfAllCandidates += matchProbability; // Don't combine this with the previous line, it introduces floating point unhappiness. elementToScore->matchProbabilityForBestScore = matchProbability; elementToScore->bestScore = score; // if (bestScore > score || // (bestScore == score && matchProbability > probabilityOfBestCandidate)) { if (matchProbability > probabilityOfBestCandidate) { // // We have a new best score. The old best score becomes the second best score, unless this is the same as the best or second best score // if ((secondBestScore == UnusedScoreValue || !(secondBestScoreGenomeLocation + maxMergeDist > genomeLocation && secondBestScoreGenomeLocation < genomeLocation + maxMergeDist)) && (bestScore == UnusedScoreValue || !(bestScoreGenomeLocation + maxMergeDist > genomeLocation && bestScoreGenomeLocation < genomeLocation + maxMergeDist)) && (!anyNearbyCandidatesAlreadyScored || (GenomeLocationAsInt64(bestScoreGenomeLocation) / maxMergeDist != GenomeLocationAsInt64(genomeLocation) / maxMergeDist && GenomeLocationAsInt64(secondBestScoreGenomeLocation) / maxMergeDist != GenomeLocationAsInt64(genomeLocation) / maxMergeDist))) { secondBestScore = bestScore; secondBestScoreGenomeLocation = bestScoreGenomeLocation; secondBestScoreDirection = primaryResult->direction; } // // If we're tracking secondary alignments, put the old best score in as a new secondary alignment // if (bestScore >= score) { if (NULL != secondaryResults && (int)(bestScore - score) <= maxEditDistanceForSecondaryResults) { // bestScore is initialized to UnusedScoreValue, which is large, so this won't fire if this is the first candidate if (secondaryResultBufferSize <= *nSecondaryResults) { *overflowedSecondaryBuffer = true; return true; } SingleAlignmentResult *result = &secondaryResults[*nSecondaryResults]; result->direction = primaryResult->direction; result->location = bestScoreGenomeLocation; result->mapq = 0; result->score = bestScore; result->status = MultipleHits; result->clippingForReadAdjustment = 0; result->usedAffineGapScoring = primaryResult->usedAffineGapScoring; result->basesClippedBefore = primaryResult->basesClippedBefore; result->basesClippedAfter = primaryResult->basesClippedAfter; result->agScore = primaryResult->agScore; _ASSERT(result->score != -1); (*nSecondaryResults)++; } } bestScore = score; probabilityOfBestCandidate = matchProbability; _ASSERT(probabilityOfBestCandidate <= probabilityOfAllCandidates); bestScoreGenomeLocation = genomeLocation; primaryResult->location = bestScoreGenomeLocation; primaryResult->score = bestScore; primaryResult->direction = elementToScore->direction; primaryResult->usedAffineGapScoring = elementToScore->usedAffineGapScoring; primaryResult->basesClippedBefore = elementToScore->basesClippedBefore; primaryResult->basesClippedAfter = elementToScore->basesClippedAfter; primaryResult->agScore = elementToScore->agScore; _ASSERT(0 == primaryResult->clippingForReadAdjustment); lvScoresAfterBestFound = 0; } else { if (secondBestScore > score) { // // A new second best. // secondBestScore = score; secondBestScoreGenomeLocation = genomeLocation; secondBestScoreDirection = elementToScore->direction; } // // If this is close enough, record it as a secondary alignment. // if (-1 != maxEditDistanceForSecondaryResults && NULL != secondaryResults && (int)(bestScore - score) <= maxEditDistanceForSecondaryResults && score != -1) { if (secondaryResultBufferSize <= *nSecondaryResults) { *overflowedSecondaryBuffer = true; return true; } SingleAlignmentResult *result = &secondaryResults[*nSecondaryResults]; result->direction = elementToScore->direction; result->location = genomeLocation; result->mapq = 0; result->score = score; result->status = MultipleHits; result->clippingForReadAdjustment = 0; result->usedAffineGapScoring = elementToScore->usedAffineGapScoring; result->basesClippedBefore = elementToScore->basesClippedBefore; result->basesClippedAfter = elementToScore->basesClippedAfter; result->agScore = elementToScore->agScore; _ASSERT(result->score != -1); (*nSecondaryResults)++; } } if (stopOnFirstHit && bestScore <= maxK) { // The user just wanted to find reads that match the database within some distance, but doesn't // care about the best alignment. Stop now but mark the result as MultipleHits because we're not // confident that it's the best one. We don't support mapq in this secnario, because we haven't // explored enough to compute it. primaryResult->status = MultipleHits; primaryResult->mapq = 0; return true; } // Taken from intersecting paired-end aligner. // Assuming maximum probability among unseen candidates is 1 and MAPQ < 1, find probability of // all candidates for each we can terminate early without exploring any more MAPQ 0 alignments // i.e., -10 log10(1 - 1/x) < 1 // i.e., x > 4.86 ~ 4.9 if (probabilityOfAllCandidates >= 4.9 && -1 == maxEditDistanceForSecondaryResults) { // // Nothing will rescue us from a 0 MAPQ, so just stop looking. // return true; } // Update scoreLimit since we may have improved bestScore or secondBestScore if (!noUkkonen) { // If we've turned off Ukkonen, then don't drop the score limit, just leave it at maxK + extraSearchDepth always scoreLimit = min(bestScore, maxK) + extraSearchDepth; } else { _ASSERT(scoreLimit == maxK + extraSearchDepth); } } // While candidates exist in the element } // If the element could possibly affect the result // // Remove the element from the weight list. // elementToScore->allExtantCandidatesScored = true; elementToScore->weightNext->weightPrev = elementToScore->weightPrev; elementToScore->weightPrev->weightNext = elementToScore->weightNext; elementToScore->weightNext = elementToScore->weightPrev = elementToScore; } while (forceResult); return false; } void BaseAligner::prefetchHashTableBucket(GenomeLocation genomeLocation, Direction direction) { HashTableAnchor *hashTable = candidateHashTable[direction]; _uint64 lowOrderGenomeLocation; _uint64 highOrderGenomeLocation; decomposeGenomeLocation(genomeLocation, &highOrderGenomeLocation, &lowOrderGenomeLocation); _uint64 hashTableIndex = hash(highOrderGenomeLocation) % candidateHashTablesSize; _mm_prefetch((const char *)&hashTable[hashTableIndex], _MM_HINT_T2); } bool BaseAligner::findElement( GenomeLocation genomeLocation, Direction direction, HashTableElement **hashTableElement) { HashTableAnchor *hashTable = candidateHashTable[direction]; _uint64 lowOrderGenomeLocation; _uint64 highOrderGenomeLocation; decomposeGenomeLocation(genomeLocation, &highOrderGenomeLocation, &lowOrderGenomeLocation); _uint64 hashTableIndex = hash(highOrderGenomeLocation) % candidateHashTablesSize; HashTableAnchor *anchor = &hashTable[hashTableIndex]; if (anchor->epoch != hashTableEpoch) { // // It's empty. // *hashTableElement = NULL; return false; } HashTableElement *lookedUpElement = anchor->element; while (NULL != lookedUpElement && lookedUpElement->baseGenomeLocation != highOrderGenomeLocation) { lookedUpElement = lookedUpElement->next; } *hashTableElement = lookedUpElement; return lookedUpElement != NULL; } void BaseAligner::findCandidate( GenomeLocation genomeLocation, Direction direction, Candidate **candidate, HashTableElement **hashTableElement) /*++ Routine Description: Find a candidate in the hash table, optionally allocating it if it doesn't exist (but the element does). Arguments: genomeLocation - the location of the candidate we'd like to look up candidate - The candidate that was found or created hashTableElement - the hashTableElement for the candidate that was found. allocateNew - if this doesn't already exist, should we allocate it? --*/ { _uint64 lowOrderGenomeLocation; decomposeGenomeLocation(genomeLocation, NULL, &lowOrderGenomeLocation); if (!findElement(genomeLocation, direction, hashTableElement)) { *hashTableElement = NULL; *candidate = NULL; return; } _uint64 bitForThisCandidate = (_uint64)1 << lowOrderGenomeLocation; *candidate = &(*hashTableElement)->candidates[lowOrderGenomeLocation]; (*hashTableElement)->allExtantCandidatesScored = (*hashTableElement)->allExtantCandidatesScored && ((*hashTableElement)->candidatesUsed & bitForThisCandidate); (*hashTableElement)->candidatesUsed |= bitForThisCandidate; } bool doAlignerPrefetch = true; void BaseAligner::allocateNewCandidate( GenomeLocation genomeLocation, Direction direction, unsigned lowestPossibleScore, int seedOffset, Candidate ** candidate, HashTableElement ** hashTableElement) /*++ Routine Description: Arguments: Return Value: --*/ { HashTableAnchor *hashTable = candidateHashTable[direction]; _uint64 lowOrderGenomeLocation; _uint64 highOrderGenomeLocation; decomposeGenomeLocation(genomeLocation, &highOrderGenomeLocation, &lowOrderGenomeLocation); unsigned hashTableIndex = hash(highOrderGenomeLocation) % candidateHashTablesSize; HashTableAnchor *anchor = &hashTable[hashTableIndex]; if (doAlignerPrefetch) { _mm_prefetch((const char *)anchor, _MM_HINT_T2); // Prefetch our anchor. We don't have enough computation to completely hide the prefetch, but at least we get some for free here. } HashTableElement *element; #if DBG element = hashTable[hashTableIndex].element; while (anchor->epoch == hashTableEpoch && NULL != element && element->genomeLocation != highOrderGenomeLocation) { element = element->next; } _ASSERT(NULL == element || anchor->epoch != hashTableEpoch); #endif // DBG _ASSERT(nUsedHashTableElements < hashTableElementPoolSize); element = &hashTableElementPool[nUsedHashTableElements]; nUsedHashTableElements++; if (doAlignerPrefetch) { // // Fetch the next candidate so we don't cache miss next time around. // _mm_prefetch((const char *)&hashTableElementPool[nUsedHashTableElements], _MM_HINT_T2); } element->candidatesUsed = (_uint64)1 << lowOrderGenomeLocation; element->candidatesScored = 0; element->lowestPossibleScore = lowestPossibleScore; element->direction = direction; element->weight = 1; element->baseGenomeLocation = highOrderGenomeLocation; element->bestScore = UnusedScoreValue; element->allExtantCandidatesScored = false; element->matchProbabilityForBestScore = 0; element->usedAffineGapScoring = false; element->basesClippedBefore = 0; element->basesClippedAfter = 0; element->agScore = 0; // // And insert it at the end of weight list 1. // element->weightNext = &weightLists[1]; element->weightPrev = weightLists[1].weightPrev; element->weightNext->weightPrev = element; element->weightPrev->weightNext = element; *candidate = &element->candidates[lowOrderGenomeLocation]; (*candidate)->seedOffset = seedOffset; *hashTableElement = element; highestUsedWeightList = __max(highestUsedWeightList,(unsigned)1); if (anchor->epoch == hashTableEpoch) { element->next = anchor->element; } else { anchor->epoch = hashTableEpoch; element->next = NULL; } anchor->element = element; } BaseAligner::~BaseAligner() /*++ Routine Description: Arguments: Return Value: --*/ { delete probDistance; if (hadBigAllocator) { // // Since these got allocated with the alloator rather than new, we want to call // their destructors without freeing their memory (which is the responsibility of // the owner of the allocator). // if (ownLandauVishkin) { if (NULL != landauVishkin) { landauVishkin->~LandauVishkin(); } if (NULL != reverseLandauVishkin) { reverseLandauVishkin->~LandauVishkin(); } } if (NULL != affineGap) { // affineGap->~AffineGap(); affineGap->~AffineGapVectorized(); } if (NULL != reverseAffineGap) { // reverseAffineGap->~AffineGap(); reverseAffineGap->~AffineGapVectorized(); } } else { if (ownLandauVishkin) { if (NULL != landauVishkin) { delete landauVishkin; } if (NULL != reverseLandauVishkin) { delete reverseLandauVishkin; } } if (NULL != affineGap) { delete affineGap; } if (NULL != reverseAffineGap) { delete reverseAffineGap; } BigDealloc(rcReadData); rcReadData = NULL; BigDealloc(reversedRead[FORWARD]); reversedRead[FORWARD] = NULL; reversedRead[RC] = NULL; BigDealloc(seedUsedAsAllocated); seedUsed = NULL; BigDealloc(candidateHashTable[FORWARD]); candidateHashTable[FORWARD] = NULL; BigDealloc(candidateHashTable[RC]); candidateHashTable[RC] = NULL; BigDealloc(weightLists); weightLists = NULL; BigDealloc(hashTableElementPool); hashTableElementPool = NULL; if (NULL != hitsPerContigCounts) { BigDealloc(hitsPerContigCounts); hitsPerContigCounts = NULL; } } } BaseAligner::HashTableElement::HashTableElement() { init(); } void BaseAligner::HashTableElement::init() { weightNext = NULL; weightPrev = NULL; next = NULL; candidatesUsed = 0; baseGenomeLocation = 0; weight = 0; lowestPossibleScore = UnusedScoreValue; bestScore = UnusedScoreValue; direction = FORWARD; allExtantCandidatesScored = false; matchProbabilityForBestScore = 0; usedAffineGapScoring = false; agScore = 0; } void BaseAligner::Candidate::init() { score = UnusedScoreValue; } void BaseAligner::clearCandidates() { hashTableEpoch++; nUsedHashTableElements = 0; highestUsedWeightList = 0; for (unsigned i = 1; i < numWeightLists; i++) { weightLists[i].weightNext = weightLists[i].weightPrev = &weightLists[i]; } } void BaseAligner::incrementWeight(HashTableElement *element) { if (element->allExtantCandidatesScored) { // // It's already scored, so it shouldn't be on a weight list. // _ASSERT(element->weightNext == element); _ASSERT(element->weightPrev == element); return; } // // It's possible to have elements with weight > maxSeedsToUse. This // happens when a single seed occurs more than once within a particular // element (imagine an element with bases ATATATATATATATAT..., it will // match the appropriate seed at offset 0, 2, 4, etc.) If that happens, // just don't let the weight get too big. // if (element->weight >= numWeightLists - 1) { return; } // // Remove it from its existing list. // element->weightNext->weightPrev = element->weightPrev; element->weightPrev->weightNext = element->weightNext; element->weight++; highestUsedWeightList = __max(highestUsedWeightList,element->weight); // // And insert it at the tail of the new list. // element->weightNext = &weightLists[element->weight]; element->weightPrev = weightLists[element->weight].weightPrev; element->weightNext->weightPrev = element; element->weightPrev->weightNext = element; } size_t BaseAligner::getBigAllocatorReservation(GenomeIndex *index, bool ownLandauVishkin, unsigned maxHitsToConsider, unsigned maxReadSize, unsigned seedLen, unsigned numSeedsFromCommandLine, double seedCoverage, int maxSecondaryAlignmentsPerContig, unsigned extraSearchDepth) { unsigned maxSeedsToUse; if (0 != numSeedsFromCommandLine) { maxSeedsToUse = numSeedsFromCommandLine; } else { maxSeedsToUse = (unsigned)(maxReadSize * seedCoverage / seedLen); } size_t candidateHashTablesSize = (maxHitsToConsider * maxSeedsToUse * 3)/2; // *1.5 for hash table slack size_t hashTableElementPoolSize = maxHitsToConsider * maxSeedsToUse * 2 ; // *2 for RC size_t contigCounters; if (maxSecondaryAlignmentsPerContig > 0) { contigCounters = sizeof(HitsPerContigCounts)* index->getGenome()->getNumContigs(); } else { contigCounters = 0; } return contigCounters + sizeof(_uint64) * 14 + // allow for alignment sizeof(BaseAligner) + // our own member variables (ownLandauVishkin ? LandauVishkin<>::getBigAllocatorReservation() + LandauVishkin<-1>::getBigAllocatorReservation() : 0) + // our LandauVishkin objects // AffineGap<>::getBigAllocatorReservation() + // AffineGap<-1>::getBigAllocatorReservation() + // our AffineGap objects AffineGapVectorized<>::getBigAllocatorReservation() + AffineGapVectorized<-1>::getBigAllocatorReservation() + // our AffineGap objects sizeof(char) * maxReadSize * 2 + // rcReadData sizeof(char) * maxReadSize * 4 + 2 * MAX_K + // reversed read (both) sizeof(BYTE) * (maxReadSize + 7 + 128) / 8 + // seed used sizeof(HashTableElement) * hashTableElementPoolSize + // hash table element pool sizeof(HashTableAnchor) * candidateHashTablesSize * 2 + // candidate hash table (both) sizeof(HashTableElement) * (maxSeedsToUse + 1) + // weight lists sizeof(unsigned) * extraSearchDepth; // hitCountByExtraSearchDepth } void BaseAligner::finalizeSecondaryResults( Read *read, SingleAlignmentResult *primaryResult, _int64 *nSecondaryResults, // in/out SingleAlignmentResult *secondaryResults, _int64 maxSecondaryResults, int maxEditDistanceForSecondaryResults, int bestScore) { // // There's no guarantee that the results are actually within the bound; the aligner records anything that's // within the bound when it's scored, but if we subsequently found a better fit, then it may no longer be // close enough. Get rid of those now. // // NB: This code is very similar to code at the end of IntersectingPairedEndAligner::align(). Sorry. // _ASSERT(bestScore == primaryResult->score); primaryResult->scorePriorToClipping = primaryResult->score; if (!ignoreAlignmentAdjustmentsForOm) { // // Start by adjusting the alignments for the primary and secondary reads, since that can affect their score // and hence whether they should be kept. // alignmentAdjuster.AdjustAlignment(read, primaryResult); if (primaryResult->status != NotFound) { bestScore = primaryResult->score; } else { bestScore = 65536; } for (int i = 0; i < *nSecondaryResults; i++) { secondaryResults[i].scorePriorToClipping = secondaryResults[i].score; alignmentAdjuster.AdjustAlignment(read, &secondaryResults[i]); if (secondaryResults[i].status != NotFound) { bestScore = __min(bestScore, secondaryResults[i].score); } } } int worstScoreToKeep = min((int)maxK, bestScore + maxEditDistanceForSecondaryResults); int i = 0; while (i < *nSecondaryResults) { if (secondaryResults[i].score > worstScoreToKeep) { // // This one is too bad to keep. Move the last one from the array here and decrement the // count. Don't move up i, because the one we just moved in may also be too // bad. // secondaryResults[i] = secondaryResults[(*nSecondaryResults)-1]; (*nSecondaryResults)--; } else { if (ignoreAlignmentAdjustmentsForOm) { secondaryResults[i].scorePriorToClipping = secondaryResults[i].score; } i++; } } if (maxSecondaryAlignmentsPerContig > 0 && primaryResult->status != NotFound) { // // Run through the results and count the number of results per contig, to see if any of them are too big. // bool anyContigHasTooManyResults = false; int primaryResultContigNum = genome->getContigNumAtLocation(primaryResult->location); hitsPerContigCounts[primaryResultContigNum].hits = 1; hitsPerContigCounts[primaryResultContigNum].epoch = hashTableEpoch; for (i = 0; i < *nSecondaryResults; i++) { int contigNum = genome->getContigNumAtLocation(secondaryResults[i].location); if (hitsPerContigCounts[contigNum].epoch != hashTableEpoch) { hitsPerContigCounts[contigNum].epoch = hashTableEpoch; hitsPerContigCounts[contigNum].hits = 0; } hitsPerContigCounts[contigNum].hits++; if (hitsPerContigCounts[contigNum].hits > maxSecondaryAlignmentsPerContig) { anyContigHasTooManyResults = true; break; } } if (anyContigHasTooManyResults) { // // Just sort them all, in order of contig then hit depth. // qsort(secondaryResults, *nSecondaryResults, sizeof(*secondaryResults), SingleAlignmentResult::compareByContigAndScore); // // Now run through and eliminate any contigs with too many hits. We can't use the same trick at the first loop above, because the // counting here relies on the results being sorted. So, instead, we just copy them as we go. // int currentContigNum = -1; int currentContigCount = 0; int destResult = 0; for (int sourceResult = 0; sourceResult < *nSecondaryResults; sourceResult++) { int contigNum = genome->getContigNumAtLocation(secondaryResults[sourceResult].location); if (contigNum != currentContigNum) { currentContigNum = contigNum; currentContigCount = (contigNum == primaryResultContigNum) ? 1 : 0; } currentContigCount++; if (currentContigCount <= maxSecondaryAlignmentsPerContig) { // // Keep it. If we don't get here, then we don't copy the result and // don't increment destResult. And yes, this will sometimes copy a // result over itself. That's harmless. // secondaryResults[destResult] = secondaryResults[sourceResult]; destResult++; } } // for each source result *nSecondaryResults = destResult; } } // if maxSecondaryAlignmentsPerContig > 0 if (*nSecondaryResults > maxSecondaryResults) { qsort(secondaryResults, *nSecondaryResults, sizeof(*secondaryResults), SingleAlignmentResult::compareByScore); *nSecondaryResults = maxSecondaryResults; // Just truncate it } } Single end aligner: remove MAPQ 0 early termination for now. Add in later after benchmarking /*++ Module Name: BaseAligner.cpp Abstract: Single-end aligner Authors: Bill Bolosky, August, 2011 Environment: User mode service. This class is NOT thread safe. It's the caller's responsibility to ensure that at most one thread uses an instance at any time. Revision History: Adapted from Matei Zaharia's Scala implementation. --*/ #include "stdafx.h" #include "BaseAligner.h" #include "Compat.h" #include "LandauVishkin.h" #include "BigAlloc.h" #include "mapq.h" #include "SeedSequencer.h" #include "exit.h" #include "AlignerOptions.h" #include "Error.h" using std::min; // #define TRACE_ALIGNER 1 #ifdef TRACE_ALIGNER // If you turn this on, then stdout writing won't work. #define TRACE printf #else #define TRACE(...) {} #endif BaseAligner::BaseAligner( GenomeIndex *i_genomeIndex, unsigned i_maxHitsToConsider, unsigned i_maxK, unsigned i_maxReadSize, unsigned i_maxSeedsToUseFromCommandLine, double i_maxSeedCoverage, unsigned i_minWeightToCheck, unsigned i_extraSearchDepth, bool i_noUkkonen, bool i_noOrderedEvaluation, bool i_noTruncation, bool i_useAffineGap, bool i_ignoreAlignmentAdjustmentsForOm, int i_maxSecondaryAlignmentsPerContig, LandauVishkin<1>*i_landauVishkin, LandauVishkin<-1>*i_reverseLandauVishkin, unsigned i_matchReward, unsigned i_subPenalty, unsigned i_gapOpenPenalty, unsigned i_gapExtendPenalty, unsigned i_minAGScore, AlignerStats *i_stats, BigAllocator *allocator) : genomeIndex(i_genomeIndex), maxHitsToConsider(i_maxHitsToConsider), maxK(i_maxK), maxReadSize(i_maxReadSize), maxSeedsToUseFromCommandLine(i_maxSeedsToUseFromCommandLine), maxSeedCoverage(i_maxSeedCoverage), readId(-1), extraSearchDepth(i_extraSearchDepth), explorePopularSeeds(false), stopOnFirstHit(false), stats(i_stats), noUkkonen(i_noUkkonen), noOrderedEvaluation(i_noOrderedEvaluation), noTruncation(i_noTruncation), useAffineGap(i_useAffineGap), matchReward(i_matchReward), subPenalty(i_subPenalty), gapOpenPenalty(i_gapOpenPenalty), gapExtendPenalty(i_gapExtendPenalty), minAGScore(i_minAGScore), minWeightToCheck(max(1u, i_minWeightToCheck)), maxSecondaryAlignmentsPerContig(i_maxSecondaryAlignmentsPerContig), alignmentAdjuster(i_genomeIndex->getGenome()), ignoreAlignmentAdjustmentsForOm(i_ignoreAlignmentAdjustmentsForOm) /*++ Routine Description: Constructor for the BaseAligner class. Aligners align reads against an indexed genome. Arguments: i_genomeIndex - The index against which to do the alignments i_maxHitsToConsider - The maximum number of hits to use from a seed lookup. Any lookups that return more than this are ignored. i_maxK - The largest string difference to consider for any comparison. i_maxReadSize - Bound on the number of bases in any read. There's no reason to make it tight, it just affects a little memory allocation. i_maxSeedsToUse - The maximum number of seeds to use when aligning any read (not counting ones ignored because they resulted in too many hits). Once we've looked up this many seeds, we just score what we've got. i_maxSeedCoverage - The maximum number of seeds to use expressed as readSize/seedSize i_extraSearchDepth - How deeply beyond bestScore do we search? i_noUkkonen - Don't use Ukkonen's algorithm (i.e., don't reduce the max edit distance depth as we score candidates) i_noOrderedEvaluation-Don't order evaluating the reads by the hit count in order to drive down the max edit distance more quickly i_noTruncation - Don't truncate searches based on count of disjoint seed misses i_useAffineGap - Use affine gap scoring for seed extension i_ignoreAlignmentAdjustmentsForOm - When a read score is adjusted because of soft clipping for being near the end of a contig, don't use the adjusted score when computing what to keep for -om i_maxSecondaryAlignmentsPerContig - Maximum secondary alignments per contig; -1 means don't limit this i_landauVishkin - an externally supplied LandauVishkin string edit distance object. This is useful if we're expecting repeated computations and use the LV cache. i_reverseLandauVishkin - the same for the reverse direction. i_matchReward - affine gap score for a match i_subPenalty - affine gap score for a substitution i_gapOpenPenalty - affine gap cost for opening a gap (indel) i_gapExtendPenalty - affine gap cost for extending a gap (indel) i_minAGScore - minimum score for alignment using affine gap score i_stats - an object into which we report out statistics allocator - an allocator that's used to allocate our local memory. This is useful for TLB optimization. If this is supplied, the caller is responsible for deallocation, we'll not deallocate any dynamic memory in our destructor. --*/ { hadBigAllocator = allocator != NULL; nHashTableLookups = 0; nLocationsScored = 0; nHitsIgnoredBecauseOfTooHighPopularity = 0; nReadsIgnoredBecauseOfTooManyNs = 0; nIndelsMerged = 0; genome = genomeIndex->getGenome(); seedLen = genomeIndex->getSeedLength(); doesGenomeIndexHave64BitLocations = genomeIndex->doesGenomeIndexHave64BitLocations(); probDistance = new ProbabilityDistance(SNP_PROB, GAP_OPEN_PROB, GAP_EXTEND_PROB); // Match Mason if ((i_landauVishkin == NULL) != (i_reverseLandauVishkin == NULL)) { WriteErrorMessage("Must supply both or neither of forward & reverse Landau-Vishkin objects. You tried exactly one.\n"); soft_exit(1); } if (i_subPenalty > (i_gapOpenPenalty + i_gapExtendPenalty)) { WriteErrorMessage("Substitutions may be penalized too high to be seen in alignments. Make sure subPenalty < gapOpen + gapExtend\n"); soft_exit(1); } if (i_landauVishkin == NULL) { if (allocator) { landauVishkin = new (allocator) LandauVishkin<>; reverseLandauVishkin = new (allocator) LandauVishkin<-1>; } else { landauVishkin = new LandauVishkin<>; reverseLandauVishkin = new LandauVishkin<-1>; } ownLandauVishkin = true; } else { landauVishkin = i_landauVishkin; reverseLandauVishkin = i_reverseLandauVishkin; ownLandauVishkin = false; } if (allocator) { // affineGap = new (allocator) AffineGap<>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty); // reverseAffineGap = new (allocator) AffineGap<-1>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty); affineGap = new (allocator) AffineGapVectorized<>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty); reverseAffineGap = new (allocator) AffineGapVectorized<-1>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty); } else { // affineGap = new AffineGap<>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty); // reverseAffineGap = new AffineGap<-1>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty); affineGap = new AffineGapVectorized<>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty); reverseAffineGap = new AffineGapVectorized<-1>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty); } unsigned maxSeedsToUse; if (0 != maxSeedsToUseFromCommandLine) { maxSeedsToUse = maxSeedsToUseFromCommandLine; } else { maxSeedsToUse = (int)(maxSeedCoverage * maxReadSize / genomeIndex->getSeedLength()); } numWeightLists = maxSeedsToUse + 1; candidateHashTablesSize = (maxHitsToConsider * maxSeedsToUse * 3)/2; // *1.5 for hash table slack hashTableElementPoolSize = maxHitsToConsider * maxSeedsToUse * 2 ; // *2 for RC if (allocator) { rcReadData = (char *)allocator->allocate(sizeof(char) * maxReadSize * 2); // The *2 is to allocte space for the quality string } else { rcReadData = (char *)BigAlloc(sizeof(char) * maxReadSize * 2); // The *2 is to allocte space for the quality string } rcReadQuality = rcReadData + maxReadSize; if (allocator) { reversedRead[FORWARD] = (char *)allocator->allocate(sizeof(char) * maxReadSize * 4 + 2 * MAX_K); // Times 4 to also hold RC version and genome data (+2MAX_K is for genome data) } else { reversedRead[FORWARD] = (char *)BigAlloc(sizeof(char) * maxReadSize * 4 + 2 * MAX_K); // Times 4 to also hold RC version and genome data (+2MAX_K is for genome data) } rcReadData = (char *)BigAlloc(sizeof(char) * maxReadSize); // treat everything but ACTG like N for (unsigned i = 0; i < 256; i++) { nTable[i] = 1; rcTranslationTable[i] = 'N'; } reversedRead[RC] = reversedRead[FORWARD] + maxReadSize; rcTranslationTable['A'] = 'T'; rcTranslationTable['G'] = 'C'; rcTranslationTable['C'] = 'G'; rcTranslationTable['T'] = 'A'; rcTranslationTable['N'] = 'N'; memset(nTable, 0, sizeof(nTable)); nTable['N'] = 1; if (allocator) { seedUsed = (BYTE *)allocator->allocate((sizeof(BYTE) * (maxReadSize + 7 + 128) / 8)); // +128 to make sure it extends at both } else { seedUsed = (BYTE *)BigAlloc((sizeof(BYTE) * (maxReadSize + 7 + 128) / 8)); // +128 to make sure it extends at both } seedUsedAsAllocated = seedUsed; // Save the pointer for the delete. seedUsed += 8; // This moves the pointer up an _int64, so we now have the appropriate before buffer. nUsedHashTableElements = 0; if (allocator) { candidateHashTable[FORWARD] = (HashTableAnchor *)allocator->allocate(sizeof(HashTableAnchor) * candidateHashTablesSize); candidateHashTable[RC] = (HashTableAnchor *)allocator->allocate(sizeof(HashTableAnchor) * candidateHashTablesSize); weightLists = (HashTableElement *)allocator->allocate(sizeof(HashTableElement) * numWeightLists); hashTableElementPool = (HashTableElement *)allocator->allocate(sizeof(HashTableElement) * hashTableElementPoolSize); // Allocte last, because it's biggest and usually unused. This puts all of the commonly used stuff into one large page. hitCountByExtraSearchDepth = (unsigned *)allocator->allocate(sizeof(*hitCountByExtraSearchDepth) * extraSearchDepth); if (maxSecondaryAlignmentsPerContig > 0) { hitsPerContigCounts = (HitsPerContigCounts *)allocator->allocate(sizeof(*hitsPerContigCounts) * genome->getNumContigs()); memset(hitsPerContigCounts, 0, sizeof(*hitsPerContigCounts) * genome->getNumContigs()); } else { hitsPerContigCounts = NULL; } } else { candidateHashTable[FORWARD] = (HashTableAnchor *)BigAlloc(sizeof(HashTableAnchor) * candidateHashTablesSize); candidateHashTable[RC] = (HashTableAnchor *)BigAlloc(sizeof(HashTableAnchor) * candidateHashTablesSize); weightLists = (HashTableElement *)BigAlloc(sizeof(HashTableElement) * numWeightLists); hashTableElementPool = (HashTableElement *)BigAlloc(sizeof(HashTableElement) * hashTableElementPoolSize); hitCountByExtraSearchDepth = (unsigned *)BigAlloc(sizeof(*hitCountByExtraSearchDepth) * extraSearchDepth); if (maxSecondaryAlignmentsPerContig > 0) { hitsPerContigCounts = (HitsPerContigCounts *)BigAlloc(sizeof(*hitsPerContigCounts) * genome->getNumContigs()); memset(hitsPerContigCounts, 0, sizeof(*hitsPerContigCounts) * genome->getNumContigs()); } else { hitsPerContigCounts = NULL; } } for (unsigned i = 0; i < hashTableElementPoolSize; i++) { hashTableElementPool[i].init(); } for (unsigned i = 0; i < maxSeedsToUse + 1; i++) { weightLists[i].init(); } for (Direction rc = 0; rc < NUM_DIRECTIONS; rc++) { memset(candidateHashTable[rc],0,sizeof(HashTableAnchor) * candidateHashTablesSize); } hashTableEpoch = 0; } #ifdef _DEBUG bool _DumpAlignments = true; #endif // _DEBUG bool BaseAligner::AlignRead( Read *inputRead, SingleAlignmentResult *primaryResult, int maxEditDistanceForSecondaryResults, _int64 secondaryResultBufferSize, _int64 *nSecondaryResults, _int64 maxSecondaryResults, SingleAlignmentResult *secondaryResults // The caller passes in a buffer of secondaryResultBufferSize and it's filled in by AlignRead() ) /*++ Routine Description: Align a particular read, possibly constraining the search around a given location. Arguments: read - the read to align primaryResult - the best alignment result found maxEditDistanceForSecondaryResults - How much worse than the primary result should we look? secondaryResultBufferSize - the size of the secondaryResults buffer. If provided, it must be at least maxK * maxSeeds * 2. nRescondaryResults - returns the number of secondary results found maxSecondaryResults - limit the number of secondary results to this secondaryResults - returns the secondary results Return Value: true if there was enough space in secondaryResults, false otherwise --*/ { bool overflowedSecondaryResultsBuffer = false; memset(hitCountByExtraSearchDepth, 0, sizeof(*hitCountByExtraSearchDepth) * extraSearchDepth); if (NULL != nSecondaryResults) { *nSecondaryResults = 0; } firstPassSeedsNotSkipped[FORWARD] = firstPassSeedsNotSkipped[RC] = 0; smallestSkippedSeed[FORWARD] = smallestSkippedSeed[RC] = 0x8fffffffffffffff; highestWeightListChecked = 0; unsigned maxSeedsToUse; if (0 != maxSeedsToUseFromCommandLine) { maxSeedsToUse = maxSeedsToUseFromCommandLine; } else { maxSeedsToUse = (int)(2 * maxSeedCoverage * inputRead->getDataLength() / genomeIndex->getSeedLength()); // 2x is for FORWARD/RC } primaryResult->location = InvalidGenomeLocation; // Value to return if we don't find a location. primaryResult->direction = FORWARD; // So we deterministically print the read forward in this case. primaryResult->score = UnusedScoreValue; primaryResult->status = NotFound; primaryResult->clippingForReadAdjustment = 0; primaryResult->usedAffineGapScoring = false; primaryResult->basesClippedBefore = 0; primaryResult->basesClippedAfter = 0; primaryResult->agScore = 0; unsigned lookupsThisRun = 0; popularSeedsSkipped = 0; // // A bitvector for used seeds, indexed on the starting location of the seed within the read. // if (inputRead->getDataLength() > maxReadSize) { WriteErrorMessage("BaseAligner:: got too big read (%d > %d)\n" "Increase MAX_READ_LENGTH at the beginning of Read.h and recompile\n", inputRead->getDataLength(), maxReadSize); soft_exit(1); } if ((int)inputRead->getDataLength() < seedLen) { // // Too short to have any seeds, it's hopeless. // No need to finalize secondary results, since we don't have any. // return true; } #ifdef TRACE_ALIGNER printf("Aligning read '%.*s':\n%.*s\n%.*s\n", inputRead->getIdLength(), inputRead->getId(), inputRead->getDataLength(), inputRead->getData(), inputRead->getDataLength(), inputRead->getQuality()); #endif #ifdef _DEBUG if (_DumpAlignments) { printf("BaseAligner: aligning read ID '%.*s', data '%.*s'\n", inputRead->getIdLength(), inputRead->getId(), inputRead->getDataLength(), inputRead->getData()); } #endif // _DEBUG // // Clear out the seed used array. // memset(seedUsed, 0, (inputRead->getDataLength() + 7) / 8); unsigned readLen = inputRead->getDataLength(); const char *readData = inputRead->getData(); const char *readQuality = inputRead->getQuality(); unsigned countOfNs = 0; for (unsigned i = 0; i < readLen; i++) { char baseByte = readData[i]; char complement = rcTranslationTable[baseByte]; rcReadData[readLen - i - 1] = complement; rcReadQuality[readLen - i - 1] = readQuality[i]; reversedRead[FORWARD][readLen - i - 1] = baseByte; reversedRead[RC][i] = complement; countOfNs += nTable[baseByte]; } if (countOfNs > maxK) { nReadsIgnoredBecauseOfTooManyNs++; // No need to finalize secondary results, since we don't have any. return true; } // // Block off any seeds that would contain an N. // if (countOfNs > 0) { int minSeedToConsiderNing = 0; // In English, any word can be verbed. Including, apparently, "N." for (int i = 0; i < (int) readLen; i++) { if (BASE_VALUE[readData[i]] > 3) { int limit = __min(i + seedLen - 1, readLen-1); for (int j = __max(minSeedToConsiderNing, i - (int) seedLen + 1); j <= limit; j++) { SetSeedUsed(j); } minSeedToConsiderNing = limit+1; if (minSeedToConsiderNing >= (int) readLen) break; } } } Read reverseComplimentRead; Read *read[NUM_DIRECTIONS]; read[FORWARD] = inputRead; read[RC] = &reverseComplimentRead; read[RC]->init(NULL, 0, rcReadData, rcReadQuality, readLen); clearCandidates(); // // Initialize the bases table, which represents which bases we've checked. // We have readSize - seeds size + 1 possible seeds. // unsigned nPossibleSeeds = readLen - seedLen + 1; TRACE("nPossibleSeeds: %d\n", nPossibleSeeds); unsigned nextSeedToTest = 0; unsigned wrapCount = 0; lowestPossibleScoreOfAnyUnseenLocation[FORWARD] = lowestPossibleScoreOfAnyUnseenLocation[RC] = 0; mostSeedsContainingAnyParticularBase[FORWARD] = mostSeedsContainingAnyParticularBase[RC] = 1; // Instead of tracking this for real, we're just conservative and use wrapCount+1. It's faster. bestScore = UnusedScoreValue; secondBestScore = UnusedScoreValue; nSeedsApplied[FORWARD] = nSeedsApplied[RC] = 0; lvScores = 0; lvScoresAfterBestFound = 0; probabilityOfAllCandidates = 0.0; probabilityOfBestCandidate = 0.0; scoreLimit = maxK + extraSearchDepth; // For MAPQ computation while (nSeedsApplied[FORWARD] + nSeedsApplied[RC] < maxSeedsToUse) { // // Choose the next seed to use. Choose the first one that isn't used // if (nextSeedToTest >= nPossibleSeeds) { // // We're wrapping. We want to space the seeds out as much as possible, so if we had // a seed length of 20 we'd want to take 0, 10, 5, 15, 2, 7, 12, 17. To make the computation // fast, we use use a table lookup. // wrapCount++; if (wrapCount >= seedLen) { // // We tried all possible seeds without matching or even getting enough seeds to // exceed our seed count. Do the best we can with what we have. // #ifdef TRACE_ALIGNER printf("Calling score with force=true because we wrapped around enough\n"); #endif score( true, read, primaryResult, maxEditDistanceForSecondaryResults, secondaryResultBufferSize, nSecondaryResults, secondaryResults, &overflowedSecondaryResultsBuffer); #ifdef _DEBUG if (_DumpAlignments) printf("\tFinal result score %d MAPQ %d (%e probability of best candidate, %e probability of all candidates) at %llu\n", primaryResult->score, primaryResult->mapq, probabilityOfBestCandidate, probabilityOfAllCandidates, primaryResult->location.location); #endif // _DEBUG if (overflowedSecondaryResultsBuffer) { return false; } finalizeSecondaryResults(read[FORWARD], primaryResult, nSecondaryResults, secondaryResults, maxSecondaryResults, maxEditDistanceForSecondaryResults, bestScore); return true; } nextSeedToTest = GetWrappedNextSeedToTest(seedLen, wrapCount); mostSeedsContainingAnyParticularBase[FORWARD] = mostSeedsContainingAnyParticularBase[RC] = wrapCount + 1; } while (nextSeedToTest < nPossibleSeeds && IsSeedUsed(nextSeedToTest)) { // // This seed is already used. Try the next one. // TRACE("Skipping due to IsSeedUsed\n"); nextSeedToTest++; } if (nextSeedToTest >= nPossibleSeeds) { // // Unusable seeds have pushed us past the end of the read. Go back around the outer loop so we wrap properly. // TRACE("Eek, we're past the end of the read\n"); continue; } SetSeedUsed(nextSeedToTest); if (!Seed::DoesTextRepresentASeed(read[FORWARD]->getData() + nextSeedToTest, seedLen)) { continue; } Seed seed(read[FORWARD]->getData() + nextSeedToTest, seedLen); _int64 nHits[NUM_DIRECTIONS]; // Number of times this seed hits in the genome const GenomeLocation *hits[NUM_DIRECTIONS]; // The actual hits (of size nHits) GenomeLocation singletonHits[NUM_DIRECTIONS]; // Storage for single hits (this is required for 64 bit genome indices, since they might use fewer than 8 bytes internally) const unsigned *hits32[NUM_DIRECTIONS]; if (doesGenomeIndexHave64BitLocations) { genomeIndex->lookupSeed(seed, &nHits[FORWARD], &hits[FORWARD], &nHits[RC], &hits[RC], &singletonHits[FORWARD], &singletonHits[RC]); } else { genomeIndex->lookupSeed32(seed, &nHits[FORWARD], &hits32[FORWARD], &nHits[RC], &hits32[RC]); } nHashTableLookups++; lookupsThisRun++; #ifdef _DEBUG if (_DumpAlignments) { printf("\tSeed offset %2d, %4lld hits, %4lld rcHits.", nextSeedToTest, nHits[0], nHits[1]); for (int rc = 0; rc < 2; rc++) { for (unsigned i = 0; i < __min(nHits[rc], 5); i++) { printf(" %sHit at %9llu.", rc == 1 ? "RC " : "", doesGenomeIndexHave64BitLocations ? hits[rc][i].location : (_int64)hits32[rc][i]); } } printf("\n"); } #endif // _DEUBG #ifdef TRACE_ALIGNER printf("Looked up seed %.*s (offset %d): hits=%u, rchits=%u\n", seedLen, inputRead->getData() + nextSeedToTest, nextSeedToTest, nHits[0], nHits[1]); for (int rc = 0; rc < 2; rc++) { if (nHits[rc] <= maxHitsToConsider) { printf("%sHits:", rc == 1 ? "RC " : ""); for (unsigned i = 0; i < nHits[rc]; i++) printf(" %9llu", doesGenomeIndexHave64BitLocations ? hits[rc][i].location : (_int64)hits32[rc][i]); printf("\n"); } } #endif bool appliedEitherSeed = false; for (Direction direction = 0; direction < NUM_DIRECTIONS; direction++) { if (nHits[direction] > maxHitsToConsider && !explorePopularSeeds) { // // This seed is matching too many places. Just pretend we never looked and keep going. // nHitsIgnoredBecauseOfTooHighPopularity++; popularSeedsSkipped++; smallestSkippedSeed[direction] = __min(nHits[direction], smallestSkippedSeed[direction]); } else { if (0 == wrapCount) { firstPassSeedsNotSkipped[direction]++; } // // Update the candidates list with any hits from this seed. If lowest possible score of any unseen location is // more than best_score + confDiff then we know that if this location is newly seen then its location won't ever be a // winner, and we can ignore it. // unsigned offset; if (direction == FORWARD) { offset = nextSeedToTest; } else { // // The RC seed is at offset ReadSize - SeedSize - seed offset in the RC seed. // // To see why, imagine that you had a read that looked like 0123456 (where the digits // represented some particular bases, and digit' is the base's complement). Then the // RC of that read is 6'5'4'3'2'1'. So, when we look up the hits for the seed at // offset 0 in the forward read (i.e. 012 assuming a seed size of 3) then the index // will also return the results for the seed's reverse complement, i.e., 3'2'1'. // This happens as the last seed in the RC read. // offset = readLen - seedLen - nextSeedToTest; } const unsigned prefetchDepth = 30; _int64 limit = min(nHits[direction], (_int64)maxHitsToConsider) + prefetchDepth; for (unsigned iBase = 0 ; iBase < limit; iBase += prefetchDepth) { // // This works in two phases: we launch prefetches for a group of hash table lines, // then we do all of the inserts, and then repeat. // _int64 innerLimit = min((_int64)iBase + prefetchDepth, min(nHits[direction], (_int64)maxHitsToConsider)); if (doAlignerPrefetch) { for (unsigned i = iBase; i < innerLimit; i++) { if (doesGenomeIndexHave64BitLocations) { prefetchHashTableBucket(GenomeLocationAsInt64(hits[direction][i]) - offset, direction); } else { prefetchHashTableBucket(hits32[direction][i] - offset, direction); } } } for (unsigned i = iBase; i < innerLimit; i++) { // // Find the genome location where the beginning of the read would hit, given a match on this seed. // GenomeLocation genomeLocationOfThisHit; if (doesGenomeIndexHave64BitLocations) { genomeLocationOfThisHit = hits[direction][i] - offset; } else { genomeLocationOfThisHit = hits32[direction][i] - offset; } Candidate *candidate = NULL; HashTableElement *hashTableElement; findCandidate(genomeLocationOfThisHit, direction, &candidate, &hashTableElement); if (NULL != hashTableElement) { if (!noOrderedEvaluation) { // If noOrderedEvaluation, just leave them all on the one-hit weight list so they get evaluated in whatever order incrementWeight(hashTableElement); } candidate->seedOffset = offset; _ASSERT((unsigned)candidate->seedOffset <= readLen - seedLen); } else if (lowestPossibleScoreOfAnyUnseenLocation[direction] <= scoreLimit || noTruncation) { _ASSERT(offset <= readLen - seedLen); allocateNewCandidate(genomeLocationOfThisHit, direction, lowestPossibleScoreOfAnyUnseenLocation[direction], offset, &candidate, &hashTableElement); } } } nSeedsApplied[direction]++; appliedEitherSeed = true; } // not too popular } // directions #if 1 nextSeedToTest += seedLen; #else // 0 // // If we don't have enough seeds left to reach the end of the read, space out the seeds more-or-less evenly. // if ((maxSeedsToUse - (nSeedsApplied[FORWARD] + nSeedsApplied[RC]) + 1) * seedLen + nextSeedToTest < nPossibleSeeds) { _ASSERT((nPossibleSeeds + nextSeedToTest) / (maxSeedsToUse - (nSeedsApplied[FORWARD] + nSeedsApplied[RC]) + 1) > seedLen); nextSeedToTest += (nPossibleSeeds + nextSeedToTest) / (maxSeedsToUse - (nSeedsApplied[FORWARD] + nSeedsApplied[RC]) + 1); } else { nextSeedToTest += seedLen; } #endif // 0 if (appliedEitherSeed) { // // And finally, try scoring. // if (score( false, read, primaryResult, maxEditDistanceForSecondaryResults, secondaryResultBufferSize, nSecondaryResults, secondaryResults, &overflowedSecondaryResultsBuffer)) { #ifdef _DEBUG if (_DumpAlignments) printf("\tFinal result score %d MAPQ %d at %llu\n", primaryResult->score, primaryResult->mapq, primaryResult->location.location); #endif // _DEBUG if (overflowedSecondaryResultsBuffer) { return false; } finalizeSecondaryResults(read[FORWARD], primaryResult, nSecondaryResults, secondaryResults, maxSecondaryResults, maxEditDistanceForSecondaryResults, bestScore); return true; } } } // // Do the best with what we've got. // #ifdef TRACE_ALIGNER printf("Calling score with force=true because we ran out of seeds\n"); #endif score( true, read, primaryResult, maxEditDistanceForSecondaryResults, secondaryResultBufferSize, nSecondaryResults, secondaryResults, &overflowedSecondaryResultsBuffer); #ifdef _DEBUG if (_DumpAlignments) printf("\tFinal result score %d MAPQ %d (%e probability of best candidate, %e probability of all candidates) at %llu\n", primaryResult->score, primaryResult->mapq, probabilityOfBestCandidate, probabilityOfAllCandidates, primaryResult->location.location); #endif // _DEBUG if (overflowedSecondaryResultsBuffer) { return false; } finalizeSecondaryResults(read[FORWARD], primaryResult, nSecondaryResults, secondaryResults, maxSecondaryResults, maxEditDistanceForSecondaryResults, bestScore); return true; } bool BaseAligner::score( bool forceResult, Read *read[NUM_DIRECTIONS], SingleAlignmentResult *primaryResult, int maxEditDistanceForSecondaryResults, _int64 secondaryResultBufferSize, _int64 *nSecondaryResults, SingleAlignmentResult *secondaryResults, bool *overflowedSecondaryBuffer) /*++ Routine Description: Make progress in scoring a possibly partial alignment. This is a private method of the BaseAligner class that's used only by AlignRead. It does a number of things. First, it computes the lowest possible score of any unseen location. This is useful because once we have a scored hit that's more than confDiff better than all unseen locations, there's no need to lookup more of them, we can just score what we've got and be sure that the answer is right (unless errors have pushed the read to be closer to a wrong location than to the correct one, in which case it's hopeless). It then decides whether it should score a location, and if so what one to score. It chooses the unscored location that's got the highest weight (i.e., appeared in the most hash table lookups), since that's most likely to be the winner. If there are multiple candidates with the same best weight, it breaks the tie using the best possible score for the candidates (which is determined when they're first hit). Remaining ties are broken arbitrarily. It merges indels with scored candidates. If there's an insertion or deletion in the read, then we'll get very close but unequal results out of the hash table lookup for parts of the read on opposite sides of the insertion or deletion. This throws out the one with the worse score. It then figures out if we have a definitive answer, and says what that is. Arguments: forceResult - should we generate an answer even if it's not definitive? read - the read we're aligning in both directions result - returns the result if we reach one singleHitGenomeLocation - returns the location in the genome if we return a single hit hitDirection - if we return a single hit, indicates its direction candidates - in/out the array of candidates that have hit and possibly been scored mapq - returns the map quality if we've reached a final result secondary - returns secondary alignment locations & directions (optional) Return Value: true iff we've reached a result. When called with forceResult, we'll always return true. --*/ { *overflowedSecondaryBuffer = false; #ifdef TRACE_ALIGNER printf("score() called with force=%d nsa=%d nrcsa=%d best=%u bestloc=%u 2nd=%u\n", forceResult, nSeedsApplied[FORWARD], nSeedsApplied[RC], bestScore, bestScoreGenomeLocation, secondBestScore); //printf("Candidates:\n"); //for (int i = 0; i < nCandidates; i++) { // Candidate* c = candidates + i; // printf(" loc=%u rc=%d weight=%u minps=%u scored=%d score=%u r=%u-%u\n", // c->genomeLocation, c->isRC, c->weight, c->minPossibleScore, c->scored, // c->score, c->minRange, c->maxRange); //} //printf("\n\n"); #endif if (0 == mostSeedsContainingAnyParticularBase[FORWARD] && 0 == mostSeedsContainingAnyParticularBase[RC]) { // // The only way we can get here is if we've tried all of the seeds that we're willing // to try and every one of them generated too many hits to process. Give up. // _ASSERT(forceResult); primaryResult->status = NotFound; primaryResult->mapq = 0; return true; } // // Recompute lowestPossibleScore. // for (Direction direction = 0; direction < 2; direction++) { if (0 != mostSeedsContainingAnyParticularBase[direction]) { lowestPossibleScoreOfAnyUnseenLocation[direction] = __max(lowestPossibleScoreOfAnyUnseenLocation[direction], nSeedsApplied[direction] / mostSeedsContainingAnyParticularBase[direction]); } } #ifdef TRACE_ALIGNER printf("Lowest possible scores for unseen locations: %d (fwd), %d (RC)\n", lowestPossibleScoreOfAnyUnseenLocation[FORWARD], lowestPossibleScoreOfAnyUnseenLocation[RC]); #endif unsigned weightListToCheck = highestUsedWeightList; do { // // Grab the next element to score, and score it. // while (weightListToCheck > 0 && weightLists[weightListToCheck].weightNext == &weightLists[weightListToCheck]) { weightListToCheck--; highestUsedWeightList = weightListToCheck; } if ((__min(lowestPossibleScoreOfAnyUnseenLocation[FORWARD],lowestPossibleScoreOfAnyUnseenLocation[RC]) > scoreLimit && !noTruncation) || forceResult) { if (weightListToCheck< minWeightToCheck) { // // We've scored all live candidates and excluded all non-candidates, or we've checked enough that we've hit the cutoff. We have our // answer. // primaryResult->score = bestScore; if (bestScore <= maxK) { primaryResult->location = bestScoreGenomeLocation; primaryResult->mapq = computeMAPQ(probabilityOfAllCandidates, probabilityOfBestCandidate, bestScore, popularSeedsSkipped); if (primaryResult->mapq >= MAPQ_LIMIT_FOR_SINGLE_HIT) { primaryResult->status = SingleHit; } else { primaryResult->status = MultipleHits; } return true; } else { primaryResult->status = NotFound; primaryResult->mapq = 0; return true; } } // // Nothing that we haven't already looked up can possibly be the answer. Score what we've got and exit. // forceResult = true; } else if (weightListToCheck == 0) { // // No candidates, look for more. // return false; } HashTableElement *elementToScore = weightLists[weightListToCheck].weightNext; _ASSERT(!elementToScore->allExtantCandidatesScored); _ASSERT(elementToScore->candidatesUsed != 0); _ASSERT(elementToScore != &weightLists[weightListToCheck]); if (doAlignerPrefetch) { // // Our prefetch pipeline is one loop out we get the genome data for the next loop, and two loops out we get the element to score. // _mm_prefetch((const char *)(elementToScore->weightNext->weightNext), _MM_HINT_T2); // prefetch the next element, it's likely to be the next thing we score. genome->prefetchData(elementToScore->weightNext->baseGenomeLocation); } if (elementToScore->lowestPossibleScore <= scoreLimit) { unsigned long candidateIndexToScore; _uint64 candidatesMask = elementToScore->candidatesUsed; while (_BitScanForward64(&candidateIndexToScore,candidatesMask)) { _uint64 candidateBit = ((_uint64)1 << candidateIndexToScore); candidatesMask &= ~candidateBit; if ((elementToScore->candidatesScored & candidateBit) != 0) { // Already scored it, or marked it as scored due to using ProbabilityDistance continue; } bool anyNearbyCandidatesAlreadyScored = elementToScore->candidatesScored != 0; elementToScore->candidatesScored |= candidateBit; _ASSERT(candidateIndexToScore < hashTableElementSize); Candidate *candidateToScore = &elementToScore->candidates[candidateIndexToScore]; GenomeLocation genomeLocation = elementToScore->baseGenomeLocation + candidateIndexToScore; GenomeLocation elementGenomeLocation = genomeLocation; // This is the genome location prior to any adjustments for indels // // We're about to run edit distance computation on the genome. Launch a prefetch for it // so that it's in cache when we do (or at least on the way). // if (doAlignerPrefetch) { genomeIndex->prefetchGenomeData(genomeLocation); } unsigned score = -1; double matchProbability = 0; unsigned readDataLength = read[elementToScore->direction]->getDataLength(); GenomeDistance genomeDataLength = readDataLength + MAX_K; // Leave extra space in case the read has deletions const char *data = genome->getSubstring(genomeLocation, genomeDataLength); bool usedAffineGapScoring = false; int basesClippedBefore = 0; int basesClippedAfter = 0; int agScore = 0; if (data != NULL) { Read *readToScore = read[elementToScore->direction]; _ASSERT(candidateToScore->seedOffset + seedLen <= readToScore->getDataLength()); // // Compute the distance separately in the forward and backward directions from the seed, to allow // arbitrary offsets at both the start and end. // double matchProb1, matchProb2; int score1, score2; // First, do the forward direction from where the seed aligns to past of it int readLen = readToScore->getDataLength(); int seedLen = genomeIndex->getSeedLength(); int seedOffset = candidateToScore->seedOffset; // Since the data is reversed int tailStart = seedOffset + seedLen; int agScore1 = seedLen, agScore2 = 0; // Compute maxK for which edit distance and affine gap scoring report the same alignment // GapOpenPenalty + k.GapExtendPenalty >= k * SubPenalty // int maxKForSameAlignment = gapOpenPenalty / (subPenalty - gapExtendPenalty); int maxKForSameAlignment = 1; int totalIndels = 0; int genomeLocationOffset; _ASSERT(!memcmp(data+seedOffset, readToScore->getData() + seedOffset, seedLen)); int textLen = (int)__min(genomeDataLength - tailStart, 0x7ffffff0); score1 = landauVishkin->computeEditDistance(data + tailStart, textLen, readToScore->getData() + tailStart, readToScore->getQuality() + tailStart, readLen - tailStart, scoreLimit, &matchProb1, NULL, &totalIndels); agScore1 = (seedLen + (readLen - tailStart - score1) * matchReward - score1 * subPenalty); if (score1 == -1) { score = -1; } else if (useAffineGap && ((totalIndels > 1) || (score1 > maxKForSameAlignment))) { agScore1 = affineGap->computeScore(data + tailStart, textLen, readToScore->getData() + tailStart, readToScore->getQuality() + tailStart, readLen - tailStart, scoreLimit, seedLen, NULL, &basesClippedAfter, &score1, &matchProb1); usedAffineGapScoring = true; if (score1 == -1) { score = -1; agScore = 0; } } if (score1 != -1) { // The tail of the read matched; now let's reverse match the reference genome and the head int limitLeft = scoreLimit - score1; totalIndels = 0; score2 = reverseLandauVishkin->computeEditDistance(data + seedOffset, seedOffset + MAX_K, reversedRead[elementToScore->direction] + readLen - seedOffset, read[OppositeDirection(elementToScore->direction)]->getQuality() + readLen - seedOffset, seedOffset, limitLeft, &matchProb2, &genomeLocationOffset, &totalIndels); agScore2 = (seedOffset - score2) * matchReward - score2 * subPenalty; if (score2 == -1) { score = -1; } else if (useAffineGap && ((totalIndels > 1) || (score2 > maxKForSameAlignment))) { agScore2 = reverseAffineGap->computeScore(data + seedOffset, seedOffset + limitLeft, reversedRead[elementToScore->direction] + readLen - seedOffset, read[OppositeDirection(elementToScore->direction)]->getQuality() + readLen - seedOffset, seedOffset, limitLeft, readLen - seedOffset, // FIXME: Assumes the rest of the read matches exactly &genomeLocationOffset, &basesClippedBefore, &score2, &matchProb2); usedAffineGapScoring = true; agScore2 -= (readLen - seedOffset); if (score2 == -1) { score = -1; agScore = 0; } } if (score2 != -1) { score = score1 + score2; // Map probabilities for substrings can be multiplied, but make sure to count seed too matchProbability = matchProb1 * matchProb2 * pow(1 - SNP_PROB, seedLen); // // Adjust the genome location based on any indels that we found. // genomeLocation += genomeLocationOffset; agScore = agScore1 + agScore2; // // We could mark as scored anything in between the old and new genome offsets, but it's probably not worth the effort since this is // so rare and all it would do is same time. // } } } else { // if we had genome data to compare against matchProbability = 0; } #ifdef TRACE_ALIGNER printf("Computing distance at %u (RC) with limit %d: %d (prob %g)\n", genomeLocation, scoreLimit, score, matchProbability); #endif #ifdef _DEBUG if (_DumpAlignments) printf("Scored %9llu weight %2d limit %d, result %2d %s\n", genomeLocation.location, elementToScore->weight, scoreLimit, score, elementToScore->direction ? "RC" : ""); #endif // _DEBUG candidateToScore->score = score; nLocationsScored++; lvScores++; lvScoresAfterBestFound++; // // Handle the special case where we just scored a different offset for a region that's already been scored. This can happen when // there are indels in the read. In this case, we want to treat them as a single aignment, not two different ones (which would // cause us to lose confidence in the alignment, since they're probably both pretty good). // if (anyNearbyCandidatesAlreadyScored) { // if (elementToScore->bestScore < score || elementToScore->bestScore == score && matchProbability <= elementToScore->matchProbabilityForBestScore) { if (matchProbability <= elementToScore->matchProbabilityForBestScore) { // // This is a no better mapping than something nearby that we already tried. Just ignore it. // continue; } } else { _ASSERT(elementToScore->matchProbabilityForBestScore == 0.0); } elementToScore->bestScoreGenomeLocation = genomeLocation; elementToScore->usedAffineGapScoring = usedAffineGapScoring; elementToScore->basesClippedBefore = basesClippedBefore; elementToScore->basesClippedAfter = basesClippedAfter; elementToScore->agScore = agScore; // // Look up the hash table element that's closest to the genomeLocation but that doesn't // contain it, to check if this location is already scored. // // We do this computation in a strange way in order to avoid generating a branch instruction that // the processor's branch predictor will get wrong half of the time. Think about it like this: // The genome location lies in a bucket of size hashTableElementSize. Its offset in the bucket // is genomeLocation % hashTableElementSize. If we take that quantity and integer divide it by // hashTableElementSize / 2, we get 0 if it's in the first half and 1 if it's in the second. Double that and subtract // one, and you're at the right place with no branches. // HashTableElement *nearbyElement; GenomeLocation nearbyGenomeLocation; if (-1 != score) { nearbyGenomeLocation = elementGenomeLocation + (2*(GenomeLocationAsInt64(elementGenomeLocation) % hashTableElementSize / (hashTableElementSize/2)) - 1) * (hashTableElementSize/2); _ASSERT((GenomeLocationAsInt64(elementGenomeLocation) % hashTableElementSize >= (hashTableElementSize/2) ? elementGenomeLocation + (hashTableElementSize/2) : elementGenomeLocation - (hashTableElementSize/2)) == nearbyGenomeLocation); // Assert that the logic in the above comment is right. findElement(nearbyGenomeLocation, elementToScore->direction, &nearbyElement); } else { nearbyElement = NULL; } if (NULL != nearbyElement && nearbyElement->candidatesScored != 0) { // // Just because there's a "nearby" element doesn't mean it's really within the maxMergeDist. Check that now. // if (!genomeLocationIsWithin(genomeLocation, nearbyElement->bestScoreGenomeLocation, maxMergeDist)) { // // There's a nearby element, but its best score is too far away to merge. Forget it. // nearbyElement = NULL; } if (NULL != nearbyElement) { // if (nearbyElement->bestScore < score || nearbyElement->bestScore == score && nearbyElement->matchProbabilityForBestScore >= matchProbability) { if (nearbyElement->matchProbabilityForBestScore >= matchProbability) { // // Again, this no better than something nearby we already tried. Give up. // continue; } anyNearbyCandidatesAlreadyScored = true; probabilityOfAllCandidates = __max(0.0, probabilityOfAllCandidates - nearbyElement->matchProbabilityForBestScore); nearbyElement->matchProbabilityForBestScore = 0; // keeps us from backing it out twice } } probabilityOfAllCandidates = __max(0.0, probabilityOfAllCandidates - elementToScore->matchProbabilityForBestScore); // need the max due to floating point lossage. probabilityOfAllCandidates += matchProbability; // Don't combine this with the previous line, it introduces floating point unhappiness. elementToScore->matchProbabilityForBestScore = matchProbability; elementToScore->bestScore = score; // if (bestScore > score || // (bestScore == score && matchProbability > probabilityOfBestCandidate)) { if (matchProbability > probabilityOfBestCandidate) { // // We have a new best score. The old best score becomes the second best score, unless this is the same as the best or second best score // if ((secondBestScore == UnusedScoreValue || !(secondBestScoreGenomeLocation + maxMergeDist > genomeLocation && secondBestScoreGenomeLocation < genomeLocation + maxMergeDist)) && (bestScore == UnusedScoreValue || !(bestScoreGenomeLocation + maxMergeDist > genomeLocation && bestScoreGenomeLocation < genomeLocation + maxMergeDist)) && (!anyNearbyCandidatesAlreadyScored || (GenomeLocationAsInt64(bestScoreGenomeLocation) / maxMergeDist != GenomeLocationAsInt64(genomeLocation) / maxMergeDist && GenomeLocationAsInt64(secondBestScoreGenomeLocation) / maxMergeDist != GenomeLocationAsInt64(genomeLocation) / maxMergeDist))) { secondBestScore = bestScore; secondBestScoreGenomeLocation = bestScoreGenomeLocation; secondBestScoreDirection = primaryResult->direction; } // // If we're tracking secondary alignments, put the old best score in as a new secondary alignment // if (bestScore >= score) { if (NULL != secondaryResults && (int)(bestScore - score) <= maxEditDistanceForSecondaryResults) { // bestScore is initialized to UnusedScoreValue, which is large, so this won't fire if this is the first candidate if (secondaryResultBufferSize <= *nSecondaryResults) { *overflowedSecondaryBuffer = true; return true; } SingleAlignmentResult *result = &secondaryResults[*nSecondaryResults]; result->direction = primaryResult->direction; result->location = bestScoreGenomeLocation; result->mapq = 0; result->score = bestScore; result->status = MultipleHits; result->clippingForReadAdjustment = 0; result->usedAffineGapScoring = primaryResult->usedAffineGapScoring; result->basesClippedBefore = primaryResult->basesClippedBefore; result->basesClippedAfter = primaryResult->basesClippedAfter; result->agScore = primaryResult->agScore; _ASSERT(result->score != -1); (*nSecondaryResults)++; } } bestScore = score; probabilityOfBestCandidate = matchProbability; _ASSERT(probabilityOfBestCandidate <= probabilityOfAllCandidates); bestScoreGenomeLocation = genomeLocation; primaryResult->location = bestScoreGenomeLocation; primaryResult->score = bestScore; primaryResult->direction = elementToScore->direction; primaryResult->usedAffineGapScoring = elementToScore->usedAffineGapScoring; primaryResult->basesClippedBefore = elementToScore->basesClippedBefore; primaryResult->basesClippedAfter = elementToScore->basesClippedAfter; primaryResult->agScore = elementToScore->agScore; _ASSERT(0 == primaryResult->clippingForReadAdjustment); lvScoresAfterBestFound = 0; } else { if (secondBestScore > score) { // // A new second best. // secondBestScore = score; secondBestScoreGenomeLocation = genomeLocation; secondBestScoreDirection = elementToScore->direction; } // // If this is close enough, record it as a secondary alignment. // if (-1 != maxEditDistanceForSecondaryResults && NULL != secondaryResults && (int)(bestScore - score) <= maxEditDistanceForSecondaryResults && score != -1) { if (secondaryResultBufferSize <= *nSecondaryResults) { *overflowedSecondaryBuffer = true; return true; } SingleAlignmentResult *result = &secondaryResults[*nSecondaryResults]; result->direction = elementToScore->direction; result->location = genomeLocation; result->mapq = 0; result->score = score; result->status = MultipleHits; result->clippingForReadAdjustment = 0; result->usedAffineGapScoring = elementToScore->usedAffineGapScoring; result->basesClippedBefore = elementToScore->basesClippedBefore; result->basesClippedAfter = elementToScore->basesClippedAfter; result->agScore = elementToScore->agScore; _ASSERT(result->score != -1); (*nSecondaryResults)++; } } if (stopOnFirstHit && bestScore <= maxK) { // The user just wanted to find reads that match the database within some distance, but doesn't // care about the best alignment. Stop now but mark the result as MultipleHits because we're not // confident that it's the best one. We don't support mapq in this secnario, because we haven't // explored enough to compute it. primaryResult->status = MultipleHits; primaryResult->mapq = 0; return true; } // Taken from intersecting paired-end aligner. // Assuming maximum probability among unseen candidates is 1 and MAPQ < 1, find probability of // all candidates for each we can terminate early without exploring any more MAPQ 0 alignments // i.e., -10 log10(1 - 1/x) < 1 // i.e., x > 4.86 ~ 4.9 //if (probabilityOfAllCandidates >= 4.9 && -1 == maxEditDistanceForSecondaryResults) { // // // // Nothing will rescue us from a 0 MAPQ, so just stop looking. // // // return true; //} // Update scoreLimit since we may have improved bestScore or secondBestScore if (!noUkkonen) { // If we've turned off Ukkonen, then don't drop the score limit, just leave it at maxK + extraSearchDepth always scoreLimit = min(bestScore, maxK) + extraSearchDepth; } else { _ASSERT(scoreLimit == maxK + extraSearchDepth); } } // While candidates exist in the element } // If the element could possibly affect the result // // Remove the element from the weight list. // elementToScore->allExtantCandidatesScored = true; elementToScore->weightNext->weightPrev = elementToScore->weightPrev; elementToScore->weightPrev->weightNext = elementToScore->weightNext; elementToScore->weightNext = elementToScore->weightPrev = elementToScore; } while (forceResult); return false; } void BaseAligner::prefetchHashTableBucket(GenomeLocation genomeLocation, Direction direction) { HashTableAnchor *hashTable = candidateHashTable[direction]; _uint64 lowOrderGenomeLocation; _uint64 highOrderGenomeLocation; decomposeGenomeLocation(genomeLocation, &highOrderGenomeLocation, &lowOrderGenomeLocation); _uint64 hashTableIndex = hash(highOrderGenomeLocation) % candidateHashTablesSize; _mm_prefetch((const char *)&hashTable[hashTableIndex], _MM_HINT_T2); } bool BaseAligner::findElement( GenomeLocation genomeLocation, Direction direction, HashTableElement **hashTableElement) { HashTableAnchor *hashTable = candidateHashTable[direction]; _uint64 lowOrderGenomeLocation; _uint64 highOrderGenomeLocation; decomposeGenomeLocation(genomeLocation, &highOrderGenomeLocation, &lowOrderGenomeLocation); _uint64 hashTableIndex = hash(highOrderGenomeLocation) % candidateHashTablesSize; HashTableAnchor *anchor = &hashTable[hashTableIndex]; if (anchor->epoch != hashTableEpoch) { // // It's empty. // *hashTableElement = NULL; return false; } HashTableElement *lookedUpElement = anchor->element; while (NULL != lookedUpElement && lookedUpElement->baseGenomeLocation != highOrderGenomeLocation) { lookedUpElement = lookedUpElement->next; } *hashTableElement = lookedUpElement; return lookedUpElement != NULL; } void BaseAligner::findCandidate( GenomeLocation genomeLocation, Direction direction, Candidate **candidate, HashTableElement **hashTableElement) /*++ Routine Description: Find a candidate in the hash table, optionally allocating it if it doesn't exist (but the element does). Arguments: genomeLocation - the location of the candidate we'd like to look up candidate - The candidate that was found or created hashTableElement - the hashTableElement for the candidate that was found. allocateNew - if this doesn't already exist, should we allocate it? --*/ { _uint64 lowOrderGenomeLocation; decomposeGenomeLocation(genomeLocation, NULL, &lowOrderGenomeLocation); if (!findElement(genomeLocation, direction, hashTableElement)) { *hashTableElement = NULL; *candidate = NULL; return; } _uint64 bitForThisCandidate = (_uint64)1 << lowOrderGenomeLocation; *candidate = &(*hashTableElement)->candidates[lowOrderGenomeLocation]; (*hashTableElement)->allExtantCandidatesScored = (*hashTableElement)->allExtantCandidatesScored && ((*hashTableElement)->candidatesUsed & bitForThisCandidate); (*hashTableElement)->candidatesUsed |= bitForThisCandidate; } bool doAlignerPrefetch = true; void BaseAligner::allocateNewCandidate( GenomeLocation genomeLocation, Direction direction, unsigned lowestPossibleScore, int seedOffset, Candidate ** candidate, HashTableElement ** hashTableElement) /*++ Routine Description: Arguments: Return Value: --*/ { HashTableAnchor *hashTable = candidateHashTable[direction]; _uint64 lowOrderGenomeLocation; _uint64 highOrderGenomeLocation; decomposeGenomeLocation(genomeLocation, &highOrderGenomeLocation, &lowOrderGenomeLocation); unsigned hashTableIndex = hash(highOrderGenomeLocation) % candidateHashTablesSize; HashTableAnchor *anchor = &hashTable[hashTableIndex]; if (doAlignerPrefetch) { _mm_prefetch((const char *)anchor, _MM_HINT_T2); // Prefetch our anchor. We don't have enough computation to completely hide the prefetch, but at least we get some for free here. } HashTableElement *element; #if DBG element = hashTable[hashTableIndex].element; while (anchor->epoch == hashTableEpoch && NULL != element && element->genomeLocation != highOrderGenomeLocation) { element = element->next; } _ASSERT(NULL == element || anchor->epoch != hashTableEpoch); #endif // DBG _ASSERT(nUsedHashTableElements < hashTableElementPoolSize); element = &hashTableElementPool[nUsedHashTableElements]; nUsedHashTableElements++; if (doAlignerPrefetch) { // // Fetch the next candidate so we don't cache miss next time around. // _mm_prefetch((const char *)&hashTableElementPool[nUsedHashTableElements], _MM_HINT_T2); } element->candidatesUsed = (_uint64)1 << lowOrderGenomeLocation; element->candidatesScored = 0; element->lowestPossibleScore = lowestPossibleScore; element->direction = direction; element->weight = 1; element->baseGenomeLocation = highOrderGenomeLocation; element->bestScore = UnusedScoreValue; element->allExtantCandidatesScored = false; element->matchProbabilityForBestScore = 0; element->usedAffineGapScoring = false; element->basesClippedBefore = 0; element->basesClippedAfter = 0; element->agScore = 0; // // And insert it at the end of weight list 1. // element->weightNext = &weightLists[1]; element->weightPrev = weightLists[1].weightPrev; element->weightNext->weightPrev = element; element->weightPrev->weightNext = element; *candidate = &element->candidates[lowOrderGenomeLocation]; (*candidate)->seedOffset = seedOffset; *hashTableElement = element; highestUsedWeightList = __max(highestUsedWeightList,(unsigned)1); if (anchor->epoch == hashTableEpoch) { element->next = anchor->element; } else { anchor->epoch = hashTableEpoch; element->next = NULL; } anchor->element = element; } BaseAligner::~BaseAligner() /*++ Routine Description: Arguments: Return Value: --*/ { delete probDistance; if (hadBigAllocator) { // // Since these got allocated with the alloator rather than new, we want to call // their destructors without freeing their memory (which is the responsibility of // the owner of the allocator). // if (ownLandauVishkin) { if (NULL != landauVishkin) { landauVishkin->~LandauVishkin(); } if (NULL != reverseLandauVishkin) { reverseLandauVishkin->~LandauVishkin(); } } if (NULL != affineGap) { // affineGap->~AffineGap(); affineGap->~AffineGapVectorized(); } if (NULL != reverseAffineGap) { // reverseAffineGap->~AffineGap(); reverseAffineGap->~AffineGapVectorized(); } } else { if (ownLandauVishkin) { if (NULL != landauVishkin) { delete landauVishkin; } if (NULL != reverseLandauVishkin) { delete reverseLandauVishkin; } } if (NULL != affineGap) { delete affineGap; } if (NULL != reverseAffineGap) { delete reverseAffineGap; } BigDealloc(rcReadData); rcReadData = NULL; BigDealloc(reversedRead[FORWARD]); reversedRead[FORWARD] = NULL; reversedRead[RC] = NULL; BigDealloc(seedUsedAsAllocated); seedUsed = NULL; BigDealloc(candidateHashTable[FORWARD]); candidateHashTable[FORWARD] = NULL; BigDealloc(candidateHashTable[RC]); candidateHashTable[RC] = NULL; BigDealloc(weightLists); weightLists = NULL; BigDealloc(hashTableElementPool); hashTableElementPool = NULL; if (NULL != hitsPerContigCounts) { BigDealloc(hitsPerContigCounts); hitsPerContigCounts = NULL; } } } BaseAligner::HashTableElement::HashTableElement() { init(); } void BaseAligner::HashTableElement::init() { weightNext = NULL; weightPrev = NULL; next = NULL; candidatesUsed = 0; baseGenomeLocation = 0; weight = 0; lowestPossibleScore = UnusedScoreValue; bestScore = UnusedScoreValue; direction = FORWARD; allExtantCandidatesScored = false; matchProbabilityForBestScore = 0; usedAffineGapScoring = false; agScore = 0; } void BaseAligner::Candidate::init() { score = UnusedScoreValue; } void BaseAligner::clearCandidates() { hashTableEpoch++; nUsedHashTableElements = 0; highestUsedWeightList = 0; for (unsigned i = 1; i < numWeightLists; i++) { weightLists[i].weightNext = weightLists[i].weightPrev = &weightLists[i]; } } void BaseAligner::incrementWeight(HashTableElement *element) { if (element->allExtantCandidatesScored) { // // It's already scored, so it shouldn't be on a weight list. // _ASSERT(element->weightNext == element); _ASSERT(element->weightPrev == element); return; } // // It's possible to have elements with weight > maxSeedsToUse. This // happens when a single seed occurs more than once within a particular // element (imagine an element with bases ATATATATATATATAT..., it will // match the appropriate seed at offset 0, 2, 4, etc.) If that happens, // just don't let the weight get too big. // if (element->weight >= numWeightLists - 1) { return; } // // Remove it from its existing list. // element->weightNext->weightPrev = element->weightPrev; element->weightPrev->weightNext = element->weightNext; element->weight++; highestUsedWeightList = __max(highestUsedWeightList,element->weight); // // And insert it at the tail of the new list. // element->weightNext = &weightLists[element->weight]; element->weightPrev = weightLists[element->weight].weightPrev; element->weightNext->weightPrev = element; element->weightPrev->weightNext = element; } size_t BaseAligner::getBigAllocatorReservation(GenomeIndex *index, bool ownLandauVishkin, unsigned maxHitsToConsider, unsigned maxReadSize, unsigned seedLen, unsigned numSeedsFromCommandLine, double seedCoverage, int maxSecondaryAlignmentsPerContig, unsigned extraSearchDepth) { unsigned maxSeedsToUse; if (0 != numSeedsFromCommandLine) { maxSeedsToUse = numSeedsFromCommandLine; } else { maxSeedsToUse = (unsigned)(maxReadSize * seedCoverage / seedLen); } size_t candidateHashTablesSize = (maxHitsToConsider * maxSeedsToUse * 3)/2; // *1.5 for hash table slack size_t hashTableElementPoolSize = maxHitsToConsider * maxSeedsToUse * 2 ; // *2 for RC size_t contigCounters; if (maxSecondaryAlignmentsPerContig > 0) { contigCounters = sizeof(HitsPerContigCounts)* index->getGenome()->getNumContigs(); } else { contigCounters = 0; } return contigCounters + sizeof(_uint64) * 14 + // allow for alignment sizeof(BaseAligner) + // our own member variables (ownLandauVishkin ? LandauVishkin<>::getBigAllocatorReservation() + LandauVishkin<-1>::getBigAllocatorReservation() : 0) + // our LandauVishkin objects // AffineGap<>::getBigAllocatorReservation() + // AffineGap<-1>::getBigAllocatorReservation() + // our AffineGap objects AffineGapVectorized<>::getBigAllocatorReservation() + AffineGapVectorized<-1>::getBigAllocatorReservation() + // our AffineGap objects sizeof(char) * maxReadSize * 2 + // rcReadData sizeof(char) * maxReadSize * 4 + 2 * MAX_K + // reversed read (both) sizeof(BYTE) * (maxReadSize + 7 + 128) / 8 + // seed used sizeof(HashTableElement) * hashTableElementPoolSize + // hash table element pool sizeof(HashTableAnchor) * candidateHashTablesSize * 2 + // candidate hash table (both) sizeof(HashTableElement) * (maxSeedsToUse + 1) + // weight lists sizeof(unsigned) * extraSearchDepth; // hitCountByExtraSearchDepth } void BaseAligner::finalizeSecondaryResults( Read *read, SingleAlignmentResult *primaryResult, _int64 *nSecondaryResults, // in/out SingleAlignmentResult *secondaryResults, _int64 maxSecondaryResults, int maxEditDistanceForSecondaryResults, int bestScore) { // // There's no guarantee that the results are actually within the bound; the aligner records anything that's // within the bound when it's scored, but if we subsequently found a better fit, then it may no longer be // close enough. Get rid of those now. // // NB: This code is very similar to code at the end of IntersectingPairedEndAligner::align(). Sorry. // _ASSERT(bestScore == primaryResult->score); primaryResult->scorePriorToClipping = primaryResult->score; if (!ignoreAlignmentAdjustmentsForOm) { // // Start by adjusting the alignments for the primary and secondary reads, since that can affect their score // and hence whether they should be kept. // alignmentAdjuster.AdjustAlignment(read, primaryResult); if (primaryResult->status != NotFound) { bestScore = primaryResult->score; } else { bestScore = 65536; } for (int i = 0; i < *nSecondaryResults; i++) { secondaryResults[i].scorePriorToClipping = secondaryResults[i].score; alignmentAdjuster.AdjustAlignment(read, &secondaryResults[i]); if (secondaryResults[i].status != NotFound) { bestScore = __min(bestScore, secondaryResults[i].score); } } } int worstScoreToKeep = min((int)maxK, bestScore + maxEditDistanceForSecondaryResults); int i = 0; while (i < *nSecondaryResults) { if (secondaryResults[i].score > worstScoreToKeep) { // // This one is too bad to keep. Move the last one from the array here and decrement the // count. Don't move up i, because the one we just moved in may also be too // bad. // secondaryResults[i] = secondaryResults[(*nSecondaryResults)-1]; (*nSecondaryResults)--; } else { if (ignoreAlignmentAdjustmentsForOm) { secondaryResults[i].scorePriorToClipping = secondaryResults[i].score; } i++; } } if (maxSecondaryAlignmentsPerContig > 0 && primaryResult->status != NotFound) { // // Run through the results and count the number of results per contig, to see if any of them are too big. // bool anyContigHasTooManyResults = false; int primaryResultContigNum = genome->getContigNumAtLocation(primaryResult->location); hitsPerContigCounts[primaryResultContigNum].hits = 1; hitsPerContigCounts[primaryResultContigNum].epoch = hashTableEpoch; for (i = 0; i < *nSecondaryResults; i++) { int contigNum = genome->getContigNumAtLocation(secondaryResults[i].location); if (hitsPerContigCounts[contigNum].epoch != hashTableEpoch) { hitsPerContigCounts[contigNum].epoch = hashTableEpoch; hitsPerContigCounts[contigNum].hits = 0; } hitsPerContigCounts[contigNum].hits++; if (hitsPerContigCounts[contigNum].hits > maxSecondaryAlignmentsPerContig) { anyContigHasTooManyResults = true; break; } } if (anyContigHasTooManyResults) { // // Just sort them all, in order of contig then hit depth. // qsort(secondaryResults, *nSecondaryResults, sizeof(*secondaryResults), SingleAlignmentResult::compareByContigAndScore); // // Now run through and eliminate any contigs with too many hits. We can't use the same trick at the first loop above, because the // counting here relies on the results being sorted. So, instead, we just copy them as we go. // int currentContigNum = -1; int currentContigCount = 0; int destResult = 0; for (int sourceResult = 0; sourceResult < *nSecondaryResults; sourceResult++) { int contigNum = genome->getContigNumAtLocation(secondaryResults[sourceResult].location); if (contigNum != currentContigNum) { currentContigNum = contigNum; currentContigCount = (contigNum == primaryResultContigNum) ? 1 : 0; } currentContigCount++; if (currentContigCount <= maxSecondaryAlignmentsPerContig) { // // Keep it. If we don't get here, then we don't copy the result and // don't increment destResult. And yes, this will sometimes copy a // result over itself. That's harmless. // secondaryResults[destResult] = secondaryResults[sourceResult]; destResult++; } } // for each source result *nSecondaryResults = destResult; } } // if maxSecondaryAlignmentsPerContig > 0 if (*nSecondaryResults > maxSecondaryResults) { qsort(secondaryResults, *nSecondaryResults, sizeof(*secondaryResults), SingleAlignmentResult::compareByScore); *nSecondaryResults = maxSecondaryResults; // Just truncate it } }